eclipse-core 0.13.2

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
//! Strict, dependency-free `.env` parser.
//!
//! Plain `KEY=VALUE` lines with `#` comments and optional quotes. There is deliberately
//! no interpolation, command substitution or `${VAR}` expansion: a `.env` file holds
//! secrets and is read before `config.toml`, so letting values reference each other (or
//! the shell) would make the load order matter and open a recursion/injection surface.

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

/// One `KEY=VALUE` assignment, with where it came from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Assignment {
    pub key: String,
    pub value: String,
    /// 1-based line number in the source text.
    pub line: usize,
}

/// Parse .env text. Returns assignments in file order.
///
/// Duplicate keys are all returned, in order; it is [`load_files`] that collapses them
/// (last wins). Errors are `Error::Config` messages starting with `line N:`.
pub fn parse(text: &str) -> Result<Vec<Assignment>> {
    parse_inner(text).map_err(Error::Config)
}

fn parse_inner(text: &str) -> std::result::Result<Vec<Assignment>, String> {
    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
    let mut out = Vec::new();
    for (idx, raw) in text.lines().enumerate() {
        let line = idx + 1;
        let raw = raw.trim_end_matches('\r').trim();
        if raw.is_empty() || raw.starts_with('#') {
            continue;
        }
        let body = strip_export(raw);
        let Some((key, value)) = body.split_once('=') else {
            return Err(format!("line {line}: expected KEY=VALUE, found no '='"));
        };
        let key = key.trim();
        if !valid_key(key) {
            return Err(format!("line {line}: invalid key {key:?}"));
        }
        let value = parse_value(value).map_err(|m| format!("line {line}: {m}"))?;
        out.push(Assignment {
            key: key.to_string(),
            value,
            line,
        });
    }
    Ok(out)
}

/// `export` only counts as a prefix when whitespace follows, so a variable literally named
/// `export` (`export=1`) still parses.
fn strip_export(s: &str) -> &str {
    match s.strip_prefix("export") {
        Some(rest) if rest.starts_with(char::is_whitespace) => rest.trim_start(),
        _ => s,
    }
}

fn valid_key(key: &str) -> bool {
    let mut chars = key.chars();
    matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_')
        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}

fn parse_value(raw: &str) -> std::result::Result<String, String> {
    let v = raw.trim_start();
    match v.chars().next() {
        Some('\'') => {
            let inner = &v[1..];
            let end = inner.find('\'').ok_or("unbalanced single quote")?;
            check_tail(&inner[end + 1..])?;
            Ok(inner[..end].to_string())
        }
        Some('"') => {
            let mut value = String::new();
            let mut chars = v[1..].char_indices();
            while let Some((i, c)) = chars.next() {
                match c {
                    '"' => {
                        check_tail(&v[1 + i + 1..])?;
                        return Ok(value);
                    }
                    // Only `\"` and `\\` are escapes; any other backslash is kept as-is so
                    // Windows paths and regexes survive without doubling.
                    '\\' => match chars.next() {
                        Some((_, e @ ('"' | '\\'))) => value.push(e),
                        Some((_, other)) => {
                            value.push('\\');
                            value.push(other);
                        }
                        None => break,
                    },
                    c => value.push(c),
                }
            }
            Err("unbalanced double quote".to_string())
        }
        _ => {
            // `#` only starts a comment at the start of the value or after whitespace, so
            // `a#b` (common in passwords and URLs) is preserved.
            let mut prev_ws = true;
            let mut end = v.len();
            for (i, c) in v.char_indices() {
                if c == '#' && prev_ws {
                    end = i;
                    break;
                }
                prev_ws = c.is_whitespace();
            }
            Ok(v[..end].trim_end().to_string())
        }
    }
}

/// After a closing quote only whitespace or a whitespace-separated comment may follow.
fn check_tail(tail: &str) -> std::result::Result<(), String> {
    let trimmed = tail.trim_start();
    if trimmed.is_empty() || (trimmed.starts_with('#') && tail.starts_with(char::is_whitespace)) {
        Ok(())
    } else {
        Err("unexpected content after closing quote".to_string())
    }
}

/// Read one file. A missing file is Ok(vec![]), not an error.
///
/// Invalid UTF-8 is an error rather than being converted lossily: silently altering a
/// secret would be worse than refusing to start.
pub fn load(path: &Path) -> Result<Vec<Assignment>> {
    let bytes = match std::fs::read(path) {
        Ok(b) => b,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(Error::io(path, e)),
    };
    let text = String::from_utf8(bytes)
        .map_err(|_| Error::Config(format!("{}: file is not valid UTF-8", path.display())))?;
    parse_inner(&text).map_err(|m| Error::Config(format!("{}: {m}", path.display())))
}

/// Read several files, later ones winning on key collision.
pub fn load_files(paths: &[PathBuf]) -> Result<BTreeMap<String, String>> {
    let mut map = BTreeMap::new();
    for path in paths {
        for a in load(path)? {
            map.insert(a.key, a.value);
        }
    }
    Ok(map)
}

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

    fn kv(text: &str) -> Vec<(String, String)> {
        parse(text)
            .unwrap()
            .into_iter()
            .map(|a| (a.key, a.value))
            .collect()
    }

    fn one(text: &str) -> String {
        let mut v = kv(text);
        assert_eq!(v.len(), 1);
        v.remove(0).1
    }

    fn err(text: &str) -> String {
        parse(text).unwrap_err().to_string()
    }

    #[test]
    fn simple_assignment() {
        assert_eq!(kv("A=1"), vec![("A".into(), "1".into())]);
        assert_eq!(one("  K_2 =  spaced value  "), "spaced value");
        assert_eq!(one("EMPTY="), "");
    }

    #[test]
    fn comments_and_blank_lines() {
        let got = kv("# top\n\n   \n  # indented\nA=1\n");
        assert_eq!(got, vec![("A".into(), "1".into())]);
    }

    #[test]
    fn export_prefix() {
        assert_eq!(kv("export A=1"), vec![("A".into(), "1".into())]);
        assert_eq!(kv("export   B = 2"), vec![("B".into(), "2".into())]);
        assert_eq!(kv("export=3"), vec![("export".into(), "3".into())]);
    }

    #[test]
    fn single_quotes_are_literal() {
        assert_eq!(one("A='$HOME'"), "$HOME");
        assert_eq!(one(r"A='a\nb'"), r"a\nb");
        assert_eq!(one(r"A='a\nb'").chars().count(), 4);
        assert_eq!(one("A='  keep  '"), "  keep  ");
        assert_eq!(one("A='x' # note"), "x");
    }

    #[test]
    fn double_quote_escapes() {
        assert_eq!(one(r#"A="say \"hi\"""#), r#"say "hi""#);
        assert_eq!(one(r#"A="back\\slash""#), r"back\slash");
        assert_eq!(one(r#"A="$HOME ${X}""#), "$HOME ${X}");
        assert_eq!(one(r#"A="  keep  " # c"#), "  keep  ");
        assert_eq!(one(r#"A="a\nb""#), r"a\nb");
    }

    #[test]
    fn invalid_key_names_line() {
        let e = err("A=1\n1X=2\n");
        assert!(e.contains("line 2"), "{e}");
        assert!(e.contains("invalid key \"1X\""), "{e}");
        assert!(err("A-B=1").contains("invalid key"));
        assert!(err("=1").contains("line 1"));
        let e = err("A=1\nNOEQUALS\n");
        assert!(e.contains("line 2"), "{e}");
    }

    #[test]
    fn unbalanced_quote() {
        for t in ["A='x", "A=\"x", "A=\"x\\\"", "A=\"x\\"] {
            let e = err(t);
            assert!(e.contains("line 1") && e.contains("unbalanced"), "{t}: {e}");
        }
        assert!(err("\nB=1\nA='x").contains("line 3"));
    }

    #[test]
    fn trailing_junk_after_quote() {
        assert!(err("A='x' y").contains("after closing quote"));
        assert!(err("A=\"x\"y").contains("line 1"));
        assert!(err("A=\"x\"#c").contains("after closing quote"));
        assert_eq!(one("A=\"x\"   "), "x");
    }

    #[test]
    fn bom_and_crlf() {
        let got = kv("\u{feff}A=1\r\n# c\r\nB='two'\r\nC=3\r\n");
        assert_eq!(
            got,
            vec![
                ("A".into(), "1".into()),
                ("B".into(), "two".into()),
                ("C".into(), "3".into())
            ]
        );
    }

    #[test]
    fn hash_in_unquoted_value() {
        assert_eq!(one("A=a#b"), "a#b");
        assert_eq!(one("A=a #b"), "a");
        assert_eq!(one("A=a\t# b"), "a");
        assert_eq!(one("A=#b"), "");
        assert_eq!(one("A=http://x/#frag"), "http://x/#frag");
    }

    #[test]
    fn duplicates_last_wins_through_load_files() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join(".env");
        std::fs::write(&p, "A=1\nB=x\nA=2\n").unwrap();
        assert_eq!(load(&p).unwrap().len(), 3);
        let m = load_files(&[p]).unwrap();
        assert_eq!(m["A"], "2");
        assert_eq!(m["B"], "x");
    }

    #[test]
    fn missing_file_empty_and_later_overrides() {
        let dir = tempfile::tempdir().unwrap();
        let missing = dir.path().join("nope.env");
        assert_eq!(load(&missing).unwrap(), vec![]);

        let a = dir.path().join("a.env");
        let b = dir.path().join("b.env");
        std::fs::write(&a, "K=shared\nONLY_A=1\n").unwrap();
        std::fs::write(&b, "K=profile\n").unwrap();
        let m = load_files(&[a, missing, b]).unwrap();
        assert_eq!(m["K"], "profile");
        assert_eq!(m["ONLY_A"], "1");
    }

    #[test]
    fn parse_keeps_order_and_line_numbers() {
        let got = parse("# c\nB=1\n\nA=2\nB=3\n").unwrap();
        let summary: Vec<_> = got
            .iter()
            .map(|a| (a.key.as_str(), a.value.as_str(), a.line))
            .collect();
        assert_eq!(summary, vec![("B", "1", 2), ("A", "2", 4), ("B", "3", 5)]);
    }

    #[test]
    fn load_errors_name_the_path_and_reject_invalid_utf8() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("bad.env");
        std::fs::write(&p, "A=1\n9=2\n").unwrap();
        let e = load(&p).unwrap_err().to_string();
        assert!(e.contains("bad.env") && e.contains("line 2"), "{e}");

        let u = dir.path().join("utf.env");
        std::fs::write(&u, b"A=\xff\xfe\n").unwrap();
        let e = load(&u).unwrap_err().to_string();
        assert!(e.contains("utf.env") && e.contains("UTF-8"), "{e}");
    }
}