pub trait Env: Send + Sync {
fn get(&self, key: &str) -> Option<String>;
fn has(&self, key: &str) -> bool {
self.get(key).is_some_and(|v| !v.is_empty())
}
}
impl<T: Env + ?Sized> Env for Box<T> {
fn get(&self, key: &str) -> Option<String> {
(**self).get(key)
}
fn has(&self, key: &str) -> bool {
(**self).has(key)
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct ProcessEnv;
impl Env for ProcessEnv {
fn get(&self, key: &str) -> Option<String> {
std::env::var(key).ok()
}
}
#[derive(Debug, Clone, Default)]
pub struct EnvList {
vars: Vec<(String, String)>,
}
impl EnvList {
pub fn new() -> Self {
Self::default()
}
pub fn from_process() -> Self {
Self {
vars: std::env::vars().collect(),
}
}
pub fn from_pairs<I, K, V>(iter: I) -> Self
where
I: IntoIterator<Item = (K, V)>,
K: Into<String>,
V: Into<String>,
{
Self {
vars: iter
.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.collect(),
}
}
pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Self {
self.vars.push((key.into(), value.into()));
self
}
}
impl Env for EnvList {
fn get(&self, key: &str) -> Option<String> {
self.vars
.iter()
.rev()
.find(|(k, _)| k == key)
.map(|(_, v)| v.clone())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn duplicate_keys_last_wins() {
let e = EnvList::from_pairs([("FOO", "a"), ("BAR", "x"), ("FOO", "b")]);
assert_eq!(e.get("FOO").as_deref(), Some("b"));
assert_eq!(e.get("BAR").as_deref(), Some("x"));
}
#[test]
fn set_shadows_earlier_value() {
let mut e = EnvList::from_pairs([("K", "first")]);
e.set("K", "second");
assert_eq!(e.get("K").as_deref(), Some("second"));
}
#[test]
fn has_requires_non_empty() {
let e = EnvList::from_pairs([("EMPTY", ""), ("SET", "v")]);
assert!(!e.has("EMPTY"));
assert!(e.has("SET"));
assert!(!e.has("MISSING"));
}
#[test]
fn boxed_env_forwards() {
let e: Box<dyn Env> = Box::new(EnvList::from_pairs([("TERM", "xterm")]));
assert_eq!(e.get("TERM").as_deref(), Some("xterm"));
assert!(e.has("TERM"));
}
#[test]
fn boxed_env_forwards_has_override() {
struct TrackedEnv(std::sync::Arc<std::sync::atomic::AtomicUsize>);
impl Env for TrackedEnv {
fn get(&self, _key: &str) -> Option<String> {
Some(String::new())
}
fn has(&self, _key: &str) -> bool {
self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
false
}
}
let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let e: Box<dyn Env> = Box::new(TrackedEnv(calls.clone()));
assert!(!e.has("ANYTHING"));
assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 1);
}
}