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
use std::collections::BTreeMap;

use pest::iterators::Pair;
use pest::Parser;

#[derive(Parser)]
#[grammar = "dotenv.pest"]
struct DotenvLineParser;

/// Parse the .env file source.
pub fn parse_dotenv(
    source: &str,
) -> Result<BTreeMap<String, String>, Box<dyn std::error::Error>> {
    let mut map = BTreeMap::new();
    let pairs = DotenvLineParser::parse(Rule::env, source)?;
    for pair in pairs {
        match pair.as_rule() {
            Rule::kv => {
                if let Some((key, value)) = parse_kv(pair) {
                    map.insert(key, value);
                }
            }
            _ => {}
        }
    }
    Ok(map)
}

/// Parse a key-value pair.
fn parse_kv(pair: Pair<Rule>) -> Option<(String, String)> {
    match pair.as_rule() {
        Rule::kv => {
            let mut inner_rules = pair.into_inner(); // key ~ "=" ~ value
            let name: &str = inner_rules.next().unwrap().as_str();
            parse_value(inner_rules.next().unwrap()).map(|v| (name.into(), v))
        }
        _ => None,
    }
}

/// Parse a value, which might be a string or a naked variable.
fn parse_value(pair: Pair<Rule>) -> Option<String> {
    match pair.as_rule() {
        Rule::value => {
            let inner = pair.clone().into_inner().next();
            // If there are no inner pairs, the current value is a naked
            // variable, otherwise it's a string and we need to extract the
            // inner_sq or inner_dq pair.
            match inner {
                None => Some(pair.as_str().into()),
                Some(inner_pair) => match inner_pair.into_inner().next() {
                    None => None,
                    Some(inner_string) => Some(inner_string.as_str().into()),
                },
            }
        }
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::parse_dotenv;
    use std::collections::BTreeMap;

    #[test]
    fn empty_file() {
        assert_eq!(parse_dotenv("").unwrap(), BTreeMap::new());
    }

    #[test]
    fn one_kv() {
        let bm = vec![("key", "value")]
            .into_iter()
            .map(|(a, b)| (a.into(), b.into()))
            .collect();
        assert_eq!(parse_dotenv("key = value").unwrap(), bm);
    }

    #[test]
    fn one_line() {
        let bm = vec![("key", "value")]
            .into_iter()
            .map(|(a, b)| (a.into(), b.into()))
            .collect();
        assert_eq!(parse_dotenv("key = value\n").unwrap(), bm);
    }

    #[test]
    fn two_lines() {
        let bm = vec![("key", "value"), ("key2", "value2")]
            .into_iter()
            .map(|(a, b)| (a.into(), b.into()))
            .collect();
        assert_eq!(parse_dotenv("key = value\nkey2 = value2").unwrap(), bm);
    }

    #[test]
    fn non_alphanumeric_chars() {
        let bm = vec![("key", "https://1.3.2.3:234/a?b=c")]
            .into_iter()
            .map(|(a, b)| (a.into(), b.into()))
            .collect();
        assert_eq!(parse_dotenv("key=https://1.3.2.3:234/a?b=c\n").unwrap(), bm);
    }

    #[test]
    fn export() {
        let bm = vec![("key", "value"), ("key2", "value2")]
            .into_iter()
            .map(|(a, b)| (a.into(), b.into()))
            .collect();
        assert_eq!(
            parse_dotenv("key = value\nexport key2 = value2").unwrap(),
            bm
        );
    }

    #[test]
    fn string_single_quotes() {
        let bm = vec![("key", "value"), ("key2", "val ue2")]
            .into_iter()
            .map(|(a, b)| (a.into(), b.into()))
            .collect();
        assert_eq!(parse_dotenv("key = value\nkey2 = 'val ue2'").unwrap(), bm);
    }

    #[test]
    fn string_double_quotes() {
        let bm = vec![("key", "value"), ("key2", "val ue2")]
            .into_iter()
            .map(|(a, b)| (a.into(), b.into()))
            .collect();
        assert_eq!(
            parse_dotenv("key = value\nkey2 = \"val ue2\"").unwrap(),
            bm
        );
    }

    #[test]
    fn comments() {
        let source = r#"
            # one here
            ENV_FOR_HYDRO=production # another one here
        "#;
        let bm = vec![("ENV_FOR_HYDRO", "production")]
            .into_iter()
            .map(|(a, b)| (a.into(), b.into()))
            .collect();
        assert_eq!(parse_dotenv(source).unwrap(), bm);
    }

    #[test]
    fn complete_dotenv() {
        let source = r#"
            # main comment

            ENV_FOR_HYDRO='testing 2' # another one here
            export USER_ID=5gpPN5rcv5G41U_S
            API_TOKEN=30af563ccc668bc8ced9e24e  # relax! these values are fake
            APP_SITE_URL=https://my.example.com
        "#;
        let bm = vec![
            ("ENV_FOR_HYDRO", "testing 2"),
            ("USER_ID", "5gpPN5rcv5G41U_S"),
            ("API_TOKEN", "30af563ccc668bc8ced9e24e"),
            ("APP_SITE_URL", "https://my.example.com"),
        ]
        .into_iter()
        .map(|(a, b)| (a.into(), b.into()))
        .collect();
        assert_eq!(parse_dotenv(source).unwrap(), bm);
    }
}