sapphire_framework_settings/
error.rs1use std::path::PathBuf;
4
5use sapphire_bridge_api::ConfigFieldError;
6use sapphire_bridge_api::settings::Scope;
7
8use crate::owner::FieldError;
9
10pub type Result<T> = std::result::Result<T, Error>;
12
13#[derive(Debug, thiserror::Error)]
15pub enum Error {
16 #[error("unknown setting `{0}`")]
18 UnknownKey(String),
19 #[error(
21 "`{key}` cannot be set in the {scope} scope (allowed: {})",
22 scope_list(allowed)
23 )]
24 ScopeNotAllowed {
25 key: String,
27 scope: Scope,
29 allowed: Vec<Scope>,
31 },
32 #[error("invalid value for `{key}`: {message}")]
34 InvalidValue {
35 key: String,
37 message: String,
39 },
40 #[error("`{0}` is a secret; give it with --stdin or a prompt, not on the command line")]
42 SecretOnCommandLine(String),
43 #[error("setting `{0}` is defined by more than one owner")]
45 Duplicate(String),
46 #[error("setting `{key}` uses the name `{name}`, which is reserved for another owner")]
48 Reserved {
49 key: String,
51 name: String,
53 },
54 #[error("setting `{key}` is defined wrongly: {message}")]
57 InvalidDef {
58 key: String,
60 message: String,
62 },
63 #[error("cannot read {}: {message}", file.display())]
65 Unparsable {
66 file: PathBuf,
68 message: String,
70 },
71 #[error("settings rejected: {}", rejected(.0))]
73 Rejected(Vec<FieldError>),
74 #[error(transparent)]
76 Io(#[from] std::io::Error),
77}
78
79impl Error {
80 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
137pub 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
156fn 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 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}