fernctl/commands/
convert.rs

1//! # Configuration Conversion Command
2//!
3//! The `convert` command transforms TOML configuration files into JSON format
4//! suitable for consumption by QuickShell. This is the bridge between the
5//! human-friendly TOML authoring format and the QML-friendly JSON runtime format.
6//!
7//! ## Usage
8//!
9//! ```bash
10//! # Convert with auto-named output (config.toml → config.json)
11//! fernctl convert config.toml
12//!
13//! # Convert with explicit output path
14//! fernctl convert config.toml --output theme.json
15//!
16//! # With verbose output
17//! fernctl convert config.toml -v
18//! ```
19//!
20//! ## Why Two Formats?
21//!
22//! TOML and JSON serve different purposes in the Fern ecosystem:
23//!
24//! | Aspect | TOML (Input) | JSON (Output) |
25//! |--------|--------------|---------------|
26//! | **Audience** | Human authors | QML runtime |
27//! | **Comments** | ✓ Supported | ✗ Not in spec |
28//! | **Readability** | Optimized | Adequate |
29//! | **Parsing** | Rust (fernctl) | JavaScript (QML) |
30//! | **Editing** | By users | Never |
31//!
32//! ## Conversion Pipeline
33//!
34//! ```text
35//! ┌─────────────────┐     ┌─────────────────┐     ┌─────────────────┐
36//! │   config.toml   │────▶│    Validate     │────▶│   config.json   │
37//! │   (user file)   │     │   & Transform   │     │  (QML runtime)  │
38//! └─────────────────┘     └─────────────────┘     └─────────────────┘
39//!         │                       │                       │
40//!         ▼                       ▼                       ▼
41//!    Human-readable         Type-safe Rust           Structured for
42//!    with comments          domain model             QML consumption
43//! ```
44//!
45//! ## Validation During Conversion
46//!
47//! Conversion is **not** a simple format translation. The configuration passes
48//! through full validation before JSON output is generated. This ensures that
49//! invalid configurations are caught early, before they reach QuickShell.
50//!
51//! ```text
52//! config.toml (valid TOML, invalid values)
53//!      │
54//!      ▼
55//! ┌────────────────────────────────────────┐
56//! │  Parse TOML                            │  ✓ Succeeds
57//! └────────────────────────────────────────┘
58//!      │
59//!      ▼
60//! ┌────────────────────────────────────────┐
61//! │  Validate Values                       │  ✗ Fails: "#gg0000" invalid
62//! │  - Check color formats                 │
63//! │  - Verify ranges                       │
64//! │  - Resolve defaults                    │
65//! └────────────────────────────────────────┘
66//!      │
67//!      ▼
68//!   Error returned, no JSON generated
69//! ```
70//!
71//! ## Output Format
72//!
73//! The generated JSON follows a specific structure optimized for QML:
74//!
75//! ```json
76//! {
77//!   "variant": "dark",
78//!   "colors": {
79//!     "background": "#1e1e2e",
80//!     "foreground": "#cdd6f4",
81//!     "accent": "#89b4fa",
82//!     ...
83//!   },
84//!   "bar": {
85//!     "height": 32,
86//!     "position": "top",
87//!     ...
88//!   },
89//!   ...
90//! }
91//! ```
92//!
93//! ## Atomicity
94//!
95//! Conversion is atomic — if any step fails, no output file is created or
96//! modified. This prevents partial writes that could leave QuickShell with
97//! a corrupted configuration.
98//!
99//! ```text
100//! ┌─────────────┐    ┌─────────────┐    ┌─────────────┐
101//! │   Success   │    │   Failure   │    │   Failure   │
102//! │   Path      │    │   (Parse)   │    │  (Validate) │
103//! └─────────────┘    └─────────────┘    └─────────────┘
104//!       │                  │                  │
105//!       ▼                  ▼                  ▼
106//!  JSON written       No file touched    No file touched
107//! ```
108//!
109//! ## Exit Codes
110//!
111//! | Code | Meaning |
112//! |------|---------|
113//! | `0` | Conversion succeeded |
114//! | `1` | Conversion failed (parse error, validation error, I/O error) |
115//!
116//! ## Programmatic Usage
117//!
118//! ```rust,ignore
119//! use fernctl::commands::convert::{run, ConvertOptions};
120//! use fernctl::adapters::{TomlConfigAdapter, FileSystemAdapter};
121//!
122//! let config_adapter = TomlConfigAdapter::new();
123//! let persist_adapter = FileSystemAdapter::new();
124//! let options = ConvertOptions { verbose: true };
125//!
126//! run(
127//!     Path::new("config.toml"),
128//!     Path::new("config.json"),
129//!     options,
130//!     &config_adapter,
131//!     &persist_adapter,
132//! )?;
133//! ```
134
135use crate::error::Result;
136use crate::ports::inbound::ConfigPort;
137use crate::ports::outbound::PersistPort;
138use std::path::Path;
139
140/// Options for the convert command.
141///
142/// These options control the behavior and output of conversion.
143///
144/// # Example
145///
146/// ```rust
147/// use fernctl::commands::convert::ConvertOptions;
148///
149/// let options = ConvertOptions {
150///     verbose: true,
151///     pretty: true,
152/// };
153/// ```
154#[derive(Debug, Clone)]
155pub struct ConvertOptions {
156    /// Whether to print detailed information during conversion.
157    ///
158    /// When enabled, prints:
159    /// - Input and output paths
160    /// - Validation status
161    /// - Any warnings encountered
162    pub verbose: bool,
163
164    /// Whether to format the JSON output with indentation.
165    ///
166    /// When `true` (default), output is human-readable:
167    /// ```json
168    /// {
169    ///   "variant": "dark",
170    ///   "colors": { ... }
171    /// }
172    /// ```
173    ///
174    /// When `false`, output is compact (smaller file size):
175    /// ```json
176    /// {"variant":"dark","colors":{...}}
177    /// ```
178    pub pretty: bool,
179}
180
181impl Default for ConvertOptions {
182    fn default() -> Self {
183        Self {
184            verbose: false,
185            pretty: true,
186        }
187    }
188}
189
190/// Result of a successful conversion.
191///
192/// Contains information about what was converted and any
193/// warnings that were encountered during validation.
194#[derive(Debug)]
195pub struct ConvertResult {
196    /// Warnings encountered during validation.
197    ///
198    /// These are non-fatal issues that didn't prevent conversion.
199    pub warnings: Vec<String>,
200}
201
202/// Converts a TOML configuration file to JSON.
203///
204/// This function loads a TOML configuration, validates it, and writes the
205/// validated theme to a JSON file. The conversion is atomic — if any step
206/// fails, no output file is created.
207///
208/// # Arguments
209///
210/// * `input` — Path to the input TOML file
211/// * `output` — Path where the JSON output will be written
212/// * `options` — Configuration for conversion behavior
213/// * `config_adapter` — Adapter for loading TOML configuration
214/// * `persist_adapter` — Adapter for writing JSON output
215///
216/// # Returns
217///
218/// - `Ok(ConvertResult)` — Conversion succeeded
219/// - `Err(FernError)` — Conversion failed
220///
221/// # Errors
222///
223/// Returns an error if:
224/// - The input file cannot be read
225/// - TOML parsing fails
226/// - Validation fails
227/// - The output file cannot be written
228///
229/// # Example
230///
231/// ```rust,ignore
232/// use fernctl::commands::convert::{run, ConvertOptions};
233/// use fernctl::adapters::{TomlConfigAdapter, FileSystemAdapter};
234/// use std::path::Path;
235///
236/// let config_adapter = TomlConfigAdapter::new();
237/// let persist_adapter = FileSystemAdapter::new();
238///
239/// let result = run(
240///     Path::new("~/.config/fern/config.toml"),
241///     Path::new("~/.config/fern/config.json"),
242///     ConvertOptions::default(),
243///     &config_adapter,
244///     &persist_adapter,
245/// )?;
246///
247/// println!("Conversion complete with {} warnings", result.warnings.len());
248/// ```
249///
250/// # Atomicity Guarantee
251///
252/// This function guarantees that either:
253/// 1. The output file is completely written with valid JSON, OR
254/// 2. No changes are made to the output file
255///
256/// This is achieved by validating completely before writing, so partial
257/// or corrupted output is never possible.
258pub fn run<P: AsRef<Path>, Q: AsRef<Path>>(
259    input: P,
260    output: Q,
261    options: ConvertOptions,
262    config_adapter: &impl ConfigPort,
263    persist_adapter: &impl PersistPort,
264) -> Result<ConvertResult> {
265    let input = input.as_ref();
266    let output = output.as_ref();
267
268    if options.verbose {
269        eprintln!("Converting: {} -> {}", input.display(), output.display());
270    }
271
272    // Load and validate
273    let raw = config_adapter.load_from_file(input)?;
274    let validated = raw.validate()?;
275
276    // Collect warnings before consuming validated
277    let warnings: Vec<String> = validated.warnings().iter().map(ToString::to_string).collect();
278
279    // Print warnings if verbose
280    if options.verbose {
281        for warning in &warnings {
282            eprintln!("Warning: {}", warning);
283        }
284    }
285
286    // Convert to theme
287    let theme = validated.into_theme();
288
289    // Persist to JSON
290    persist_adapter.save_theme(&theme, output)?;
291
292    if options.verbose {
293        eprintln!("Wrote {}", output.display());
294    }
295
296    Ok(ConvertResult { warnings })
297}
298
299/// Derives the output path from an input path.
300///
301/// Replaces the file extension with `.json`. If the input has no extension,
302/// `.json` is appended.
303///
304/// # Examples
305///
306/// ```rust
307/// use fernctl::commands::convert::derive_output_path;
308/// use std::path::PathBuf;
309///
310/// assert_eq!(
311///     derive_output_path("config.toml"),
312///     PathBuf::from("config.json")
313/// );
314///
315/// assert_eq!(
316///     derive_output_path("my-theme"),
317///     PathBuf::from("my-theme.json")
318/// );
319/// ```
320#[must_use]
321pub fn derive_output_path(input: impl AsRef<Path>) -> std::path::PathBuf {
322    let input = input.as_ref();
323    input.with_extension("json")
324}
325
326#[cfg(test)]
327mod tests {
328    use super::*;
329    use std::path::PathBuf;
330
331    #[test]
332    fn derive_output_replaces_extension() {
333        assert_eq!(derive_output_path("config.toml"), PathBuf::from("config.json"));
334    }
335
336    #[test]
337    fn derive_output_handles_no_extension() {
338        assert_eq!(derive_output_path("config"), PathBuf::from("config.json"));
339    }
340
341    #[test]
342    fn derive_output_handles_multiple_dots() {
343        assert_eq!(
344            derive_output_path("my.config.toml"),
345            PathBuf::from("my.config.json")
346        );
347    }
348
349    #[test]
350    fn convert_options_default() {
351        let options = ConvertOptions::default();
352        assert!(!options.verbose);
353        assert!(options.pretty);
354    }
355}