use std::path::PathBuf;
use sapphire_bridge_api::ConfigFieldError;
use sapphire_bridge_api::settings::Scope;
use crate::owner::FieldError;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("unknown setting `{0}`")]
UnknownKey(String),
#[error(
"`{key}` cannot be set in the {scope} scope (allowed: {})",
scope_list(allowed)
)]
ScopeNotAllowed {
key: String,
scope: Scope,
allowed: Vec<Scope>,
},
#[error("invalid value for `{key}`: {message}")]
InvalidValue {
key: String,
message: String,
},
#[error("`{0}` is a secret; give it with --stdin or a prompt, not on the command line")]
SecretOnCommandLine(String),
#[error("setting `{0}` is defined by more than one owner")]
Duplicate(String),
#[error("setting `{key}` uses the name `{name}`, which is reserved for another owner")]
Reserved {
key: String,
name: String,
},
#[error("setting `{key}` is defined wrongly: {message}")]
InvalidDef {
key: String,
message: String,
},
#[error("cannot read {}: {message}", file.display())]
Unparsable {
file: PathBuf,
message: String,
},
#[error("settings rejected: {}", rejected(.0))]
Rejected(Vec<FieldError>),
#[error(transparent)]
Io(#[from] std::io::Error),
}
impl Error {
pub fn field_errors(&self) -> Vec<ConfigFieldError> {
let one = |key: &String, message: String| {
vec![ConfigFieldError {
key: key.clone(),
message,
}]
};
match self {
Self::UnknownKey(key) => one(key, "unknown setting".to_owned()),
Self::ScopeNotAllowed {
key,
scope,
allowed,
} => one(
key,
format!(
"cannot be set in the {scope} scope (allowed: {})",
scope_list(allowed)
),
),
Self::InvalidValue { key, message } => one(key, message.clone()),
Self::SecretOnCommandLine(key) => one(
key,
"is a secret; give it with --stdin or a prompt, not on the command line".to_owned(),
),
Self::Rejected(errors) => errors
.iter()
.filter_map(|e| {
Some(ConfigFieldError {
key: e.key.clone()?,
message: e.message.clone(),
})
})
.collect(),
_ => Vec::new(),
}
}
}
fn scope_list(scopes: &[Scope]) -> String {
scopes
.iter()
.map(Scope::to_string)
.collect::<Vec<_>>()
.join(", ")
}
fn rejected(errors: &[FieldError]) -> String {
errors
.iter()
.map(FieldError::to_string)
.collect::<Vec<_>>()
.join("; ")
}
pub fn describe_toml_error(
text: &str,
span: Option<std::ops::Range<usize>>,
message: &str,
) -> String {
let message = without_found_value(message.trim());
let message = message.as_str();
let Some(span) = span else {
return message.to_owned();
};
let before = &text[..span.start.min(text.len())];
let line = before.matches('\n').count() + 1;
let column = before.rsplit('\n').next().unwrap_or("").chars().count() + 1;
format!("line {line}, column {column}: {message}")
}
fn without_found_value(message: &str) -> String {
for (prefix, kept) in [
("invalid type: ", "invalid type"),
("invalid value: ", "invalid value"),
("unknown variant ", "unknown variant"),
] {
if let Some(at) = message
.strip_prefix(prefix)
.and_then(|rest| rest.rfind(", expected "))
{
return format!("{kept}{}", &message[prefix.len() + at..]);
}
}
message.to_owned()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn field_errors_name_the_keys() {
let key = || "net.discovery".to_owned();
let keyed = |e: Error| {
e.field_errors()
.into_iter()
.map(|f| f.key)
.collect::<Vec<_>>()
};
let expect = vec![key()];
assert_eq!(keyed(Error::UnknownKey(key())), expect);
assert_eq!(
keyed(Error::ScopeNotAllowed {
key: key(),
scope: Scope::Workspace,
allowed: vec![Scope::Device],
}),
expect
);
assert_eq!(
keyed(Error::InvalidValue {
key: key(),
message: "expected a bool".into()
}),
expect
);
assert_eq!(keyed(Error::SecretOnCommandLine(key())), expect);
let rejected = Error::Rejected(vec![
FieldError {
key: Some(key()),
file: None,
message: "no".into(),
},
FieldError {
key: None,
file: None,
message: "unkeyed".into(),
},
]);
assert_eq!(keyed(rejected), expect);
assert!(
Error::Io(std::io::Error::other("x"))
.field_errors()
.is_empty()
);
}
#[test]
fn a_toml_error_names_the_place_not_the_text() {
let text = "a = 1\ntoken = \"hunter2\" x\n";
let err = text.parse::<toml::Table>().unwrap_err();
let described = describe_toml_error(text, err.span(), err.message());
assert!(described.starts_with("line 2, column "), "{described}");
assert!(!described.contains("hunter2"), "{described}");
let err = text.parse::<toml_edit::DocumentMut>().unwrap_err();
let described = describe_toml_error(text, err.span(), err.message());
assert!(described.starts_with("line 2, column "), "{described}");
assert!(!described.contains("hunter2"), "{described}");
}
#[test]
fn a_type_error_does_not_quote_the_value_it_found() {
#[derive(Debug, serde::Deserialize)]
#[allow(dead_code)]
struct Typed {
list: Option<Vec<String>>,
flag: Option<bool>,
choice: Option<Choice>,
}
#[derive(Debug, serde::Deserialize)]
enum Choice {
A,
}
for text in [
"list = \"hunter2\"\n",
"flag = \"hunter2, expected x\"\n",
"choice = \"hunter2\"\n",
] {
let err = toml::from_str::<Typed>(text).unwrap_err();
let described = describe_toml_error(text, err.span(), err.message());
assert!(described.starts_with("line 1, column "), "{described}");
assert!(described.contains("expected"), "{described}");
assert!(!described.contains("hunter2"), "{described}");
}
}
}