Skip to main content

sapphire_framework_settings/
error.rs

1//! Errors of the settings registry.
2
3use std::path::PathBuf;
4
5use sapphire_bridge_api::ConfigFieldError;
6use sapphire_bridge_api::settings::Scope;
7
8use crate::owner::FieldError;
9
10/// Result alias for this crate.
11pub type Result<T> = std::result::Result<T, Error>;
12
13/// Why a settings operation failed.
14#[derive(Debug, thiserror::Error)]
15pub enum Error {
16    /// No setting has this key.
17    #[error("unknown setting `{0}`")]
18    UnknownKey(String),
19    /// The key exists but may not be set in this scope.
20    #[error(
21        "`{key}` cannot be set in the {scope} scope (allowed: {})",
22        scope_list(allowed)
23    )]
24    ScopeNotAllowed {
25        /// The key.
26        key: String,
27        /// The scope that was asked for.
28        scope: Scope,
29        /// The scopes the key accepts.
30        allowed: Vec<Scope>,
31    },
32    /// The value does not fit the key's kind.
33    #[error("invalid value for `{key}`: {message}")]
34    InvalidValue {
35        /// The key.
36        key: String,
37        /// What is wrong with the value.
38        message: String,
39    },
40    /// A secret was given as text on the command line.
41    #[error("`{0}` is a secret; give it with --stdin or a prompt, not on the command line")]
42    SecretOnCommandLine(String),
43    /// Two owners define the same key.
44    #[error("setting `{0}` is defined by more than one owner")]
45    Duplicate(String),
46    /// A key uses a top-level name reserved for another owner.
47    #[error("setting `{key}` uses the name `{name}`, which is reserved for another owner")]
48    Reserved {
49        /// The offending key.
50        key: String,
51        /// The reserved top-level name.
52        name: String,
53    },
54    /// A definition breaks the registry's rules: it names no scope, or it is a secret
55    /// outside the device scope.
56    #[error("setting `{key}` is defined wrongly: {message}")]
57    InvalidDef {
58        /// The offending key.
59        key: String,
60        /// Which rule it breaks.
61        message: String,
62    },
63    /// A settings file is not valid TOML, or holds a value of an unsupported type.
64    #[error("cannot read {}: {message}", file.display())]
65    Unparsable {
66        /// The file.
67        file: PathBuf,
68        /// What is wrong with it.
69        message: String,
70    },
71    /// An owner refused the edited settings.
72    #[error("settings rejected: {}", rejected(.0))]
73    Rejected(Vec<FieldError>),
74    /// A filesystem error.
75    #[error(transparent)]
76    Io(#[from] std::io::Error),
77}
78
79impl Error {
80    /// The keys this error names, for a client to show under each field; empty when it
81    /// names none. The messages never hold a value.
82    pub fn field_errors(&self) -> Vec<ConfigFieldError> {
83        let one = |key: &String, message: String| {
84            vec![ConfigFieldError {
85                key: key.clone(),
86                message,
87            }]
88        };
89        match self {
90            Self::UnknownKey(key) => one(key, "unknown setting".to_owned()),
91            Self::ScopeNotAllowed {
92                key,
93                scope,
94                allowed,
95            } => one(
96                key,
97                format!(
98                    "cannot be set in the {scope} scope (allowed: {})",
99                    scope_list(allowed)
100                ),
101            ),
102            Self::InvalidValue { key, message } => one(key, message.clone()),
103            Self::SecretOnCommandLine(key) => one(
104                key,
105                "is a secret; give it with --stdin or a prompt, not on the command line".to_owned(),
106            ),
107            Self::Rejected(errors) => errors
108                .iter()
109                .filter_map(|e| {
110                    Some(ConfigFieldError {
111                        key: e.key.clone()?,
112                        message: e.message.clone(),
113                    })
114                })
115                .collect(),
116            _ => Vec::new(),
117        }
118    }
119}
120
121fn scope_list(scopes: &[Scope]) -> String {
122    scopes
123        .iter()
124        .map(Scope::to_string)
125        .collect::<Vec<_>>()
126        .join(", ")
127}
128
129fn rejected(errors: &[FieldError]) -> String {
130    errors
131        .iter()
132        .map(FieldError::to_string)
133        .collect::<Vec<_>>()
134        .join("; ")
135}
136
137/// A TOML parse error of `text` as the line and column it is at and what is wrong, never
138/// the text itself: a settings file may hold an application's tokens beside the settings.
139/// `span` and `message` are the error's own (`toml::de::Error`, `toml_edit::TomlError`).
140pub fn describe_toml_error(
141    text: &str,
142    span: Option<std::ops::Range<usize>>,
143    message: &str,
144) -> String {
145    let message = without_found_value(message.trim());
146    let message = message.as_str();
147    let Some(span) = span else {
148        return message.to_owned();
149    };
150    let before = &text[..span.start.min(text.len())];
151    let line = before.matches('\n').count() + 1;
152    let column = before.rsplit('\n').next().unwrap_or("").chars().count() + 1;
153    format!("line {line}, column {column}: {message}")
154}
155
156/// `message` without what serde found when it was not what it expected: a typed parse's
157/// `invalid type: string "…", expected …` quotes the value, so keep only the expectation.
158fn without_found_value(message: &str) -> String {
159    for (prefix, kept) in [
160        ("invalid type: ", "invalid type"),
161        ("invalid value: ", "invalid value"),
162        ("unknown variant ", "unknown variant"),
163    ] {
164        // The last one: the found value may itself hold ", expected ".
165        if let Some(at) = message
166            .strip_prefix(prefix)
167            .and_then(|rest| rest.rfind(", expected "))
168        {
169            return format!("{kept}{}", &message[prefix.len() + at..]);
170        }
171    }
172    message.to_owned()
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178
179    #[test]
180    fn field_errors_name_the_keys() {
181        let key = || "net.discovery".to_owned();
182        let keyed = |e: Error| {
183            e.field_errors()
184                .into_iter()
185                .map(|f| f.key)
186                .collect::<Vec<_>>()
187        };
188        let expect = vec![key()];
189        assert_eq!(keyed(Error::UnknownKey(key())), expect);
190        assert_eq!(
191            keyed(Error::ScopeNotAllowed {
192                key: key(),
193                scope: Scope::Workspace,
194                allowed: vec![Scope::Device],
195            }),
196            expect
197        );
198        assert_eq!(
199            keyed(Error::InvalidValue {
200                key: key(),
201                message: "expected a bool".into()
202            }),
203            expect
204        );
205        assert_eq!(keyed(Error::SecretOnCommandLine(key())), expect);
206        let rejected = Error::Rejected(vec![
207            FieldError {
208                key: Some(key()),
209                file: None,
210                message: "no".into(),
211            },
212            FieldError {
213                key: None,
214                file: None,
215                message: "unkeyed".into(),
216            },
217        ]);
218        assert_eq!(keyed(rejected), expect);
219        assert!(
220            Error::Io(std::io::Error::other("x"))
221                .field_errors()
222                .is_empty()
223        );
224    }
225
226    #[test]
227    fn a_toml_error_names_the_place_not_the_text() {
228        let text = "a = 1\ntoken = \"hunter2\" x\n";
229        let err = text.parse::<toml::Table>().unwrap_err();
230        let described = describe_toml_error(text, err.span(), err.message());
231        assert!(described.starts_with("line 2, column "), "{described}");
232        assert!(!described.contains("hunter2"), "{described}");
233        let err = text.parse::<toml_edit::DocumentMut>().unwrap_err();
234        let described = describe_toml_error(text, err.span(), err.message());
235        assert!(described.starts_with("line 2, column "), "{described}");
236        assert!(!described.contains("hunter2"), "{described}");
237    }
238
239    #[test]
240    fn a_type_error_does_not_quote_the_value_it_found() {
241        #[derive(Debug, serde::Deserialize)]
242        #[allow(dead_code)]
243        struct Typed {
244            list: Option<Vec<String>>,
245            flag: Option<bool>,
246            choice: Option<Choice>,
247        }
248        #[derive(Debug, serde::Deserialize)]
249        enum Choice {
250            A,
251        }
252        for text in [
253            "list = \"hunter2\"\n",
254            "flag = \"hunter2, expected x\"\n",
255            "choice = \"hunter2\"\n",
256        ] {
257            let err = toml::from_str::<Typed>(text).unwrap_err();
258            let described = describe_toml_error(text, err.span(), err.message());
259            assert!(described.starts_with("line 1, column "), "{described}");
260            assert!(described.contains("expected"), "{described}");
261            assert!(!described.contains("hunter2"), "{described}");
262        }
263    }
264}