1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
use regex::{Captures, Regex};
use errors::*;
pub type ParsedLine = Result<Option<(String, String)>>;
pub fn parse_line(line: &str) -> ParsedLine {
lazy_static! {
static ref LINE_REGEX: Regex = Regex::new(r#"(?x)
^(
\s*
(
\#.*| # A comment, or...
\s*| # ...an empty string, or...
(export\s+)? # ...(optionally preceded by "export")...
(?P<key>[A-Za-z_][A-Za-z0-9_]*) # ...a key,...
= # ...then an equal sign,...
(?P<value>.+?)? # ...and then its corresponding value.
)\s*
)
[\r\n]*
$
"#).unwrap();
}
LINE_REGEX
.captures(line)
.map_or(Err(Error::LineParse(line.into()).into()), |captures| {
let key = named_string(&captures, "key");
let value = named_string(&captures, "value");
match (key, value) {
(Some(k), Some(v)) => {
let parsed_value = try!(parse_value(&v));
Ok(Some((k, parsed_value)))
}
(Some(k), None) => {
Ok(Some((k, String::from(""))))
}
_ => {
Ok(None)
}
}
})
}
fn named_string(captures: &Captures, name: &str) -> Option<String> {
captures
.name(name)
.and_then(|v| Some(v.as_str().to_owned()))
}
fn parse_value(input: &str) -> Result<String> {
let mut strong_quote = false;
let mut weak_quote = false;
let mut escaped = false;
let mut expecting_end = false;
let mut output = String::new();
for c in input.chars() {
if expecting_end {
if c == ' ' || c == '\t' {
continue;
} else if c == '#' {
break;
} else {
return Err(Error::LineParse(input.to_owned()));
}
} else if strong_quote {
if c == '\'' {
strong_quote = false;
} else {
output.push(c);
}
} else if weak_quote {
if escaped {
match c {
'\\' | '"' | '$' => output.push(c),
_ => return Err(Error::LineParse(input.to_owned())),
}
escaped = false;
} else if c == '"' {
weak_quote = false;
} else if c == '\\' {
escaped = true;
} else {
output.push(c);
}
} else if escaped {
match c {
'\\' | '\'' | '"' | '$' | ' ' => output.push(c),
_ => return Err(Error::LineParse(input.to_owned())),
}
escaped = false;
} else if c == '\'' {
strong_quote = true;
} else if c == '"' {
weak_quote = true;
} else if c == '\\' {
escaped = true;
} else if c == '$' {
return Err(Error::LineParse(input.to_owned()));
} else if c == ' ' || c == '\t' {
expecting_end = true;
} else {
output.push(c);
}
}
if strong_quote || weak_quote {
Err(Error::LineParse(input.to_owned()).into())
} else {
Ok(output)
}
}
#[cfg(test)]
mod test {
use super::*;
use iter::Iter;
#[test]
fn test_parse_line_env() {
let actual_iter = Iter::new(r#"
KEY=1
KEY2="2"
KEY3='3'
KEY4='fo ur'
KEY5="fi ve"
KEY6=s\ ix
KEY7=
KEY8=
KEY9= # foo
export SHELL_LOVER=1
"#.as_bytes());
let expected_iter = vec![
("KEY", "1"),
("KEY2", "2"),
("KEY3", "3"),
("KEY4", "fo ur"),
("KEY5", "fi ve"),
("KEY6", "s ix"),
("KEY7", ""),
("KEY8", ""),
("KEY9", ""),
("SHELL_LOVER", "1"),
].into_iter()
.map(|(key, value)| (key.to_string(), value.to_string()));
let mut count = 0;
for (expected, actual) in expected_iter.zip(actual_iter) {
assert!(actual.is_ok());
assert_eq!(expected, actual.ok().unwrap());
count += 1;
}
assert_eq!(count, 10);
}
#[test]
fn test_parse_line_comment() {
let result: Result<Vec<(String, String)>> = Iter::new(r#"
# foo=bar
# "#.as_bytes()).collect();
assert!(result.unwrap().is_empty());
}
#[test]
fn test_parse_line_invalid() {
let actual_iter = Iter::new(r#"
invalid
KEY =val
KEY2= val
very bacon = yes indeed
=value"#.as_bytes());
let mut count = 0;
for actual in actual_iter {
assert!(actual.is_err());
count += 1;
}
assert_eq!(count, 5);
}
#[test]
fn test_parse_value_escapes() {
let actual_iter = Iter::new(r#"
KEY=my\ cool\ value
KEY2=\$sweet
KEY3="awesome stuff \"mang\""
KEY4='sweet $\fgs'\''fds'
KEY5="'\"yay\\"\ "stuff"
KEY6="lol" #well you see when I say lol wh
"#.as_bytes());
let expected_iter = vec![
("KEY", r#"my cool value"#),
("KEY2", r#"$sweet"#),
("KEY3", r#"awesome stuff "mang""#),
("KEY4", r#"sweet $\fgs'fds"#),
("KEY5", r#"'"yay\ stuff"#),
("KEY6", "lol"),
].into_iter()
.map(|(key, value)| (key.to_string(), value.to_string()));
for (expected, actual) in expected_iter.zip(actual_iter) {
assert!(actual.is_ok());
assert_eq!(expected, actual.unwrap());
}
}
#[test]
fn test_parse_value_escapes_invalid() {
let actual_iter = Iter::new(r#"
KEY=my uncool value
KEY2=$notcool
KEY3="why
KEY4='please stop''
KEY5=h\8u
"#.as_bytes());
for actual in actual_iter {
assert!(actual.is_err());
}
}
}