fernctl/commands/
validate.rs

1//! # Configuration Validation Command
2//!
3//! The `validate` command checks a configuration file for correctness without
4//! producing any output files. It performs both syntactic validation (is it
5//! valid TOML?) and semantic validation (are the values sensible?).
6//!
7//! ## Usage
8//!
9//! ```bash
10//! # Validate default config location
11//! fernctl validate
12//!
13//! # Validate specific file
14//! fernctl validate --config ./my-config.toml
15//!
16//! # With verbose output
17//! fernctl validate -v
18//! ```
19//!
20//! ## Validation Stages
21//!
22//! Validation proceeds in three stages:
23//!
24//! ```text
25//! ┌─────────────┐    ┌──────────────┐    ┌────────────────┐
26//! │   Stage 1   │───▶│   Stage 2    │───▶│    Stage 3     │
27//! │   Parsing   │    │  Type Check  │    │   Semantics    │
28//! └─────────────┘    └──────────────┘    └────────────────┘
29//!     TOML syntax       Value types        Business rules
30//!     Well-formed       Color formats      Range limits
31//!     Structure         Required fields    Consistency
32//! ```
33//!
34//! ### Stage 1: Parsing
35//!
36//! Checks that the file is syntactically valid TOML:
37//!
38//! - Proper key-value syntax
39//! - Balanced brackets and quotes
40//! - Valid escape sequences
41//!
42//! **Errors at this stage:**
43//! - `fern::config::parse_error` — Invalid TOML syntax
44//!
45//! ### Stage 2: Type Checking
46//!
47//! Validates that values have the expected types:
48//!
49//! - Numbers where numbers are expected
50//! - Strings where strings are expected
51//! - Required fields are present
52//!
53//! **Errors at this stage:**
54//! - `fern::config::type_mismatch` — Wrong value type
55//! - `fern::config::missing_field` — Required field absent
56//!
57//! ### Stage 3: Semantic Validation
58//!
59//! Checks business rules and constraints:
60//!
61//! - Color values are valid hex (`#RRGGBB` or `#RRGGBBAA`)
62//! - Numbers are within allowed ranges
63//! - Enum values are recognized (`"top"`, `"bottom"`, etc.)
64//!
65//! **Errors at this stage:**
66//! - `fern::config::invalid_color` — Malformed color value
67//! - `fern::config::out_of_range` — Number outside limits
68//! - `fern::config::unknown_key` — Unrecognized configuration key
69//!
70//! ## Warnings vs Errors
71//!
72//! Not all problems are fatal. The validator distinguishes:
73//!
74//! | Severity | Behavior | Example |
75//! |----------|----------|---------|
76//! | **Error** | Validation fails | Invalid color format |
77//! | **Warning** | Validation passes, issue reported | Unknown key |
78//!
79//! Warnings allow forward compatibility — new config files may have keys
80//! that older `fernctl` versions don't recognize.
81//!
82//! ## Exit Codes
83//!
84//! | Code | Meaning |
85//! |------|---------|
86//! | `0` | Validation passed (possibly with warnings) |
87//! | `1` | Validation failed with errors |
88//!
89//! ## Programmatic Usage
90//!
91//! ```rust,ignore
92//! use fernctl::commands::validate::{run, ValidateOptions};
93//! use fernctl::adapters::TomlConfigAdapter;
94//!
95//! let adapter = TomlConfigAdapter::new();
96//! let options = ValidateOptions { verbose: true };
97//!
98//! match run(&path, options, &adapter) {
99//!     Ok(result) => {
100//!         println!("Valid! {} warnings", result.warnings.len());
101//!     }
102//!     Err(e) => {
103//!         eprintln!("Invalid: {}", e);
104//!     }
105//! }
106//! ```
107
108use crate::domain::theme::Theme;
109use crate::error::Result;
110use crate::ports::inbound::ConfigPort;
111use std::path::Path;
112
113/// Options for the validate command.
114///
115/// These options control the behavior and output of validation.
116///
117/// # Example
118///
119/// ```rust
120/// use fernctl::commands::validate::ValidateOptions;
121///
122/// let options = ValidateOptions {
123///     verbose: true,
124/// };
125/// ```
126#[derive(Debug, Clone, Default)]
127pub struct ValidateOptions {
128    /// Whether to print detailed information during validation.
129    ///
130    /// When enabled, prints:
131    /// - The file being validated
132    /// - Theme variant detected
133    /// - Key configuration values
134    pub verbose: bool,
135}
136
137/// Result of a successful validation.
138///
139/// Contains the validated theme and any warnings encountered.
140/// Warnings indicate non-fatal issues that don't prevent the
141/// configuration from being used.
142///
143/// # Example
144///
145/// ```rust,ignore
146/// let result = validate::run(&path, options, &adapter)?;
147///
148/// for warning in &result.warnings {
149///     eprintln!("Warning: {}", warning);
150/// }
151///
152/// // Use the validated theme
153/// let theme = result.theme;
154/// ```
155#[derive(Debug)]
156pub struct ValidateResult {
157    /// The validated theme.
158    pub theme: Theme,
159
160    /// Non-fatal warnings encountered during validation.
161    ///
162    /// Common warnings include:
163    /// - Unknown configuration keys (possibly typos)
164    /// - Deprecated keys (still work, but will be removed)
165    pub warnings: Vec<String>,
166}
167
168/// Validates a configuration file.
169///
170/// This function performs comprehensive validation of a TOML configuration
171/// file, checking both syntax and semantics. It returns a [`ValidateResult`]
172/// containing the parsed theme and any warnings.
173///
174/// # Arguments
175///
176/// * `path` — Path to the configuration file to validate
177/// * `options` — Configuration for validation behavior
178/// * `adapter` — The configuration parser to use
179///
180/// # Returns
181///
182/// - `Ok(ValidateResult)` — Configuration is valid
183/// - `Err(FernError)` — Configuration has errors
184///
185/// # Errors
186///
187/// Returns an error if:
188/// - The file cannot be read ([`FernError::Io`](crate::error::FernError::Io))
189/// - TOML syntax is invalid ([`ConfigError::ParseError`](crate::error::ConfigError::ParseError))
190/// - Values fail validation ([`ConfigError::InvalidColor`](crate::error::ConfigError::InvalidColor), etc.)
191///
192/// # Example
193///
194/// ```rust,ignore
195/// use fernctl::commands::validate::{run, ValidateOptions};
196/// use fernctl::adapters::TomlConfigAdapter;
197/// use std::path::Path;
198///
199/// let adapter = TomlConfigAdapter::new();
200/// let options = ValidateOptions::default();
201///
202/// match run(Path::new("config.toml"), options, &adapter) {
203///     Ok(result) => {
204///         println!("Configuration is valid!");
205///         println!("Theme variant: {}", result.theme.variant.name());
206///
207///         if !result.warnings.is_empty() {
208///             println!("\nWarnings:");
209///             for warning in &result.warnings {
210///                 println!("  - {}", warning);
211///             }
212///         }
213///     }
214///     Err(e) => {
215///         // Error includes rich diagnostic information
216///         eprintln!("{:?}", miette::Report::new(e));
217///         std::process::exit(1);
218///     }
219/// }
220/// ```
221pub fn run<P: AsRef<Path>>(
222    path: P,
223    options: ValidateOptions,
224    adapter: &impl ConfigPort,
225) -> Result<ValidateResult> {
226    let path = path.as_ref();
227
228    if options.verbose {
229        eprintln!("Validating: {}", path.display());
230    }
231
232    // Load and parse the configuration
233    let raw = adapter.load_from_file(path)?;
234
235    // Validate the parsed configuration
236    let validated = raw.validate()?;
237
238    // Collect warnings
239    let warnings: Vec<String> = validated.warnings().iter().map(ToString::to_string).collect();
240
241    // Convert to theme
242    let theme = validated.into_theme();
243
244    if options.verbose {
245        eprintln!("Theme variant: {}", theme.variant.name());
246        eprintln!("Bar height: {}px", theme.bar.height);
247        eprintln!("Bar position: {}", theme.bar.position.name());
248    }
249
250    Ok(ValidateResult { theme, warnings })
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256
257    #[test]
258    fn validate_options_default() {
259        let options = ValidateOptions::default();
260        assert!(!options.verbose);
261    }
262}