1use std::{
2 collections::HashMap,
3 fs::File,
4 io::{BufRead, BufReader},
5};
6
7pub struct EnvFile {
8 pub path: String,
9 pub lines: HashMap<String, String>,
10}
11
12#[allow(dead_code)]
13pub fn load(path: &str) -> EnvFile {
14 let file = File::open(path).unwrap();
15 let reader = BufReader::new(file);
16 let lines = reader
17 .lines()
18 .map(|line| line.unwrap())
19 .filter(|line| !line.starts_with('#'))
20 .map(|line| {
21 let mut parts = line.splitn(2, '=');
22 let key = parts.next().unwrap().trim().to_string();
23 let value = parts.next().unwrap().trim().to_string();
24 (key, value)
25 })
26 .collect();
27
28 EnvFile {
29 path: path.to_string(),
30 lines,
31 }
32}
33
34impl EnvFile {
35 pub fn get(&self, key: &str) -> Option<String> {
36 self.lines.get(key).cloned()
37 }
38}
39
40#[cfg(test)]
41mod tests {
42 use super::*;
43 use std::{env, io::Write};
44
45 #[test]
46 fn test_load() {
47 let path = env::current_dir().unwrap().join("test.env");
48 let _ = std::fs::remove_file(&path);
49 let mut file = File::create(&path).unwrap();
50 file.write_all(
51 b"TEST=123
52TEST2=456",
53 )
54 .unwrap();
55
56 let env_file = load(path.to_str().unwrap());
57 assert_eq!(env_file.get("TEST"), Some("123".to_string()));
58 assert_eq!(env_file.get("TEST2"), Some("456".to_string()));
59 }
60}