rust-lang/cargo · error

could not be found in the environment snapshot

Error message

{key:?} could not be found in the environment snapshot

What it means

`GlobalContext::get_env(key)` looks up an environment variable in Cargo's captured snapshot (`self.env`), not the live `std::env`. The snapshot had no entry (case-insensitively on Windows) for the requested key, so it returns this error rather than falling back to the OS environment.

Solutions

  1. Ensure the variable is exported in the shell/CI before invoking cargo: `export FOO=...`.
  2. Use `get_env_os` and handle `None` if absence is expected.
  3. Set the var in `.cargo/config.toml` `[env]` section so it enters the snapshot.
  4. Verify spelling and case (on Windows, case-insensitive but must be valid UTF-8).

Example fix

// before
let v = gctx.get_env("MY_TOOL")?;  // not in snapshot

// after (in .cargo/config.toml)
[env]
MY_TOOL = "/usr/local/bin/my-tool"
Defensive patterns

Strategy: try-catch

Validate before calling

fn env_snapshot_has(gctx: &GlobalContext, key: &str) -> bool {
    gctx.get_env_os(key).is_some()
}

Type guard

null

Try / catch

match gctx.get_env("MY_VAR") {
    Ok(v) => v.to_string(),
    Err(_) => std::env::var("MY_VAR").unwrap_or_default(),
}

Prevention

When it happens

Trigger: Calling `gctx.get_env("FOO")` for a variable that wasn't in the process environment when `GlobalContext` was constructed, or one Cargo intentionally did not snapshot (e.g. read before snapshot rebuild).

Common situations: Cargo-internal callers expecting `RUSTUP_TOOLCHAIN`, `CARGO_HOME`, or a custom var that the user forgot to export; env vars cleared by a sandbox; race between construction and a later setter.

Related errors


AI-assisted analysis of rust-lang/cargo@eb98b54bc9 (2026-08-11). Data as JSON: /api/errors/e525db0cafacd419. Report an issue: GitHub.

Appendix: source

Thrown at src/context/environment.rs:133

            None => {
                if cfg!(windows) {
                    self.get_env_case_insensitive(key)
                } else {
                    None
                }
            }
        }
    }

    /// Get the value of environment variable `key` through the `self.env` snapshot.
    ///
    /// This can be used similarly to `std::env::var`.
    /// On Windows, we check for case mismatch since environment keys are case-insensitive.
    pub fn get_env(&self, key: impl AsRef<OsStr>) -> CargoResult<&str> {
        let key = key.as_ref();
        let s = self
            .get_env_os(key)
            .ok_or_else(|| anyhow!("{key:?} could not be found in the environment snapshot"))?;

        match s.to_str() {
            Some(s) => Ok(s),
            None => bail!("environment variable value is not valid unicode: {s:?}"),
        }
    }

    /// Performs a case-insensitive lookup of `key` in the environment.
    ///
    /// This is relevant on Windows, where environment variables are case-insensitive.
    /// Note that this only works on keys that are valid UTF-8 and it uses Unicode uppercase,
    /// which may differ from the OS's notion of uppercase.
    fn get_env_case_insensitive(&self, key: impl AsRef<OsStr>) -> Option<&OsStr> {
        let upper_case_key = key.as_ref().to_str()?.to_uppercase();
        let env_key: &OsStr = self.case_insensitive_env.get(&upper_case_key)?.as_ref();
        self.env.get(env_key).map(|v| v.as_ref())
    }

View on GitHub (pinned to eb98b54bc9)