Skip to main content

eclipse_core/
dotenv.rs

1//! Strict, dependency-free `.env` parser.
2//!
3//! Plain `KEY=VALUE` lines with `#` comments and optional quotes. There is deliberately
4//! no interpolation, command substitution or `${VAR}` expansion: a `.env` file holds
5//! secrets and is read before `config.toml`, so letting values reference each other (or
6//! the shell) would make the load order matter and open a recursion/injection surface.
7
8use crate::error::{Error, Result};
9use std::collections::BTreeMap;
10use std::path::{Path, PathBuf};
11
12/// One `KEY=VALUE` assignment, with where it came from.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct Assignment {
15    pub key: String,
16    pub value: String,
17    /// 1-based line number in the source text.
18    pub line: usize,
19}
20
21/// Parse .env text. Returns assignments in file order.
22///
23/// Duplicate keys are all returned, in order; it is [`load_files`] that collapses them
24/// (last wins). Errors are `Error::Config` messages starting with `line N:`.
25pub fn parse(text: &str) -> Result<Vec<Assignment>> {
26    parse_inner(text).map_err(Error::Config)
27}
28
29fn parse_inner(text: &str) -> std::result::Result<Vec<Assignment>, String> {
30    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
31    let mut out = Vec::new();
32    for (idx, raw) in text.lines().enumerate() {
33        let line = idx + 1;
34        let raw = raw.trim_end_matches('\r').trim();
35        if raw.is_empty() || raw.starts_with('#') {
36            continue;
37        }
38        let body = strip_export(raw);
39        let Some((key, value)) = body.split_once('=') else {
40            return Err(format!("line {line}: expected KEY=VALUE, found no '='"));
41        };
42        let key = key.trim();
43        if !valid_key(key) {
44            return Err(format!("line {line}: invalid key {key:?}"));
45        }
46        let value = parse_value(value).map_err(|m| format!("line {line}: {m}"))?;
47        out.push(Assignment {
48            key: key.to_string(),
49            value,
50            line,
51        });
52    }
53    Ok(out)
54}
55
56/// `export` only counts as a prefix when whitespace follows, so a variable literally named
57/// `export` (`export=1`) still parses.
58fn strip_export(s: &str) -> &str {
59    match s.strip_prefix("export") {
60        Some(rest) if rest.starts_with(char::is_whitespace) => rest.trim_start(),
61        _ => s,
62    }
63}
64
65fn valid_key(key: &str) -> bool {
66    let mut chars = key.chars();
67    matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_')
68        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
69}
70
71fn parse_value(raw: &str) -> std::result::Result<String, String> {
72    let v = raw.trim_start();
73    match v.chars().next() {
74        Some('\'') => {
75            let inner = &v[1..];
76            let end = inner.find('\'').ok_or("unbalanced single quote")?;
77            check_tail(&inner[end + 1..])?;
78            Ok(inner[..end].to_string())
79        }
80        Some('"') => {
81            let mut value = String::new();
82            let mut chars = v[1..].char_indices();
83            while let Some((i, c)) = chars.next() {
84                match c {
85                    '"' => {
86                        check_tail(&v[1 + i + 1..])?;
87                        return Ok(value);
88                    }
89                    // Only `\"` and `\\` are escapes; any other backslash is kept as-is so
90                    // Windows paths and regexes survive without doubling.
91                    '\\' => match chars.next() {
92                        Some((_, e @ ('"' | '\\'))) => value.push(e),
93                        Some((_, other)) => {
94                            value.push('\\');
95                            value.push(other);
96                        }
97                        None => break,
98                    },
99                    c => value.push(c),
100                }
101            }
102            Err("unbalanced double quote".to_string())
103        }
104        _ => {
105            // `#` only starts a comment at the start of the value or after whitespace, so
106            // `a#b` (common in passwords and URLs) is preserved.
107            let mut prev_ws = true;
108            let mut end = v.len();
109            for (i, c) in v.char_indices() {
110                if c == '#' && prev_ws {
111                    end = i;
112                    break;
113                }
114                prev_ws = c.is_whitespace();
115            }
116            Ok(v[..end].trim_end().to_string())
117        }
118    }
119}
120
121/// After a closing quote only whitespace or a whitespace-separated comment may follow.
122fn check_tail(tail: &str) -> std::result::Result<(), String> {
123    let trimmed = tail.trim_start();
124    if trimmed.is_empty() || (trimmed.starts_with('#') && tail.starts_with(char::is_whitespace)) {
125        Ok(())
126    } else {
127        Err("unexpected content after closing quote".to_string())
128    }
129}
130
131/// Read one file. A missing file is Ok(vec![]), not an error.
132///
133/// Invalid UTF-8 is an error rather than being converted lossily: silently altering a
134/// secret would be worse than refusing to start.
135pub fn load(path: &Path) -> Result<Vec<Assignment>> {
136    let bytes = match std::fs::read(path) {
137        Ok(b) => b,
138        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
139        Err(e) => return Err(Error::io(path, e)),
140    };
141    let text = String::from_utf8(bytes)
142        .map_err(|_| Error::Config(format!("{}: file is not valid UTF-8", path.display())))?;
143    parse_inner(&text).map_err(|m| Error::Config(format!("{}: {m}", path.display())))
144}
145
146/// Read several files, later ones winning on key collision.
147pub fn load_files(paths: &[PathBuf]) -> Result<BTreeMap<String, String>> {
148    let mut map = BTreeMap::new();
149    for path in paths {
150        for a in load(path)? {
151            map.insert(a.key, a.value);
152        }
153    }
154    Ok(map)
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    fn kv(text: &str) -> Vec<(String, String)> {
162        parse(text)
163            .unwrap()
164            .into_iter()
165            .map(|a| (a.key, a.value))
166            .collect()
167    }
168
169    fn one(text: &str) -> String {
170        let mut v = kv(text);
171        assert_eq!(v.len(), 1);
172        v.remove(0).1
173    }
174
175    fn err(text: &str) -> String {
176        parse(text).unwrap_err().to_string()
177    }
178
179    #[test]
180    fn simple_assignment() {
181        assert_eq!(kv("A=1"), vec![("A".into(), "1".into())]);
182        assert_eq!(one("  K_2 =  spaced value  "), "spaced value");
183        assert_eq!(one("EMPTY="), "");
184    }
185
186    #[test]
187    fn comments_and_blank_lines() {
188        let got = kv("# top\n\n   \n  # indented\nA=1\n");
189        assert_eq!(got, vec![("A".into(), "1".into())]);
190    }
191
192    #[test]
193    fn export_prefix() {
194        assert_eq!(kv("export A=1"), vec![("A".into(), "1".into())]);
195        assert_eq!(kv("export   B = 2"), vec![("B".into(), "2".into())]);
196        assert_eq!(kv("export=3"), vec![("export".into(), "3".into())]);
197    }
198
199    #[test]
200    fn single_quotes_are_literal() {
201        assert_eq!(one("A='$HOME'"), "$HOME");
202        assert_eq!(one(r"A='a\nb'"), r"a\nb");
203        assert_eq!(one(r"A='a\nb'").chars().count(), 4);
204        assert_eq!(one("A='  keep  '"), "  keep  ");
205        assert_eq!(one("A='x' # note"), "x");
206    }
207
208    #[test]
209    fn double_quote_escapes() {
210        assert_eq!(one(r#"A="say \"hi\"""#), r#"say "hi""#);
211        assert_eq!(one(r#"A="back\\slash""#), r"back\slash");
212        assert_eq!(one(r#"A="$HOME ${X}""#), "$HOME ${X}");
213        assert_eq!(one(r#"A="  keep  " # c"#), "  keep  ");
214        assert_eq!(one(r#"A="a\nb""#), r"a\nb");
215    }
216
217    #[test]
218    fn invalid_key_names_line() {
219        let e = err("A=1\n1X=2\n");
220        assert!(e.contains("line 2"), "{e}");
221        assert!(e.contains("invalid key \"1X\""), "{e}");
222        assert!(err("A-B=1").contains("invalid key"));
223        assert!(err("=1").contains("line 1"));
224        let e = err("A=1\nNOEQUALS\n");
225        assert!(e.contains("line 2"), "{e}");
226    }
227
228    #[test]
229    fn unbalanced_quote() {
230        for t in ["A='x", "A=\"x", "A=\"x\\\"", "A=\"x\\"] {
231            let e = err(t);
232            assert!(e.contains("line 1") && e.contains("unbalanced"), "{t}: {e}");
233        }
234        assert!(err("\nB=1\nA='x").contains("line 3"));
235    }
236
237    #[test]
238    fn trailing_junk_after_quote() {
239        assert!(err("A='x' y").contains("after closing quote"));
240        assert!(err("A=\"x\"y").contains("line 1"));
241        assert!(err("A=\"x\"#c").contains("after closing quote"));
242        assert_eq!(one("A=\"x\"   "), "x");
243    }
244
245    #[test]
246    fn bom_and_crlf() {
247        let got = kv("\u{feff}A=1\r\n# c\r\nB='two'\r\nC=3\r\n");
248        assert_eq!(
249            got,
250            vec![
251                ("A".into(), "1".into()),
252                ("B".into(), "two".into()),
253                ("C".into(), "3".into())
254            ]
255        );
256    }
257
258    #[test]
259    fn hash_in_unquoted_value() {
260        assert_eq!(one("A=a#b"), "a#b");
261        assert_eq!(one("A=a #b"), "a");
262        assert_eq!(one("A=a\t# b"), "a");
263        assert_eq!(one("A=#b"), "");
264        assert_eq!(one("A=http://x/#frag"), "http://x/#frag");
265    }
266
267    #[test]
268    fn duplicates_last_wins_through_load_files() {
269        let dir = tempfile::tempdir().unwrap();
270        let p = dir.path().join(".env");
271        std::fs::write(&p, "A=1\nB=x\nA=2\n").unwrap();
272        assert_eq!(load(&p).unwrap().len(), 3);
273        let m = load_files(&[p]).unwrap();
274        assert_eq!(m["A"], "2");
275        assert_eq!(m["B"], "x");
276    }
277
278    #[test]
279    fn missing_file_empty_and_later_overrides() {
280        let dir = tempfile::tempdir().unwrap();
281        let missing = dir.path().join("nope.env");
282        assert_eq!(load(&missing).unwrap(), vec![]);
283
284        let a = dir.path().join("a.env");
285        let b = dir.path().join("b.env");
286        std::fs::write(&a, "K=shared\nONLY_A=1\n").unwrap();
287        std::fs::write(&b, "K=profile\n").unwrap();
288        let m = load_files(&[a, missing, b]).unwrap();
289        assert_eq!(m["K"], "profile");
290        assert_eq!(m["ONLY_A"], "1");
291    }
292
293    #[test]
294    fn parse_keeps_order_and_line_numbers() {
295        let got = parse("# c\nB=1\n\nA=2\nB=3\n").unwrap();
296        let summary: Vec<_> = got
297            .iter()
298            .map(|a| (a.key.as_str(), a.value.as_str(), a.line))
299            .collect();
300        assert_eq!(summary, vec![("B", "1", 2), ("A", "2", 4), ("B", "3", 5)]);
301    }
302
303    #[test]
304    fn load_errors_name_the_path_and_reject_invalid_utf8() {
305        let dir = tempfile::tempdir().unwrap();
306        let p = dir.path().join("bad.env");
307        std::fs::write(&p, "A=1\n9=2\n").unwrap();
308        let e = load(&p).unwrap_err().to_string();
309        assert!(e.contains("bad.env") && e.contains("line 2"), "{e}");
310
311        let u = dir.path().join("utf.env");
312        std::fs::write(&u, b"A=\xff\xfe\n").unwrap();
313        let e = load(&u).unwrap_err().to_string();
314        assert!(e.contains("utf.env") && e.contains("UTF-8"), "{e}");
315    }
316}