1use std::fs;
2
3pub struct DotEnv {
4 pub pairs: Vec<DotEnvPair>,
5}
6
7pub struct DotEnvPair {
8 pub key: String,
9 pub value: String,
10}
11
12impl DotEnv {
13 pub fn new() -> DotEnv {
14 DotEnv {
15 pairs: Vec::new(),
16 }
17 }
18
19 pub fn load(&mut self) {
20 self.load_path(".env");
21 }
22
23 pub fn load_path(&mut self, path: &str) {
24 let contents = fs::read_to_string(path)
25 .expect("Something went wrong reading the file");
26
27 for line in contents.lines() {
28 let pair = DotEnv::parse_line(line);
29 self.pairs.push(pair);
30 }
31 }
32
33 pub fn parse_line(line: &str) -> DotEnvPair {
34 let mut split = line.split("=");
35 if split.clone().count() != 2 {
36 panic!("Invalid line: {}", line);
37 }
38
39 let key = split.next().unwrap().to_string();
40 let value = split.next().unwrap().to_string();
41
42 DotEnvPair::new(key, value)
43 }
44
45 pub fn get(&self, key: &str) -> &str {
46 for pair in &self.pairs {
47 if pair.key == key {
48 return &pair.value;
49 }
50 }
51
52 panic!("Key not found: {}", key);
53 }
54}
55
56impl DotEnvPair {
57 fn new(key: String, value: String) -> DotEnvPair {
58 DotEnvPair {
59 key,
60 value,
61 }
62 }
63}