Skip to main content

cuno_core/
env.rs

1//! The environment snapshot the binary passes to libraries, which never read
2//! the process environment themselves (`docs/en/specs/architecture.md`,
3//! "Dependencies between crates").
4
5use std::collections::BTreeMap;
6use std::ffi::{OsStr, OsString};
7
8/// How names are compared, variables' and files' alike, which depends on
9/// the operating system they came from.
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub enum NameCase {
12    /// `Path` and `PATH` are one name (Windows).
13    Insensitive,
14    /// `Path` and `PATH` are two names (other systems).
15    Sensitive,
16}
17
18/// Environment variables, looked up by name.
19#[derive(Clone, Debug)]
20pub struct Env {
21    case: NameCase,
22    /// Keyed by the name as compared (see `key`); the value keeps the name
23    /// as it was spelled, for passing the environment on to a child process.
24    vars: BTreeMap<OsString, (OsString, OsString)>,
25}
26
27impl Default for Env {
28    /// An empty environment that compares names as this platform does.
29    fn default() -> Env {
30        Env::from_pairs([], NameCase::host())
31    }
32}
33
34impl NameCase {
35    /// How the operating system cuno is running on compares names. Used only
36    /// for the process's own environment ([`Env::from_process`]): the host is
37    /// otherwise received as a value (`docs/en/specs/architecture.md`), and
38    /// every other `Env` is built with an explicit `NameCase`, so both
39    /// behaviours are tested on any system.
40    pub fn host() -> NameCase {
41        if cfg!(windows) {
42            NameCase::Insensitive
43        } else {
44            NameCase::Sensitive
45        }
46    }
47}
48
49impl NameCase {
50    /// `name` as compared: two names are one when these are equal.
51    pub fn fold(self, name: &OsStr) -> OsString {
52        fold(name, self)
53    }
54
55    /// Whether `a` and `b` are one name.
56    pub fn same(self, a: &str, b: &str) -> bool {
57        fold(OsStr::new(a), self) == fold(OsStr::new(b), self)
58    }
59}
60
61impl Env {
62    /// How this environment's names are compared, which is how the system
63    /// it came from compares file names too.
64    pub fn case(&self) -> NameCase {
65        self.case
66    }
67
68    /// The environment of the running process. Only the binary calls this.
69    pub fn from_process() -> Env {
70        Env::from_pairs(std::env::vars_os(), NameCase::host())
71    }
72
73    /// An environment holding exactly `pairs`, with names compared as `case`
74    /// says; a later pair replaces an earlier one with the same name.
75    pub fn from_pairs(
76        pairs: impl IntoIterator<Item = (OsString, OsString)>,
77        case: NameCase,
78    ) -> Env {
79        let vars = pairs
80            .into_iter()
81            .map(|(name, value)| (fold(&name, case), (name, value)))
82            .collect();
83        Env { case, vars }
84    }
85
86    /// The value of `name`, if it is set.
87    pub fn get(&self, name: &str) -> Option<&OsStr> {
88        self.vars
89            .get(&fold(OsStr::new(name), self.case))
90            .map(|(_, value)| value.as_os_str())
91    }
92
93    /// The value of cuno's own variable `name` (`CUNO_HOME` and the like),
94    /// or `None` when it is unset or empty: an empty one counts as unset
95    /// (`docs/en/specs/manifest.md`, "Two levels of settings"). Not for
96    /// `NO_COLOR`, which is set even when empty.
97    pub fn set_value(&self, name: &str) -> Option<&OsStr> {
98        self.get(name).filter(|value| !value.is_empty())
99    }
100
101    /// Every variable, as (name as spelled, value), for giving a child
102    /// process exactly this environment.
103    pub fn vars(&self) -> impl Iterator<Item = (&OsStr, &OsStr)> {
104        self.vars
105            .values()
106            .map(|(name, value)| (name.as_os_str(), value.as_os_str()))
107    }
108
109    /// This environment with `name` set to `value`, replacing any variable
110    /// that has the same name as this environment compares names.
111    pub fn with(&self, name: &str, value: OsString) -> Env {
112        let mut env = self.clone();
113        env.vars
114            .insert(fold(OsStr::new(name), self.case), (name.into(), value));
115        env
116    }
117
118    /// This environment without the variables named in `names`, compared as
119    /// this environment compares names.
120    pub fn without(&self, names: &[&str]) -> Env {
121        let mut env = self.clone();
122        for name in names {
123            env.vars.remove(&fold(OsStr::new(name), self.case));
124        }
125        env
126    }
127}
128
129/// The name as compared. Case-insensitive names are upper-cased one character
130/// at a time, keeping a character whose upper case is more than one character
131/// (such as `ß`): Windows folds names character by character, so `ß` must not
132/// become `SS`. Names that are not valid Unicode are kept as they are.
133pub(crate) fn fold(name: &OsStr, case: NameCase) -> OsString {
134    match (case, name.to_str()) {
135        (NameCase::Insensitive, Some(name)) => name
136            .chars()
137            .map(|c| {
138                let mut upper = c.to_uppercase();
139                match (upper.next(), upper.next()) {
140                    (Some(u), None) => u,
141                    _ => c,
142                }
143            })
144            .collect::<String>()
145            .into(),
146        _ => name.to_owned(),
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    fn env(pairs: &[(&str, &str)], case: NameCase) -> Env {
155        Env::from_pairs(pairs.iter().map(|(n, v)| (n.into(), v.into())), case)
156    }
157
158    /// An empty value counts as unset for `set_value` and not for `get`.
159    ///
160    /// Mutation: let `set_value` return an empty value or drop a non-empty
161    /// one, or make `get` drop an empty one; this test fails.
162    #[test]
163    fn an_empty_value_is_unset_for_set_value_only() {
164        let e = env(
165            &[("CUNO_HOME", ""), ("CUNO_COMPILER", "clang")],
166            NameCase::Insensitive,
167        );
168        assert_eq!(e.set_value("CUNO_HOME"), None);
169        assert_eq!(e.get("CUNO_HOME"), Some(OsStr::new("")));
170        assert_eq!(e.set_value("CUNO_COMPILER"), Some(OsStr::new("clang")));
171        assert_eq!(e.set_value("CUNO_TARGET_DIR"), None);
172    }
173
174    /// Mutation: make `fold` ignore `case`, in either direction, or have an
175    /// `Env` report another case than it was built with; this test fails.
176    #[test]
177    fn names_are_compared_as_the_case_says() {
178        let windows = env(&[("Path", "C:\\bin")], NameCase::Insensitive);
179        assert_eq!(windows.get("PATH"), Some(OsStr::new("C:\\bin")));
180        assert_eq!(windows.get("path"), Some(OsStr::new("C:\\bin")));
181        let other = env(&[("Path", "/bin")], NameCase::Sensitive);
182        assert_eq!(other.get("Path"), Some(OsStr::new("/bin")));
183        assert_eq!(other.get("PATH"), None);
184        assert_eq!(
185            (windows.case(), other.case()),
186            (NameCase::Insensitive, NameCase::Sensitive)
187        );
188        assert!(NameCase::Insensitive.same("Main", "MAIN"));
189        assert!(!NameCase::Sensitive.same("Main", "MAIN"));
190    }
191
192    /// Mutation: upper-case with `str::to_uppercase` (which turns `ß` into
193    /// `SS`); this test fails.
194    #[test]
195    fn folding_is_character_by_character() {
196        let e = env(&[("STRAßE", "1")], NameCase::Insensitive);
197        assert_eq!(e.get("straße"), Some(OsStr::new("1")));
198        assert_eq!(e.get("STRASSE"), None);
199    }
200
201    /// Mutation: make `without` compare names case-sensitively, or make `vars`
202    /// return the folded key instead of the spelling; this test fails.
203    #[test]
204    fn without_removes_by_name_and_vars_keeps_the_spelling() {
205        let e = env(
206            &[("Path", "C:\\bin"), ("cl", "/nologo")],
207            NameCase::Insensitive,
208        );
209        let rest = e.without(&["CL"]);
210        assert_eq!(rest.get("cl"), None);
211        let vars: Vec<_> = rest.vars().collect();
212        assert_eq!(vars, [(OsStr::new("Path"), OsStr::new("C:\\bin"))]);
213    }
214
215    /// Mutation: keep the first of two pairs with the same name; this test
216    /// fails.
217    /// Mutation: insert under the name as spelled instead of as compared;
218    /// this test fails (`Path` would survive beside `PATH`).
219    #[test]
220    fn with_replaces_a_variable_spelled_differently() {
221        let env = env(&[("Path", "old")], NameCase::Insensitive).with("path", "new".into());
222        assert_eq!(env.get("PATH"), Some(OsStr::new("new")));
223        assert_eq!(env.vars().count(), 1);
224    }
225
226    #[test]
227    fn a_later_pair_replaces_an_earlier_one() {
228        let e = env(
229            &[("CUNO_X", "first"), ("CUNO_X", "second")],
230            NameCase::Sensitive,
231        );
232        assert_eq!(e.get("CUNO_X"), Some(OsStr::new("second")));
233    }
234
235    /// Mutation: make `from_process` return an empty environment; this test
236    /// fails (`PATH` is set in every process the tests run in).
237    #[test]
238    fn from_process_reads_the_process_environment() {
239        assert!(Env::from_process().get("PATH").is_some());
240    }
241
242    /// Mutation: make `NameCase::host` return the other variant; this test
243    /// fails.
244    #[test]
245    fn the_host_case_matches_the_platform() {
246        let expected = if cfg!(windows) {
247            NameCase::Insensitive
248        } else {
249            NameCase::Sensitive
250        };
251        assert_eq!(NameCase::host(), expected);
252    }
253}