Skip to main content

agent_first_data/document/format/
dotenv.rs

1//! Source-preserving dotenv backend.
2
3use crate::document::{DocumentError, DocumentResult, Value};
4use std::collections::BTreeMap;
5
6const MAX_DOTENV_VALUE_BYTES: usize = 1024 * 1024;
7
8#[derive(Debug)]
9pub struct DotenvDocument<'a> {
10    source: &'a str,
11    keys: Vec<String>,
12}
13
14impl<'a> DotenvDocument<'a> {
15    pub fn parse(source: &'a str) -> DocumentResult<Self> {
16        let value = parse_semantic(source)?;
17        let keys = value
18            .as_object()
19            .map(|object| object.keys().cloned().collect())
20            .unwrap_or_default();
21        Ok(Self { source, keys })
22    }
23
24    fn has_key(&self, key: &str) -> bool {
25        self.keys.iter().any(|candidate| candidate == key)
26    }
27
28    #[allow(dead_code)]
29    fn source(&self) -> &'a str {
30        self.source
31    }
32}
33
34/// Parse dotenv without shell execution, environment lookup, or variable expansion.
35pub fn load(content: &str) -> DocumentResult<Value> {
36    parse_semantic(content)
37}
38
39fn parse_semantic(content: &str) -> DocumentResult<Value> {
40    if content.starts_with('\u{feff}') {
41        return Err(DocumentError::SourceRefused {
42            format: "dotenv".to_string(),
43            detail: "line 1, column 1: unexpected UTF-8 byte-order mark (BOM)".to_string(),
44        });
45    }
46    let mut values = BTreeMap::new();
47
48    for (line_number, raw_line) in logical_lines(content)? {
49        let raw_line = raw_line.trim_suffix('\n');
50        let line = raw_line.trim_suffix('\r').trim_start();
51        if line.is_empty() || line.starts_with('#') {
52            continue;
53        }
54
55        let assignment = line
56            .strip_prefix("export")
57            .and_then(|rest| {
58                rest.starts_with(char::is_whitespace)
59                    .then(|| rest.trim_start())
60            })
61            .unwrap_or(line);
62        let Some((raw_key, raw_value)) = assignment.split_once('=') else {
63            return Err(parse_error(line_number, "expected KEY=value assignment"));
64        };
65        let key = raw_key.trim();
66        if !valid_key(key) {
67            return Err(parse_error(line_number, "invalid variable name"));
68        }
69
70        let value = parse_value(raw_value.trim_start(), line_number)?;
71        if values.contains_key(key) {
72            return Err(parse_error(line_number, "duplicate variable name"));
73        }
74        values.insert(key.to_string(), Value::String(value));
75    }
76
77    Ok(Value::Object(values))
78}
79
80/// Split `content` into logical lines, joining the physical lines a quoted
81/// value spans.
82///
83/// A quote only opens a value where a value can start: after the `=`, before
84/// any other non-whitespace character, and never inside a comment. Tracking
85/// less than that made an ordinary English comment — `# set KEY=value if it
86/// isn't already there` — open a quote at the apostrophe that no later line
87/// closed, swallowing the rest of the file into one unparseable line and
88/// yielding zero keys with no error at all.
89fn logical_lines(content: &str) -> DocumentResult<Vec<(usize, &str)>> {
90    let mut lines = Vec::new();
91    let mut start = 0;
92    let mut first_line = 1;
93    let mut line_number = 1;
94    let mut quote = None;
95    let mut quote_opened_at = 0;
96    let mut escaped = false;
97    let mut value_may_open = false;
98    let mut assignment_started = false;
99    let mut in_comment = false;
100    let mut at_line_start = true;
101
102    for (offset, character) in content.char_indices() {
103        if quote.is_none() {
104            if at_line_start && !character.is_whitespace() {
105                at_line_start = false;
106                in_comment = character == '#';
107            }
108            if !in_comment {
109                if value_may_open
110                    && character.is_whitespace()
111                    && character != '\n'
112                    && character != '\r'
113                {
114                    continue;
115                }
116                if value_may_open && (character == '\'' || character == '"') {
117                    quote = Some(character);
118                    quote_opened_at = line_number;
119                    value_may_open = false;
120                } else if character == '=' && !assignment_started {
121                    value_may_open = true;
122                    assignment_started = true;
123                } else if !character.is_whitespace() {
124                    // The value has already started unquoted, so a quote from
125                    // here on is an ordinary character, not a delimiter.
126                    value_may_open = false;
127                }
128            }
129        } else if escaped {
130            escaped = false;
131        } else if character == '\\' {
132            escaped = true;
133        } else if Some(character) == quote {
134            quote = None;
135        }
136        if character == '\n' && quote.is_none() {
137            lines.push((first_line, &content[start..offset + 1]));
138            start = offset + 1;
139            first_line = line_number + 1;
140        }
141        if character == '\n' {
142            line_number += 1;
143            if quote.is_none() {
144                value_may_open = false;
145                assignment_started = false;
146                in_comment = false;
147                at_line_start = true;
148            }
149        }
150    }
151    if quote.is_some() {
152        // Reaching end of input inside a quote means the file is malformed.
153        // Reporting zero keys instead let `value --default` hand a caller its
154        // fallback while the real value sat in the file, unread and unmentioned.
155        return Err(parse_error(quote_opened_at, "unterminated quoted value"));
156    }
157    if start < content.len() || content.is_empty() {
158        lines.push((first_line, &content[start..]));
159    }
160    Ok(lines)
161}
162
163/// dotenv has no whole-document writer: re-rendering from the generic value would
164/// lose comments, ordering, and quoting. [`Format::save`](super::Format::save)
165/// therefore refuses; edits go through `set_preserving` / `unset_preserving`,
166/// which splice only the touched assignment.
167pub fn save(_value: &Value) -> DocumentResult<String> {
168    Err(DocumentError::UnsupportedOperation {
169        format: "dotenv".to_string(),
170        operation: "save".to_string(),
171        detail: "dotenv files are read-only because rewriting would lose comments, ordering, and quoting"
172            .to_string(),
173    })
174}
175
176/// Set one variable while preserving every other source byte: an existing
177/// assignment is rewritten in place, and a missing one is appended as a new line.
178pub(crate) fn set_preserving(content: &str, key: &str, value: &Value) -> DocumentResult<String> {
179    let Value::String(value) = value else {
180        return Err(unsupported("set", "dotenv values are strings"));
181    };
182    let replacement = encode_value(value);
183    edit_line(content, key, Some(&replacement))
184}
185
186/// Remove one existing assignment while preserving every other source byte.
187pub(crate) fn unset_preserving(content: &str, key: &str) -> DocumentResult<String> {
188    edit_line(content, key, None)
189}
190
191fn edit_line(content: &str, key: &str, replacement: Option<&str>) -> DocumentResult<String> {
192    // The path is at fault here, not the file: a parse error would send the
193    // caller looking for a malformed line that does not exist.
194    if !valid_key(key) {
195        let operation = if replacement.is_some() {
196            "set"
197        } else {
198            "unset"
199        };
200        return Err(unsupported(
201            operation,
202            &format!("`{key}` is not a dotenv variable name"),
203        ));
204    }
205    let document = DotenvDocument::parse(content).map_err(|error| with_path(error, key))?;
206    let mut output = String::with_capacity(content.len());
207    let found = document.has_key(key);
208    for (line_number, line) in logical_lines(content)? {
209        let body = line.trim_suffix('\n');
210        let bare = body.trim_suffix('\r');
211        let trimmed = bare.trim_start();
212        let assignment = trimmed
213            .strip_prefix("export")
214            .and_then(|rest| {
215                rest.starts_with(char::is_whitespace)
216                    .then(|| rest.trim_start())
217            })
218            .unwrap_or(trimmed);
219        let matches = assignment
220            .split_once('=')
221            .is_some_and(|(name, _)| name.trim() == key);
222        if matches {
223            if let Some(value) = replacement {
224                let prefix_len = bare.len() - assignment.len();
225                let prefix = &body[..prefix_len];
226                let (name, old_value) = assignment.split_once('=').unwrap_or((key, ""));
227                let old_trimmed = old_value.trim_start();
228                let spacing = &old_value[..old_value.len() - old_trimmed.len()];
229                let suffix = value_suffix(old_trimmed, line_number)?;
230                output.push_str(prefix);
231                output.push_str(name);
232                output.push('=');
233                output.push_str(spacing);
234                output.push_str(value);
235                output.push_str(suffix);
236                if body.ends_with('\r') {
237                    output.push('\r');
238                }
239                if line.ends_with('\n') {
240                    output.push('\n');
241                }
242            }
243        } else {
244            output.push_str(line);
245        }
246    }
247    if !found {
248        if let Some(value) = replacement {
249            let newline = if content.contains("\r\n") {
250                "\r\n"
251            } else {
252                "\n"
253            };
254            if !output.is_empty() && !output.ends_with('\n') {
255                output.push_str(newline);
256            }
257            output.push_str(key);
258            output.push('=');
259            output.push_str(value);
260            if content.ends_with('\n') || !output.ends_with('\n') {
261                output.push_str(newline);
262            }
263            return Ok(output);
264        }
265        return Err(DocumentError::PathNotFound {
266            path: key.to_string(),
267        });
268    }
269    Ok(output)
270}
271
272/// Encode a value so the file reads back the same here and when a shell
273/// sources it (`set -a; . ./.env`): bare only for characters no shell treats
274/// specially, plain double quotes when nothing inside would expand or need an
275/// escape, single quotes (no expansion at all) when the value allows them, and
276/// double quotes with `$` and `` ` `` escaped otherwise.
277///
278/// Newlines and tabs are written literally inside the quotes, since a shell
279/// reads `\n` in double quotes as two characters. A carriage return is the
280/// one exception: written as `\r`, so editors and line-ending conversion
281/// cannot silently change the value, at the cost of a shell seeing `\r`.
282fn encode_value(value: &str) -> String {
283    if !value.is_empty()
284        && value.chars().all(|c| {
285            c.is_alphanumeric()
286                || matches!(c, '_' | '.' | '/' | ':' | '@' | '%' | '+' | ',' | '=' | '-')
287        })
288    {
289        return value.to_string();
290    }
291    // Double quotes need nothing escaped here, and nothing in them expands.
292    if !value.contains(['$', '`', '\\', '"', '\r']) {
293        return format!("\"{value}\"");
294    }
295    // The reader treats `\'` inside single quotes as an escaped quote, so a
296    // trailing backslash would swallow the closing quote.
297    if !value.contains(['\'', '\r']) && !value.ends_with('\\') {
298        return format!("'{value}'");
299    }
300    format!(
301        "\"{}\"",
302        value
303            .replace('\\', "\\\\")
304            .replace('"', "\\\"")
305            .replace('$', "\\$")
306            .replace('`', "\\`")
307            .replace('\r', "\\r")
308    )
309}
310
311fn unsupported(operation: &str, detail: &str) -> DocumentError {
312    DocumentError::UnsupportedOperation {
313        format: "dotenv".to_string(),
314        operation: operation.to_string(),
315        detail: detail.to_string(),
316    }
317}
318
319fn valid_key(key: &str) -> bool {
320    let mut chars = key.chars();
321    chars
322        .next()
323        .is_some_and(|first| first == '_' || first.is_ascii_alphabetic())
324        && chars.all(|character| character == '_' || character.is_ascii_alphanumeric())
325}
326
327fn parse_value(input: &str, line_number: usize) -> DocumentResult<String> {
328    if input.len() > MAX_DOTENV_VALUE_BYTES {
329        return Err(parse_error(line_number, "value exceeds 1 MiB"));
330    }
331    match input.chars().next() {
332        Some('\'') => parse_quoted(input, '\'', line_number).map(|(value, _)| value),
333        Some('"') => parse_quoted(input, '"', line_number).map(|(value, _)| value),
334        _ => parse_unquoted(input),
335    }
336}
337
338fn parse_quoted(input: &str, quote: char, line_number: usize) -> DocumentResult<(String, usize)> {
339    let mut output = String::new();
340    let mut escaped = false;
341
342    for (offset, character) in input[quote.len_utf8()..].char_indices() {
343        if escaped {
344            match (quote, character) {
345                ('"', 'n') => output.push('\n'),
346                ('"', 'r') => output.push('\r'),
347                ('"', 't') => output.push('\t'),
348                ('"', '\\') => output.push('\\'),
349                ('"', '"') => output.push('"'),
350                ('"', '$') => output.push('$'),
351                ('"', '`') => output.push('`'),
352                ('\'', '\'') => output.push('\''),
353                (_, other) => {
354                    output.push('\\');
355                    output.push(other);
356                }
357            }
358            escaped = false;
359            continue;
360        }
361        if character == '\\' {
362            escaped = true;
363            continue;
364        }
365        if character == quote {
366            let remainder_index = quote.len_utf8() + offset + character.len_utf8();
367            let remainder = input[remainder_index..].trim_start();
368            if !remainder.is_empty() && !remainder.starts_with('#') {
369                return Err(parse_error(
370                    line_number,
371                    "unexpected content after quoted value",
372                ));
373            }
374            return Ok((output, remainder_index));
375        }
376        output.push(character);
377    }
378
379    Err(parse_error(line_number, "unterminated quoted value"))
380}
381
382/// Keep only an actual trailing comment or whitespace, never a ` #` inside a
383/// quoted value. The parser and editor share the quote boundary.
384fn value_suffix(input: &str, line_number: usize) -> DocumentResult<&str> {
385    if let Some(quote @ ('\'' | '"')) = input.chars().next() {
386        let (_, end) = parse_quoted(input, quote, line_number)?;
387        return Ok(&input[end..]);
388    }
389    let mut escaped = false;
390    let mut whitespace = None;
391    for (offset, character) in input.char_indices() {
392        if escaped {
393            escaped = false;
394        } else if character == '\\' {
395            escaped = true;
396            continue;
397        } else if character == '#'
398            && let Some(start) = whitespace
399        {
400            return Ok(&input[start..]);
401        }
402        if character.is_whitespace() {
403            whitespace.get_or_insert(offset);
404        } else {
405            whitespace = None;
406        }
407    }
408    Ok(&input[whitespace.unwrap_or(input.len())..])
409}
410
411fn parse_unquoted(input: &str) -> DocumentResult<String> {
412    let mut output = String::new();
413    let mut escaped = false;
414
415    for character in input.chars() {
416        if escaped {
417            output.push(character);
418            escaped = false;
419        } else if character == '\\' {
420            escaped = true;
421        } else if character == '#' && output.chars().last().is_some_and(char::is_whitespace) {
422            break;
423        } else {
424            output.push(character);
425        }
426    }
427    if escaped {
428        output.push('\\');
429    }
430    Ok(output.trim_end().to_string())
431}
432
433fn parse_error(line_number: usize, detail: &str) -> DocumentError {
434    DocumentError::ParseError {
435        format: "dotenv".to_string(),
436        detail: format!("line {line_number}: {detail}"),
437    }
438}
439
440fn with_path(error: DocumentError, path: &str) -> DocumentError {
441    match error {
442        DocumentError::ParseError { format, detail } => DocumentError::ParseError {
443            format,
444            detail: format!("path `{path}`: {detail}"),
445        },
446        other => other,
447    }
448}
449
450#[cfg(test)]
451mod tests {
452    use super::*;
453
454    #[test]
455    fn a_comment_does_not_swallow_the_file() {
456        // The apostrophe in "isn't" follows an `=` earlier on the same comment
457        // line. Treating it as an opening quote consumed every later line, so
458        // the file parsed to zero keys and reported success — a caller using
459        // `--default` got its fallback while the real value sat in the file.
460        let source =
461            "# set KEY=value if it isn't already there\nAPI_HOST=example.com\nAPI_PORT=8080\n";
462        let Value::Object(values) = load(source).unwrap() else {
463            panic!("expected an object");
464        };
465        assert_eq!(values.len(), 2);
466        assert_eq!(
467            values.get("API_HOST"),
468            Some(&Value::String("example.com".to_string()))
469        );
470    }
471
472    #[test]
473    fn a_quote_after_the_value_started_is_literal() {
474        let Value::Object(values) = load("MESSAGE=it isn't quoted\n").unwrap() else {
475            panic!("expected an object");
476        };
477        assert_eq!(
478            values.get("MESSAGE"),
479            Some(&Value::String("it isn't quoted".to_string()))
480        );
481    }
482
483    #[test]
484    fn quoted_values_still_span_lines() {
485        let Value::Object(values) = load("A=\"line1\nline2\"\nB=after\n").unwrap() else {
486            panic!("expected an object");
487        };
488        assert_eq!(
489            values.get("A"),
490            Some(&Value::String("line1\nline2".to_string()))
491        );
492        assert_eq!(values.get("B"), Some(&Value::String("after".to_string())));
493    }
494
495    #[test]
496    fn editing_a_multiline_value_replaces_its_whole_assignment() {
497        let source = "# before\r\n export A = \"first # value\r\nB=inside\"\t# keep\r\nB=after\r\n";
498        let value = Value::String("\"quoted\"\r\t\n".into());
499        let edited = set_preserving(source, "A", &value).unwrap();
500        assert!(edited.starts_with("# before\r\n export A = "));
501        assert!(edited.ends_with("\t# keep\r\nB=after\r\n"));
502        assert!(!edited.contains("B=inside"));
503        let Value::Object(values) = load(&edited).unwrap() else {
504            panic!("expected an object");
505        };
506        assert_eq!(values["A"], value);
507        assert_eq!(values["B"], Value::String("after".into()));
508        assert_eq!(
509            unset_preserving(source, "A").unwrap(),
510            "# before\r\nB=after\r\n"
511        );
512    }
513
514    #[test]
515    fn written_quotes_and_comment_like_values_round_trip() {
516        for value in [
517            "\"quoted\"",
518            "'quoted'",
519            "x=\"literal",
520            "x # value",
521            "a\r\nb\tc",
522        ] {
523            let value = Value::String(value.into());
524            let edited = set_preserving("A=old # keep\n", "A", &value).unwrap();
525            let Value::Object(values) = load(&edited).unwrap() else {
526                panic!("expected an object");
527            };
528            assert_eq!(values["A"], value, "{edited}");
529            assert!(edited.ends_with(" # keep\n"));
530        }
531        assert_eq!(
532            set_preserving("A=\"old # value\"\n", "A", &Value::String("new".into())).unwrap(),
533            "A=new\n"
534        );
535    }
536
537    /// A written value must mean the same thing to a shell that sources the
538    /// file as it does to this reader, and must never run anything there.
539    #[cfg(unix)]
540    #[test]
541    fn written_values_are_inert_when_a_shell_sources_the_file() {
542        let dir = std::env::temp_dir().join(format!("afdata-dotenv-{}", std::process::id()));
543        std::fs::create_dir_all(&dir).unwrap();
544        let file = dir.join("t.env");
545        for value in [
546            "x;touch pwned",
547            "a $(touch pwned)",
548            "`touch pwned`",
549            "it's $HOME",
550            "it's `x` \\ $y\\",
551            "~/path",
552            "a|b&c>d<e*f?g[h]",
553            "plain-value_1.2",
554            "line1\nline2\tend",
555            "it's\nmulti $x",
556            "a\\\nb",
557        ] {
558            let value = Value::String(value.into());
559            let edited = set_preserving("", "A", &value).unwrap();
560            let Value::Object(values) = load(&edited).unwrap() else {
561                panic!("expected an object");
562            };
563            assert_eq!(values["A"], value, "{edited}");
564            std::fs::write(&file, &edited).unwrap();
565            let output = std::process::Command::new("sh")
566                .arg("-c")
567                .arg("set -a; . ./t.env; printf %s \"$A\"")
568                .current_dir(&dir)
569                .output()
570                .unwrap();
571            assert!(output.status.success(), "{edited}");
572            assert_eq!(
573                Value::String(String::from_utf8(output.stdout).unwrap()),
574                value,
575                "{edited}"
576            );
577            assert!(!dir.join("pwned").exists(), "{edited}");
578        }
579        std::fs::remove_dir_all(&dir).unwrap();
580    }
581
582    #[test]
583    fn later_equals_signs_cannot_open_an_unquoted_value() {
584        let Value::Object(values) = load("A=query=\"literal\nB=after\n").unwrap() else {
585            panic!("expected an object");
586        };
587        assert_eq!(values["A"], Value::String("query=\"literal".into()));
588        assert_eq!(values["B"], Value::String("after".into()));
589    }
590
591    #[test]
592    fn an_unterminated_quote_is_a_parse_error() {
593        // Silence was the unacceptable answer here: an unreadable file has to
594        // say so rather than present itself as an empty one.
595        let error = load("A=\"unterminated\nB=after\n").unwrap_err();
596        assert_eq!(error.code(), "document_parse_failed");
597    }
598}