eclipse-core 0.13.1

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
//! `${VAR}` substitution for configuration values.
//!
//! Config files are checked into repos and shared; secrets are not. So a value may name an
//! environment variable instead of carrying one:
//!
//! ```toml
//! [provider]
//! api_key = "${OPENAI_API_KEY}"
//! ```
//!
//! Two forms, and both are deliberately small:
//!
//! - `${NAME}` — the value of `NAME`; **an unset variable is an error that names the key**,
//!   never an empty string. A provider that silently gets `""` for its key fails much later
//!   and much less clearly than a config that refuses to load.
//! - `${NAME:-fallback}` — the value, or `fallback` when `NAME` is unset *or empty* (the
//!   shell's meaning of `:-`).
//!
//! `$$` escapes a literal `$`, so `$${X}` stays `${X}`. There is no recursion — the result
//! of a substitution is never itself substituted — and no command substitution. Anything
//! else starting with `$` is left alone, which keeps prices, `$HOME`-looking prose in a
//! prompt, and regex fragments working.
//!
//! Substitution happens on parsed TOML values, not on the file text: a comment that
//! *mentions* `${HOME}` is documentation, not a reference, and must not be able to break a
//! config or leak a value into the wrong place.

use crate::error::{Error, Result};
use std::path::Path;

/// Substitute `${...}` in every string inside `value`, in place.
///
/// `file` is only used to make errors locatable; `lookup` is the resolver (the real
/// environment layered over `.env` files, in the order the caller decides).
pub fn in_value(
    value: &mut toml::Value,
    file: &Path,
    lookup: &dyn Fn(&str) -> Option<String>,
) -> Result<()> {
    walk(value, "", file, lookup)
}

fn walk(
    value: &mut toml::Value,
    path: &str,
    file: &Path,
    lookup: &dyn Fn(&str) -> Option<String>,
) -> Result<()> {
    match value {
        toml::Value::String(s) => {
            if s.contains('$') {
                *s = substitute(s, path, file, lookup)?;
            }
            Ok(())
        }
        toml::Value::Table(t) => {
            for (k, v) in t.iter_mut() {
                let child = if path.is_empty() {
                    k.clone()
                } else {
                    format!("{path}.{k}")
                };
                walk(v, &child, file, lookup)?;
            }
            Ok(())
        }
        toml::Value::Array(items) => {
            for (i, v) in items.iter_mut().enumerate() {
                let child = format!("{path}[{i}]");
                walk(v, &child, file, lookup)?;
            }
            Ok(())
        }
        _ => Ok(()),
    }
}

/// Substitute in one string. `path` is the config key, for error messages.
pub fn substitute(
    text: &str,
    path: &str,
    file: &Path,
    lookup: &dyn Fn(&str) -> Option<String>,
) -> Result<String> {
    let mut out = String::with_capacity(text.len());
    let chars: Vec<char> = text.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] != '$' {
            out.push(chars[i]);
            i += 1;
            continue;
        }
        // `$$` is a literal dollar.
        if chars.get(i + 1) == Some(&'$') {
            out.push('$');
            i += 2;
            continue;
        }
        if chars.get(i + 1) != Some(&'{') {
            // A lone `$` (a price, a regex anchor) is not a reference.
            out.push('$');
            i += 1;
            continue;
        }
        let start = i;
        let Some(end) = find_close(&chars, i + 2) else {
            return Err(Error::Config(format!(
                "{}: {}: unterminated ${{...}} at character {}",
                file.display(),
                label(path),
                start + 1
            )));
        };
        let inner: String = chars[i + 2..end].iter().collect();
        let (name, default) = match inner.split_once(":-") {
            Some((n, d)) => (n.trim().to_string(), Some(d.to_string())),
            None => (inner.trim().to_string(), None),
        };
        if !valid_name(&name) {
            return Err(Error::Config(format!(
                "{}: {}: ${{{inner}}} is not a variable name",
                file.display(),
                label(path)
            )));
        }
        let found = lookup(&name).filter(|v| !v.is_empty());
        match (found, default) {
            (Some(v), _) => out.push_str(&v),
            // `:-` covers empty as well as unset, which is what a shell user expects.
            (None, Some(d)) => out.push_str(&substitute(&d, path, file, lookup)?),
            (None, None) => {
                return Err(Error::Config(format!(
                    "{}: {}: {name} is not set (referenced as ${{{name}}})",
                    file.display(),
                    label(path)
                )))
            }
        }
        i = end + 1;
    }
    Ok(out)
}

/// The matching closing brace. Defaults may hold a reference of their own
/// (`${A:-${B}}`), so braces are counted rather than taking the first `}`.
fn find_close(chars: &[char], from: usize) -> Option<usize> {
    let mut depth = 1usize;
    for (i, c) in chars[from..].iter().enumerate() {
        match c {
            '{' => depth += 1,
            '}' => {
                depth -= 1;
                if depth == 0 {
                    return Some(from + i);
                }
            }
            _ => {}
        }
    }
    None
}

fn valid_name(name: &str) -> bool {
    !name.is_empty()
        && name.len() <= 128
        && name
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}

fn label(path: &str) -> &str {
    if path.is_empty() {
        "<root>"
    } else {
        path
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::path::PathBuf;

    fn lookup_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
        let m: HashMap<String, String> = pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        move |k| m.get(k).cloned()
    }

    fn file() -> PathBuf {
        PathBuf::from("/etc/eclipse/config.toml")
    }

    fn sub(text: &str, pairs: &[(&str, &str)]) -> Result<String> {
        substitute(text, "provider.api_key", &file(), &lookup_of(pairs))
    }

    #[test]
    fn a_plain_string_is_untouched() {
        assert_eq!(sub("hello", &[]).unwrap(), "hello");
        assert_eq!(sub("", &[]).unwrap(), "");
    }

    #[test]
    fn a_set_variable_is_replaced() {
        assert_eq!(
            sub("${OPENAI_API_KEY}", &[("OPENAI_API_KEY", "sk-123")]).unwrap(),
            "sk-123"
        );
        assert_eq!(sub("Bearer ${K}", &[("K", "abc")]).unwrap(), "Bearer abc");
        assert_eq!(sub("${A}-${B}", &[("A", "1"), ("B", "2")]).unwrap(), "1-2");
    }

    #[test]
    fn an_unset_variable_is_an_error_naming_the_key_and_the_variable() {
        let err = sub("${MISSING_KEY}", &[]).unwrap_err().to_string();
        assert!(err.contains("provider.api_key"), "{err}");
        assert!(err.contains("MISSING_KEY"), "{err}");
        assert!(err.contains("not set"), "{err}");
    }

    #[test]
    fn a_default_is_used_when_the_variable_is_unset_or_empty() {
        assert_eq!(sub("${HOST:-localhost}", &[]).unwrap(), "localhost");
        assert_eq!(
            sub("${HOST:-localhost}", &[("HOST", "")]).unwrap(),
            "localhost"
        );
        assert_eq!(
            sub("${HOST:-localhost}", &[("HOST", "example")]).unwrap(),
            "example"
        );
        // A default may itself be empty, and may be more than one word.
        assert_eq!(sub("${X:-}", &[]).unwrap(), "");
        assert_eq!(sub("${X:-two words}", &[]).unwrap(), "two words");
    }

    #[test]
    fn a_default_can_reference_another_variable() {
        assert_eq!(sub("${A:-${B}}", &[("B", "from-b")]).unwrap(), "from-b");
    }

    #[test]
    fn a_double_dollar_is_a_literal_dollar() {
        assert_eq!(sub("$${NOT_A_VAR}", &[]).unwrap(), "${NOT_A_VAR}");
        assert_eq!(sub("costs $$5", &[]).unwrap(), "costs $5");
    }

    #[test]
    fn a_lone_dollar_is_left_alone() {
        // Prices, regex anchors and prose all contain solitary dollars.
        for text in ["$5", "^$", "a $ b", "$", "100%$"] {
            assert_eq!(sub(text, &[]).unwrap(), text);
        }
    }

    #[test]
    fn an_unterminated_reference_is_an_error() {
        let err = sub("${OOPS", &[("OOPS", "x")]).unwrap_err().to_string();
        assert!(err.contains("unterminated"), "{err}");
    }

    #[test]
    fn a_malformed_name_is_an_error() {
        for text in ["${}", "${1X}", "${a b}", "${a-b}"] {
            assert!(sub(text, &[]).is_err(), "{text} must be refused");
        }
    }

    #[test]
    fn substitution_reaches_nested_strings_and_leaves_other_types_alone() {
        let mut v: toml::Value = toml::from_str(
            r#"
            top = "${TOP}"
            n = 5
            flag = true
            [provider]
            api_key = "${KEY}"
            model = "m"
            [tools]
            list = ["${A}", "plain"]
        "#,
        )
        .unwrap();
        in_value(
            &mut v,
            &file(),
            &lookup_of(&[("TOP", "t"), ("KEY", "k"), ("A", "a")]),
        )
        .unwrap();
        assert_eq!(v["top"].as_str(), Some("t"));
        assert_eq!(v["provider"]["api_key"].as_str(), Some("k"));
        assert_eq!(v["tools"]["list"][0].as_str(), Some("a"));
        assert_eq!(v["tools"]["list"][1].as_str(), Some("plain"));
        assert_eq!(v["n"].as_integer(), Some(5));
        assert_eq!(v["flag"].as_bool(), Some(true));
    }

    #[test]
    fn an_error_inside_a_table_names_the_full_key() {
        let mut v: toml::Value = toml::from_str("[provider]\napi_key = \"${NOPE}\"\n").unwrap();
        let err = in_value(&mut v, &file(), &lookup_of(&[]))
            .unwrap_err()
            .to_string();
        assert!(err.contains("provider.api_key"), "{err}");
        assert!(err.contains("config.toml"), "{err}");
    }

    #[test]
    fn a_comment_mentioning_a_variable_is_not_a_reference() {
        // The point of substituting after parsing: this file must load.
        let text = "# set ${SOMETHING_UNSET} in the environment\nkey = \"literal\"\n";
        let mut v: toml::Value = toml::from_str(text).unwrap();
        in_value(&mut v, &file(), &lookup_of(&[])).unwrap();
        assert_eq!(v["key"].as_str(), Some("literal"));
    }
}