use core::fmt;
use serde::de::DeserializeOwned;
#[cfg(feature = "schema")]
use shep_core::config::DogTable;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SectionError {
section: String,
line: Option<usize>,
}
impl SectionError {
#[must_use]
pub fn section(&self) -> &str {
&self.section
}
#[must_use]
pub fn line(&self) -> Option<usize> {
self.line
}
#[must_use]
pub const fn exit_code(&self) -> u8 {
shep_core::exit::INVALID_CONFIG
}
}
impl fmt::Display for SectionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self { section, line } = self;
match line {
Some(line) => write!(
f,
"line {line} under [{section}] in dogs.toml does not fit this dog's settings"
),
None => write!(
f,
"[{section}] in dogs.toml does not fit this dog's settings"
),
}
}
}
impl core::error::Error for SectionError {}
pub fn parse_section<T>(section: &str, text: &str) -> Result<T, SectionError>
where
T: DeserializeOwned + Default,
{
if text.is_empty() {
return Ok(T::default());
}
toml::from_str(text).map_err(|err| refusal(section, text, &err))
}
#[cfg(feature = "schema")]
pub(super) fn section_table(section: &str, text: &str) -> Result<DogTable, SectionError> {
if text.is_empty() {
return Ok(DogTable::from(serde_json::Map::new()));
}
toml::from_str(text).map_err(|err| refusal(section, text, &err))
}
fn refusal(section: &str, text: &str, err: &toml::de::Error) -> SectionError {
SectionError {
section: section.to_owned(),
line: err
.span()
.map(|span| text[..span.start.min(text.len())].matches('\n').count() + 1),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug, Default, serde::Deserialize, PartialEq)]
#[serde(deny_unknown_fields, default)]
struct Settings {
port: u16,
webhook: String,
}
#[test]
fn an_empty_section_parses_to_the_defaults_even_with_a_required_field() {
#[derive(Debug, Default, serde::Deserialize, PartialEq)]
struct Required {
port: u16,
}
assert!(
toml::from_str::<Required>("").is_err(),
"the fixture must refuse an empty document, or this proves nothing"
);
assert_eq!(
parse_section::<Required>("metrics", "").unwrap(),
Required::default()
);
}
#[test]
fn a_section_that_fits_parses() {
let parsed = parse_section::<Settings>("bark", "port = 9000\n").unwrap();
assert_eq!(parsed.port, 9000);
}
#[test]
fn a_refusal_names_the_line_and_never_the_value() {
let secret = "https://hooks.example.com/services/T00/B00/super-secret-token";
let refused = [
(format!("webhook = \"{secret}\"\nport = \"{secret}\"\n"), 2),
(format!("port = 1\n\n{secret} = 1\n"), 3),
(format!("webhook = [\"{secret}\"]\n"), 1),
];
for (text, line) in refused {
let err = parse_section::<Settings>("bark", &text).unwrap_err();
assert_eq!(err.line(), Some(line), "{text}");
for shown in [err.to_string(), format!("{err:?}")] {
assert!(!shown.contains("super-secret-token"), "{shown}");
}
}
}
#[test]
fn the_message_names_the_line_and_the_section() {
let err = parse_section::<Settings>("metrics", "port = \"x\"\n").unwrap_err();
assert_eq!(
err.to_string(),
"line 1 under [metrics] in dogs.toml does not fit this dog's settings"
);
assert_eq!(err.exit_code(), shep_core::exit::INVALID_CONFIG);
}
}