cornerlibstone 0.1.0

Lib Cornerstone — a zero-dependency foundation for building command-line tools in Rust: argument parsing, nested subcommands, themeable help in multiple presets, structured errors and exit codes, config loading, interactive prompts, shell-completion and man/markdown generation, logging, JSON output, and root/destructive-operation guards.
Documentation
//! Configuration loading with a clear precedence chain:
//! **flag > environment > config file > default**.
//!
//! Zero dependencies, so the file parsers deliberately support a *practical
//! subset* of each format — flat and one-level-nested key/value pairs, which is
//! what CLI config almost always is. If a tool needs full spec compliance it can
//! parse the file itself and feed values in via [`Config::set`].
//!
//! Supported inputs:
//! * INI / conf: `key = value`, `[section]` headers → `section.key`.
//! * TOML subset: same as INI plus `#` comments and quoted strings.
//! * JSON subset: flat object of string/number/bool values, and one level of
//!   nested objects flattened to `parent.child`.

use crate::error::{Error, Result};
use std::collections::BTreeMap;

/// A resolved configuration: a flat map of dotted keys to string values, plus
/// the precedence machinery to overlay env and flags.
#[derive(Debug, Default, Clone)]
pub struct Config {
    values: BTreeMap<String, String>,
    env_prefix: Option<String>,
}

impl Config {
    pub fn new() -> Self {
        Config::default()
    }

    /// Set an environment-variable prefix used by [`Config::get`] to overlay
    /// env values. With prefix `MYTOOL`, key `port` reads `MYTOOL_PORT`.
    pub fn env_prefix<S: Into<String>>(mut self, prefix: S) -> Self {
        self.env_prefix = Some(prefix.into());
        self
    }

    /// Directly set a value (lowest-effort source, e.g. a default).
    pub fn set<K: Into<String>, V: Into<String>>(&mut self, key: K, value: V) -> &mut Self {
        self.values.insert(key.into(), value.into());
        self
    }

    /// Load and merge a config file, autodetecting the format by extension
    /// (`.toml`, `.ini`/`.conf`, `.json`). Values overwrite existing keys.
    pub fn load_file(&mut self, path: &str) -> Result<&mut Self> {
        let text = std::fs::read_to_string(path)
            .map_err(|e| Error::not_found(format!("cannot read config {}: {}", path, e)))?;
        let parsed = if path.ends_with(".json") {
            parse_json(&text)?
        } else {
            // TOML-subset and INI share the same parser here.
            parse_ini(&text)?
        };
        for (k, v) in parsed {
            self.values.insert(k, v);
        }
        Ok(self)
    }

    /// Try to load a file if it exists; missing files are not an error. Handy
    /// for "load ~/.config/tool.toml if present".
    pub fn load_file_opt(&mut self, path: &str) -> Result<&mut Self> {
        if std::path::Path::new(path).exists() {
            self.load_file(path)?;
        }
        Ok(self)
    }

    /// Resolve a key using precedence: environment (if a prefix is set) wins over
    /// the loaded file/default values.
    pub fn get(&self, key: &str) -> Option<String> {
        if let Some(prefix) = &self.env_prefix {
            let env_key = format!("{}_{}", prefix, key.replace('.', "_")).to_uppercase();
            if let Ok(v) = std::env::var(&env_key) {
                return Some(v);
            }
        }
        self.values.get(key).cloned()
    }

    /// Resolve with an explicit flag value taking top precedence. Pass the flag
    /// value the user supplied (or `None`); this returns the first of
    /// flag → env → file → `default`.
    pub fn resolve(&self, key: &str, flag: Option<&str>, default: &str) -> String {
        if let Some(f) = flag {
            return f.to_string();
        }
        self.get(key).unwrap_or_else(|| default.to_string())
    }

    /// Parse a resolved value into any type.
    pub fn get_as<T: std::str::FromStr>(&self, key: &str) -> Result<Option<T>> {
        match self.get(key) {
            None => Ok(None),
            Some(v) => v
                .parse::<T>()
                .map(Some)
                .map_err(|_| Error::msg(format!("invalid value for config key '{}': {}", key, v))),
        }
    }

    /// All resolved keys (file/default layer only; env is overlaid at `get`).
    pub fn keys(&self) -> impl Iterator<Item = &String> {
        self.values.keys()
    }
}

/// Parse an INI / TOML-subset document into dotted key/value pairs.
fn parse_ini(text: &str) -> Result<BTreeMap<String, String>> {
    let mut out = BTreeMap::new();
    let mut section = String::new();
    for (lineno, raw) in text.lines().enumerate() {
        let line = strip_comment(raw).trim();
        if line.is_empty() {
            continue;
        }
        if line.starts_with('[') && line.ends_with(']') {
            section = line[1..line.len() - 1].trim().to_string();
            continue;
        }
        let (k, v) = line
            .split_once('=')
            .ok_or_else(|| Error::msg(format!("config parse error on line {}: expected key = value", lineno + 1)))?;
        let key = k.trim();
        let val = unquote(v.trim());
        let full = if section.is_empty() {
            key.to_string()
        } else {
            format!("{}.{}", section, key)
        };
        out.insert(full, val);
    }
    Ok(out)
}

/// Parse a JSON-subset object (flat + one level of nesting) into dotted pairs.
fn parse_json(text: &str) -> Result<BTreeMap<String, String>> {
    let mut out = BTreeMap::new();
    let bytes = text.trim().as_bytes();
    let mut i = 0;
    skip_ws(bytes, &mut i);
    expect(bytes, &mut i, b'{')?;
    loop {
        skip_ws(bytes, &mut i);
        if peek(bytes, i) == Some(b'}') {
            break;
        }
        let key = parse_json_string(bytes, &mut i)?;
        skip_ws(bytes, &mut i);
        expect(bytes, &mut i, b':')?;
        skip_ws(bytes, &mut i);
        match peek(bytes, i) {
            Some(b'{') => {
                // One level of nesting: flatten to key.child.
                i += 1;
                loop {
                    skip_ws(bytes, &mut i);
                    if peek(bytes, i) == Some(b'}') {
                        i += 1;
                        break;
                    }
                    let ck = parse_json_string(bytes, &mut i)?;
                    skip_ws(bytes, &mut i);
                    expect(bytes, &mut i, b':')?;
                    skip_ws(bytes, &mut i);
                    let cv = parse_json_scalar(bytes, &mut i)?;
                    out.insert(format!("{}.{}", key, ck), cv);
                    skip_ws(bytes, &mut i);
                    if peek(bytes, i) == Some(b',') {
                        i += 1;
                    }
                }
            }
            _ => {
                let v = parse_json_scalar(bytes, &mut i)?;
                out.insert(key, v);
            }
        }
        skip_ws(bytes, &mut i);
        if peek(bytes, i) == Some(b',') {
            i += 1;
        }
    }
    Ok(out)
}

fn strip_comment(line: &str) -> &str {
    // Strip `#` and `;` comments not inside quotes (config keys rarely quote,
    // so a simple scan suffices for the supported subset).
    let mut in_q = false;
    for (idx, ch) in line.char_indices() {
        match ch {
            '"' => in_q = !in_q,
            '#' | ';' if !in_q => return &line[..idx],
            _ => {}
        }
    }
    line
}

fn unquote(s: &str) -> String {
    let b = s.as_bytes();
    if b.len() >= 2 && (b[0] == b'"' && b[b.len() - 1] == b'"') {
        s[1..s.len() - 1].to_string()
    } else {
        s.to_string()
    }
}

// --- tiny JSON scanner helpers ---
fn skip_ws(b: &[u8], i: &mut usize) {
    while *i < b.len() && (b[*i] as char).is_whitespace() {
        *i += 1;
    }
}
fn peek(b: &[u8], i: usize) -> Option<u8> {
    b.get(i).copied()
}
fn expect(b: &[u8], i: &mut usize, c: u8) -> Result<()> {
    if peek(b, *i) == Some(c) {
        *i += 1;
        Ok(())
    } else {
        Err(Error::msg(format!(
            "config JSON parse error: expected '{}' at byte {}",
            c as char, *i
        )))
    }
}
fn parse_json_string(b: &[u8], i: &mut usize) -> Result<String> {
    expect(b, i, b'"')?;
    let mut out = String::new();
    while *i < b.len() {
        let c = b[*i];
        *i += 1;
        match c {
            b'"' => return Ok(out),
            b'\\' => {
                if let Some(&e) = b.get(*i) {
                    *i += 1;
                    out.push(match e {
                        b'n' => '\n',
                        b't' => '\t',
                        b'r' => '\r',
                        other => other as char,
                    });
                }
            }
            other => out.push(other as char),
        }
    }
    Err(Error::msg("config JSON parse error: unterminated string"))
}
fn parse_json_scalar(b: &[u8], i: &mut usize) -> Result<String> {
    if peek(b, *i) == Some(b'"') {
        return parse_json_string(b, i);
    }
    let start = *i;
    while *i < b.len() && !matches!(b[*i], b',' | b'}' | b' ' | b'\n' | b'\t' | b'\r') {
        *i += 1;
    }
    Ok(String::from_utf8_lossy(&b[start..*i]).to_string())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn ini_flat_and_sections() {
        let text = "key = value\n[server]\nhost = localhost\nport = 8080\n";
        let m = parse_ini(text).unwrap();
        assert_eq!(m.get("key").map(|s| s.as_str()), Some("value"));
        assert_eq!(m.get("server.host").map(|s| s.as_str()), Some("localhost"));
        assert_eq!(m.get("server.port").map(|s| s.as_str()), Some("8080"));
    }

    #[test]
    fn ini_comments_and_quotes() {
        let text = "# a comment\nname = \"quoted value\" # trailing\n";
        let m = parse_ini(text).unwrap();
        assert_eq!(m.get("name").map(|s| s.as_str()), Some("quoted value"));
    }

    #[test]
    fn json_flat_and_nested() {
        let text = r#"{"name": "demo", "count": 3, "server": {"host": "h", "port": 9}}"#;
        let m = parse_json(text).unwrap();
        assert_eq!(m.get("name").map(|s| s.as_str()), Some("demo"));
        assert_eq!(m.get("count").map(|s| s.as_str()), Some("3"));
        assert_eq!(m.get("server.host").map(|s| s.as_str()), Some("h"));
        assert_eq!(m.get("server.port").map(|s| s.as_str()), Some("9"));
    }

    #[test]
    fn precedence_flag_over_env_over_file() {
        std::env::set_var("CSTEST_PORT", "5000");
        let mut c = Config::new().env_prefix("CSTEST");
        c.set("port", "3000"); // file/default layer
        // env wins over file
        assert_eq!(c.get("port").as_deref(), Some("5000"));
        // flag wins over env
        assert_eq!(c.resolve("port", Some("9999"), "1000"), "9999");
        // no flag -> env
        assert_eq!(c.resolve("port", None, "1000"), "5000");
        std::env::remove_var("CSTEST_PORT");
        // no flag, no env -> file
        assert_eq!(c.resolve("port", None, "1000"), "3000");
    }

    #[test]
    fn get_as_parses() {
        let mut c = Config::new();
        c.set("n", "42");
        assert_eq!(c.get_as::<i64>("n").unwrap(), Some(42));
        c.set("bad", "notnum");
        assert!(c.get_as::<i64>("bad").is_err());
    }
}