Skip to main content

argenv_resolve/
source.rs

1//! [`EnvSource`] — where a variable is read from.
2//!
3//! Reading is deliberately not hardwired to the current process. A launcher
4//! composes the environment it is *about to hand a child process* and needs to
5//! check that before `exec`, not after; a diagnostic tool reads a snapshot taken
6//! from elsewhere; a test wants an isolated map instead of mutating global state
7//! shared with every other test in the binary.
8use std::collections::{BTreeMap, HashMap};
9
10/// A set of environment variables that can be read and enumerated.
11///
12/// Enumeration is required because catching a misspelled name means noticing a
13/// variable that is *present but undeclared* — which is impossible if you can
14/// only look up names you already know.
15pub trait EnvSource {
16    /// The raw value of `name`, if present.
17    fn get(&self, name: &str) -> Option<String>;
18
19    /// Every variable name present in this source.
20    fn names(&self) -> Vec<String>;
21}
22
23/// The current process's environment.
24#[derive(Clone, Copy, Debug, Default)]
25pub struct ProcessEnv;
26
27impl EnvSource for ProcessEnv {
28    fn get(&self, name: &str) -> Option<String> {
29        std::env::var(name).ok()
30    }
31    fn names(&self) -> Vec<String> {
32        std::env::vars().map(|(k, _)| k).collect()
33    }
34}
35
36impl EnvSource for BTreeMap<String, String> {
37    fn get(&self, name: &str) -> Option<String> {
38        BTreeMap::get(self, name).cloned()
39    }
40    fn names(&self) -> Vec<String> {
41        self.keys().cloned().collect()
42    }
43}
44
45impl EnvSource for HashMap<String, String> {
46    fn get(&self, name: &str) -> Option<String> {
47        HashMap::get(self, name).cloned()
48    }
49    fn names(&self) -> Vec<String> {
50        self.keys().cloned().collect()
51    }
52}
53
54impl<T: EnvSource + ?Sized> EnvSource for &T {
55    fn get(&self, name: &str) -> Option<String> {
56        (**self).get(name)
57    }
58    fn names(&self) -> Vec<String> {
59        (**self).names()
60    }
61}