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
extern crate subprocess;
use std::collections::HashMap;
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io::{self, BufRead};
use std::path::{Path, PathBuf};

use subprocess::{Popen, PopenConfig};

type DenvM = HashMap<String, String>;

pub fn read_lines(pth: &dyn AsRef<Path>) -> io::Result<io::Lines<io::BufReader<File>>> {
    let f = File::open(pth)?;
    Ok(io::BufReader::new(f).lines())
}

fn is_valid_ident(s: &str) -> bool {
    if let Some(fst) = s.chars().next() {
        fst.is_alphabetic()
    } else {
        false
    }
}

pub fn split_line(s: String) -> Option<(String, String)> {
    if is_valid_ident(&s) {
        let mut sp = s.split("=");
        let a = sp.next().unwrap();
        if let Some(b) = sp.next() {
            Some((
                a.to_string(),
                b.trim_matches(|c| c == '\'' || c == '"').to_string(),
            ))
        } else {
            None
        }
    } else {
        None
    }
}

pub fn to_denvm(v: Vec<(String, String)>) -> DenvM {
    v.into_iter().collect()
}

pub fn mk_env(de: DenvM) -> Option<Vec<(OsString, OsString)>> {
    Some(
        de.iter()
            .map(|(k, v)| (OsString::from(k), OsString::from(v)))
            .collect(),
    )
}

fn merge(fst: DenvM, snd: DenvM) -> DenvM {
    let mut merged = HashMap::new();
    for (k, v) in fst.into_iter() {
        merged.insert(k, v);
    }
    for (k, v) in snd.into_iter() {
        merged.insert(k, v);
    }
    merged
}

pub fn merge_l(l: DenvM, r: DenvM) -> DenvM {
    merge(r, l)
}

pub fn merge_r(l: DenvM, r: DenvM) -> DenvM {
    merge(l, r)
}

pub fn mk_cfg(env: DenvM) -> PopenConfig {
    PopenConfig {
        env: mk_env(env),
        ..Default::default()
    }
}

pub fn run_with_env(s: Vec<impl AsRef<OsStr>>, env: DenvM) -> () {
    let conf = mk_cfg(env);
    Popen::create(&s, conf).unwrap();
}

pub fn get_vars() -> DenvM {
    to_denvm(env::vars().into_iter().collect())
}

fn get_envf_path(name: Option<String>) -> io::Result<PathBuf> {
    let cwd = env::current_dir()?;
    let fname = {
        if let Some(n) = name {
            let lowered = n.to_lowercase();
            let mut ef = String::from(".");
            ef.push_str(&lowered);
            ef.push_str(".env");
            ef
        } else {
            ".env".to_string()
        }
    };
    Ok(cwd.join(fname))
}

fn name_to_denvm(name: Option<String>) -> io::Result<DenvM> {
    let pth = get_envf_path(name)?;
    let lines = read_lines(&pth)?;
    lines
        .map(|line| line.map(|l| split_line(l)))
        .filter_map(|x| x.transpose())
        .collect()
}

pub enum Dir {
    L,
    R,
}

pub fn merge_envs(names: Vec<&str>, dir: Dir) -> io::Result<DenvM> {
    let e = get_vars();
    let base = name_to_denvm(None)?;
    let mut es = vec![base];
    let f = {
        match dir {
            Dir::L => merge_l,
            Dir::R => merge_r,
        }
    };
    for name in names {
        let env = name_to_denvm(Some(name.to_string()))?;
        es.push(env);
    }
    Ok(es.into_iter().fold(e, f))
}

pub fn set(env: &mut DenvM, k: String, v: String) -> () {
    env.insert(k, v);
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_to_devm() {
        let s = "a=b\nc=d";
        let it = s
            .lines()
            .map(|s| s.to_owned())
            .map(|s| split_line(s))
            .filter_map(|x| x)
            .collect();
        let m = to_denvm(it);
        assert_eq!(m.get("a"), Some(&"b".to_string()));
        assert_eq!(m.get("c"), Some(&"d".to_string()));
    }

    #[test]
    fn test_to_denvm_cmts() {
        let s = "a=b\n# comment\nc=d\nx=";
        let it = s
            .lines()
            .map(|s| s.to_owned())
            .map(|s| split_line(s))
            .filter_map(|x| x)
            .collect();
        let m = to_denvm(it);
        assert_eq!(m.get("a"), Some(&"b".to_string()));
        assert_eq!(m.get("c"), Some(&"d".to_string()));
    }

    #[test]
    fn test_mk_env() {
        let de: DenvM = vec![
            ("a".to_string(), "b".to_string()),
            ("c".to_string(), "d".to_string()),
        ]
        .into_iter()
        .collect();
        let expected: Vec<(OsString, OsString)> = vec![
            (
                OsString::from("a".to_string()),
                OsString::from("b".to_string()),
            ),
            (
                OsString::from("c".to_string()),
                OsString::from("d".to_string()),
            ),
        ];
        if let Some(mut e) = mk_env(de) {
            e.sort();
            assert_eq!(e, expected);
        } else {
            unreachable!()
        }
    }

    #[test]
    fn test_merge() {
        let fst = vec![
            ("a".to_string(), "a_fst".to_string()),
            ("b".to_string(), "b_fst".to_string()),
        ]
        .into_iter()
        .collect();
        let snd = vec![("a".to_string(), "a_snd".to_string())]
            .into_iter()
            .collect();
        let m = merge(fst, snd);
        assert_eq!(m.get("a"), Some(&"a_snd".to_string()));
        assert_eq!(m.get("b"), Some(&"b_fst".to_string()));
    }

    #[test]
    fn test_run_with_env() {
        let de: DenvM = vec![("A".to_string(), "b".to_string())]
            .into_iter()
            .collect();
        let argv = vec!["echo", "$A"];
        println!("{:?}", argv);
        run_with_env(argv, de);
    }

    #[test]
    fn test_get_enf_path_none() -> io::Result<()> {
        let p = get_envf_path(None)?;
        assert!(p.ends_with(".env"));
        Ok(())
    }

    #[test]
    fn test_get_envf_path_some() -> io::Result<()> {
        let p = get_envf_path(Some("dev".to_string()))?;
        assert!(p.ends_with(".dev.env"));
        let p = get_envf_path(Some("DEV".to_string()))?;
        assert!(p.ends_with(".dev.env"));
        Ok(())
    }
}