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    /// The directories on `PATH` a program is searched in, in order: only
63    /// absolute ones. An empty or relative entry would be resolved against
64    /// cuno's working directory, often the project, which can hold a file
65    /// named like the program (`docs/en/specs/toolchain.md`, "LLVM
66    /// (clang / clang-cl / clang-format / clang-tidy)").
67    pub fn search_dirs(&self) -> Vec<std::path::PathBuf> {
68        self.get("PATH")
69            .map(|path| {
70                std::env::split_paths(path)
71                    .filter(|d| d.is_absolute())
72                    .collect()
73            })
74            .unwrap_or_default()
75    }
76
77    /// How this environment's names are compared, which is how the system
78    /// it came from compares file names too.
79    pub fn case(&self) -> NameCase {
80        self.case
81    }
82
83    /// The environment of the running process. Only the binary calls this.
84    pub fn from_process() -> Env {
85        Env::from_pairs(std::env::vars_os(), NameCase::host())
86    }
87
88    /// An environment holding exactly `pairs`, with names compared as `case`
89    /// says; a later pair replaces an earlier one with the same name.
90    pub fn from_pairs(
91        pairs: impl IntoIterator<Item = (OsString, OsString)>,
92        case: NameCase,
93    ) -> Env {
94        let vars = pairs
95            .into_iter()
96            .map(|(name, value)| (fold(&name, case), (name, value)))
97            .collect();
98        Env { case, vars }
99    }
100
101    /// The value of `name`, if it is set.
102    pub fn get(&self, name: &str) -> Option<&OsStr> {
103        self.vars
104            .get(&fold(OsStr::new(name), self.case))
105            .map(|(_, value)| value.as_os_str())
106    }
107
108    /// The value of cuno's own variable `name` (`CUNO_HOME` and the like),
109    /// or `None` when it is unset or empty: an empty one counts as unset
110    /// (`docs/en/specs/manifest.md`, "Two levels of settings"). Not for
111    /// `NO_COLOR`, which is set even when empty.
112    pub fn set_value(&self, name: &str) -> Option<&OsStr> {
113        self.get(name).filter(|value| !value.is_empty())
114    }
115
116    /// Every variable, as (name as spelled, value), for giving a child
117    /// process exactly this environment.
118    pub fn vars(&self) -> impl Iterator<Item = (&OsStr, &OsStr)> {
119        self.vars
120            .values()
121            .map(|(name, value)| (name.as_os_str(), value.as_os_str()))
122    }
123
124    /// This environment with `name` set to `value`, replacing any variable
125    /// that has the same name as this environment compares names.
126    pub fn with(&self, name: &str, value: OsString) -> Env {
127        let mut env = self.clone();
128        env.vars
129            .insert(fold(OsStr::new(name), self.case), (name.into(), value));
130        env
131    }
132
133    /// This environment without the variables named in `names`, compared as
134    /// this environment compares names.
135    pub fn without(&self, names: &[&str]) -> Env {
136        let mut env = self.clone();
137        for name in names {
138            env.vars.remove(&fold(OsStr::new(name), self.case));
139        }
140        env
141    }
142}
143
144/// The name as compared. Case-insensitive names are upper-cased one character
145/// at a time, keeping a character whose upper case is more than one character
146/// (such as `ß`): Windows folds names character by character, so `ß` must not
147/// become `SS`. Names that are not valid Unicode are kept as they are.
148pub(crate) fn fold(name: &OsStr, case: NameCase) -> OsString {
149    match (case, name.to_str()) {
150        (NameCase::Insensitive, Some(name)) => name
151            .chars()
152            .map(|c| {
153                let mut upper = c.to_uppercase();
154                match (upper.next(), upper.next()) {
155                    (Some(u), None) => u,
156                    _ => c,
157                }
158            })
159            .collect::<String>()
160            .into(),
161        _ => name.to_owned(),
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    /// Only `PATH`'s absolute entries are searched, in their order; an
170    /// empty or relative one is left out.
171    ///
172    /// Mutation: keep relative or empty entries, or drop the order; this
173    /// test fails.
174    #[test]
175    fn only_absolute_path_entries_are_searched() {
176        let a = std::env::temp_dir().join("a");
177        let b = std::env::temp_dir().join("b");
178        let path = std::env::join_paths([b.clone(), "rel".into(), "".into(), a.clone()]).unwrap();
179        let env = Env::from_pairs([("PATH".into(), path)], NameCase::Insensitive);
180        assert_eq!(env.search_dirs(), [b, a]);
181        assert!(
182            Env::from_pairs([], NameCase::Insensitive)
183                .search_dirs()
184                .is_empty()
185        );
186    }
187
188    fn env(pairs: &[(&str, &str)], case: NameCase) -> Env {
189        Env::from_pairs(pairs.iter().map(|(n, v)| (n.into(), v.into())), case)
190    }
191
192    /// An empty value counts as unset for `set_value` and not for `get`.
193    ///
194    /// Mutation: let `set_value` return an empty value or drop a non-empty
195    /// one, or make `get` drop an empty one; this test fails.
196    #[test]
197    fn an_empty_value_is_unset_for_set_value_only() {
198        let e = env(
199            &[("CUNO_HOME", ""), ("CUNO_COMPILER", "clang")],
200            NameCase::Insensitive,
201        );
202        assert_eq!(e.set_value("CUNO_HOME"), None);
203        assert_eq!(e.get("CUNO_HOME"), Some(OsStr::new("")));
204        assert_eq!(e.set_value("CUNO_COMPILER"), Some(OsStr::new("clang")));
205        assert_eq!(e.set_value("CUNO_TARGET_DIR"), None);
206    }
207
208    /// Mutation: make `fold` ignore `case`, in either direction, or have an
209    /// `Env` report another case than it was built with; this test fails.
210    #[test]
211    fn names_are_compared_as_the_case_says() {
212        let windows = env(&[("Path", "C:\\bin")], NameCase::Insensitive);
213        assert_eq!(windows.get("PATH"), Some(OsStr::new("C:\\bin")));
214        assert_eq!(windows.get("path"), Some(OsStr::new("C:\\bin")));
215        let other = env(&[("Path", "/bin")], NameCase::Sensitive);
216        assert_eq!(other.get("Path"), Some(OsStr::new("/bin")));
217        assert_eq!(other.get("PATH"), None);
218        assert_eq!(
219            (windows.case(), other.case()),
220            (NameCase::Insensitive, NameCase::Sensitive)
221        );
222        assert!(NameCase::Insensitive.same("Main", "MAIN"));
223        assert!(!NameCase::Sensitive.same("Main", "MAIN"));
224    }
225
226    /// Mutation: upper-case with `str::to_uppercase` (which turns `ß` into
227    /// `SS`); this test fails.
228    #[test]
229    fn folding_is_character_by_character() {
230        let e = env(&[("STRAßE", "1")], NameCase::Insensitive);
231        assert_eq!(e.get("straße"), Some(OsStr::new("1")));
232        assert_eq!(e.get("STRASSE"), None);
233    }
234
235    /// Mutation: make `without` compare names case-sensitively, or make `vars`
236    /// return the folded key instead of the spelling; this test fails.
237    #[test]
238    fn without_removes_by_name_and_vars_keeps_the_spelling() {
239        let e = env(
240            &[("Path", "C:\\bin"), ("cl", "/nologo")],
241            NameCase::Insensitive,
242        );
243        let rest = e.without(&["CL"]);
244        assert_eq!(rest.get("cl"), None);
245        let vars: Vec<_> = rest.vars().collect();
246        assert_eq!(vars, [(OsStr::new("Path"), OsStr::new("C:\\bin"))]);
247    }
248
249    /// Mutation: keep the first of two pairs with the same name; this test
250    /// fails.
251    /// Mutation: insert under the name as spelled instead of as compared;
252    /// this test fails (`Path` would survive beside `PATH`).
253    #[test]
254    fn with_replaces_a_variable_spelled_differently() {
255        let env = env(&[("Path", "old")], NameCase::Insensitive).with("path", "new".into());
256        assert_eq!(env.get("PATH"), Some(OsStr::new("new")));
257        assert_eq!(env.vars().count(), 1);
258    }
259
260    #[test]
261    fn a_later_pair_replaces_an_earlier_one() {
262        let e = env(
263            &[("CUNO_X", "first"), ("CUNO_X", "second")],
264            NameCase::Sensitive,
265        );
266        assert_eq!(e.get("CUNO_X"), Some(OsStr::new("second")));
267    }
268
269    /// Mutation: make `from_process` return an empty environment; this test
270    /// fails (`PATH` is set in every process the tests run in).
271    #[test]
272    fn from_process_reads_the_process_environment() {
273        assert!(Env::from_process().get("PATH").is_some());
274    }
275
276    /// Mutation: make `NameCase::host` return the other variant; this test
277    /// fails.
278    #[test]
279    fn the_host_case_matches_the_platform() {
280        let expected = if cfg!(windows) {
281            NameCase::Insensitive
282        } else {
283            NameCase::Sensitive
284        };
285        assert_eq!(NameCase::host(), expected);
286    }
287}