Skip to main content

eclipse_core/
interpolate.rs

1//! `${VAR}` substitution for configuration values.
2//!
3//! Config files are checked into repos and shared; secrets are not. So a value may name an
4//! environment variable instead of carrying one:
5//!
6//! ```toml
7//! [provider]
8//! api_key = "${OPENAI_API_KEY}"
9//! ```
10//!
11//! Two forms, and both are deliberately small:
12//!
13//! - `${NAME}` — the value of `NAME`; **an unset variable is an error that names the key**,
14//!   never an empty string. A provider that silently gets `""` for its key fails much later
15//!   and much less clearly than a config that refuses to load.
16//! - `${NAME:-fallback}` — the value, or `fallback` when `NAME` is unset *or empty* (the
17//!   shell's meaning of `:-`).
18//!
19//! `$$` escapes a literal `$`, so `$${X}` stays `${X}`. There is no recursion — the result
20//! of a substitution is never itself substituted — and no command substitution. Anything
21//! else starting with `$` is left alone, which keeps prices, `$HOME`-looking prose in a
22//! prompt, and regex fragments working.
23//!
24//! Substitution happens on parsed TOML values, not on the file text: a comment that
25//! *mentions* `${HOME}` is documentation, not a reference, and must not be able to break a
26//! config or leak a value into the wrong place.
27
28use crate::error::{Error, Result};
29use std::path::Path;
30
31/// Substitute `${...}` in every string inside `value`, in place.
32///
33/// `file` is only used to make errors locatable; `lookup` is the resolver (the real
34/// environment layered over `.env` files, in the order the caller decides).
35pub fn in_value(
36    value: &mut toml::Value,
37    file: &Path,
38    lookup: &dyn Fn(&str) -> Option<String>,
39) -> Result<()> {
40    walk(value, "", file, lookup)
41}
42
43fn walk(
44    value: &mut toml::Value,
45    path: &str,
46    file: &Path,
47    lookup: &dyn Fn(&str) -> Option<String>,
48) -> Result<()> {
49    match value {
50        toml::Value::String(s) => {
51            if s.contains('$') {
52                *s = substitute(s, path, file, lookup)?;
53            }
54            Ok(())
55        }
56        toml::Value::Table(t) => {
57            for (k, v) in t.iter_mut() {
58                let child = if path.is_empty() {
59                    k.clone()
60                } else {
61                    format!("{path}.{k}")
62                };
63                walk(v, &child, file, lookup)?;
64            }
65            Ok(())
66        }
67        toml::Value::Array(items) => {
68            for (i, v) in items.iter_mut().enumerate() {
69                let child = format!("{path}[{i}]");
70                walk(v, &child, file, lookup)?;
71            }
72            Ok(())
73        }
74        _ => Ok(()),
75    }
76}
77
78/// Substitute in one string. `path` is the config key, for error messages.
79pub fn substitute(
80    text: &str,
81    path: &str,
82    file: &Path,
83    lookup: &dyn Fn(&str) -> Option<String>,
84) -> Result<String> {
85    let mut out = String::with_capacity(text.len());
86    let chars: Vec<char> = text.chars().collect();
87    let mut i = 0;
88    while i < chars.len() {
89        if chars[i] != '$' {
90            out.push(chars[i]);
91            i += 1;
92            continue;
93        }
94        // `$$` is a literal dollar.
95        if chars.get(i + 1) == Some(&'$') {
96            out.push('$');
97            i += 2;
98            continue;
99        }
100        if chars.get(i + 1) != Some(&'{') {
101            // A lone `$` (a price, a regex anchor) is not a reference.
102            out.push('$');
103            i += 1;
104            continue;
105        }
106        let start = i;
107        let Some(end) = find_close(&chars, i + 2) else {
108            return Err(Error::Config(format!(
109                "{}: {}: unterminated ${{...}} at character {}",
110                file.display(),
111                label(path),
112                start + 1
113            )));
114        };
115        let inner: String = chars[i + 2..end].iter().collect();
116        let (name, default) = match inner.split_once(":-") {
117            Some((n, d)) => (n.trim().to_string(), Some(d.to_string())),
118            None => (inner.trim().to_string(), None),
119        };
120        if !valid_name(&name) {
121            return Err(Error::Config(format!(
122                "{}: {}: ${{{inner}}} is not a variable name",
123                file.display(),
124                label(path)
125            )));
126        }
127        let found = lookup(&name).filter(|v| !v.is_empty());
128        match (found, default) {
129            (Some(v), _) => out.push_str(&v),
130            // `:-` covers empty as well as unset, which is what a shell user expects.
131            (None, Some(d)) => out.push_str(&substitute(&d, path, file, lookup)?),
132            (None, None) => {
133                return Err(Error::Config(format!(
134                    "{}: {}: {name} is not set (referenced as ${{{name}}})",
135                    file.display(),
136                    label(path)
137                )))
138            }
139        }
140        i = end + 1;
141    }
142    Ok(out)
143}
144
145/// The matching closing brace. Defaults may hold a reference of their own
146/// (`${A:-${B}}`), so braces are counted rather than taking the first `}`.
147fn find_close(chars: &[char], from: usize) -> Option<usize> {
148    let mut depth = 1usize;
149    for (i, c) in chars[from..].iter().enumerate() {
150        match c {
151            '{' => depth += 1,
152            '}' => {
153                depth -= 1;
154                if depth == 0 {
155                    return Some(from + i);
156                }
157            }
158            _ => {}
159        }
160    }
161    None
162}
163
164fn valid_name(name: &str) -> bool {
165    !name.is_empty()
166        && name.len() <= 128
167        && name
168            .chars()
169            .next()
170            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
171        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
172}
173
174fn label(path: &str) -> &str {
175    if path.is_empty() {
176        "<root>"
177    } else {
178        path
179    }
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185    use std::collections::HashMap;
186    use std::path::PathBuf;
187
188    fn lookup_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
189        let m: HashMap<String, String> = pairs
190            .iter()
191            .map(|(k, v)| (k.to_string(), v.to_string()))
192            .collect();
193        move |k| m.get(k).cloned()
194    }
195
196    fn file() -> PathBuf {
197        PathBuf::from("/etc/eclipse/config.toml")
198    }
199
200    fn sub(text: &str, pairs: &[(&str, &str)]) -> Result<String> {
201        substitute(text, "provider.api_key", &file(), &lookup_of(pairs))
202    }
203
204    #[test]
205    fn a_plain_string_is_untouched() {
206        assert_eq!(sub("hello", &[]).unwrap(), "hello");
207        assert_eq!(sub("", &[]).unwrap(), "");
208    }
209
210    #[test]
211    fn a_set_variable_is_replaced() {
212        assert_eq!(
213            sub("${OPENAI_API_KEY}", &[("OPENAI_API_KEY", "sk-123")]).unwrap(),
214            "sk-123"
215        );
216        assert_eq!(sub("Bearer ${K}", &[("K", "abc")]).unwrap(), "Bearer abc");
217        assert_eq!(sub("${A}-${B}", &[("A", "1"), ("B", "2")]).unwrap(), "1-2");
218    }
219
220    #[test]
221    fn an_unset_variable_is_an_error_naming_the_key_and_the_variable() {
222        let err = sub("${MISSING_KEY}", &[]).unwrap_err().to_string();
223        assert!(err.contains("provider.api_key"), "{err}");
224        assert!(err.contains("MISSING_KEY"), "{err}");
225        assert!(err.contains("not set"), "{err}");
226    }
227
228    #[test]
229    fn a_default_is_used_when_the_variable_is_unset_or_empty() {
230        assert_eq!(sub("${HOST:-localhost}", &[]).unwrap(), "localhost");
231        assert_eq!(
232            sub("${HOST:-localhost}", &[("HOST", "")]).unwrap(),
233            "localhost"
234        );
235        assert_eq!(
236            sub("${HOST:-localhost}", &[("HOST", "example")]).unwrap(),
237            "example"
238        );
239        // A default may itself be empty, and may be more than one word.
240        assert_eq!(sub("${X:-}", &[]).unwrap(), "");
241        assert_eq!(sub("${X:-two words}", &[]).unwrap(), "two words");
242    }
243
244    #[test]
245    fn a_default_can_reference_another_variable() {
246        assert_eq!(sub("${A:-${B}}", &[("B", "from-b")]).unwrap(), "from-b");
247    }
248
249    #[test]
250    fn a_double_dollar_is_a_literal_dollar() {
251        assert_eq!(sub("$${NOT_A_VAR}", &[]).unwrap(), "${NOT_A_VAR}");
252        assert_eq!(sub("costs $$5", &[]).unwrap(), "costs $5");
253    }
254
255    #[test]
256    fn a_lone_dollar_is_left_alone() {
257        // Prices, regex anchors and prose all contain solitary dollars.
258        for text in ["$5", "^$", "a $ b", "$", "100%$"] {
259            assert_eq!(sub(text, &[]).unwrap(), text);
260        }
261    }
262
263    #[test]
264    fn an_unterminated_reference_is_an_error() {
265        let err = sub("${OOPS", &[("OOPS", "x")]).unwrap_err().to_string();
266        assert!(err.contains("unterminated"), "{err}");
267    }
268
269    #[test]
270    fn a_malformed_name_is_an_error() {
271        for text in ["${}", "${1X}", "${a b}", "${a-b}"] {
272            assert!(sub(text, &[]).is_err(), "{text} must be refused");
273        }
274    }
275
276    #[test]
277    fn substitution_reaches_nested_strings_and_leaves_other_types_alone() {
278        let mut v: toml::Value = toml::from_str(
279            r#"
280            top = "${TOP}"
281            n = 5
282            flag = true
283            [provider]
284            api_key = "${KEY}"
285            model = "m"
286            [tools]
287            list = ["${A}", "plain"]
288        "#,
289        )
290        .unwrap();
291        in_value(
292            &mut v,
293            &file(),
294            &lookup_of(&[("TOP", "t"), ("KEY", "k"), ("A", "a")]),
295        )
296        .unwrap();
297        assert_eq!(v["top"].as_str(), Some("t"));
298        assert_eq!(v["provider"]["api_key"].as_str(), Some("k"));
299        assert_eq!(v["tools"]["list"][0].as_str(), Some("a"));
300        assert_eq!(v["tools"]["list"][1].as_str(), Some("plain"));
301        assert_eq!(v["n"].as_integer(), Some(5));
302        assert_eq!(v["flag"].as_bool(), Some(true));
303    }
304
305    #[test]
306    fn an_error_inside_a_table_names_the_full_key() {
307        let mut v: toml::Value = toml::from_str("[provider]\napi_key = \"${NOPE}\"\n").unwrap();
308        let err = in_value(&mut v, &file(), &lookup_of(&[]))
309            .unwrap_err()
310            .to_string();
311        assert!(err.contains("provider.api_key"), "{err}");
312        assert!(err.contains("config.toml"), "{err}");
313    }
314
315    #[test]
316    fn a_comment_mentioning_a_variable_is_not_a_reference() {
317        // The point of substituting after parsing: this file must load.
318        let text = "# set ${SOMETHING_UNSET} in the environment\nkey = \"literal\"\n";
319        let mut v: toml::Value = toml::from_str(text).unwrap();
320        in_value(&mut v, &file(), &lookup_of(&[])).unwrap();
321        assert_eq!(v["key"].as_str(), Some("literal"));
322    }
323}