Skip to main content

cornerstone/
config.rs

1//! Configuration loading with a clear precedence chain:
2//! **flag > environment > config file > default**.
3//!
4//! Zero dependencies, so the file parsers deliberately support a *practical
5//! subset* of each format — flat and one-level-nested key/value pairs, which is
6//! what CLI config almost always is. If a tool needs full spec compliance it can
7//! parse the file itself and feed values in via [`Config::set`].
8//!
9//! Supported inputs:
10//! * INI / conf: `key = value`, `[section]` headers → `section.key`.
11//! * TOML subset: same as INI plus `#` comments and quoted strings.
12//! * JSON subset: flat object of string/number/bool values, and one level of
13//!   nested objects flattened to `parent.child`.
14
15use crate::error::{Error, Result};
16use std::collections::BTreeMap;
17
18/// A resolved configuration: a flat map of dotted keys to string values, plus
19/// the precedence machinery to overlay env and flags.
20#[derive(Debug, Default, Clone)]
21pub struct Config {
22    values: BTreeMap<String, String>,
23    env_prefix: Option<String>,
24}
25
26impl Config {
27    pub fn new() -> Self {
28        Config::default()
29    }
30
31    /// Set an environment-variable prefix used by [`Config::get`] to overlay
32    /// env values. With prefix `MYTOOL`, key `port` reads `MYTOOL_PORT`.
33    pub fn env_prefix<S: Into<String>>(mut self, prefix: S) -> Self {
34        self.env_prefix = Some(prefix.into());
35        self
36    }
37
38    /// Directly set a value (lowest-effort source, e.g. a default).
39    pub fn set<K: Into<String>, V: Into<String>>(&mut self, key: K, value: V) -> &mut Self {
40        self.values.insert(key.into(), value.into());
41        self
42    }
43
44    /// Load and merge a config file, autodetecting the format by extension
45    /// (`.toml`, `.ini`/`.conf`, `.json`). Values overwrite existing keys.
46    pub fn load_file(&mut self, path: &str) -> Result<&mut Self> {
47        let text = std::fs::read_to_string(path)
48            .map_err(|e| Error::not_found(format!("cannot read config {}: {}", path, e)))?;
49        let parsed = if path.ends_with(".json") {
50            parse_json(&text)?
51        } else {
52            // TOML-subset and INI share the same parser here.
53            parse_ini(&text)?
54        };
55        for (k, v) in parsed {
56            self.values.insert(k, v);
57        }
58        Ok(self)
59    }
60
61    /// Try to load a file if it exists; missing files are not an error. Handy
62    /// for "load ~/.config/tool.toml if present".
63    pub fn load_file_opt(&mut self, path: &str) -> Result<&mut Self> {
64        if std::path::Path::new(path).exists() {
65            self.load_file(path)?;
66        }
67        Ok(self)
68    }
69
70    /// Resolve a key using precedence: environment (if a prefix is set) wins over
71    /// the loaded file/default values.
72    pub fn get(&self, key: &str) -> Option<String> {
73        if let Some(prefix) = &self.env_prefix {
74            let env_key = format!("{}_{}", prefix, key.replace('.', "_")).to_uppercase();
75            if let Ok(v) = std::env::var(&env_key) {
76                return Some(v);
77            }
78        }
79        self.values.get(key).cloned()
80    }
81
82    /// Resolve with an explicit flag value taking top precedence. Pass the flag
83    /// value the user supplied (or `None`); this returns the first of
84    /// flag → env → file → `default`.
85    pub fn resolve(&self, key: &str, flag: Option<&str>, default: &str) -> String {
86        if let Some(f) = flag {
87            return f.to_string();
88        }
89        self.get(key).unwrap_or_else(|| default.to_string())
90    }
91
92    /// Parse a resolved value into any type.
93    pub fn get_as<T: std::str::FromStr>(&self, key: &str) -> Result<Option<T>> {
94        match self.get(key) {
95            None => Ok(None),
96            Some(v) => v
97                .parse::<T>()
98                .map(Some)
99                .map_err(|_| Error::msg(format!("invalid value for config key '{}': {}", key, v))),
100        }
101    }
102
103    /// All resolved keys (file/default layer only; env is overlaid at `get`).
104    pub fn keys(&self) -> impl Iterator<Item = &String> {
105        self.values.keys()
106    }
107}
108
109/// Parse an INI / TOML-subset document into dotted key/value pairs.
110fn parse_ini(text: &str) -> Result<BTreeMap<String, String>> {
111    let mut out = BTreeMap::new();
112    let mut section = String::new();
113    for (lineno, raw) in text.lines().enumerate() {
114        let line = strip_comment(raw).trim();
115        if line.is_empty() {
116            continue;
117        }
118        if line.starts_with('[') && line.ends_with(']') {
119            section = line[1..line.len() - 1].trim().to_string();
120            continue;
121        }
122        let (k, v) = line
123            .split_once('=')
124            .ok_or_else(|| Error::msg(format!("config parse error on line {}: expected key = value", lineno + 1)))?;
125        let key = k.trim();
126        let val = unquote(v.trim());
127        let full = if section.is_empty() {
128            key.to_string()
129        } else {
130            format!("{}.{}", section, key)
131        };
132        out.insert(full, val);
133    }
134    Ok(out)
135}
136
137/// Parse a JSON-subset object (flat + one level of nesting) into dotted pairs.
138fn parse_json(text: &str) -> Result<BTreeMap<String, String>> {
139    let mut out = BTreeMap::new();
140    let bytes = text.trim().as_bytes();
141    let mut i = 0;
142    skip_ws(bytes, &mut i);
143    expect(bytes, &mut i, b'{')?;
144    loop {
145        skip_ws(bytes, &mut i);
146        if peek(bytes, i) == Some(b'}') {
147            break;
148        }
149        let key = parse_json_string(bytes, &mut i)?;
150        skip_ws(bytes, &mut i);
151        expect(bytes, &mut i, b':')?;
152        skip_ws(bytes, &mut i);
153        match peek(bytes, i) {
154            Some(b'{') => {
155                // One level of nesting: flatten to key.child.
156                i += 1;
157                loop {
158                    skip_ws(bytes, &mut i);
159                    if peek(bytes, i) == Some(b'}') {
160                        i += 1;
161                        break;
162                    }
163                    let ck = parse_json_string(bytes, &mut i)?;
164                    skip_ws(bytes, &mut i);
165                    expect(bytes, &mut i, b':')?;
166                    skip_ws(bytes, &mut i);
167                    let cv = parse_json_scalar(bytes, &mut i)?;
168                    out.insert(format!("{}.{}", key, ck), cv);
169                    skip_ws(bytes, &mut i);
170                    if peek(bytes, i) == Some(b',') {
171                        i += 1;
172                    }
173                }
174            }
175            _ => {
176                let v = parse_json_scalar(bytes, &mut i)?;
177                out.insert(key, v);
178            }
179        }
180        skip_ws(bytes, &mut i);
181        if peek(bytes, i) == Some(b',') {
182            i += 1;
183        }
184    }
185    Ok(out)
186}
187
188fn strip_comment(line: &str) -> &str {
189    // Strip `#` and `;` comments not inside quotes (config keys rarely quote,
190    // so a simple scan suffices for the supported subset).
191    let mut in_q = false;
192    for (idx, ch) in line.char_indices() {
193        match ch {
194            '"' => in_q = !in_q,
195            '#' | ';' if !in_q => return &line[..idx],
196            _ => {}
197        }
198    }
199    line
200}
201
202fn unquote(s: &str) -> String {
203    let b = s.as_bytes();
204    if b.len() >= 2 && (b[0] == b'"' && b[b.len() - 1] == b'"') {
205        s[1..s.len() - 1].to_string()
206    } else {
207        s.to_string()
208    }
209}
210
211// --- tiny JSON scanner helpers ---
212fn skip_ws(b: &[u8], i: &mut usize) {
213    while *i < b.len() && (b[*i] as char).is_whitespace() {
214        *i += 1;
215    }
216}
217fn peek(b: &[u8], i: usize) -> Option<u8> {
218    b.get(i).copied()
219}
220fn expect(b: &[u8], i: &mut usize, c: u8) -> Result<()> {
221    if peek(b, *i) == Some(c) {
222        *i += 1;
223        Ok(())
224    } else {
225        Err(Error::msg(format!(
226            "config JSON parse error: expected '{}' at byte {}",
227            c as char, *i
228        )))
229    }
230}
231fn parse_json_string(b: &[u8], i: &mut usize) -> Result<String> {
232    expect(b, i, b'"')?;
233    let mut out = String::new();
234    while *i < b.len() {
235        let c = b[*i];
236        *i += 1;
237        match c {
238            b'"' => return Ok(out),
239            b'\\' => {
240                if let Some(&e) = b.get(*i) {
241                    *i += 1;
242                    out.push(match e {
243                        b'n' => '\n',
244                        b't' => '\t',
245                        b'r' => '\r',
246                        other => other as char,
247                    });
248                }
249            }
250            other => out.push(other as char),
251        }
252    }
253    Err(Error::msg("config JSON parse error: unterminated string"))
254}
255fn parse_json_scalar(b: &[u8], i: &mut usize) -> Result<String> {
256    if peek(b, *i) == Some(b'"') {
257        return parse_json_string(b, i);
258    }
259    let start = *i;
260    while *i < b.len() && !matches!(b[*i], b',' | b'}' | b' ' | b'\n' | b'\t' | b'\r') {
261        *i += 1;
262    }
263    Ok(String::from_utf8_lossy(&b[start..*i]).to_string())
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    #[test]
271    fn ini_flat_and_sections() {
272        let text = "key = value\n[server]\nhost = localhost\nport = 8080\n";
273        let m = parse_ini(text).unwrap();
274        assert_eq!(m.get("key").map(|s| s.as_str()), Some("value"));
275        assert_eq!(m.get("server.host").map(|s| s.as_str()), Some("localhost"));
276        assert_eq!(m.get("server.port").map(|s| s.as_str()), Some("8080"));
277    }
278
279    #[test]
280    fn ini_comments_and_quotes() {
281        let text = "# a comment\nname = \"quoted value\" # trailing\n";
282        let m = parse_ini(text).unwrap();
283        assert_eq!(m.get("name").map(|s| s.as_str()), Some("quoted value"));
284    }
285
286    #[test]
287    fn json_flat_and_nested() {
288        let text = r#"{"name": "demo", "count": 3, "server": {"host": "h", "port": 9}}"#;
289        let m = parse_json(text).unwrap();
290        assert_eq!(m.get("name").map(|s| s.as_str()), Some("demo"));
291        assert_eq!(m.get("count").map(|s| s.as_str()), Some("3"));
292        assert_eq!(m.get("server.host").map(|s| s.as_str()), Some("h"));
293        assert_eq!(m.get("server.port").map(|s| s.as_str()), Some("9"));
294    }
295
296    #[test]
297    fn precedence_flag_over_env_over_file() {
298        std::env::set_var("CSTEST_PORT", "5000");
299        let mut c = Config::new().env_prefix("CSTEST");
300        c.set("port", "3000"); // file/default layer
301        // env wins over file
302        assert_eq!(c.get("port").as_deref(), Some("5000"));
303        // flag wins over env
304        assert_eq!(c.resolve("port", Some("9999"), "1000"), "9999");
305        // no flag -> env
306        assert_eq!(c.resolve("port", None, "1000"), "5000");
307        std::env::remove_var("CSTEST_PORT");
308        // no flag, no env -> file
309        assert_eq!(c.resolve("port", None, "1000"), "3000");
310    }
311
312    #[test]
313    fn get_as_parses() {
314        let mut c = Config::new();
315        c.set("n", "42");
316        assert_eq!(c.get_as::<i64>("n").unwrap(), Some(42));
317        c.set("bad", "notnum");
318        assert!(c.get_as::<i64>("bad").is_err());
319    }
320}