Skip to main content

kizz_core/
dotenv.rs

1// Copyright (c) 2026 Sakura Industries LLC.
2//
3// SPDX-License-Identifier: AGPL-3.0-only
4
5//! The dotenv files that `env.load_file` and `env.read` read.
6//!
7//! A dotenv file holds one assignment per line, `NAME=value`, optionally after
8//! `export` and whitespace. Blank lines and lines whose first non-blank character
9//! is `#` are skipped. A value is either unquoted, the rest of the line with
10//! surrounding whitespace removed, or quoted:
11//!
12//! * single quotes keep every character literally, up to the closing quote;
13//! * double quotes support the escapes `\n`, `\t`, `\"` and `\\`, and no other.
14//!
15//! After a closing quote only whitespace may follow. A name starts with a letter or
16//! `_` and continues with letters, digits, and `_`. There is no `${VAR}` expansion:
17//! `$` is an ordinary character. When a name is assigned twice, the later value
18//! wins. Any other line is a syntax error that names its line, and it fails the
19//! task.
20
21use std::collections::BTreeMap;
22
23/// A line of a dotenv file that is not blank, not a comment, and not an
24/// assignment in a supported form.
25#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
26#[error("line {line}: {message}")]
27pub struct DotenvError {
28    /// The line, counting from 1.
29    pub line: usize,
30    /// What is wrong with it.
31    pub message: String,
32}
33
34/// Parse the dotenv `text` into its variables.
35///
36/// # Errors
37///
38/// Returns [`DotenvError`] for the first line that is not blank, not a comment,
39/// and not an assignment in a supported form.
40pub fn parse(text: &str) -> Result<BTreeMap<String, String>, DotenvError> {
41    let mut vars = BTreeMap::new();
42    for (line, content) in (1..).zip(text.lines()) {
43        if let Some((name, value)) =
44            parse_line(content).map_err(|message| DotenvError { line, message })?
45        {
46            vars.insert(name, value);
47        }
48    }
49    Ok(vars)
50}
51
52/// Parse one line: `None` for a blank line or a comment, the name and value of an
53/// assignment, or what is wrong with the line.
54fn parse_line(line: &str) -> Result<Option<(String, String)>, String> {
55    let line = line.trim();
56    if line.is_empty() || line.starts_with('#') {
57        return Ok(None);
58    }
59    let assignment = line
60        .strip_prefix("export")
61        .filter(|rest| rest.starts_with([' ', '\t']))
62        .map_or(line, str::trim_start);
63    let Some((name, value)) = assignment.split_once('=') else {
64        return Err(format!(
65            "expected NAME=value, a comment starting with #, or a blank line, not `{line}`"
66        ));
67    };
68    if !is_valid_name(name) {
69        return Err(format!(
70            "`{name}` is not a valid variable name: a name starts with a letter or _ and \
71             continues with letters, digits and _, with no space before ="
72        ));
73    }
74    Ok(Some((name.to_owned(), parse_value(value)?)))
75}
76
77/// Whether `name` is a variable name: a letter or `_`, then letters, digits, and
78/// `_`.
79fn is_valid_name(name: &str) -> bool {
80    let mut chars = name.chars();
81    chars
82        .next()
83        .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
84        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
85}
86
87/// Parse the value after `=`: unquoted, single-quoted, or double-quoted.
88fn parse_value(value: &str) -> Result<String, String> {
89    let value = value.trim();
90    let mut chars = value.chars();
91    let (text, rest) = match chars.next() {
92        Some('\'') => {
93            let inner = chars.as_str();
94            let Some((text, rest)) = inner.split_once('\'') else {
95                return Err("the single-quoted value has no closing '".to_owned());
96            };
97            (text.to_owned(), rest)
98        },
99        Some('"') => parse_double_quoted(chars.as_str())?,
100        _ => return Ok(value.to_owned()),
101    };
102    if rest.trim().is_empty() {
103        Ok(text)
104    } else {
105        Err(format!(
106            "unexpected `{}` after the closing quote",
107            rest.trim()
108        ))
109    }
110}
111
112/// Parse a double-quoted value after its opening quote, returning the value and
113/// the text after the closing quote.
114fn parse_double_quoted(inner: &str) -> Result<(String, &str), String> {
115    let mut text = String::new();
116    let mut chars = inner.chars();
117    loop {
118        match chars.next() {
119            None => return Err("the double-quoted value has no closing \"".to_owned()),
120            Some('"') => return Ok((text, chars.as_str())),
121            Some('\\') => {
122                match chars.next() {
123                    Some('n') => text.push('\n'),
124                    Some('t') => text.push('\t'),
125                    Some('"') => text.push('"'),
126                    Some('\\') => text.push('\\'),
127                    Some(other) => {
128                        return Err(format!(
129                            "`\\{other}` is not a supported escape; double quotes support \\n, \
130                             \\t, \\\" and \\\\"
131                        ));
132                    },
133                    None => return Err("the double-quoted value has no closing \"".to_owned()),
134                }
135            },
136            Some(other) => text.push(other),
137        }
138    }
139}
140
141/// Unit tests for the dotenv parser.
142#[cfg(test)]
143#[allow(
144    clippy::disallowed_macros,
145    clippy::disallowed_methods,
146    reason = "test code: the tests assert and lock"
147)]
148mod tests {
149    use std::collections::BTreeMap;
150
151    use super::{DotenvError, parse};
152
153    /// The variables of `pairs`.
154    fn vars(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
155        pairs
156            .iter()
157            .map(|&(name, value)| (name.to_owned(), value.to_owned()))
158            .collect()
159    }
160
161    /// `NAME=value` lines, comments, blank lines, and the `export` prefix.
162    #[test]
163    fn assignments_comments_blank_lines_and_export() {
164        let text = "# a comment\n\nPLAIN=value\n  INDENTED=yes  \nexport EXPORTED=1\nexport\tTABBED=2\n   \
165                    # indented comment\nEMPTY=\n_UNDER_9=x y  z\nexport=not a prefix\nURL=http://h/p#frag\r\n";
166        assert_eq!(
167            parse(text),
168            Ok(vars(&[
169                ("PLAIN", "value"),
170                ("INDENTED", "yes"),
171                ("EXPORTED", "1"),
172                ("TABBED", "2"),
173                ("EMPTY", ""),
174                ("_UNDER_9", "x y  z"),
175                ("export", "not a prefix"),
176                ("URL", "http://h/p#frag"),
177            ]))
178        );
179    }
180
181    /// Single quotes keep every character literally, escapes and `#` included.
182    #[test]
183    fn single_quotes_are_literal() {
184        assert_eq!(
185            parse("A='  spaced  '\nB='back\\n\\slash \"q\" # not a comment'\nC=''\n"),
186            Ok(vars(&[
187                ("A", "  spaced  "),
188                ("B", "back\\n\\slash \"q\" # not a comment"),
189                ("C", ""),
190            ]))
191        );
192    }
193
194    /// Double quotes support `\n`, `\t`, `\"`, and `\\`.
195    #[test]
196    fn double_quotes_support_each_escape() {
197        assert_eq!(
198            parse(
199                "NL=\"a\\nb\"\nTAB=\"a\\tb\"\nQUOTE=\"say \\\"hi\\\"\"\nSLASH=\"c:\\\\dir\"\nALL=\" \
200                 \\n\\t\\\"\\\\ \"\nSINGLE=\"it's\"\n"
201            ),
202            Ok(vars(&[
203                ("NL", "a\nb"),
204                ("TAB", "a\tb"),
205                ("QUOTE", "say \"hi\""),
206                ("SLASH", "c:\\dir"),
207                ("ALL", " \n\t\"\\ "),
208                ("SINGLE", "it's"),
209            ]))
210        );
211    }
212
213    /// `${VAR}` and `$VAR` stay as written, in every form, even when the variable
214    /// is set earlier in the file.
215    #[test]
216    fn there_is_no_expansion() {
217        assert_eq!(
218            parse("HOME=/home/me\nA=${HOME}/x\nB=\"$HOME/y\"\nC='${HOME}'\n"),
219            Ok(vars(&[
220                ("HOME", "/home/me"),
221                ("A", "${HOME}/x"),
222                ("B", "$HOME/y"),
223                ("C", "${HOME}"),
224            ]))
225        );
226    }
227
228    /// A later assignment of the same name wins.
229    #[test]
230    fn the_later_assignment_wins() {
231        assert_eq!(parse("A=1\nA=2\n"), Ok(vars(&[("A", "2")])));
232    }
233
234    /// Every line that is not blank, not a comment, and not an assignment in a
235    /// supported form is an error that names its line (PI6).
236    #[test]
237    fn syntax_errors_name_the_line() {
238        for (text, line, part) in [
239            ("A=1\njust words\n", 2, "expected NAME=value"),
240            ("A=1\n\n=value\n", 3, "is not a valid variable name"),
241            ("1A=x\n", 1, "`1A` is not a valid variable name"),
242            ("A B=x\n", 1, "`A B` is not a valid variable name"),
243            ("A =x\n", 1, "with no space before ="),
244            ("export A\n", 1, "expected NAME=value"),
245            ("A='open\n", 1, "no closing '"),
246            ("A=\"open\n", 1, "no closing \""),
247            ("A=\"end\\\n", 1, "no closing \""),
248            ("A=\"bad \\x\"\n", 1, "`\\x` is not a supported escape"),
249            (
250                "A='x' trailing\n",
251                1,
252                "unexpected `trailing` after the closing quote",
253            ),
254            ("A=\"x\" # comment\n", 1, "unexpected `# comment`"),
255        ] {
256            let Err(DotenvError {
257                line: found,
258                message,
259            }) = parse(text)
260            else {
261                panic!("{text:?} must be a syntax error");
262            };
263            assert_eq!(found, line, "{text:?}: {message}");
264            assert!(message.contains(part), "{part:?} in {message}");
265        }
266        assert_eq!(
267            parse("A=1\nbad\n").map_err(|error| error.to_string()),
268            Err(
269                "line 2: expected NAME=value, a comment starting with #, or a blank line, not \
270                 `bad`"
271                    .to_owned()
272            )
273        );
274    }
275}