Skip to main content

mads_core/configuration/
error.rs

1//! Ordered, value-free typed configuration failures.
2
3use std::fmt;
4
5use crate::{Diagnostic, Error, MADS020};
6
7/// The result of parsing or validating a typed configuration.
8pub type ConfigurationResult<T> = Result<T, ConfigurationErrors>;
9
10/// A safe failure for one configuration key.
11///
12/// Application-supplied codes, messages, and source labels must not contain
13/// configured values. Built-in parsing never retains rejected values.
14#[derive(Debug)]
15pub struct ConfigurationIssue {
16    key: String,
17    code: String,
18    message: String,
19    source: Option<String>,
20}
21
22impl ConfigurationIssue {
23    /// Creates a failure without inventing source attribution.
24    pub fn new(
25        key: impl Into<String>,
26        code: impl Into<String>,
27        message: impl Into<String>,
28    ) -> Self {
29        Self {
30            key: key.into(),
31            code: code.into(),
32            message: message.into(),
33            source: None,
34        }
35    }
36
37    /// Attaches the winning source label, or `default` for a rejected default.
38    pub fn with_source(mut self, source: impl Into<String>) -> Self {
39        self.source = Some(source.into());
40        self
41    }
42
43    /// Returns the complete dotted key.
44    pub fn key(&self) -> &str {
45        &self.key
46    }
47
48    /// Returns the stable reason code.
49    pub fn code(&self) -> &str {
50        &self.code
51    }
52
53    /// Returns the safe explanation.
54    pub fn message(&self) -> &str {
55        &self.message
56    }
57
58    /// Returns source attribution when a value or default supplied it.
59    pub fn source(&self) -> Option<&str> {
60        self.source.as_deref()
61    }
62}
63
64/// One or more typed configuration failures in declaration order.
65///
66/// Conversion to the framework error preserves every issue as an ordered
67/// `MADS020` diagnostic without attaching arbitrary parser errors.
68#[derive(Debug)]
69pub struct ConfigurationErrors {
70    // The public constructors and mutation methods preserve non-emptiness.
71    issues: Vec<ConfigurationIssue>,
72}
73
74impl ConfigurationErrors {
75    /// Creates an ordered collection containing one issue.
76    pub fn from_issue(issue: ConfigurationIssue) -> Self {
77        Self {
78            issues: vec![issue],
79        }
80    }
81
82    /// Appends one issue.
83    pub fn push(&mut self, issue: ConfigurationIssue) {
84        self.issues.push(issue);
85    }
86
87    /// Appends another collection, preserving both collections' order.
88    pub fn extend(&mut self, other: Self) {
89        self.issues.extend(other.issues);
90    }
91
92    /// Returns the failures in declaration order.
93    pub fn issues(&self) -> &[ConfigurationIssue] {
94        &self.issues
95    }
96
97    pub(super) fn prefix(&mut self, prefix: &str) {
98        if prefix.is_empty() {
99            return;
100        }
101        for issue in &mut self.issues {
102            issue.key = if issue.key.is_empty() {
103                prefix.to_owned()
104            } else {
105                format!("{prefix}.{}", issue.key)
106            };
107        }
108    }
109}
110
111impl fmt::Display for ConfigurationErrors {
112    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
113        for (index, issue) in self.issues.iter().enumerate() {
114            if index > 0 {
115                formatter.write_str("\n")?;
116            }
117            write!(
118                formatter,
119                "{} [{}]: {}",
120                issue.key, issue.code, issue.message
121            )?;
122            if let Some(source) = &issue.source {
123                write!(formatter, " (source: {source})")?;
124            }
125        }
126        Ok(())
127    }
128}
129
130impl std::error::Error for ConfigurationErrors {}
131
132impl From<ConfigurationErrors> for Error {
133    fn from(errors: ConfigurationErrors) -> Self {
134        let mut diagnostics = errors.issues.into_iter().map(|issue| {
135            let mut message = format!("[{}]: {}", issue.code, issue.message);
136            if let Some(source) = issue.source {
137                message.push_str(&format!(" (source: {source})"));
138            }
139            Diagnostic::new(MADS020, "typed configuration is invalid", message)
140                .with_subject(issue.key)
141        });
142        let primary = diagnostics
143            .next()
144            .expect("configuration errors are non-empty");
145        Self::from_diagnostics(primary, diagnostics)
146    }
147}