Skip to main content

cargo_util_config/
env.rs

1//! Encapsulates snapshotting of environment variables.
2
3use cargo_util::collections::{BuildHasher, HashMap};
4use std::ffi::{OsStr, OsString};
5
6use anyhow::{Result, anyhow, bail};
7
8/// A snapshot of the environment variables available to `GlobalContext`.
9///
10/// Currently, the `GlobalContext` supports lookup of environment variables
11/// through two different means:
12///
13/// - `GlobalContext::get_env`
14///   and `GlobalContext::get_env_os`
15///   for process environment variables (similar to [`std::env::var`] and [`std::env::var_os`]),
16/// - Typed Config Value API via `GlobalContext::get`.
17///   This is only available for `CARGO_` prefixed environment keys.
18///
19/// This type contains the env var snapshot and helper methods for both APIs.
20#[derive(Default, Debug)]
21pub struct Env {
22    /// A snapshot of the process's environment variables.
23    env: HashMap<OsString, OsString>,
24    /// Used in the typed Config value API for warning messages when config keys are
25    /// given in the wrong format.
26    ///
27    /// Maps from "normalized" (upper case and with "-" replaced by "_") env keys
28    /// to the actual keys in the environment.
29    /// The normalized format is the one expected by Cargo.
30    ///
31    /// This only holds env keys that are valid UTF-8, since [`super::ConfigKey`] only supports UTF-8 keys.
32    /// In addition, this only holds env keys whose value in the environment is also valid UTF-8,
33    /// since the typed Config value API only supports UTF-8 values.
34    normalized_env: HashMap<String, String>,
35    /// Used to implement `get_env` and `get_env_os` on Windows, where env keys are case-insensitive.
36    ///
37    /// Maps from uppercased env keys to the actual key in the environment.
38    /// For example, this might hold a pair `("PATH", "Path")`.
39    /// Currently only supports UTF-8 keys and values.
40    #[cfg(windows)]
41    case_insensitive_env: HashMap<String, String>,
42}
43
44impl Env {
45    /// Creates an empty environment.
46    pub const fn new() -> Self {
47        Self {
48            env: HashMap::with_hasher(BuildHasher),
49            normalized_env: HashMap::with_hasher(BuildHasher),
50            #[cfg(windows)]
51            case_insensitive_env: HashMap::with_hasher(BuildHasher),
52        }
53    }
54
55    /// Takes a snapshot of the current process's environment variables.
56    pub fn from_env() -> Self {
57        #[expect(clippy::disallowed_methods, reason = "seeds `GlobalContext::get_env`")]
58        let env: HashMap<_, _> = std::env::vars_os().collect();
59        Self::from_map_os(env)
60    }
61
62    /// Set the env directly from a `HashMap`.
63    /// This should be used for debugging purposes only.
64    pub fn from_map(env: HashMap<String, String>) -> Self {
65        let env = env.into_iter().map(|(k, v)| (k.into(), v.into())).collect();
66        Self::from_map_os(env)
67    }
68
69    pub(crate) fn from_map_os(env: HashMap<OsString, OsString>) -> Self {
70        #[cfg(windows)]
71        let case_insensitive_env = make_case_insensitive_env(&env);
72        let normalized_env = make_normalized_env(&env);
73        Self {
74            env,
75            #[cfg(windows)]
76            case_insensitive_env,
77            normalized_env,
78        }
79    }
80
81    /// Returns all environment variables as an iterator,
82    /// keeping only entries where both the key and value are valid UTF-8.
83    pub fn iter_str(&self) -> impl Iterator<Item = (&str, &str)> {
84        self.env
85            .iter()
86            .filter_map(|(k, v)| Some((k.to_str()?, v.to_str()?)))
87    }
88
89    /// Returns all environment variable keys, filtering out keys that are not valid UTF-8.
90    pub fn keys_str(&self) -> impl Iterator<Item = &str> {
91        self.env.keys().filter_map(|k| k.to_str())
92    }
93
94    /// Get the value of environment variable `key` through the snapshot in
95    /// `GlobalContext`.
96    ///
97    /// This can be used similarly to [`std::env::var_os`].
98    /// On Windows, we check for case mismatch since environment keys are case-insensitive.
99    pub fn get_env_os(&self, key: impl AsRef<OsStr>) -> Option<&OsStr> {
100        #[cfg(windows)]
101        match self.env.get(key.as_ref()) {
102            Some(s) => Some(s),
103            #[cfg(windows)]
104            None => self.get_env_case_insensitive(key),
105        }
106        #[cfg(not(windows))]
107        self.env.get(key.as_ref()).map(|s| s.as_os_str())
108    }
109
110    /// Get the value of environment variable `key` through the `self.env` snapshot.
111    ///
112    /// This can be used similarly to `std::env::var`.
113    /// On Windows, we check for case mismatch since environment keys are case-insensitive.
114    pub fn get_env(&self, key: impl AsRef<OsStr>) -> Result<&str> {
115        let key = key.as_ref();
116        let s = self
117            .get_env_os(key)
118            .ok_or_else(|| anyhow!("{key:?} could not be found in the environment snapshot"))?;
119
120        match s.to_str() {
121            Some(s) => Ok(s),
122            None => bail!("environment variable value is not valid unicode: {s:?}"),
123        }
124    }
125
126    /// Performs a case-insensitive lookup of `key` in the environment.
127    ///
128    /// This is relevant on Windows, where environment variables are case-insensitive.
129    /// Note that this only works on keys that are valid UTF-8 and it uses Unicode uppercase,
130    /// which may differ from the OS's notion of uppercase.
131    #[cfg(windows)]
132    fn get_env_case_insensitive(&self, key: impl AsRef<OsStr>) -> Option<&OsStr> {
133        let upper_case_key = key.as_ref().to_str()?.to_uppercase();
134        let env_key: &OsStr = self.case_insensitive_env.get(&upper_case_key)?.as_ref();
135        self.env.get(env_key).map(|v| v.as_ref())
136    }
137
138    /// Get the value of environment variable `key` as a `&str`.
139    /// Returns `None` if `key` is not in `self.env` or if the value is not valid UTF-8.
140    ///
141    /// This is intended for use in private methods of `GlobalContext`,
142    /// and does not check for env key case mismatch.
143    ///
144    /// This is case-sensitive on Windows (even though environment keys on Windows are usually
145    /// case-insensitive) due to an unintended regression in 1.28 (via #5552).
146    /// This should only affect keys used for cargo's config-system env variables (`CARGO_`
147    /// prefixed ones), which are currently all uppercase.
148    /// We may want to consider rectifying it if users report issues.
149    /// One thing that adds a wrinkle here is the unstable advanced-env option that *requires*
150    /// case-sensitive keys.
151    ///
152    /// Do not use this for any other purposes.
153    /// Use [`Env::get_env_os`] or [`Env::get_env`] instead, which properly handle case
154    /// insensitivity on Windows.
155    pub(crate) fn get_str(&self, key: impl AsRef<OsStr>) -> Option<&str> {
156        self.env.get(key.as_ref()).and_then(|s| s.to_str())
157    }
158
159    /// Check if the environment contains `key`.
160    ///
161    /// This is intended for use in private methods of `GlobalContext`,
162    /// and does not check for env key case mismatch.
163    /// See the docstring of [`Env::get_str`] for more context.
164    pub(crate) fn contains_key(&self, key: impl AsRef<OsStr>) -> bool {
165        self.env.contains_key(key.as_ref())
166    }
167
168    /// Looks up a normalized `key` in the `normalized_env`.
169    /// Returns the corresponding (non-normalized) env key if it exists, else `None`.
170    ///
171    /// Used to diagnose configuration environment variables with mismatched case.
172    pub(crate) fn get_normalized(&self, key: &str) -> Option<&str> {
173        self.normalized_env.get(key).map(|s| s.as_ref())
174    }
175}
176
177/// Generate `case_insensitive_env` from the `env`.
178#[cfg(windows)]
179fn make_case_insensitive_env(env: &HashMap<OsString, OsString>) -> HashMap<String, String> {
180    env.keys()
181        .filter_map(|k| k.to_str())
182        .map(|k| (k.to_uppercase(), k.to_owned()))
183        .collect()
184}
185
186/// Generate `normalized_env` from the `env`.
187fn make_normalized_env(env: &HashMap<OsString, OsString>) -> HashMap<String, String> {
188    env.iter()
189        // Only keep entries where both the key and value are valid UTF-8,
190        // since the config env vars only support UTF-8 keys and values.
191        // Otherwise, the normalized map warning could incorrectly warn about entries that can't be
192        // read by the config system.
193        // Please see the docs for `Env` for more context.
194        .filter_map(|(k, v)| Some((k.to_str()?, v.to_str()?)))
195        .map(|(k, _)| (k.to_uppercase().replace("-", "_"), k.to_owned()))
196        .collect()
197}