Skip to main content

rushls_common/config/
example.rs

1//! Reads an annotated example configuration, commented settings included.
2//!
3//! An application ships one example that documents every TOML setting, with
4//! optional ones commented out. Its tests use this to check that the example
5//! names every schema option and that every documented value, active or
6//! commented, still parses — so the file an operator copies cannot drift from
7//! the binary that reads it.
8
9use thiserror::Error;
10
11#[derive(Debug, Error)]
12pub enum ExampleError {
13    #[error("unfinished table header: {0}")]
14    Header(String),
15    #[error("example line {line:?} is not TOML: {source}")]
16    Toml {
17        line: String,
18        source: toml::de::Error,
19    },
20    #[error("example path {0} passes through a scalar")]
21    Scalar(String),
22}
23
24/// Every setting the example mentions, merged into one document.
25pub struct AnnotatedExample {
26    /// Active and commented settings together. Alternatives for one key
27    /// overwrite each other, so this proves presence, not one valid file.
28    pub document: toml::Table,
29    /// Each documented `(path, value)`, in file order, to parse one at a time.
30    pub examples: Vec<(String, toml::Value)>,
31}
32
33impl AnnotatedExample {
34    /// A line is a setting when, after an optional `#`, it starts with a bare
35    /// key and `=`; prose that merely contains `=` is skipped.
36    pub fn parse(text: &str) -> Result<Self, ExampleError> {
37        let mut example = Self {
38            document: toml::Table::new(),
39            examples: Vec::new(),
40        };
41        let mut section = "";
42        for line in text.lines() {
43            let line = line.trim().strip_prefix('#').unwrap_or(line).trim();
44            if let Some(header) = line.strip_prefix('[') {
45                section = header
46                    .split_once(']')
47                    .ok_or_else(|| ExampleError::Header(line.to_owned()))?
48                    .0;
49                continue;
50            }
51            let Some((key, _)) = line.split_once('=') else {
52                continue;
53            };
54            let key = key.trim();
55            if key.is_empty() || !key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
56                continue;
57            }
58            let fields: toml::Table =
59                toml::from_str(line).map_err(|source| ExampleError::Toml {
60                    line: line.to_owned(),
61                    source,
62                })?;
63            for (key, value) in fields {
64                let path = if section.is_empty() {
65                    key
66                } else {
67                    format!("{section}.{key}")
68                };
69                set(&mut example.document, &path, value.clone())?;
70                example.examples.push((path, value));
71            }
72        }
73        Ok(example)
74    }
75}
76
77/// Inserts `value` at a dotted `path`, creating intermediate tables.
78pub fn set(document: &mut toml::Table, path: &str, value: toml::Value) -> Result<(), ExampleError> {
79    let mut table = document;
80    let mut parts = path.split('.').peekable();
81    while let Some(part) = parts.next() {
82        if parts.peek().is_none() {
83            table.insert(part.to_owned(), value);
84            return Ok(());
85        }
86        table = table
87            .entry(part)
88            .or_insert_with(|| toml::Value::Table(toml::Table::new()))
89            .as_table_mut()
90            .ok_or_else(|| ExampleError::Scalar(path.to_owned()))?;
91    }
92    Ok(())
93}
94
95/// Whether a dotted `path` exists in `document`.
96pub fn contains(document: &toml::Table, path: &str) -> bool {
97    let mut parts = path.split('.');
98    let Some(first) = parts.next() else {
99        return false;
100    };
101    let mut value = document.get(first);
102    for part in parts {
103        value = value.and_then(|value| value.get(part));
104    }
105    value.is_some()
106}