1use std::collections::BTreeMap;
22
23#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
26#[error("line {line}: {message}")]
27pub struct DotenvError {
28 pub line: usize,
30 pub message: String,
32}
33
34pub 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
52fn 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
77fn 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
87fn 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
112fn 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#[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 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 #[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 #[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 #[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 #[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 #[test]
230 fn the_later_assignment_wins() {
231 assert_eq!(parse("A=1\nA=2\n"), Ok(vars(&[("A", "2")])));
232 }
233
234 #[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}