Skip to main content

cargo/context/
environment.rs

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