mads_core/configuration/
error.rs1use std::fmt;
4
5use crate::{Diagnostic, Error, MADS020};
6
7pub type ConfigurationResult<T> = Result<T, ConfigurationErrors>;
9
10#[derive(Debug)]
15pub struct ConfigurationIssue {
16 key: String,
17 code: String,
18 message: String,
19 source: Option<String>,
20}
21
22impl ConfigurationIssue {
23 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 pub fn with_source(mut self, source: impl Into<String>) -> Self {
39 self.source = Some(source.into());
40 self
41 }
42
43 pub fn key(&self) -> &str {
45 &self.key
46 }
47
48 pub fn code(&self) -> &str {
50 &self.code
51 }
52
53 pub fn message(&self) -> &str {
55 &self.message
56 }
57
58 pub fn source(&self) -> Option<&str> {
60 self.source.as_deref()
61 }
62}
63
64#[derive(Debug)]
69pub struct ConfigurationErrors {
70 issues: Vec<ConfigurationIssue>,
72}
73
74impl ConfigurationErrors {
75 pub fn from_issue(issue: ConfigurationIssue) -> Self {
77 Self {
78 issues: vec![issue],
79 }
80 }
81
82 pub fn push(&mut self, issue: ConfigurationIssue) {
84 self.issues.push(issue);
85 }
86
87 pub fn extend(&mut self, other: Self) {
89 self.issues.extend(other.issues);
90 }
91
92 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}