1use std::collections::{hash_map, HashMap};
2
3#[derive(Clone)]
5pub struct Env(HashMap<String, String>);
6
7impl Env {
8 pub fn new(data: HashMap<String, String>) -> Self {
10 Self(data)
11 }
12
13 pub fn empty() -> Self {
15 Self(HashMap::new())
16 }
17
18 pub fn from_vec<K: ToString, V: ToString>(kvs: Vec<(K, V)>) -> Self {
20 let mut data = HashMap::with_capacity(kvs.len());
21 for (k, v) in kvs {
22 data.insert(k.to_string(), v.to_string());
23 }
24 Self(data)
25 }
26
27 pub fn one<K: ToString, V: ToString>(k: K, v: V) -> Self {
29 let mut data = HashMap::with_capacity(1);
30 data.insert(k.to_string(), v.to_string());
31 Self(data)
32 }
33
34 pub fn parent() -> Self {
36 let env = std::env::vars();
37 let mut data = HashMap::new();
38 for (k, v) in env {
39 data.insert(k, v);
40 }
41 Self(data)
42 }
43
44 pub fn insert<K: ToString, V: ToString>(mut self, k: K, v: V) -> Self {
46 self.0.insert(k.to_string(), v.to_string());
47 self
48 }
49
50 pub fn insert_cloned<K: ToString, V: ToString>(&self, k: K, v: V) -> Self {
52 let mut cloned = self.0.clone();
53 cloned.insert(k.to_string(), v.to_string());
54 Self(cloned)
55 }
56
57 pub fn extend(mut self, env: Self) -> Self {
59 self.0.extend(env.0);
60 self
61 }
62
63 pub fn extend_cloned(&self, env: Self) -> Self {
65 Self(self.0.clone().into_iter().chain(env.0).collect())
66 }
67
68 pub fn get(&self, k: &str) -> Option<&String> {
70 self.0.get(k)
71 }
72}
73
74impl IntoIterator for Env {
75 type Item = (String, String);
76 type IntoIter = hash_map::IntoIter<String, String>;
77
78 fn into_iter(self) -> Self::IntoIter {
79 self.0.into_iter()
80 }
81}
82
83pub struct PATH;
85
86impl PATH {
87 #[cfg(unix)]
88 const DEL: char = ':';
89
90 #[cfg(windows)]
91 const DEL: char = ';';
92
93 pub fn get() -> Option<String> {
95 Env::parent().get("PATH").map(|x| x.to_owned())
96 }
97
98 pub fn extend(x: impl ToString) -> String {
100 match PATH::get() {
101 Some(path) => format!("{}{}{}", path, PATH::DEL, x.to_string()),
102 None => x.to_string(),
103 }
104 }
105}