Newer
Older
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
use std::env;
use std::env::VarError;
use crate::parser::{file, FileLine};
use nom_locate::LocatedSpan;
use std::str::FromStr;
use std::string::ParseError;
#[derive(Clone, Debug, Default)]
pub struct EnvironmentFile {
lines: Vec<FileLine>,
}
#[derive(Debug, thiserror::Error)]
pub enum EnvironmentFileError {
#[error("Unable to determine eof marker")]
InvalidEof,
#[error("Parse error at line {line}, column {column}: {kind:?}")]
ParseError {
line: usize,
column: usize,
kind: nom::error::ErrorKind,
},
#[error(transparent)]
StdParseError(#[from] ParseError),
#[error("Value could not be determined to be valid UTF-8")]
InvalidValue,
}
impl FromStr for EnvironmentFile {
type Err = EnvironmentFileError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (_, lines) = file(LocatedSpan::new(s)).map_err(|err| match err {
nom::Err::Incomplete(_) => EnvironmentFileError::InvalidEof,
nom::Err::Error(err) | nom::Err::Failure(err) => EnvironmentFileError::ParseError {
column: err.input.get_column(),
line: err.input.location_line() as usize,
kind: err.code,
},
})?;
Ok(Self::new(lines))
}
}
fn is_kv_line(line: &FileLine) -> bool {
matches!(line, FileLine::KeyValue { .. })
}
fn is_comment_line(line: &FileLine) -> bool {
matches!(line, FileLine::Comment(_))
}
impl EnvironmentFile {
pub fn new(lines: Vec<FileLine>) -> Self {
Self { lines }
}
pub fn parse(value: impl AsRef<str>) -> Result<Self, EnvironmentFileError> {
value.as_ref().parse()
}
pub fn iter(&self) -> EnvFileIterator {
EnvFileIterator {
lines: &self.lines,
current: 0,
}
}
pub fn lines_kv(&self) -> SubTypeFileIterator {
SubTypeFileIterator {
lines: &self.lines,
current: 0,
predicate: is_kv_line,
}
}
pub fn lines_comment(&self) -> SubTypeFileIterator {
SubTypeFileIterator {
lines: &self.lines,
current: 0,
predicate: is_comment_line,
}
}
pub fn get_raw(&self, key: &str) -> Option<String> {
for line in &self.lines {
if let FileLine::KeyValue { key: k, value } = line {
if k == key {
return Some(value.iter().map(|part| part.to_string()).collect::<String>());
}
}
}
None
}
pub fn len(&self) -> usize {
self.lines.len()
}
pub fn is_empty(&self) -> bool {
self.lines.is_empty()
}
pub fn apply(&self) -> Result<(), EnvironmentFileError> {
set_from_file(self)
}
}
pub struct EnvFileIterator<'a> {
lines: &'a [FileLine],
current: usize,
}
impl<'a> Iterator for EnvFileIterator<'a> {
type Item = &'a FileLine;
fn next(&mut self) -> Option<Self::Item> {
if self.current >= self.lines.len() {
None
} else {
let line = &self.lines[self.current];
self.current += 1;
Some(line)
}
}
}
impl ExactSizeIterator for EnvFileIterator<'_> {
fn len(&self) -> usize {
self.lines.len() - self.current
}
}
pub struct SubTypeFileIterator<'a> {
lines: &'a [FileLine],
current: usize,
predicate: fn(&FileLine) -> bool,
}
impl<'a> Iterator for SubTypeFileIterator<'a> {
type Item = &'a FileLine;
fn next(&mut self) -> Option<Self::Item> {
let mut found = None;
while self.current < self.lines.len() {
let line = &self.lines[self.current];
self.current += 1;
if (self.predicate)(line) {
found = Some(line);
break;
}
}
found
}
}
fn is_missing_key(key: &str) -> Result<bool, EnvironmentFileError> {
match env::var(key) {
Ok(_) => Ok(false),
Err(VarError::NotPresent) => Ok(true),
Err(_) => Err(EnvironmentFileError::InvalidValue),
}
}
fn set_from_file(file: &EnvironmentFile) -> Result<(), EnvironmentFileError> {
let mut defferred = Vec::with_capacity(file.len());
for line in file.lines_kv() {
if let FileLine::KeyValue { key, .. } = &line {
if is_missing_key(key)? {
if line.is_complete() {
env::set_var(key, line.assemble_value());
} else {
defferred.push(line);
}
}
}
}
for line in defferred {
if let FileLine::KeyValue { key, .. } = line {
env::set_var(key, line.assemble_value());
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parser::ValuePart;
#[test]
fn test_lines_kv_iterator() {
let env_file = EnvironmentFile::new(vec![
FileLine::empty(),
FileLine::comment("# This is a comment"),
FileLine::key_value("KEY1".to_string(), vec![ValuePart::Static("VALUE1".to_string())]),
FileLine::empty(),
FileLine::key_value("KEY2".to_string(), vec![ValuePart::Static("VALUE2".to_string())]),
]);
let kv_lines: Vec<&FileLine> = env_file.lines_kv().collect();
assert_eq!(kv_lines.len(), 2);
assert!(
matches!(kv_lines[0], FileLine::KeyValue { key, value } if key == "KEY1" && value == &vec![ValuePart::Static("VALUE1".to_string())])
);
assert!(
matches!(kv_lines[1], FileLine::KeyValue { key, value } if key == "KEY2" && value == &vec![ValuePart::Static("VALUE2".to_string())])
);
}
#[test]
fn test_lines_comment_iterator() {
let env_file = EnvironmentFile::new(vec![
FileLine::empty(),
FileLine::comment(" Comment 1"),
FileLine::key_value("KEY1".to_string(), vec![ValuePart::Static("VALUE1".to_string())]),
FileLine::comment(" Comment 2"),
FileLine::key_value("KEY2".to_string(), vec![ValuePart::Static("VALUE2".to_string())]),
FileLine::comment(" Comment 3"),
]);
let comment_lines: Vec<&FileLine> = env_file.lines_comment().collect();
assert_eq!(comment_lines.len(), 3);
assert!(matches!(comment_lines[0], FileLine::Comment(comment) if comment == " Comment 1"));
assert!(matches!(comment_lines[1], FileLine::Comment(comment) if comment == " Comment 2"));
assert!(matches!(comment_lines[2], FileLine::Comment(comment) if comment == " Comment 3"));
}
#[test]
fn test_iter_returns_all_lines() {
let env_file = EnvironmentFile::new(vec![
FileLine::empty(),
FileLine::comment("This is a comment"),
FileLine::key_value("KEY1".to_string(), vec![ValuePart::Static("VALUE1".to_string())]),
FileLine::empty(),
FileLine::key_value("KEY2".to_string(), vec![ValuePart::Static("VALUE2".to_string())]),
]);
let all_lines: Vec<&FileLine> = env_file.iter().collect();
assert_eq!(all_lines.len(), 5);
assert!(matches!(all_lines[0], FileLine::Empty));
assert!(matches!(all_lines[1], FileLine::Comment(comment) if comment == "This is a comment"));
assert!(
matches!(all_lines[2], FileLine::KeyValue { key, value } if key == "KEY1" && value == &vec![ValuePart::Static("VALUE1".to_string())])
);
assert!(matches!(all_lines[3], FileLine::Empty));
assert!(
matches!(all_lines[4], FileLine::KeyValue { key, value } if key == "KEY2" && value == &vec![ValuePart::Static("VALUE2".to_string())])
);
}
#[test]
fn test_lines_kv_maintains_order() {
let env_file = EnvironmentFile::new(vec![
FileLine::empty(),
FileLine::key_value("KEY1".to_string(), vec![ValuePart::Static("VALUE1".to_string())]),
FileLine::comment("Comment"),
FileLine::key_value("KEY2".to_string(), vec![ValuePart::Static("VALUE2".to_string())]),
FileLine::key_value("KEY3".to_string(), vec![ValuePart::Static("VALUE3".to_string())]),
FileLine::empty(),
]);
let kv_lines: Vec<&FileLine> = env_file.lines_kv().collect();
assert_eq!(kv_lines.len(), 3);
assert!(
matches!(kv_lines[0], FileLine::KeyValue { key, value } if key == "KEY1" && value == &vec![ValuePart::Static("VALUE1".to_string())])
);
assert!(
matches!(kv_lines[1], FileLine::KeyValue { key, value } if key == "KEY2" && value == &vec![ValuePart::Static("VALUE2".to_string())])
);
assert!(
matches!(kv_lines[2], FileLine::KeyValue { key, value } if key == "KEY3" && value == &vec![ValuePart::Static("VALUE3".to_string())])
);
}
}