use std::collections::{hash_map, HashMap};
#[derive(Clone)]
pub struct Env(HashMap<String, String>);
impl Env {
pub fn new(data: HashMap<String, String>) -> Self {
Self(data)
}
pub fn empty() -> Self {
Self(HashMap::new())
}
pub fn from_vec<K: ToString, V: ToString>(kvs: Vec<(K, V)>) -> Self {
let mut data = HashMap::with_capacity(kvs.len());
for (k, v) in kvs {
data.insert(k.to_string(), v.to_string());
}
Self(data)
}
pub fn one<K: ToString, V: ToString>(k: K, v: V) -> Self {
let mut data = HashMap::with_capacity(1);
data.insert(k.to_string(), v.to_string());
Self(data)
}
pub fn parent() -> Self {
let env = std::env::vars();
let mut data = HashMap::new();
for (k, v) in env {
data.insert(k, v);
}
Self(data)
}
pub fn insert<K: ToString, V: ToString>(mut self, k: K, v: V) -> Self {
self.0.insert(k.to_string(), v.to_string());
self
}
pub fn insert_cloned<K: ToString, V: ToString>(&self, k: K, v: V) -> Self {
let mut cloned = self.0.clone();
cloned.insert(k.to_string(), v.to_string());
Self(cloned)
}
pub fn extend(mut self, env: Self) -> Self {
self.0.extend(env.0);
self
}
pub fn extend_cloned(&self, env: Self) -> Self {
Self(self.0.clone().into_iter().chain(env.0).collect())
}
pub fn get(&self, k: &str) -> Option<&String> {
self.0.get(k)
}
}
impl IntoIterator for Env {
type Item = (String, String);
type IntoIter = hash_map::IntoIter<String, String>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
pub struct PATH;
impl PATH {
#[cfg(unix)]
const DEL: char = ':';
#[cfg(windows)]
const DEL: char = ';';
pub fn get() -> Option<String> {
Env::parent().get("PATH").map(|x| x.to_owned())
}
pub fn extend(x: impl ToString) -> String {
match PATH::get() {
Some(path) => format!("{}{}{}", path, PATH::DEL, x.to_string()),
None => x.to_string(),
}
}
}