fernctl/error/
config.rs

1//! # Configuration Error Types
2//!
3//! This module defines error types for configuration parsing and validation.
4//! Each error variant includes:
5//!
6//! - A human-readable message
7//! - A unique error code for documentation lookup
8//! - Source location information (when available)
9//! - Actionable suggestions for fixing the problem
10//!
11//! ## Error Categories
12//!
13//! | Category | Examples |
14//! |----------|----------|
15//! | **Parse Errors** | Invalid TOML syntax |
16//! | **Type Errors** | String where number expected |
17//! | **Value Errors** | Invalid color format, out of range |
18//! | **Schema Errors** | Missing required field, unknown key |
19//!
20//! ## Integration with miette
21//!
22//! All errors implement [`miette::Diagnostic`] for rich terminal output.
23//! When source code is available, errors display the problematic line:
24//!
25//! ```text
26//! Error: fern::config::invalid_color
27//!
28//!   × Invalid color format: #gg0000
29//!    ╭─[config.toml:5:10]
30//!  4 │ [appearance]
31//!  5 │ accent = "#gg0000"
32//!    ·          ────────── this color value is not valid hex
33//!    ╰────
34//!   help: Colors must be hex format: #RRGGBB or #RRGGBBAA
35//!         Examples: #89b4fa, #ff6b6bff
36//! ```
37
38use super::{Notifiable, Severity};
39use miette::{Diagnostic, SourceSpan};
40use std::path::PathBuf;
41use thiserror::Error;
42
43/// Location within a configuration file.
44///
45/// This struct captures where an error occurred, enabling rich error messages
46/// that point to the exact location of the problem.
47///
48/// # Fields
49///
50/// - `file` — Path to the configuration file
51/// - `line` — Line number (1-indexed)
52/// - `column` — Column number (1-indexed)
53/// - `key_path` — Dotted path to the key (e.g., "appearance.radius.md")
54///
55/// # Example
56///
57/// ```rust,ignore
58/// let loc = ConfigLocation {
59///     file: PathBuf::from("config.toml"),
60///     line: Some(5),
61///     column: Some(10),
62///     key_path: "appearance.accent".to_string(),
63/// };
64/// ```
65// TODO: Wire up ConfigLocation to ConfigError variants for rich source spans
66#[allow(dead_code)]
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub(crate) struct ConfigLocation {
69    /// Path to the configuration file.
70    pub file: PathBuf,
71    /// Line number (1-indexed), if known.
72    pub line: Option<usize>,
73    /// Column number (1-indexed), if known.
74    pub column: Option<usize>,
75    /// Dotted key path (e.g., "appearance.accent").
76    pub key_path: String,
77}
78
79#[allow(dead_code)]
80impl ConfigLocation {
81    /// Creates a new config location.
82    fn new(file: impl Into<PathBuf>, key_path: impl Into<String>) -> Self {
83        Self {
84            file: file.into(),
85            line: None,
86            column: None,
87            key_path: key_path.into(),
88        }
89    }
90
91    /// Sets the line number.
92    fn with_line(mut self, line: usize) -> Self {
93        self.line = Some(line);
94        self
95    }
96
97    /// Sets the column number.
98    fn with_column(mut self, column: usize) -> Self {
99        self.column = Some(column);
100        self
101    }
102
103    /// Formats the location for display.
104    fn display(&self) -> String {
105        match (self.line, self.column) {
106            (Some(l), Some(c)) => format!("{}:{}:{}", self.file.display(), l, c),
107            (Some(l), None) => format!("{}:{}", self.file.display(), l),
108            _ => self.file.display().to_string(),
109        }
110    }
111}
112
113/// Errors that occur during configuration parsing and validation.
114///
115/// `ConfigError` provides detailed, actionable error messages for configuration
116/// problems. Each variant includes context about what went wrong and how to
117/// fix it.
118///
119/// # Error Codes
120///
121/// Every error has a unique code (e.g., `fern::config::invalid_color`) that
122/// can be looked up in documentation for detailed explanations.
123///
124/// # Severity Levels
125///
126/// Most configuration errors are [`Severity::Error`], but some are warnings:
127///
128/// | Variant | Severity | Behavior |
129/// |---------|----------|----------|
130/// | `UnknownKey` | Warning | Config loads, key ignored |
131/// | `DeprecatedKey` | Warning | Config loads, warning shown |
132/// | Others | Error | Config fails to load |
133///
134/// # Example
135///
136/// ```rust,ignore
137/// use fernctl::error::ConfigError;
138///
139/// let error = ConfigError::InvalidColor {
140///     value: "#gg0000".to_string(),
141///     span: None,
142///     location: None,
143/// };
144///
145/// // Rich error output with miette
146/// println!("{:?}", miette::Report::new(error));
147/// ```
148#[derive(Debug, Error, Diagnostic)]
149#[non_exhaustive]
150pub enum ConfigError {
151    /// Invalid color format.
152    ///
153    /// The provided value is not a valid hex color. Colors must be in the
154    /// format `#RRGGBB` or `#RRGGBBAA` where each character is a hex digit.
155    ///
156    /// # Valid Examples
157    ///
158    /// - `#89b4fa` — 6-digit hex (opaque)
159    /// - `#89b4fa80` — 8-digit hex (with alpha)
160    /// - `#fff` — 3-digit shorthand (expands to #ffffff)
161    ///
162    /// # Invalid Examples
163    ///
164    /// - `#gg0000` — Contains non-hex characters
165    /// - `89b4fa` — Missing `#` prefix
166    /// - `#89b` — Invalid length (not 3, 6, or 8)
167    #[error("invalid color format: {value}")]
168    #[diagnostic(code(fern::config::invalid_color))]
169    InvalidColor {
170        /// The invalid color value.
171        value: String,
172        /// Source span for highlighting.
173        #[label("this color value is not valid hex")]
174        span: Option<SourceSpan>,
175        /// Location in config file.
176        #[source_code]
177        source_code: Option<String>,
178    },
179
180    /// Value is outside the valid range.
181    ///
182    /// Numeric values must fall within specified bounds. This error indicates
183    /// the value is too large or too small.
184    #[error("{key} must be between {min} and {max}, got {value}")]
185    #[diagnostic(code(fern::config::out_of_range))]
186    OutOfRange {
187        /// The configuration key.
188        key: String,
189        /// The invalid value.
190        value: i64,
191        /// Minimum allowed value.
192        min: i64,
193        /// Maximum allowed value.
194        max: i64,
195        /// Source span for highlighting.
196        #[label("value out of range")]
197        span: Option<SourceSpan>,
198        /// Location in config file.
199        #[source_code]
200        source_code: Option<String>,
201    },
202
203    /// Unknown configuration key.
204    ///
205    /// The configuration contains a key that is not recognized. This is a
206    /// **warning**, not an error — the configuration will still load, but
207    /// the unknown key will be ignored.
208    ///
209    /// # Common Causes
210    ///
211    /// - Typo in key name
212    /// - Using a key from a different version
213    /// - Copy-pasting from incompatible configuration
214    #[error("unknown configuration key: {key}")]
215    #[diagnostic(code(fern::config::unknown_key))]
216    UnknownKey {
217        /// The unrecognized key.
218        key: String,
219        /// Similar valid keys (for "did you mean?" suggestions).
220        similar: Vec<String>,
221        /// Source span for highlighting.
222        #[label("unrecognized key")]
223        span: Option<SourceSpan>,
224        /// Location in config file.
225        #[source_code]
226        source_code: Option<String>,
227    },
228
229    /// Required field is missing.
230    ///
231    /// A required configuration field was not provided and has no default
232    /// value.
233    #[error("missing required field: {key}")]
234    #[diagnostic(code(fern::config::missing_field))]
235    MissingField {
236        /// The missing key.
237        key: String,
238        /// Expected type description.
239        expected_type: String,
240    },
241
242    /// Type mismatch in configuration value.
243    ///
244    /// The value has the wrong type. For example, a string was provided
245    /// where a number was expected.
246    #[error("type mismatch for {key}: expected {expected}, got {actual}")]
247    #[diagnostic(code(fern::config::type_mismatch))]
248    TypeMismatch {
249        /// The configuration key.
250        key: String,
251        /// Expected type name.
252        expected: String,
253        /// Actual type name.
254        actual: String,
255        /// Source span for highlighting.
256        #[label("wrong type")]
257        span: Option<SourceSpan>,
258        /// Location in config file.
259        #[source_code]
260        source_code: Option<String>,
261    },
262
263    /// TOML syntax error.
264    ///
265    /// The configuration file is not valid TOML. This is a **fatal** error
266    /// because no configuration can be loaded.
267    #[error("TOML syntax error")]
268    #[diagnostic(code(fern::config::parse_error))]
269    ParseError {
270        /// The underlying TOML parse error.
271        #[source]
272        source: toml::de::Error,
273        /// The source file content for error display.
274        #[source_code]
275        src: String,
276    },
277
278    /// Invalid theme name.
279    ///
280    /// The theme must be one of: "dark", "light", or "auto".
281    #[error("invalid theme: {value}")]
282    #[diagnostic(code(fern::config::invalid_theme))]
283    InvalidTheme {
284        /// The invalid theme value.
285        value: String,
286        /// Source span for highlighting.
287        #[label("invalid theme")]
288        span: Option<SourceSpan>,
289        /// Location in config file.
290        #[source_code]
291        source_code: Option<String>,
292    },
293
294    /// Invalid bar position.
295    ///
296    /// The bar position must be "top" or "bottom".
297    #[error("invalid bar position: {value}")]
298    #[diagnostic(code(fern::config::invalid_position))]
299    InvalidPosition {
300        /// The invalid position value.
301        value: String,
302        /// Source span for highlighting.
303        #[label("invalid position")]
304        span: Option<SourceSpan>,
305        /// Location in config file.
306        #[source_code]
307        source_code: Option<String>,
308    },
309
310    /// Deprecated configuration key.
311    ///
312    /// This key still works but will be removed in a future version.
313    /// This is a **warning**.
314    #[error("deprecated configuration key: {key}")]
315    #[diagnostic(code(fern::config::deprecated))]
316    DeprecatedKey {
317        /// The deprecated key.
318        key: String,
319        /// The replacement key to use.
320        replacement: String,
321        /// Version when this key will be removed.
322        removed_in: String,
323        /// Source span for highlighting.
324        #[label("deprecated")]
325        span: Option<SourceSpan>,
326        /// Location in config file.
327        #[source_code]
328        source_code: Option<String>,
329    },
330
331    /// Invalid font family.
332    ///
333    /// The specified font is not available on the system.
334    #[error("font not found: {family}")]
335    #[diagnostic(code(fern::config::font_not_found))]
336    FontNotFound {
337        /// The font family that was not found.
338        family: String,
339    },
340}
341
342impl ConfigError {
343    /// Returns the severity level of this error.
344    ///
345    /// Most config errors are [`Severity::Error`], but some are warnings.
346    #[must_use]
347    pub fn severity(&self) -> Severity {
348        match self {
349            Self::UnknownKey { .. } | Self::DeprecatedKey { .. } => Severity::Warning,
350            Self::ParseError { .. } => Severity::Fatal,
351            _ => Severity::Error,
352        }
353    }
354
355    /// Returns the error code for documentation lookup.
356    #[must_use]
357    pub fn code(&self) -> &'static str {
358        match self {
359            Self::InvalidColor { .. } => "fern::config::invalid_color",
360            Self::OutOfRange { .. } => "fern::config::out_of_range",
361            Self::UnknownKey { .. } => "fern::config::unknown_key",
362            Self::MissingField { .. } => "fern::config::missing_field",
363            Self::TypeMismatch { .. } => "fern::config::type_mismatch",
364            Self::ParseError { .. } => "fern::config::parse_error",
365            Self::InvalidTheme { .. } => "fern::config::invalid_theme",
366            Self::InvalidPosition { .. } => "fern::config::invalid_position",
367            Self::DeprecatedKey { .. } => "fern::config::deprecated",
368            Self::FontNotFound { .. } => "fern::config::font_not_found",
369        }
370    }
371
372    /// Returns a short title for notification display.
373    #[must_use]
374    pub fn title(&self) -> String {
375        match self {
376            Self::InvalidColor { .. } => "Invalid Color".to_string(),
377            Self::OutOfRange { key, .. } => format!("Invalid {key}"),
378            Self::UnknownKey { key, .. } => format!("Unknown Key: {key}"),
379            Self::MissingField { key, .. } => format!("Missing: {key}"),
380            Self::TypeMismatch { key, .. } => format!("Wrong Type: {key}"),
381            Self::ParseError { .. } => "Config Parse Error".to_string(),
382            Self::InvalidTheme { .. } => "Invalid Theme".to_string(),
383            Self::InvalidPosition { .. } => "Invalid Position".to_string(),
384            Self::DeprecatedKey { key, .. } => format!("Deprecated: {key}"),
385            Self::FontNotFound { family, .. } => format!("Font Not Found: {family}"),
386        }
387    }
388}
389
390impl Notifiable for ConfigError {
391    fn severity(&self) -> Severity {
392        ConfigError::severity(self)
393    }
394
395    fn title(&self) -> String {
396        ConfigError::title(self)
397    }
398
399    fn body(&self) -> String {
400        self.to_string()
401    }
402
403    fn suggestion(&self) -> Option<String> {
404        match self {
405            Self::InvalidColor { .. } => {
406                Some("Use hex format: #RRGGBB or #RRGGBBAA".to_string())
407            }
408            Self::OutOfRange { min, max, .. } => {
409                Some(format!("Value must be between {min} and {max}"))
410            }
411            Self::UnknownKey { similar, .. } if !similar.is_empty() => {
412                Some(format!("Did you mean: {}?", similar.join(", ")))
413            }
414            Self::MissingField { expected_type, .. } => {
415                Some(format!("Expected type: {expected_type}"))
416            }
417            Self::TypeMismatch { expected, .. } => {
418                Some(format!("Change the value to be a {expected}"))
419            }
420            Self::InvalidTheme { .. } => {
421                Some("Theme must be one of: dark, light, auto".to_string())
422            }
423            Self::InvalidPosition { .. } => {
424                Some("Position must be one of: top, bottom".to_string())
425            }
426            Self::DeprecatedKey { replacement, removed_in, .. } => {
427                Some(format!("Use `{replacement}` instead (removing in {removed_in})"))
428            }
429            Self::FontNotFound { .. } => {
430                Some("Install the font or use a different family".to_string())
431            }
432            _ => None,
433        }
434    }
435
436    fn code(&self) -> Option<&'static str> {
437        Some(ConfigError::code(self))
438    }
439}
440
441#[cfg(test)]
442mod tests {
443    use super::*;
444
445    #[test]
446    fn invalid_color_has_correct_severity() {
447        let err = ConfigError::InvalidColor {
448            value: "#gg0000".to_string(),
449            span: None,
450            source_code: None,
451        };
452        assert_eq!(err.severity(), Severity::Error);
453    }
454
455    #[test]
456    fn unknown_key_is_warning() {
457        let err = ConfigError::UnknownKey {
458            key: "colour".to_string(),
459            similar: vec!["color".to_string()],
460            span: None,
461            source_code: None,
462        };
463        assert_eq!(err.severity(), Severity::Warning);
464    }
465
466    #[test]
467    fn parse_error_is_fatal() {
468        let toml_err = toml::from_str::<toml::Value>("invalid toml [[[")
469            .expect_err("should fail");
470        let err = ConfigError::ParseError {
471            source: toml_err,
472            src: "invalid toml [[[".to_string(),
473        };
474        assert_eq!(err.severity(), Severity::Fatal);
475    }
476
477    #[test]
478    fn notifiable_suggestion() {
479        let err = ConfigError::UnknownKey {
480            key: "colour".to_string(),
481            similar: vec!["color".to_string()],
482            span: None,
483            source_code: None,
484        };
485        assert_eq!(err.suggestion(), Some("Did you mean: color?".to_string()));
486    }
487}