Skip to main content

cargo/context/
mod.rs

1//! Cargo's config system.
2//!
3//! The [`GlobalContext`] object contains general information about the environment,
4//! and provides access to Cargo's configuration files.
5//!
6//! ## Config value API
7//!
8//! The primary API for fetching user-defined config values is the
9//! [`GlobalContext::get`] method. It uses `serde` to translate config values to a
10//! target type.
11//!
12//! There are a variety of helper types for deserializing some common formats:
13//!
14//! - [`value::Value`]: This type provides access to the location where the
15//!   config value was defined.
16//! - [`ConfigRelativePath`]: For a path that is relative to where it is
17//!   defined.
18//! - [`PathAndArgs`]: Similar to [`ConfigRelativePath`],
19//!   but also supports a list of arguments, useful for programs to execute.
20//! - [`StringList`]: Get a value that is either a list or a whitespace split
21//!   string.
22//!
23//! # Config schemas
24//!
25//! Configuration schemas are defined in the [`schema`] module.
26//!
27//! ## Config deserialization
28//!
29//! Cargo uses a two-layer deserialization approach:
30//!
31//! 1. **External sources → `ConfigValue`** ---
32//!    Configuration files, environment variables, and CLI `--config` arguments
33//!    are parsed into [`ConfigValue`] instances via [`ConfigValue::from_toml`].
34//!    These parsed results are stored in [`GlobalContext`].
35//!
36//! 2. **`ConfigValue` → Target types** ---
37//!    The [`GlobalContext::get`] method uses a [custom serde deserializer](Deserializer)
38//!    to convert [`ConfigValue`] instances to the caller's desired type.
39//!    Precedence between [`ConfigValue`] sources is resolved during retrieval
40//!    based on [`Definition`] priority.
41//!    See the top-level documentation of the [`de`] module for more.
42//!
43//! ## Map key recommendations
44//!
45//! Handling tables that have arbitrary keys can be tricky, particularly if it
46//! should support environment variables. In general, if possible, the caller
47//! should pass the full key path into the `get()` method so that the config
48//! deserializer can properly handle environment variables (which need to be
49//! uppercased, and dashes converted to underscores).
50//!
51//! A good example is the `[target]` table. The code will request
52//! `target.$TUPLE` and the config system can then appropriately fetch
53//! environment variables like `CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER`.
54//! Conversely, it is not possible do the same thing for the `cfg()` target
55//! tables (because Cargo must fetch all of them), so those do not support
56//! environment variables.
57//!
58//! Try to avoid keys that are a prefix of another with a dash/underscore. For
59//! example `build.target` and `build.target-dir`. This is OK if these are not
60//! structs/maps, but if it is a struct or map, then it will not be able to
61//! read the environment variable due to ambiguity. (See `ConfigMapAccess` for
62//! more details.)
63
64use crate::util::data_structures::{HashMap, HashSet};
65use std::borrow::Cow;
66use std::env;
67use std::ffi::{OsStr, OsString};
68use std::fmt;
69use std::fs::File;
70use std::io::SeekFrom;
71use std::io::prelude::*;
72use std::path::{Path, PathBuf};
73use std::str::FromStr;
74use std::sync::{Arc, LazyLock, Mutex, MutexGuard, OnceLock};
75use std::time::Instant;
76
77use self::ConfigValue as CV;
78use crate::ops::RegistryCredentialConfig;
79use crate::sources::CRATES_IO_INDEX;
80use crate::sources::CRATES_IO_REGISTRY;
81use crate::util::OnceExt as _;
82use crate::util::VersionReqMatchMode;
83use crate::util::cache_lock::{CacheLock, CacheLockMode, CacheLocker};
84use crate::util::errors::CargoResult;
85use crate::util::network::http::{HandleConfiguration, configure_http_handle, http_handle};
86use crate::util::network::http_async;
87use crate::util::restricted_names::is_glob_pattern;
88use crate::util::{CanonicalUrl, closest_msg, internal};
89use crate::util::{Filesystem, IntoUrl, IntoUrlWithBase, Rustc};
90use crate::workspace::global_cache_tracker::{DeferredGlobalLastUse, GlobalCacheTracker};
91use crate::workspace::{CliUnstable, SourceId, Workspace, WorkspaceRootConfig, features};
92
93use anyhow::{Context as _, anyhow, bail, format_err};
94use cargo_credential::Secret;
95use cargo_util::paths;
96use cargo_util_schemas::manifest::RegistryName;
97use cargo_util_terminal::report::Level;
98use cargo_util_terminal::{Shell, Verbosity};
99use curl::easy::Easy;
100use itertools::Itertools;
101use serde::Deserialize;
102use serde::de::IntoDeserializer as _;
103use time::OffsetDateTime;
104use toml_edit::Item;
105use url::Url;
106
107mod de;
108use de::Deserializer;
109
110mod error;
111pub use error::ConfigError;
112
113use crate::config::is_nonmergeable_list;
114pub use crate::config::{ConfigKey, ConfigStore, ConfigValue, Definition, DefinitionKind};
115
116mod value;
117pub use value::{OptValue, Value};
118
119mod path;
120pub use path::BracketType;
121pub use path::ConfigRelativePath;
122pub use path::PathAndArgs;
123pub use path::ResolveTemplateError;
124
125mod target;
126pub use target::{TargetCfgConfig, TargetConfig};
127
128mod environment;
129use environment::Env;
130
131mod schema;
132pub use schema::*;
133
134/// Helper macro for creating typed access methods.
135macro_rules! get_value_typed {
136    ($name:ident, $ty:ty, $variant:ident, $expected:expr) => {
137        /// Low-level private method for getting a config value as an [`OptValue`].
138        fn $name(&self, key: &ConfigKey) -> Result<OptValue<$ty>, ConfigError> {
139            let cv = self.config()?.get_cv(key)?;
140            let env = self.get_config_env::<$ty>(key)?;
141            match (cv, env) {
142                (Some(CV::$variant(val, definition)), Some(env)) => {
143                    if definition.is_higher_priority(&env.definition) {
144                        Ok(Some(Value { val, definition }))
145                    } else {
146                        Ok(Some(env))
147                    }
148                }
149                (Some(CV::$variant(val, definition)), None) => Ok(Some(Value { val, definition })),
150                (Some(cv), _) => Err(ConfigError::expected(key, $expected, &cv)),
151                (None, Some(env)) => Ok(Some(env)),
152                (None, None) => Ok(None),
153            }
154        }
155    };
156}
157
158pub const TOP_LEVEL_CONFIG_KEYS: &[&str] = &[
159    "paths",
160    "alias",
161    "build",
162    "credential-alias",
163    "doc",
164    "env",
165    "future-incompat-report",
166    "cache",
167    "cargo-new",
168    "http",
169    "install",
170    "net",
171    "patch",
172    "profile",
173    "resolver",
174    "registries",
175    "registry",
176    "source",
177    "target",
178    "term",
179];
180
181/// A previously generated authentication token and the data needed to determine if it can be reused.
182#[derive(Debug)]
183pub struct CredentialCacheValue {
184    pub token_value: Secret<String>,
185    pub expiration: Option<OffsetDateTime>,
186    pub operation_independent: bool,
187}
188
189/// Configuration information for cargo. This is not specific to a build, it is information
190/// relating to cargo itself.
191#[derive(Debug)]
192pub struct GlobalContext {
193    /// The location of the user's Cargo home directory. OS-dependent.
194    home_path: Filesystem,
195    /// Information about how to write messages to the shell
196    shell: Mutex<Shell>,
197    /// A collection of configuration options
198    config: OnceLock<ConfigStore>,
199    /// A collection of configuration options from the credentials file
200    credentials_config: OnceLock<ConfigStore>,
201    /// CLI config values, passed in via `configure`.
202    cli_config: Option<Vec<String>>,
203    /// The current working directory of cargo
204    cwd: PathBuf,
205    /// Directory where config file searching should stop (inclusive).
206    search_stop_path: Option<PathBuf>,
207    /// The location of the cargo executable (path to current process)
208    cargo_exe: OnceLock<PathBuf>,
209    /// The location of the rustdoc executable
210    rustdoc: OnceLock<PathBuf>,
211    /// Whether we are printing extra verbose messages
212    extra_verbose: bool,
213    /// `frozen` is the same as `locked`, but additionally will not access the
214    /// network to determine if the lock file is out-of-date.
215    frozen: bool,
216    /// `locked` is set if we should not update lock files. If the lock file
217    /// is missing, or needs to be updated, an error is produced.
218    locked: bool,
219    /// `offline` is set if we should never access the network, but otherwise
220    /// continue operating if possible.
221    offline: bool,
222    /// A global static IPC control mechanism (used for managing parallel builds)
223    jobserver: Option<&'static jobserver::Client>,
224    /// Cli flags of the form "-Z something" merged with config file values
225    unstable_flags: CliUnstable,
226    /// Cli flags of the form "-Z something"
227    unstable_flags_cli: Option<Vec<String>>,
228    /// A handle on curl easy mode for http calls
229    easy: OnceLock<Mutex<Easy>>,
230    /// Cache of the `SourceId` for crates.io
231    crates_io_source_id: OnceLock<SourceId>,
232    /// If false, don't cache `rustc --version --verbose` invocations
233    cache_rustc_info: bool,
234    /// Monotonic start of this cargo invocation for reporting time elapsed.
235    invocation_instant: Instant,
236    /// Wall-clock time of this cargo invocation.
237    ///
238    /// Currently used as the reference time for `min-publish-age` and `-Zbuild-analysis`.
239    invocation_time: jiff::Timestamp,
240    /// Target Directory via resolved Cli parameter
241    target_dir: Option<Filesystem>,
242    /// Environment variable snapshot.
243    env: Env,
244    /// Tracks which sources have been updated to avoid multiple updates.
245    updated_sources: Mutex<HashSet<SourceId>>,
246    /// Cache of credentials from configuration or credential providers.
247    /// Maps from url to credential value.
248    credential_cache: Mutex<HashMap<CanonicalUrl, CredentialCacheValue>>,
249    /// Cache of registry config from the `[registries]` table.
250    registry_config: Mutex<HashMap<SourceId, Option<RegistryConfig>>>,
251    /// Locks on the package and index caches.
252    package_cache_lock: CacheLocker,
253    /// Cached configuration parsed by Cargo
254    http_config: OnceLock<CargoHttpConfig>,
255    http_async: OnceLock<http_async::Client>,
256    future_incompat_config: OnceLock<CargoFutureIncompatConfig>,
257    net_config: OnceLock<CargoNetConfig>,
258    build_config: OnceLock<CargoBuildConfig>,
259    target_cfgs: OnceLock<Vec<(String, TargetCfgConfig)>>,
260    doc_extern_map: OnceLock<RustdocExternMap>,
261    progress_config: ProgressConfig,
262    env_config: OnceLock<Arc<HashMap<String, OsString>>>,
263    /// This should be false if:
264    /// - this is an artifact of the rustc distribution process for "stable" or for "beta"
265    /// - this is an `#[test]` that does not opt in with `enable_nightly_features`
266    /// - this is an integration test that uses `ProcessBuilder`
267    ///      that does not opt in with `masquerade_as_nightly_cargo`
268    /// This should be true if:
269    /// - this is an artifact of the rustc distribution process for "nightly"
270    /// - this is being used in the rustc distribution process internally
271    /// - this is a cargo executable that was built from source
272    /// - this is an `#[test]` that called `enable_nightly_features`
273    /// - this is an integration test that uses `ProcessBuilder`
274    ///       that called `masquerade_as_nightly_cargo`
275    /// It's public to allow tests use nightly features.
276    /// NOTE: this should be set before `configure()`. If calling this from an integration test,
277    /// consider using `ConfigBuilder::enable_nightly_features` instead.
278    pub nightly_features_allowed: bool,
279    /// `WorkspaceRootConfigs` that have been found
280    ws_roots: Mutex<HashMap<PathBuf, WorkspaceRootConfig>>,
281    /// The global cache tracker is a database used to track disk cache usage.
282    global_cache_tracker: OnceLock<Mutex<GlobalCacheTracker>>,
283    /// A cache of modifications to make to [`GlobalContext::global_cache_tracker`],
284    /// saved to disk in a batch to improve performance.
285    deferred_global_last_use: OnceLock<Mutex<DeferredGlobalLastUse>>,
286}
287
288impl GlobalContext {
289    /// Creates a new config instance.
290    ///
291    /// This is typically used for tests or other special cases. `default` is
292    /// preferred otherwise.
293    ///
294    /// This does only minimal initialization. In particular, it does not load
295    /// any config files from disk. Those will be loaded lazily as-needed.
296    pub fn new(mut shell: Shell, cwd: PathBuf, homedir: PathBuf) -> GlobalContext {
297        static GLOBAL_JOBSERVER: LazyLock<CargoResult<Option<jobserver::Client>>> = LazyLock::new(
298            || {
299                use jobserver::FromEnvErrorKind;
300                // Note that this is unsafe because it may misinterpret file descriptors
301                // on Unix as jobserver file descriptors. We hopefully execute this near
302                // the beginning of the process though to ensure we don't get false
303                // positives, or in other words we try to execute this before we open
304                // any file descriptors ourselves.
305                let jobserver::FromEnv { client, var } =
306                    unsafe { jobserver::Client::from_env_ext(true) };
307
308                match client {
309                    Ok(client) => return Ok(Some(client)),
310                    Err(e)
311                        if matches!(
312                            e.kind(),
313                            FromEnvErrorKind::NoEnvVar
314                                | FromEnvErrorKind::NoJobserver
315                                | FromEnvErrorKind::NegativeFd
316                                | FromEnvErrorKind::Unsupported
317                        ) =>
318                    {
319                        Ok(None)
320                    }
321                    Err(e) => {
322                        let (name, value) = var.unwrap();
323                        Err(anyhow::anyhow!(
324                            "failed to connect to jobserver from environment variable `{name}={value:?}`: {e}"
325                        ))
326                    }
327                }
328            },
329        );
330        let jobserver = match &*GLOBAL_JOBSERVER {
331            Ok(jobserver) => jobserver.as_ref(),
332            Err(e) => {
333                let _ = shell.warn(e);
334                None
335            }
336        };
337
338        let env = Env::new();
339
340        let cache_key = "CARGO_CACHE_RUSTC_INFO";
341        let cache_rustc_info = match env.get_env_os(cache_key) {
342            Some(cache) => cache != "0",
343            _ => true,
344        };
345
346        #[expect(
347            clippy::disallowed_methods,
348            reason = "testing only, no reason for config support"
349        )]
350        let invocation_time = match env::var("__CARGO_TEST_INVOCATION_TIME") {
351            Ok(now) => now.parse().unwrap(),
352            Err(_) => jiff::Timestamp::now(),
353        };
354
355        GlobalContext {
356            home_path: Filesystem::new(homedir),
357            shell: Mutex::new(shell),
358            cwd,
359            search_stop_path: None,
360            config: Default::default(),
361            credentials_config: Default::default(),
362            cli_config: None,
363            cargo_exe: Default::default(),
364            rustdoc: Default::default(),
365            extra_verbose: false,
366            frozen: false,
367            locked: false,
368            offline: false,
369            jobserver,
370            unstable_flags: CliUnstable::default(),
371            unstable_flags_cli: None,
372            easy: Default::default(),
373            crates_io_source_id: Default::default(),
374            cache_rustc_info,
375            invocation_instant: Instant::now(),
376            invocation_time,
377            target_dir: None,
378            env,
379            updated_sources: Default::default(),
380            credential_cache: Default::default(),
381            registry_config: Default::default(),
382            package_cache_lock: CacheLocker::new(),
383            http_config: Default::default(),
384            http_async: Default::default(),
385            future_incompat_config: Default::default(),
386            net_config: Default::default(),
387            build_config: Default::default(),
388            target_cfgs: Default::default(),
389            doc_extern_map: Default::default(),
390            progress_config: ProgressConfig::default(),
391            env_config: Default::default(),
392            nightly_features_allowed: matches!(&*features::channel(), "nightly" | "dev"),
393            ws_roots: Default::default(),
394            global_cache_tracker: Default::default(),
395            deferred_global_last_use: Default::default(),
396        }
397    }
398
399    /// Creates a new instance, with all default settings.
400    ///
401    /// This does only minimal initialization. In particular, it does not load
402    /// any config files from disk. Those will be loaded lazily as-needed.
403    pub fn default() -> CargoResult<GlobalContext> {
404        let shell = Shell::new();
405        let cwd =
406            env::current_dir().context("couldn't get the current directory of the process")?;
407        let homedir = homedir(&cwd).ok_or_else(|| {
408            anyhow!(
409                "Cargo couldn't find your home directory. \
410                 This probably means that $HOME was not set."
411            )
412        })?;
413        Ok(GlobalContext::new(shell, cwd, homedir))
414    }
415
416    /// Gets the user's Cargo home directory (OS-dependent).
417    pub fn home(&self) -> &Filesystem {
418        &self.home_path
419    }
420
421    /// Returns a path to display to the user with the location of their home
422    /// config file (to only be used for displaying a diagnostics suggestion,
423    /// such as recommending where to add a config value).
424    pub fn diagnostic_home_config(&self) -> String {
425        let home = self.home_path.as_path_unlocked();
426        let path = match self.get_file_path(home, "config", false) {
427            Ok(Some(existing_path)) => existing_path,
428            _ => home.join("config.toml"),
429        };
430        path.to_string_lossy().to_string()
431    }
432
433    /// Gets the Cargo Git directory (`<cargo_home>/git`).
434    pub fn git_path(&self) -> Filesystem {
435        self.home_path.join("git")
436    }
437
438    /// Gets the directory of code sources Cargo checkouts from Git bare repos
439    /// (`<cargo_home>/git/checkouts`).
440    pub fn git_checkouts_path(&self) -> Filesystem {
441        self.git_path().join("checkouts")
442    }
443
444    /// Gets the directory for all Git bare repos Cargo clones
445    /// (`<cargo_home>/git/db`).
446    pub fn git_db_path(&self) -> Filesystem {
447        self.git_path().join("db")
448    }
449
450    /// Gets the Cargo base directory for all registry information (`<cargo_home>/registry`).
451    pub fn registry_base_path(&self) -> Filesystem {
452        self.home_path.join("registry")
453    }
454
455    /// Gets the Cargo registry index directory (`<cargo_home>/registry/index`).
456    pub fn registry_index_path(&self) -> Filesystem {
457        self.registry_base_path().join("index")
458    }
459
460    /// Gets the Cargo registry cache directory (`<cargo_home>/registry/cache`).
461    pub fn registry_cache_path(&self) -> Filesystem {
462        self.registry_base_path().join("cache")
463    }
464
465    /// Gets the Cargo registry source directory (`<cargo_home>/registry/src`).
466    pub fn registry_source_path(&self) -> Filesystem {
467        self.registry_base_path().join("src")
468    }
469
470    /// Gets the default Cargo registry.
471    pub fn default_registry(&self) -> CargoResult<Option<String>> {
472        Ok(self
473            .get_string(["registry", "default"])?
474            .map(|registry| registry.val))
475    }
476
477    /// Gets a reference to the shell, e.g., for writing error messages.
478    pub fn shell(&self) -> MutexGuard<'_, Shell> {
479        self.shell.lock().unwrap()
480    }
481
482    /// Assert [`Self::shell`] is not in use
483    ///
484    /// Testing might not identify bugs with two accesses to `shell` at once
485    /// due to conditional logic,
486    /// so place this outside of the conditions to catch these bugs in more situations.
487    pub fn debug_assert_shell_not_borrowed(&self) {
488        if cfg!(debug_assertions) {
489            match self.shell.try_lock() {
490                Ok(_) | Err(std::sync::TryLockError::Poisoned(_)) => (),
491                Err(std::sync::TryLockError::WouldBlock) => panic!("shell is borrowed!"),
492            }
493        }
494    }
495
496    /// Gets the path to the `rustdoc` executable.
497    pub fn rustdoc(&self) -> CargoResult<&Path> {
498        self.rustdoc
499            .try_borrow_with(|| Ok(self.get_tool(Tool::Rustdoc, &self.build_config()?.rustdoc)))
500            .map(AsRef::as_ref)
501    }
502
503    /// Gets the path to the `rustc` executable.
504    pub fn load_global_rustc(&self, ws: Option<&Workspace<'_>>) -> CargoResult<Rustc> {
505        let cache_location =
506            ws.map(|ws| ws.build_dir().join(".rustc_info.json").into_path_unlocked());
507        let wrapper = self.maybe_get_tool("rustc_wrapper", &self.build_config()?.rustc_wrapper);
508        let rustc_workspace_wrapper = self.maybe_get_tool(
509            "rustc_workspace_wrapper",
510            &self.build_config()?.rustc_workspace_wrapper,
511        );
512
513        Rustc::new(
514            self.get_tool(Tool::Rustc, &self.build_config()?.rustc),
515            wrapper,
516            rustc_workspace_wrapper,
517            &self
518                .home()
519                .join("bin")
520                .join("rustc")
521                .into_path_unlocked()
522                .with_extension(env::consts::EXE_EXTENSION),
523            if self.cache_rustc_info {
524                cache_location
525            } else {
526                None
527            },
528            self,
529        )
530    }
531
532    /// Gets the path to the `cargo` executable.
533    pub fn cargo_exe(&self) -> CargoResult<&Path> {
534        self.cargo_exe
535            .try_borrow_with(|| {
536                let from_env = || -> CargoResult<PathBuf> {
537                    // Try re-using the `cargo` set in the environment already. This allows
538                    // commands that use Cargo as a library to inherit (via `cargo <subcommand>`)
539                    // or set (by setting `$CARGO`) a correct path to `cargo` when the current exe
540                    // is not actually cargo (e.g., `cargo-*` binaries, Valgrind, `ld.so`, etc.).
541                    let exe = self
542                        .get_env_os(crate::CARGO_ENV)
543                        .map(PathBuf::from)
544                        .ok_or_else(|| anyhow!("$CARGO not set"))?;
545                    Ok(exe)
546                };
547
548                fn from_current_exe() -> CargoResult<PathBuf> {
549                    // Try fetching the path to `cargo` using `env::current_exe()`.
550                    // The method varies per operating system and might fail; in particular,
551                    // it depends on `/proc` being mounted on Linux, and some environments
552                    // (like containers or chroots) may not have that available.
553                    let exe = env::current_exe()?;
554                    Ok(exe)
555                }
556
557                fn from_argv() -> CargoResult<PathBuf> {
558                    // Grab `argv[0]` and attempt to resolve it to an absolute path.
559                    // If `argv[0]` has one component, it must have come from a `PATH` lookup,
560                    // so probe `PATH` in that case.
561                    // Otherwise, it has multiple components and is either:
562                    // - a relative path (e.g., `./cargo`, `target/debug/cargo`), or
563                    // - an absolute path (e.g., `/usr/local/bin/cargo`).
564                    let argv0 = env::args_os()
565                        .map(PathBuf::from)
566                        .next()
567                        .ok_or_else(|| anyhow!("no argv[0]"))?;
568                    paths::resolve_executable(&argv0)
569                }
570
571                // Determines whether `path` is a cargo binary.
572                // See: https://github.com/rust-lang/cargo/issues/15099#issuecomment-2666737150
573                fn is_cargo(path: &Path) -> bool {
574                    path.file_stem() == Some(OsStr::new("cargo"))
575                }
576
577                let from_current_exe = from_current_exe();
578                if from_current_exe.as_deref().is_ok_and(is_cargo) {
579                    return from_current_exe;
580                }
581
582                let from_argv = from_argv();
583                if from_argv.as_deref().is_ok_and(is_cargo) {
584                    return from_argv;
585                }
586
587                let exe = from_env()
588                    .or(from_current_exe)
589                    .or(from_argv)
590                    .context("couldn't get the path to cargo executable")?;
591                Ok(exe)
592            })
593            .map(AsRef::as_ref)
594    }
595
596    /// Which package sources have been updated, used to ensure it is only done once.
597    pub fn updated_sources(&self) -> MutexGuard<'_, HashSet<SourceId>> {
598        self.updated_sources.lock().unwrap()
599    }
600
601    /// Cached credentials from credential providers or configuration.
602    pub fn credential_cache(&self) -> MutexGuard<'_, HashMap<CanonicalUrl, CredentialCacheValue>> {
603        self.credential_cache.lock().unwrap()
604    }
605
606    /// Gets the configuration for a remote registry.
607    ///
608    /// The registry name is resolved from its index URL. This may emit a note if
609    /// the resolved name differs from the source's configured name. Returns
610    /// `None` if no configuration is found.
611    ///
612    /// **Note:** this does not load tokens from `credentials.toml`, see instead
613    /// [`Self::registry_credentials`].
614    pub fn registry_config(&self, sid: &SourceId) -> CargoResult<Option<RegistryConfig>> {
615        let mut cache = self.registry_config.lock().unwrap();
616        if let Some(cfg) = cache.get(sid) {
617            return Ok(cfg.clone());
618        }
619        let cfg = registry_config_uncached(self, sid)?;
620        cache.insert(*sid, cfg.clone());
621        Ok(cfg)
622    }
623
624    /// Gets the credentials configured for a remote registry.
625    ///
626    /// This loads credentials if needed and resolves the registry name in the
627    /// same way as [`GlobalContext::registry_config`].
628    pub fn registry_credentials(&self, sid: &SourceId) -> CargoResult<Option<RegistryCredential>> {
629        let credentials = self.credentials_config()?;
630        let mut key = if sid.is_crates_io() {
631            ConfigKey::from_parts(["registry"])
632        } else if let Some(name) = registry_name(self, sid)? {
633            ConfigKey::from_parts(["registries", &name])
634        } else {
635            return Ok(None);
636        };
637        let has_credentials = credentials.get_cv(&key)?.is_some();
638        key.push("token");
639        let credentials_token = match credentials.get_cv(&key)? {
640            Some(CV::String(val, definition)) => Some(Value {
641                val: Secret::from(val),
642                definition,
643            }),
644            Some(cv) => return Err(ConfigError::expected(&key, "a string", &cv).into()),
645            None => None,
646        };
647
648        let config = self.registry_config(sid)?;
649        let has_config = config.is_some();
650        let config_token = config.and_then(|config| {
651            #[expect(deprecated)]
652            config.token
653        });
654
655        let token = match (config_token, credentials_token) {
656            (Some(config_token), Some(credentials_token))
657                if config_token
658                    .definition
659                    .is_higher_priority(&credentials_token.definition) =>
660            {
661                Some(config_token)
662            }
663            (_, Some(credentials_token)) => Some(credentials_token),
664            (config_token, None) => config_token,
665        };
666
667        Ok((has_config || has_credentials).then_some(RegistryCredential { token }))
668    }
669
670    /// Gets all config values from disk.
671    ///
672    /// This will lazy-load the values as necessary. Callers are responsible
673    /// for checking environment variables. Callers outside of the `config`
674    /// module should avoid using this.
675    pub fn config(&self) -> CargoResult<&ConfigStore> {
676        self.config.try_borrow_with(|| self.load_config())
677    }
678
679    /// Gets a mutable copy of the on-disk config values.
680    ///
681    /// This requires the config values to already have been loaded. This
682    /// currently only exists for `cargo vendor` to remove the `source`
683    /// entries. This doesn't respect environment variables. You should avoid
684    /// using this if possible.
685    pub fn config_mut(&mut self) -> CargoResult<&mut ConfigStore> {
686        let _ = self.config()?;
687        Ok(self.config.get_mut().expect("already loaded config values"))
688    }
689
690    /// Sets the path where ancestor config file searching will stop. The
691    /// given path is included, but its ancestors are not.
692    pub fn set_search_stop_path<P: Into<PathBuf>>(&mut self, path: P) {
693        let path = path.into();
694        debug_assert!(self.cwd.starts_with(&path));
695        self.search_stop_path = Some(path);
696    }
697
698    /// Switches the working directory to [`std::env::current_dir`]
699    ///
700    /// There is not a need to also call [`Self::reload_rooted_at`].
701    pub fn reload_cwd(&mut self) -> CargoResult<()> {
702        let cwd =
703            env::current_dir().context("couldn't get the current directory of the process")?;
704        let homedir = homedir(&cwd).ok_or_else(|| {
705            anyhow!(
706                "Cargo couldn't find your home directory. \
707                 This probably means that $HOME was not set."
708            )
709        })?;
710
711        self.cwd = cwd;
712        self.home_path = Filesystem::new(homedir);
713        self.reload_rooted_at(self.cwd.clone())?;
714        Ok(())
715    }
716
717    /// Reloads on-disk configuration values, starting at the given path and
718    /// walking up its ancestors.
719    pub fn reload_rooted_at<P: AsRef<Path>>(&mut self, path: P) -> CargoResult<()> {
720        let config = self.load_config_from(path.as_ref())?;
721        self.config.replace(config);
722        self.merge_cli_args()?;
723        self.load_unstable_flags_from_config()?;
724        Ok(())
725    }
726
727    /// The current working directory.
728    pub fn cwd(&self) -> &Path {
729        &self.cwd
730    }
731
732    /// The `target` output directory to use.
733    ///
734    /// Returns `None` if the user has not chosen an explicit directory.
735    ///
736    /// Callers should prefer [`Workspace::target_dir`] instead.
737    pub fn target_dir(&self) -> CargoResult<Option<Filesystem>> {
738        if let Some(dir) = &self.target_dir {
739            Ok(Some(dir.clone()))
740        } else if let Some(dir) = self.get_env_os("CARGO_TARGET_DIR") {
741            // Check if the CARGO_TARGET_DIR environment variable is set to an empty string.
742            if dir.is_empty() {
743                bail!(
744                    "the target directory is set to an empty string in the \
745                     `CARGO_TARGET_DIR` environment variable"
746                )
747            }
748
749            Ok(Some(Filesystem::new(self.cwd.join(dir))))
750        } else if let Some(val) = &self.build_config()?.target_dir {
751            let path = val.resolve_path(self);
752
753            // Check if the target directory is set to an empty string in the config.toml file.
754            if val.raw_value().is_empty() {
755                bail!(
756                    "the target directory is set to an empty string in {}",
757                    val.value().definition
758                )
759            }
760
761            Ok(Some(Filesystem::new(path)))
762        } else {
763            Ok(None)
764        }
765    }
766
767    /// The directory to use for intermediate build artifacts.
768    ///
769    /// Callers should prefer [`Workspace::build_dir`] instead.
770    pub fn build_dir(&self, workspace_manifest_path: &Path) -> CargoResult<Option<Filesystem>> {
771        let Some(val) = &self.build_config()?.build_dir else {
772            return Ok(None);
773        };
774        self.custom_build_dir(val, workspace_manifest_path)
775            .map(Some)
776    }
777
778    /// The directory to use for intermediate build artifacts.
779    ///
780    /// Callers should prefer [`Workspace::build_dir`] instead.
781    pub fn custom_build_dir(
782        &self,
783        val: &ConfigRelativePath,
784        workspace_manifest_path: &Path,
785    ) -> CargoResult<Filesystem> {
786        let replacements = [
787            (
788                "{workspace-root}",
789                workspace_manifest_path
790                    .parent()
791                    .unwrap()
792                    .to_str()
793                    .context("workspace root was not valid utf-8")?
794                    .to_string(),
795            ),
796            (
797                "{cargo-cache-home}",
798                self.home()
799                    .as_path_unlocked()
800                    .to_str()
801                    .context("cargo home was not valid utf-8")?
802                    .to_string(),
803            ),
804            ("{workspace-path-hash}", {
805                let real_path = std::fs::canonicalize(workspace_manifest_path)
806                    .unwrap_or_else(|_err| workspace_manifest_path.to_owned());
807                let hash = crate::util::hex::short_hash(&real_path);
808                format!("{}{}{}", &hash[0..2], std::path::MAIN_SEPARATOR, &hash[2..])
809            }),
810        ];
811
812        let template_variables = replacements
813            .iter()
814            .map(|(key, _)| key[1..key.len() - 1].to_string())
815            .collect_vec();
816
817        let path = val
818            .resolve_templated_path(self, replacements)
819            .map_err(|e| match e {
820                path::ResolveTemplateError::UnexpectedVariable {
821                    variable,
822                    raw_template,
823                } => {
824                    let mut suggestion = closest_msg(&variable, template_variables.iter(), |key| key, "template variable");
825                    if suggestion == "" {
826                        let variables = template_variables.iter().map(|v| format!("`{{{v}}}`")).join(", ");
827                        suggestion = format!("\n\nhelp: available template variables are {variables}");
828                    }
829                    anyhow!(
830                            "unexpected variable `{variable}` in build.build-dir path `{raw_template}`{suggestion}"
831                        )
832                }
833                path::ResolveTemplateError::UnexpectedBracket { bracket_type, raw_template } => {
834                    let (btype, literal) = match bracket_type {
835                        path::BracketType::Opening => ("opening", "{"),
836                        path::BracketType::Closing => ("closing", "}"),
837                    };
838
839                    anyhow!(
840                            "unexpected {btype} bracket `{literal}` in build.build-dir path `{raw_template}`"
841                        )
842                }
843            })?;
844
845        // Check if the target directory is set to an empty string in the config.toml file.
846        if val.raw_value().is_empty() {
847            bail!(
848                "the build directory is set to an empty string in {}",
849                val.value().definition
850            )
851        }
852
853        Ok(Filesystem::new(path))
854    }
855
856    /// This is a helper for getting a CV from a file or env var.
857    pub(crate) fn get_cv_with_env(&self, key: &ConfigKey) -> CargoResult<Option<CV>> {
858        // Determine if value comes from env, cli, or file, and merge env if
859        // possible.
860        let cv = self.config()?.get_cv(key)?;
861        if key.is_root() {
862            // Root table can't have env value.
863            return Ok(cv);
864        }
865        let env = self.env.get_str(key.as_env_key());
866        let env_def = Definition::Environment(key.as_env_key().to_string());
867        let use_env = match (&cv, env) {
868            // Lists are always merged.
869            (Some(CV::List(..)), Some(_)) => true,
870            (Some(cv), Some(_)) => env_def.is_higher_priority(cv.definition()),
871            (None, Some(_)) => true,
872            _ => false,
873        };
874
875        if !use_env {
876            return Ok(cv);
877        }
878
879        // Future note: If you ever need to deserialize a non-self describing
880        // map type, this should implement a starts_with check (similar to how
881        // ConfigMapAccess does).
882        let env = env.unwrap();
883        if env == "true" {
884            Ok(Some(CV::Boolean(true, env_def)))
885        } else if env == "false" {
886            Ok(Some(CV::Boolean(false, env_def)))
887        } else if let Ok(i) = env.parse::<i64>() {
888            Ok(Some(CV::Integer(i, env_def)))
889        } else if self.cli_unstable().advanced_env && env.starts_with('[') && env.ends_with(']') {
890            match cv {
891                Some(CV::List(mut cv_list, cv_def)) => {
892                    // Merge with config file.
893                    self.get_env_list(key, &mut cv_list)?;
894                    Ok(Some(CV::List(cv_list, cv_def)))
895                }
896                Some(cv) => {
897                    // This can't assume StringList.
898                    // Return an error, which is the behavior of merging
899                    // multiple config.toml files with the same scenario.
900                    bail!(
901                        "unable to merge array env for config `{}`\n\
902                        file: {:?}\n\
903                        env: {}",
904                        key,
905                        cv,
906                        env
907                    );
908                }
909                None => {
910                    let mut cv_list = Vec::new();
911                    self.get_env_list(key, &mut cv_list)?;
912                    Ok(Some(CV::List(cv_list, env_def)))
913                }
914            }
915        } else {
916            // Try to merge if possible.
917            match cv {
918                Some(CV::List(mut cv_list, cv_def)) => {
919                    // Merge with config file.
920                    self.get_env_list(key, &mut cv_list)?;
921                    Ok(Some(CV::List(cv_list, cv_def)))
922                }
923                _ => {
924                    // Note: CV::Table merging is not implemented, as env
925                    // vars do not support table values. In the future, we
926                    // could check for `{}`, and interpret it as TOML if
927                    // that seems useful.
928                    Ok(Some(CV::String(env.to_string(), env_def)))
929                }
930            }
931        }
932    }
933
934    /// Helper primarily for testing.
935    pub fn set_env(&mut self, env: HashMap<String, String>) {
936        self.env = Env::from_map(env);
937    }
938
939    /// Returns all environment variables as an iterator,
940    /// keeping only entries where both the key and value are valid UTF-8.
941    pub(crate) fn env(&self) -> impl Iterator<Item = (&str, &str)> {
942        self.env.iter_str()
943    }
944
945    /// Returns all environment variable keys, filtering out keys that are not valid UTF-8.
946    fn env_keys(&self) -> impl Iterator<Item = &str> {
947        self.env.keys_str()
948    }
949
950    fn get_config_env<T>(&self, key: &ConfigKey) -> Result<OptValue<T>, ConfigError>
951    where
952        T: FromStr,
953        <T as FromStr>::Err: fmt::Display,
954    {
955        match self.env.get_str(key.as_env_key()) {
956            Some(value) => {
957                let definition = Definition::Environment(key.as_env_key().to_string());
958                Ok(Some(Value {
959                    val: value
960                        .parse()
961                        .map_err(|e| ConfigError::new(format!("{}", e), definition.clone()))?,
962                    definition,
963                }))
964            }
965            None => {
966                self.check_environment_key_case_mismatch(key);
967                Ok(None)
968            }
969        }
970    }
971
972    /// Get the value of environment variable `key` through the snapshot in
973    /// [`GlobalContext`].
974    ///
975    /// This can be used similarly to [`std::env::var`].
976    pub fn get_env(&self, key: impl AsRef<OsStr>) -> CargoResult<&str> {
977        self.env.get_env(key)
978    }
979
980    /// Get the value of environment variable `key` through the snapshot in
981    /// [`GlobalContext`].
982    ///
983    /// This can be used similarly to [`std::env::var_os`].
984    pub fn get_env_os(&self, key: impl AsRef<OsStr>) -> Option<&OsStr> {
985        self.env.get_env_os(key)
986    }
987
988    /// Check if the [`GlobalContext`] contains a given [`ConfigKey`].
989    ///
990    /// See `ConfigMapAccess` for a description of `env_prefix_ok`.
991    fn has_key(&self, key: &ConfigKey, env_prefix_ok: bool) -> CargoResult<bool> {
992        if self.env.contains_key(key.as_env_key()) {
993            return Ok(true);
994        }
995        if env_prefix_ok {
996            let env_prefix = format!("{}_", key.as_env_key());
997            if self.env_keys().any(|k| k.starts_with(&env_prefix)) {
998                return Ok(true);
999            }
1000        }
1001        if self.config()?.get_cv(key)?.is_some() {
1002            return Ok(true);
1003        }
1004        self.check_environment_key_case_mismatch(key);
1005
1006        Ok(false)
1007    }
1008
1009    fn check_environment_key_case_mismatch(&self, key: &ConfigKey) {
1010        if let Some(env_key) = self.env.get_normalized(key.as_env_key()) {
1011            let _ = self.shell().warn(format!(
1012                "environment variables are expected to use uppercase letters and underscores, \
1013                the variable `{}` will be ignored and have no effect",
1014                env_key
1015            ));
1016        }
1017    }
1018
1019    /// Get a string config value.
1020    ///
1021    /// See `get` for more details.
1022    pub fn get_string(
1023        &self,
1024        key: impl IntoIterator<Item = impl AsRef<str>>,
1025    ) -> CargoResult<OptValue<String>> {
1026        self.get::<OptValue<String>>(key)
1027    }
1028
1029    fn string_to_path(&self, value: &str, definition: &Definition) -> PathBuf {
1030        let is_path = value.contains('/') || (cfg!(windows) && value.contains('\\'));
1031        if is_path {
1032            definition.root(self.cwd()).join(value)
1033        } else {
1034            // A pathless name.
1035            PathBuf::from(value)
1036        }
1037    }
1038
1039    /// Internal method for getting an environment variable as a list.
1040    /// If the key is a non-mergeable list and a value is found in the environment, existing values are cleared.
1041    fn get_env_list(&self, key: &ConfigKey, output: &mut Vec<ConfigValue>) -> CargoResult<()> {
1042        let Some(env_val) = self.env.get_str(key.as_env_key()) else {
1043            self.check_environment_key_case_mismatch(key);
1044            return Ok(());
1045        };
1046
1047        let env_def = Definition::Environment(key.as_env_key().to_string());
1048
1049        if is_nonmergeable_list(&key) {
1050            assert!(
1051                output
1052                    .windows(2)
1053                    .all(|cvs| cvs[0].definition() == cvs[1].definition()),
1054                "non-mergeable list must have only one definition: {output:?}",
1055            );
1056
1057            // Keep existing config if higher priority than env (e.g., --config CLI),
1058            // otherwise clear for env
1059            if output
1060                .first()
1061                .map(|o| o.definition() > &env_def)
1062                .unwrap_or_default()
1063            {
1064                return Ok(());
1065            } else {
1066                output.clear();
1067            }
1068        }
1069
1070        if self.cli_unstable().advanced_env && env_val.starts_with('[') && env_val.ends_with(']') {
1071            // Parse an environment string as a TOML array.
1072            let toml_v = env_val.parse::<toml::Value>().map_err(|e| {
1073                ConfigError::new(format!("could not parse TOML list: {}", e), env_def.clone())
1074            })?;
1075            let values = toml_v.as_array().expect("env var was not array");
1076            for value in values {
1077                // Until we figure out how to deal with it through `-Zadvanced-env`,
1078                // complex array types are unsupported.
1079                let s = value.as_str().ok_or_else(|| {
1080                    ConfigError::new(
1081                        format!("expected string, found {}", value.type_str()),
1082                        env_def.clone(),
1083                    )
1084                })?;
1085                output.push(CV::String(s.to_string(), env_def.clone()))
1086            }
1087        } else {
1088            output.extend(
1089                env_val
1090                    .split_whitespace()
1091                    .map(|s| CV::String(s.to_string(), env_def.clone())),
1092            );
1093        }
1094        output.sort_by(|a, b| a.definition().cmp(b.definition()));
1095        Ok(())
1096    }
1097
1098    /// Low-level method for getting a config value as an `OptValue<HashMap<String, CV>>`.
1099    ///
1100    /// NOTE: This does not read from env. The caller is responsible for that.
1101    fn get_table(&self, key: &ConfigKey) -> CargoResult<OptValue<HashMap<String, CV>>> {
1102        match self.config()?.get_cv(key)? {
1103            Some(CV::Table(val, definition)) => Ok(Some(Value { val, definition })),
1104            Some(val) => self.expected("table", key, &val),
1105            None => Ok(None),
1106        }
1107    }
1108
1109    get_value_typed! {get_integer, i64, Integer, "an integer"}
1110    get_value_typed! {get_bool, bool, Boolean, "true/false"}
1111    get_value_typed! {get_string_priv, String, String, "a string"}
1112
1113    /// Generate an error when the given value is the wrong type.
1114    fn expected<T>(&self, ty: &str, key: &ConfigKey, val: &CV) -> CargoResult<T> {
1115        val.expected(ty, &key.to_string())
1116            .map_err(|e| anyhow!("invalid configuration for key `{}`\n{}", key, e))
1117    }
1118
1119    /// Update the instance based on settings typically passed in on
1120    /// the command-line.
1121    ///
1122    /// This may also load the config from disk if it hasn't already been
1123    /// loaded.
1124    pub fn configure(
1125        &mut self,
1126        verbose: u32,
1127        quiet: bool,
1128        color: Option<&str>,
1129        frozen: bool,
1130        locked: bool,
1131        offline: bool,
1132        target_dir: &Option<PathBuf>,
1133        unstable_flags: &[String],
1134        cli_config: &[String],
1135    ) -> CargoResult<()> {
1136        for warning in self
1137            .unstable_flags
1138            .parse(unstable_flags, self.nightly_features_allowed)?
1139        {
1140            self.shell().warn(warning)?;
1141        }
1142        if !unstable_flags.is_empty() {
1143            // store a copy of the cli flags separately for `load_unstable_flags_from_config`
1144            // (we might also need it again for `reload_rooted_at`)
1145            self.unstable_flags_cli = Some(unstable_flags.to_vec());
1146        }
1147        if !cli_config.is_empty() {
1148            self.cli_config = Some(cli_config.iter().map(|s| s.to_string()).collect());
1149            self.merge_cli_args()?;
1150        }
1151
1152        self.load_unstable_flags_from_config()?;
1153
1154        // Ignore errors in the configuration files. We don't want basic
1155        // commands like `cargo version` to error out due to config file
1156        // problems.
1157        let term = self.get::<TermConfig>(["term"]).unwrap_or_default();
1158
1159        // The command line takes precedence over configuration.
1160        let extra_verbose = verbose >= 2;
1161        let verbose = verbose != 0;
1162        let verbosity = match (verbose, quiet) {
1163            (true, true) => bail!("cannot set both --verbose and --quiet"),
1164            (true, false) => Verbosity::Verbose,
1165            (false, true) => Verbosity::Quiet,
1166            (false, false) => match (term.verbose, term.quiet) {
1167                (Some(true), Some(true)) => {
1168                    bail!("cannot set both `term.verbose` and `term.quiet`")
1169                }
1170                (Some(true), _) => Verbosity::Verbose,
1171                (_, Some(true)) => Verbosity::Quiet,
1172                _ => Verbosity::Normal,
1173            },
1174        };
1175        self.shell().set_verbosity(verbosity);
1176        self.extra_verbose = extra_verbose;
1177
1178        let color = color.or_else(|| term.color.as_deref());
1179        self.shell().set_color_choice(color)?;
1180        if let Some(hyperlinks) = term.hyperlinks {
1181            self.shell().set_hyperlinks(hyperlinks)?;
1182        }
1183        if let Some(unicode) = term.unicode {
1184            self.shell().set_unicode(unicode)?;
1185        }
1186
1187        self.progress_config = term.progress.unwrap_or_default();
1188
1189        self.frozen = frozen;
1190        self.locked = locked;
1191        self.offline = offline
1192            || self
1193                .net_config()
1194                .ok()
1195                .and_then(|n| n.offline)
1196                .unwrap_or(false);
1197        let cli_target_dir = target_dir.as_ref().map(|dir| Filesystem::new(dir.clone()));
1198        self.target_dir = cli_target_dir;
1199
1200        self.shell()
1201            .set_unstable_flags_rustc_unicode(self.unstable_flags.rustc_unicode)?;
1202
1203        Ok(())
1204    }
1205
1206    fn load_unstable_flags_from_config(&mut self) -> CargoResult<()> {
1207        // If nightly features are enabled, allow setting Z-flags from config
1208        // using the `unstable` table. Ignore that block otherwise.
1209        if self.nightly_features_allowed {
1210            self.unstable_flags = self
1211                .get::<Option<CliUnstable>>(["unstable"])?
1212                .unwrap_or_default();
1213            if let Some(unstable_flags_cli) = &self.unstable_flags_cli {
1214                // NB. It's not ideal to parse these twice, but doing it again here
1215                //     allows the CLI to override config files for both enabling
1216                //     and disabling, and doing it up top allows CLI Zflags to
1217                //     control config parsing behavior.
1218                self.unstable_flags.parse(unstable_flags_cli, true)?;
1219            }
1220        }
1221
1222        Ok(())
1223    }
1224
1225    pub fn cli_unstable(&self) -> &CliUnstable {
1226        &self.unstable_flags
1227    }
1228
1229    pub fn extra_verbose(&self) -> bool {
1230        self.extra_verbose
1231    }
1232
1233    pub fn network_allowed(&self) -> bool {
1234        !self.offline_flag().is_some()
1235    }
1236
1237    pub fn offline_flag(&self) -> Option<&'static str> {
1238        if self.frozen {
1239            Some("--frozen")
1240        } else if self.offline {
1241            Some("--offline")
1242        } else {
1243            None
1244        }
1245    }
1246
1247    pub fn set_locked(&mut self, locked: bool) {
1248        self.locked = locked;
1249    }
1250
1251    pub fn lock_update_allowed(&self) -> bool {
1252        !self.locked_flag().is_some()
1253    }
1254
1255    pub fn locked_flag(&self) -> Option<&'static str> {
1256        if self.frozen {
1257            Some("--frozen")
1258        } else if self.locked {
1259            Some("--locked")
1260        } else {
1261            None
1262        }
1263    }
1264
1265    /// Loads configuration from the filesystem.
1266    pub fn load_config(&self) -> CargoResult<ConfigStore> {
1267        self.load_config_from(&self.cwd)
1268    }
1269
1270    /// Like [`load_config`](GlobalContext::load_config) but without merging config values.
1271    ///
1272    /// This is primarily crafted for `cargo config` command.
1273    pub(crate) fn load_config_unmerged(&self) -> CargoResult<Vec<ConfigStore>> {
1274        let mut result = Vec::new();
1275        let mut seen = HashSet::default();
1276        let home = self.home_path.clone().into_path_unlocked();
1277        self.walk_tree(&self.cwd, &home, |path| {
1278            let mut config = self._load_file(path, &mut seen, false, DefinitionKind::Path)?;
1279            self.load_unmerged_include(&mut config, &mut seen, &mut result)?;
1280            result.push(config);
1281            Ok(())
1282        })
1283        .context("could not load Cargo configuration")?;
1284        Ok(result)
1285    }
1286
1287    /// Like [`load_includes`](GlobalContext::load_includes) but without merging config values.
1288    ///
1289    /// This is primarily crafted for `cargo config` command.
1290    fn load_unmerged_include(
1291        &self,
1292        config: &mut ConfigStore,
1293        seen: &mut HashSet<PathBuf>,
1294        output: &mut Vec<ConfigStore>,
1295    ) -> CargoResult<()> {
1296        let includes = self.include_paths(config, false)?;
1297        for include in includes {
1298            let Some(abs_path) = include.resolve_path(self) else {
1299                continue;
1300            };
1301
1302            let mut config = self
1303                ._load_file(&abs_path, seen, false, DefinitionKind::Path)
1304                .with_context(|| {
1305                    format!(
1306                        "failed to load config include `{}` from `{}`",
1307                        include.path.display(),
1308                        include.def
1309                    )
1310                })?;
1311            self.load_unmerged_include(&mut config, seen, output)?;
1312            output.push(config);
1313        }
1314        Ok(())
1315    }
1316
1317    /// Start a config file discovery from a path and merges all config values found.
1318    fn load_config_from(&self, path: &Path) -> CargoResult<ConfigStore> {
1319        let mut cfg = ConfigStore::default();
1320        let home = self.home_path.clone().into_path_unlocked();
1321
1322        self.walk_tree(path, &home, |path| {
1323            let config = self.load_file(path)?;
1324            cfg.merge(config, false).with_context(|| {
1325                format!("failed to merge configuration at `{}`", path.display())
1326            })?;
1327            Ok(())
1328        })
1329        .context("could not load Cargo configuration")?;
1330
1331        Ok(cfg)
1332    }
1333
1334    /// Loads configuration from a path.
1335    ///
1336    /// This is used during config file discovery.
1337    fn load_file(&self, path: &Path) -> CargoResult<ConfigStore> {
1338        self._load_file(path, &mut HashSet::default(), true, DefinitionKind::Path)
1339    }
1340
1341    /// Loads configuration from a path with options.
1342    ///
1343    /// This is the implementation of loading configuration from a path.
1344    ///
1345    /// * `includes` determines whether to load configs from [`ConfigInclude`].
1346    /// * `seen` is used to check for cyclic includes.
1347    /// * `definition_kind` tells why a config is being loaded.
1348    fn _load_file(
1349        &self,
1350        path: &Path,
1351        seen: &mut HashSet<PathBuf>,
1352        includes: bool,
1353        definition_kind: DefinitionKind,
1354    ) -> CargoResult<ConfigStore> {
1355        if !seen.insert(path.to_path_buf()) {
1356            bail!(
1357                "config `include` cycle detected with path `{}`",
1358                path.display()
1359            );
1360        }
1361        tracing::debug!(?path, ?definition_kind, includes, "load config from file");
1362
1363        let config = ConfigStore::read_layer(path, definition_kind)?;
1364
1365        if includes {
1366            self.load_includes(config, seen, definition_kind)
1367        } else {
1368            Ok(config)
1369        }
1370    }
1371
1372    /// Load any `include` files listed in the given `config`.
1373    ///
1374    /// Returns `config` with the given include files merged into it.
1375    ///
1376    /// * `seen` is used to check for cyclic includes.
1377    /// * `definition_kind` tells why a config is being loaded.
1378    fn load_includes(
1379        &self,
1380        mut config: ConfigStore,
1381        seen: &mut HashSet<PathBuf>,
1382        definition_kind: DefinitionKind,
1383    ) -> CargoResult<ConfigStore> {
1384        // Get the list of files to load.
1385        let includes = self.include_paths(&mut config, true)?;
1386
1387        // Accumulate all values here.
1388        let root = CV::Table(HashMap::default(), config.definition().clone());
1389        let mut root = ConfigStore::with_table_value(root).unwrap();
1390        for include in includes {
1391            let Some(abs_path) = include.resolve_path(self) else {
1392                continue;
1393            };
1394
1395            self._load_file(&abs_path, seen, true, definition_kind)
1396                .and_then(|include| root.merge(include, true))
1397                .with_context(|| {
1398                    format!(
1399                        "failed to load config include `{}` from `{}`",
1400                        include.path.display(),
1401                        include.def
1402                    )
1403                })?;
1404        }
1405        root.merge(config, true)?;
1406        Ok(root)
1407    }
1408
1409    /// Converts the `include` config value to a list of absolute paths.
1410    fn include_paths(
1411        &self,
1412        config: &mut ConfigStore,
1413        remove: bool,
1414    ) -> CargoResult<Vec<ConfigInclude>> {
1415        let table = config.values_mut();
1416        let include = if remove {
1417            table.remove("include").map(Cow::Owned)
1418        } else {
1419            table.get("include").map(Cow::Borrowed)
1420        };
1421        let includes = match include.map(|c| c.into_owned()) {
1422            Some(CV::List(list, _def)) => list
1423                .into_iter()
1424                .enumerate()
1425                .map(|(idx, cv)| match cv {
1426                    CV::String(s, def) => Ok(ConfigInclude::new(s, def)),
1427                    CV::Table(mut table, def) => {
1428                        // Extract `include.path`
1429                        let s = match table.remove("path") {
1430                            Some(CV::String(s, _)) => s,
1431                            Some(other) => bail!(
1432                                "expected a string, but found {} at `include[{idx}].path` in `{def}`",
1433                                other.desc()
1434                            ),
1435                            None => bail!("missing field `path` at `include[{idx}]` in `{def}`"),
1436                        };
1437
1438                        // Extract optional `include.optional` field
1439                        let optional = match table.remove("optional") {
1440                            Some(CV::Boolean(b, _)) => b,
1441                            Some(other) => bail!(
1442                                "expected a boolean, but found {} at `include[{idx}].optional` in `{def}`",
1443                                other.desc()
1444                            ),
1445                            None => false,
1446                        };
1447
1448                        let mut include = ConfigInclude::new(s, def);
1449                        include.optional = optional;
1450                        Ok(include)
1451                    }
1452                    other => bail!(
1453                        "expected a string or table, but found {} at `include[{idx}]` in {}",
1454                        other.desc(),
1455                        other.definition(),
1456                    ),
1457                })
1458                .collect::<CargoResult<Vec<_>>>()?,
1459            Some(other) => bail!(
1460                "expected a list of strings or a list of tables, but found {} at `include` in `{}",
1461                other.desc(),
1462                other.definition()
1463            ),
1464            None => {
1465                return Ok(Vec::new());
1466            }
1467        };
1468
1469        for include in &includes {
1470            if include.path.extension() != Some(OsStr::new("toml")) {
1471                bail!(
1472                    "expected a config include path ending with `.toml`, \
1473                     but found `{}` from `{}`",
1474                    include.path.display(),
1475                    include.def,
1476                )
1477            }
1478
1479            if let Some(path) = include.path.to_str() {
1480                // Ignore non UTF-8 bytes as glob and template syntax are for textual config.
1481                if is_glob_pattern(path) {
1482                    bail!(
1483                        "expected a config include path without glob patterns, \
1484                         but found `{}` from `{}`",
1485                        include.path.display(),
1486                        include.def,
1487                    )
1488                }
1489                if path.contains(&['{', '}']) {
1490                    bail!(
1491                        "expected a config include path without template braces, \
1492                         but found `{}` from `{}`",
1493                        include.path.display(),
1494                        include.def,
1495                    )
1496                }
1497            }
1498        }
1499
1500        Ok(includes)
1501    }
1502
1503    /// Parses the CLI config args and returns them as a table.
1504    pub(crate) fn cli_args_to_config(&self) -> CargoResult<ConfigStore> {
1505        let mut loaded_args =
1506            ConfigStore::with_table_value(CV::Table(HashMap::default(), Definition::Cli(None)))
1507                .unwrap();
1508        let Some(cli_args) = &self.cli_config else {
1509            return Ok(loaded_args);
1510        };
1511        let mut seen = HashSet::default();
1512        for arg in cli_args {
1513            let arg_as_path = self.cwd.join(arg);
1514            let arg_config = if !arg.is_empty() && arg_as_path.exists() {
1515                // --config path_to_file
1516                self._load_file(&arg_as_path, &mut seen, true, DefinitionKind::Cli)
1517                    .with_context(|| {
1518                        format!("failed to load config from `{}`", arg_as_path.display())
1519                    })?
1520            } else {
1521                let doc = toml_dotted_keys(arg)?;
1522                let doc: toml::Value = toml::Value::deserialize(doc.into_deserializer())
1523                    .with_context(|| {
1524                        format!("failed to parse value from --config argument `{arg}`")
1525                    })?;
1526
1527                if doc
1528                    .get("registry")
1529                    .and_then(|v| v.as_table())
1530                    .and_then(|t| t.get("token"))
1531                    .is_some()
1532                {
1533                    bail!("registry.token cannot be set through --config for security reasons");
1534                } else if let Some((k, _)) = doc
1535                    .get("registries")
1536                    .and_then(|v| v.as_table())
1537                    .and_then(|t| t.iter().find(|(_, v)| v.get("token").is_some()))
1538                {
1539                    bail!(
1540                        "registries.{}.token cannot be set through --config for security reasons",
1541                        k
1542                    );
1543                }
1544
1545                let table = CV::from_toml(Definition::Cli(None), doc)
1546                    .with_context(|| format!("failed to convert --config argument `{arg}`"))?;
1547                ConfigStore::with_table_value(table).unwrap()
1548            };
1549            let arg_config = self
1550                .load_includes(arg_config, &mut HashSet::default(), DefinitionKind::Cli)
1551                .context("failed to load --config include".to_string())?;
1552            loaded_args
1553                .merge(arg_config, true)
1554                .with_context(|| format!("failed to merge --config argument `{arg}`"))?;
1555        }
1556        Ok(loaded_args)
1557    }
1558
1559    /// Add config arguments passed on the command line.
1560    fn merge_cli_args(&mut self) -> CargoResult<()> {
1561        let cli_config = self.cli_args_to_config()?;
1562        self.config_mut()?.merge(cli_config, true)
1563    }
1564
1565    /// The purpose of this function is to aid in the transition to using
1566    /// .toml extensions on Cargo's config files, which were historically not used.
1567    /// Both 'config.toml' and 'credentials.toml' should be valid with or without extension.
1568    /// When both exist, we want to prefer the one without an extension for
1569    /// backwards compatibility, but warn the user appropriately.
1570    fn get_file_path(
1571        &self,
1572        dir: &Path,
1573        filename_without_extension: &str,
1574        warn: bool,
1575    ) -> CargoResult<Option<PathBuf>> {
1576        let possible = dir.join(filename_without_extension);
1577        let possible_with_extension = dir.join(format!("{}.toml", filename_without_extension));
1578
1579        if let Ok(possible_handle) = same_file::Handle::from_path(&possible) {
1580            if warn {
1581                if let Ok(possible_with_extension_handle) =
1582                    same_file::Handle::from_path(&possible_with_extension)
1583                {
1584                    // We don't want to print a warning if the version
1585                    // without the extension is just a symlink to the version
1586                    // WITH an extension, which people may want to do to
1587                    // support multiple Cargo versions at once and not
1588                    // get a warning.
1589                    if possible_handle != possible_with_extension_handle {
1590                        self.shell().warn(format!(
1591                            "both `{}` and `{}` exist. Using `{}`",
1592                            possible.display(),
1593                            possible_with_extension.display(),
1594                            possible.display()
1595                        ))?;
1596                    }
1597                } else {
1598                    self.shell().print_report(&[
1599                        Level::WARNING.secondary_title(
1600                            format!(
1601                                "`{}` is deprecated in favor of `{filename_without_extension}.toml`",
1602                                possible.display(),
1603                            )).element(Level::HELP.message(
1604                            format!("if you need to support cargo 1.38 or earlier, you can symlink `{filename_without_extension}` to `{filename_without_extension}.toml`")))
1605                    ], false)?;
1606                }
1607            }
1608
1609            Ok(Some(possible))
1610        } else if possible_with_extension.exists() {
1611            Ok(Some(possible_with_extension))
1612        } else {
1613            Ok(None)
1614        }
1615    }
1616
1617    fn walk_tree<F>(&self, pwd: &Path, home: &Path, mut walk: F) -> CargoResult<()>
1618    where
1619        F: FnMut(&Path) -> CargoResult<()>,
1620    {
1621        let mut seen_dir = HashSet::default();
1622
1623        for current in paths::ancestors(pwd, self.search_stop_path.as_deref()) {
1624            let config_root = current.join(".cargo");
1625            if let Some(path) = self.get_file_path(&config_root, "config", true)? {
1626                walk(&path)?;
1627            }
1628
1629            let canonical_root = config_root.canonicalize().unwrap_or(config_root);
1630            seen_dir.insert(canonical_root);
1631        }
1632
1633        let canonical_home = home.canonicalize().unwrap_or(home.to_path_buf());
1634
1635        // Once we're done, also be sure to walk the home directory even if it's not
1636        // in our history to be sure we pick up that standard location for
1637        // information.
1638        if !seen_dir.contains(&canonical_home) && !seen_dir.contains(home) {
1639            if let Some(path) = self.get_file_path(home, "config", true)? {
1640                walk(&path)?;
1641            }
1642        }
1643
1644        Ok(())
1645    }
1646
1647    /// Gets the index for a registry.
1648    pub fn get_registry_index(&self, registry: &str) -> CargoResult<Url> {
1649        RegistryName::new(registry)?;
1650        if let Some(index) = self.get_string(["registries", registry, "index"])? {
1651            self.resolve_registry_index(&index).with_context(|| {
1652                format!(
1653                    "invalid index URL for registry `{}` defined in {}",
1654                    registry, index.definition
1655                )
1656            })
1657        } else {
1658            bail!(
1659                "registry index was not found in any configuration: `{}`",
1660                registry
1661            );
1662        }
1663    }
1664
1665    /// Returns an error if `registry.index` is set.
1666    pub fn check_registry_index_not_set(&self) -> CargoResult<()> {
1667        if self.get_string(["registry", "index"])?.is_some() {
1668            bail!(
1669                "the `registry.index` config value is no longer supported\n\
1670                Use `[source]` replacement to alter the default index for crates.io."
1671            );
1672        }
1673        Ok(())
1674    }
1675
1676    fn resolve_registry_index(&self, index: &Value<String>) -> CargoResult<Url> {
1677        // This handles relative file: URLs, relative to the config definition.
1678        let base = index
1679            .definition
1680            .root(self.cwd())
1681            .join("truncated-by-url_with_base");
1682        // Parse val to check it is a URL, not a relative path without a protocol.
1683        let _parsed = index.val.into_url()?;
1684        let url = index.val.into_url_with_base(Some(&*base))?;
1685        if url.password().is_some() {
1686            bail!("registry URLs may not contain passwords");
1687        }
1688        Ok(url)
1689    }
1690
1691    /// Gets configuration values from the credentials file, loading them on first use.
1692    fn credentials_config(&self) -> CargoResult<&ConfigStore> {
1693        self.credentials_config
1694            .try_borrow_with(|| self.load_credentials())
1695    }
1696
1697    /// Loads credentials config from the credentials file, if present.
1698    fn load_credentials(&self) -> CargoResult<ConfigStore> {
1699        let home_path = self.home_path.clone().into_path_unlocked();
1700        let Some(credentials) = self.get_file_path(&home_path, "credentials", true)? else {
1701            return Ok(ConfigStore::default());
1702        };
1703
1704        let mut config = ConfigStore::read_layer(&credentials, DefinitionKind::Path)?;
1705        // Backwards compatibility for old `.cargo/credentials` layout.
1706        {
1707            let def = config.definition().clone();
1708            let value_map = config.values_mut();
1709
1710            if let Some(token) = value_map.remove("token") {
1711                value_map.entry("registry".into()).or_insert_with(|| {
1712                    let map = HashMap::from_iter([("token".into(), token)]);
1713                    CV::Table(map, def.clone())
1714                });
1715            }
1716        }
1717
1718        Ok(config)
1719    }
1720
1721    /// Looks for a path for `tool` in an environment variable or the given config, and returns
1722    /// `None` if it's not present.
1723    fn maybe_get_tool(
1724        &self,
1725        tool: &str,
1726        from_config: &Option<ConfigRelativePath>,
1727    ) -> Option<PathBuf> {
1728        let var = tool.to_uppercase();
1729
1730        match self.get_env_os(&var).as_ref().and_then(|s| s.to_str()) {
1731            Some(tool_path) => {
1732                let maybe_relative = tool_path.contains('/') || tool_path.contains('\\');
1733                let path = if maybe_relative {
1734                    self.cwd.join(tool_path)
1735                } else {
1736                    PathBuf::from(tool_path)
1737                };
1738                Some(path)
1739            }
1740
1741            None => from_config.as_ref().map(|p| p.resolve_program(self)),
1742        }
1743    }
1744
1745    /// Returns the path for the given tool.
1746    ///
1747    /// This will look for the tool in the following order:
1748    ///
1749    /// 1. From an environment variable matching the tool name (such as `RUSTC`).
1750    /// 2. From the given config value (which is usually something like `build.rustc`).
1751    /// 3. Finds the tool in the PATH environment variable.
1752    ///
1753    /// This is intended for tools that are rustup proxies. If you need to get
1754    /// a tool that is not a rustup proxy, use `maybe_get_tool` instead.
1755    fn get_tool(&self, tool: Tool, from_config: &Option<ConfigRelativePath>) -> PathBuf {
1756        let tool_str = tool.as_str();
1757        self.maybe_get_tool(tool_str, from_config)
1758            .or_else(|| {
1759                // This is an optimization to circumvent the rustup proxies
1760                // which can have a significant performance hit. The goal here
1761                // is to determine if calling `rustc` from PATH would end up
1762                // calling the proxies.
1763                //
1764                // This is somewhat cautious trying to determine if it is safe
1765                // to circumvent rustup, because there are some situations
1766                // where users may do things like modify PATH, call cargo
1767                // directly, use a custom rustup toolchain link without a
1768                // cargo executable, etc. However, there is still some risk
1769                // this may make the wrong decision in unusual circumstances.
1770                //
1771                // First, we must be running under rustup in the first place.
1772                let toolchain = self.get_env_os("RUSTUP_TOOLCHAIN")?;
1773                // Rustup supports named toolchains and absolute path toolchains,
1774                // but not relative path toolchains. This also enforces UTF-8.
1775                let toolchain = toolchain.to_str()?;
1776                let toolchain_path = Path::new(toolchain);
1777                let toolchain_dir = if toolchain_path.is_absolute() {
1778                    toolchain_path.to_path_buf()
1779                } else if !toolchain.contains(&['/', '\\']) {
1780                    home::rustup_home().ok()?.join("toolchains").join(toolchain)
1781                } else {
1782                    return None;
1783                };
1784                // If the tool on PATH is the same as `rustup` on path, then
1785                // there is pretty good evidence that it will be a proxy.
1786                let tool_resolved = paths::resolve_executable(Path::new(tool_str)).ok()?;
1787                let rustup_resolved = paths::resolve_executable(Path::new("rustup")).ok()?;
1788                let tool_meta = tool_resolved.metadata().ok()?;
1789                let rustup_meta = rustup_resolved.metadata().ok()?;
1790                // This works on the assumption that rustup and its proxies
1791                // use hard links to a single binary. If rustup ever changes
1792                // that setup, then I think the worst consequence is that this
1793                // optimization will not work, and it will take the slow path.
1794                if tool_meta.len() != rustup_meta.len() {
1795                    return None;
1796                }
1797                // Try to find the tool in rustup's toolchain directory.
1798                let tool_exe = Path::new(tool_str).with_extension(env::consts::EXE_EXTENSION);
1799                let toolchain_exe = toolchain_dir.join("bin").join(&tool_exe);
1800                toolchain_exe.exists().then_some(toolchain_exe)
1801            })
1802            .unwrap_or_else(|| PathBuf::from(tool_str))
1803    }
1804
1805    /// Get the `paths` overrides config value.
1806    pub fn paths_overrides(&self) -> CargoResult<OptValue<Vec<(String, Definition)>>> {
1807        let key = ConfigKey::from_parts(["paths"]);
1808        // paths overrides cannot be set via env config, so use get_cv here.
1809        match self.config()?.get_cv(&key)? {
1810            Some(CV::List(val, definition)) => {
1811                let val = val
1812                    .into_iter()
1813                    .map(|cv| match cv {
1814                        CV::String(s, def) => Ok((s, def)),
1815                        other => self.expected("string", &key, &other),
1816                    })
1817                    .collect::<CargoResult<Vec<_>>>()?;
1818                Ok(Some(Value { val, definition }))
1819            }
1820            Some(val) => self.expected("list", &key, &val),
1821            None => Ok(None),
1822        }
1823    }
1824
1825    pub fn jobserver_from_env(&self) -> Option<&jobserver::Client> {
1826        self.jobserver
1827    }
1828
1829    pub fn http(&self) -> CargoResult<&Mutex<Easy>> {
1830        let http = self
1831            .easy
1832            .try_borrow_with(|| http_handle(self).map(Into::into))?;
1833        {
1834            let mut http = http.lock().unwrap();
1835            http.reset();
1836            let timeout = configure_http_handle(self, &mut http)?;
1837            timeout.configure(&mut http)?;
1838        }
1839        Ok(http)
1840    }
1841
1842    pub fn http_async(&self) -> CargoResult<&http_async::Client> {
1843        self.http_async.try_borrow_with(|| {
1844            let handle_config = HandleConfiguration::new(&self)?;
1845            Ok(http_async::Client::new(handle_config))
1846        })
1847    }
1848
1849    pub fn http_config(&self) -> CargoResult<&CargoHttpConfig> {
1850        self.http_config.try_borrow_with(|| {
1851            let mut http = self.get::<CargoHttpConfig>(["http"])?;
1852            let curl_v = curl::Version::get();
1853            disables_multiplexing_for_bad_curl(curl_v.version(), &mut http, self);
1854            Ok(http)
1855        })
1856    }
1857
1858    pub fn future_incompat_config(&self) -> CargoResult<&CargoFutureIncompatConfig> {
1859        self.future_incompat_config
1860            .try_borrow_with(|| self.get::<CargoFutureIncompatConfig>(["future-incompat-report"]))
1861    }
1862
1863    pub fn net_config(&self) -> CargoResult<&CargoNetConfig> {
1864        self.net_config
1865            .try_borrow_with(|| self.get::<CargoNetConfig>(["net"]))
1866    }
1867
1868    pub fn build_config(&self) -> CargoResult<&CargoBuildConfig> {
1869        self.build_config
1870            .try_borrow_with(|| self.get::<CargoBuildConfig>(["build"]))
1871    }
1872
1873    pub fn progress_config(&self) -> &ProgressConfig {
1874        &self.progress_config
1875    }
1876
1877    /// Get the env vars from the config `[env]` table which
1878    /// are `force = true` or don't exist in the env snapshot [`GlobalContext::get_env`].
1879    pub fn env_config(&self) -> CargoResult<&Arc<HashMap<String, OsString>>> {
1880        let env_config = self.env_config.try_borrow_with(|| {
1881            CargoResult::Ok(Arc::new({
1882                let env_config = self.get::<EnvConfig>(["env"])?;
1883                // Reasons for disallowing these values:
1884                //
1885                // - CARGO_HOME: The initial call to cargo does not honor this value
1886                //   from the [env] table. Recursive calls to cargo would use the new
1887                //   value, possibly behaving differently from the outer cargo.
1888                //
1889                // - RUSTUP_HOME and RUSTUP_TOOLCHAIN: Under normal usage with rustup,
1890                //   this will have no effect because the rustup proxy sets
1891                //   RUSTUP_HOME and RUSTUP_TOOLCHAIN, and that would override the
1892                //   [env] table. If the outer cargo is executed directly
1893                //   circumventing the rustup proxy, then this would affect calls to
1894                //   rustc (assuming that is a proxy), which could potentially cause
1895                //   problems with cargo and rustc being from different toolchains. We
1896                //   consider this to be not a use case we would like to support,
1897                //   since it will likely cause problems or lead to confusion.
1898                for disallowed in &["CARGO_HOME", "RUSTUP_HOME", "RUSTUP_TOOLCHAIN"] {
1899                    if env_config.contains_key(*disallowed) {
1900                        bail!(
1901                            "setting the `{disallowed}` environment variable is not supported \
1902                            in the `[env]` configuration table"
1903                        );
1904                    }
1905                }
1906                env_config
1907                    .into_iter()
1908                    .filter_map(|(k, v)| {
1909                        if v.is_force() || self.get_env_os(&k).is_none() {
1910                            Some((k, v.resolve(self.cwd()).to_os_string()))
1911                        } else {
1912                            None
1913                        }
1914                    })
1915                    .collect()
1916            }))
1917        })?;
1918
1919        Ok(env_config)
1920    }
1921
1922    /// This is used to validate the `term` table has valid syntax.
1923    ///
1924    /// This is necessary because loading the term settings happens very
1925    /// early, and in some situations (like `cargo version`) we don't want to
1926    /// fail if there are problems with the config file.
1927    pub fn validate_term_config(&self) -> CargoResult<()> {
1928        drop(self.get::<TermConfig>(["term"])?);
1929        Ok(())
1930    }
1931
1932    /// Returns a list of `target.'cfg()'` tables.
1933    ///
1934    /// The list is sorted by the table name.
1935    pub fn target_cfgs(&self) -> CargoResult<&Vec<(String, TargetCfgConfig)>> {
1936        self.target_cfgs
1937            .try_borrow_with(|| target::load_target_cfgs(self))
1938    }
1939
1940    pub fn doc_extern_map(&self) -> CargoResult<&RustdocExternMap> {
1941        // Note: This does not support environment variables. The `Unit`
1942        // fundamentally does not have access to the registry name, so there is
1943        // nothing to query. Plumbing the name into SourceId is quite challenging.
1944        self.doc_extern_map
1945            .try_borrow_with(|| self.get::<RustdocExternMap>(["doc", "extern-map"]))
1946    }
1947
1948    /// Returns true if the `[target]` table should be applied to host targets.
1949    pub fn target_applies_to_host(&self) -> CargoResult<bool> {
1950        target::get_target_applies_to_host(self)
1951    }
1952
1953    /// Returns the `[host]` table definition for the given target tuple.
1954    pub fn host_cfg_tuple(&self, target: &str) -> CargoResult<TargetConfig> {
1955        target::load_host_tuple(self, target)
1956    }
1957
1958    /// Returns the `[target]` table definition for the given target tuple.
1959    pub fn target_cfg_tuple(&self, target: &str) -> CargoResult<TargetConfig> {
1960        target::load_target_tuple(self, target)
1961    }
1962
1963    /// Returns the cached [`SourceId`] corresponding to the main repository.
1964    ///
1965    /// This is the main cargo registry by default, but it can be overridden in
1966    /// a `.cargo/config.toml`.
1967    pub fn crates_io_source_id(&self) -> CargoResult<SourceId> {
1968        let source_id = self.crates_io_source_id.try_borrow_with(|| {
1969            self.check_registry_index_not_set()?;
1970            let url = CRATES_IO_INDEX.into_url().unwrap();
1971            SourceId::for_alt_registry(&url, CRATES_IO_REGISTRY)
1972        })?;
1973        Ok(*source_id)
1974    }
1975
1976    pub fn invocation_instant(&self) -> Instant {
1977        self.invocation_instant
1978    }
1979
1980    /// Returns the wall-clock time of this cargo invocation.
1981    ///
1982    /// See the [`invocation_time`] field doc for details.
1983    ///
1984    /// [`invocation_time`]: GlobalContext::invocation_time
1985    pub fn invocation_time(&self) -> jiff::Timestamp {
1986        self.invocation_time
1987    }
1988
1989    /// Retrieves a config variable.
1990    ///
1991    /// This supports most serde `Deserialize` types. Examples:
1992    ///
1993    /// ```rust,ignore
1994    /// let v: Option<u32> = config.get(["some", "nested", "key"])?;
1995    /// let v: Option<MyStruct> = config.get(["some", "key"])?;
1996    /// let v: Option<HashMap<String, MyStruct>> = config.get(["foo"])?;
1997    /// ```
1998    ///
1999    /// The key may be a dotted key, but this does NOT support TOML key
2000    /// quoting. Avoid key components that may have dots. For example,
2001    /// `foo.'a.b'.bar" does not work if you try to fetch `foo.'a.b'". You can
2002    /// fetch `foo` if it is a map, though.
2003    pub fn get<'de, T: serde::de::Deserialize<'de>>(
2004        &self,
2005
2006        key: impl IntoIterator<Item = impl AsRef<str>>,
2007    ) -> CargoResult<T> {
2008        let d = Deserializer {
2009            gctx: self,
2010            key: ConfigKey::from_parts(key),
2011            env_prefix_ok: true,
2012        };
2013        T::deserialize(d).map_err(|e| e.into())
2014    }
2015
2016    /// Obtain a [`Path`] from a [`Filesystem`], verifying that the
2017    /// appropriate lock is already currently held.
2018    ///
2019    /// Locks are usually acquired via [`GlobalContext::acquire_package_cache_lock`]
2020    /// or [`GlobalContext::try_acquire_package_cache_lock`].
2021    #[track_caller]
2022    #[tracing::instrument(skip_all)]
2023    pub fn assert_package_cache_locked<'a>(
2024        &self,
2025        mode: CacheLockMode,
2026        f: &'a Filesystem,
2027    ) -> &'a Path {
2028        let ret = f.as_path_unlocked();
2029        assert!(
2030            self.package_cache_lock.is_locked(mode),
2031            "package cache lock is not currently held, Cargo forgot to call \
2032             `acquire_package_cache_lock` before we got to this stack frame",
2033        );
2034        assert!(ret.starts_with(self.home_path.as_path_unlocked()));
2035        ret
2036    }
2037
2038    /// Acquires a lock on the global "package cache", blocking if another
2039    /// cargo holds the lock.
2040    ///
2041    /// See [`crate::util::cache_lock`] for an in-depth discussion of locking
2042    /// and lock modes.
2043    #[tracing::instrument(skip_all)]
2044    pub fn acquire_package_cache_lock(&self, mode: CacheLockMode) -> CargoResult<CacheLock<'_>> {
2045        self.package_cache_lock.lock(self, mode)
2046    }
2047
2048    /// Acquires a lock on the global "package cache", returning `None` if
2049    /// another cargo holds the lock.
2050    ///
2051    /// See [`crate::util::cache_lock`] for an in-depth discussion of locking
2052    /// and lock modes.
2053    #[tracing::instrument(skip_all)]
2054    pub fn try_acquire_package_cache_lock(
2055        &self,
2056        mode: CacheLockMode,
2057    ) -> CargoResult<Option<CacheLock<'_>>> {
2058        self.package_cache_lock.try_lock(self, mode)
2059    }
2060
2061    /// Returns a reference to the shared [`GlobalCacheTracker`].
2062    ///
2063    /// The package cache lock must be held to call this function (and to use
2064    /// it in general).
2065    pub fn global_cache_tracker(&self) -> CargoResult<MutexGuard<'_, GlobalCacheTracker>> {
2066        let tracker = self.global_cache_tracker.try_borrow_with(|| {
2067            Ok::<_, anyhow::Error>(Mutex::new(GlobalCacheTracker::new(self)?))
2068        })?;
2069        Ok(tracker.lock().unwrap())
2070    }
2071
2072    /// Returns a reference to the shared [`DeferredGlobalLastUse`].
2073    pub fn deferred_global_last_use(&self) -> CargoResult<MutexGuard<'_, DeferredGlobalLastUse>> {
2074        let deferred = self
2075            .deferred_global_last_use
2076            .try_borrow_with(|| Ok::<_, anyhow::Error>(Mutex::new(DeferredGlobalLastUse::new())))?;
2077        Ok(deferred.lock().unwrap())
2078    }
2079
2080    /// Get the global [`WarningHandling`] configuration.
2081    pub fn warning_handling(&self) -> CargoResult<WarningHandling> {
2082        Ok(self.build_config()?.warnings.unwrap_or_default())
2083    }
2084
2085    pub fn ws_roots(&self) -> MutexGuard<'_, HashMap<PathBuf, WorkspaceRootConfig>> {
2086        self.ws_roots.lock().unwrap()
2087    }
2088
2089    /// Mode for matching version requirements
2090    /// against versions already selected / locked.
2091    ///
2092    /// Once stabilized,
2093    /// this always returns [`VersionReqMatchMode::Prerelease`] (or remove and inline).
2094    pub fn version_req_match_mode(&self) -> VersionReqMatchMode {
2095        if self.cli_unstable().prerelease {
2096            VersionReqMatchMode::Prerelease
2097        } else {
2098            VersionReqMatchMode::Default
2099        }
2100    }
2101}
2102
2103fn registry_config_uncached(
2104    gctx: &GlobalContext,
2105    sid: &SourceId,
2106) -> CargoResult<Option<RegistryConfig>> {
2107    tracing::trace!("loading registry config for {}", sid);
2108    if !sid.is_remote_registry() {
2109        bail!(
2110            "{} does not support API commands.\n\
2111             Check for a source-replacement in .cargo/config.",
2112            sid
2113        );
2114    }
2115
2116    // Handle crates.io specially, since it uses different configuration keys.
2117    if sid.is_crates_io() {
2118        gctx.check_registry_index_not_set()?;
2119        return Ok(gctx
2120            .get::<Option<GlobalRegistryConfig>>(["registry"])?
2121            .map(|c| c.to_registry_config()));
2122    }
2123
2124    let name = registry_name(gctx, sid)?;
2125
2126    // It's possible to have a registry configured in a Cargo config file,
2127    // then override it with configuration from environment variables.
2128    // If the name doesn't match, leave a note to help the user understand
2129    // the potentially confusing situation.
2130    if let Some(name) = name.as_deref() {
2131        if Some(name) != sid.alt_registry_key() {
2132            gctx.shell().note(format!(
2133                "name of alternative registry `{}` set to `{name}`",
2134                sid.url()
2135            ))?
2136        }
2137    }
2138
2139    if let Some(name) = &name {
2140        tracing::debug!("found alternative registry name `{name}` for {sid}");
2141        gctx.get::<Option<RegistryConfig>>(["registries", name.as_str()])
2142    } else {
2143        tracing::debug!("no registry name found for {sid}");
2144        Ok(None)
2145    }
2146}
2147
2148fn registry_name(gctx: &GlobalContext, sid: &SourceId) -> CargoResult<Option<String>> {
2149    // Find the SourceId's name by its index URL. If environment variables
2150    // are available they will be preferred over configuration values.
2151    //
2152    // The fundamental problem is that we only know the index url of the registry
2153    // for certain. For example, an unnamed registry source can come from the `--index`
2154    // command line argument, or from a Cargo.lock file. For this reason, we always
2155    // attempt to discover the name by looking it up by the index URL.
2156    //
2157    // This also allows the authorization token for a registry to be set
2158    // without knowing the registry name by using the _INDEX and _TOKEN
2159    // environment variables.
2160
2161    let name = {
2162        // Discover names from environment variables.
2163        let index = sid.canonical_url();
2164        let mut names: Vec<_> = gctx
2165            .env()
2166            .filter_map(|(k, v)| {
2167                Some((
2168                    k.strip_prefix("CARGO_REGISTRIES_")?
2169                        .strip_suffix("_INDEX")?,
2170                    v,
2171                ))
2172            })
2173            .filter_map(|(k, v)| Some((k, CanonicalUrl::new(&v.into_url().ok()?).ok()?)))
2174            .filter(|(_, v)| v == index)
2175            .map(|(k, _)| k.to_lowercase())
2176            .collect();
2177
2178        // Discover names from the configuration only if none were found in the environment.
2179        if names.len() == 0 {
2180            if let Some(registries) = gctx.config()?.values().get("registries") {
2181                let (registries, _) = registries.table("registries")?;
2182                for (name, value) in registries {
2183                    if let Some(v) = value.table(&format!("registries.{name}"))?.0.get("index") {
2184                        let (v, _) = v.string(&format!("registries.{name}.index"))?;
2185                        if index == &CanonicalUrl::new(&v.into_url()?)? {
2186                            names.push(name.clone());
2187                        }
2188                    }
2189                }
2190            }
2191        }
2192        names.sort();
2193        match names.len() {
2194            0 => None,
2195            1 => Some(std::mem::take(&mut names[0])),
2196            _ => anyhow::bail!(
2197                "multiple registries are configured with the same index url '{}': {}",
2198                &sid.as_url(),
2199                names.join(", ")
2200            ),
2201        }
2202    };
2203
2204    Ok(name)
2205}
2206
2207pub fn homedir(cwd: &Path) -> Option<PathBuf> {
2208    ::home::cargo_home_with_cwd(cwd)
2209        .ok()
2210        // https://github.com/rust-lang/cargo/issues/15981
2211        // This is so everything shares one spelling and
2212        // isn't incorrectly seen as distinct.
2213        .map(|home| paths::normalize_path(&home))
2214}
2215
2216pub fn save_credentials(
2217    gctx: &GlobalContext,
2218    token: Option<RegistryCredentialConfig>,
2219    registry: &SourceId,
2220) -> CargoResult<()> {
2221    let registry = if registry.is_crates_io() {
2222        None
2223    } else {
2224        let name = registry
2225            .alt_registry_key()
2226            .ok_or_else(|| internal("can't save credentials for anonymous registry"))?;
2227        Some(name)
2228    };
2229
2230    // If 'credentials' exists, write to that for backward compatibility reasons.
2231    // Otherwise write to 'credentials.toml'. There's no need to print the
2232    // warning here, because it would already be printed at load time.
2233    let home_path = gctx.home_path.clone().into_path_unlocked();
2234    let filename = match gctx.get_file_path(&home_path, "credentials", false)? {
2235        Some(path) => match path.file_name() {
2236            Some(filename) => Path::new(filename).to_owned(),
2237            None => Path::new("credentials.toml").to_owned(),
2238        },
2239        None => Path::new("credentials.toml").to_owned(),
2240    };
2241
2242    let mut file = {
2243        gctx.home_path.create_dir()?;
2244        gctx.home_path
2245            .open_rw_exclusive_create(filename, gctx, "credentials' config file")?
2246    };
2247
2248    let mut contents = String::new();
2249    file.read_to_string(&mut contents).with_context(|| {
2250        format!(
2251            "failed to read configuration file `{}`",
2252            file.path().display()
2253        )
2254    })?;
2255
2256    let mut toml = contents.parse::<toml::Table>()?;
2257
2258    // Move the old token location to the new one.
2259    if let Some(token) = toml.remove("token") {
2260        #[expect(
2261            clippy::disallowed_types,
2262            reason = "need stdlib's HashMap because of TOML compatibility"
2263        )]
2264        let map = std::collections::HashMap::from([("token".to_string(), token)]);
2265        toml.insert("registry".into(), map.into());
2266    }
2267
2268    if let Some(token) = token {
2269        // login
2270
2271        let path_def = Definition::Path(file.path().to_path_buf());
2272        let (key, mut value) = match token {
2273            RegistryCredentialConfig::Token(token) => {
2274                // login with token
2275
2276                let key = "token".to_string();
2277                let value = ConfigValue::String(token.expose(), path_def.clone());
2278                let map = HashMap::from_iter([(key, value)]);
2279                let table = CV::Table(map, path_def.clone());
2280
2281                if let Some(registry) = registry {
2282                    let map = HashMap::from_iter([(registry.to_string(), table)]);
2283                    ("registries".into(), CV::Table(map, path_def.clone()))
2284                } else {
2285                    ("registry".into(), table)
2286                }
2287            }
2288            _ => unreachable!(),
2289        };
2290
2291        if registry.is_some() {
2292            if let Some(table) = toml.remove("registries") {
2293                let v = CV::from_toml(path_def, table)?;
2294                value.merge(v, false)?;
2295            }
2296        }
2297        toml.insert(key, value.into_toml());
2298    } else {
2299        // logout
2300        if let Some(registry) = registry {
2301            if let Some(registries) = toml.get_mut("registries") {
2302                if let Some(reg) = registries.get_mut(registry) {
2303                    let rtable = reg.as_table_mut().ok_or_else(|| {
2304                        format_err!("expected `[registries.{}]` to be a table", registry)
2305                    })?;
2306                    rtable.remove("token");
2307                }
2308            }
2309        } else if let Some(registry) = toml.get_mut("registry") {
2310            let reg_table = registry
2311                .as_table_mut()
2312                .ok_or_else(|| format_err!("expected `[registry]` to be a table"))?;
2313            reg_table.remove("token");
2314        }
2315    }
2316
2317    let contents = toml.to_string();
2318    file.seek(SeekFrom::Start(0))?;
2319    file.write_all(contents.as_bytes())
2320        .with_context(|| format!("failed to write to `{}`", file.path().display()))?;
2321    file.file().set_len(contents.len() as u64)?;
2322    set_permissions(file.file(), 0o600)
2323        .with_context(|| format!("failed to set permissions of `{}`", file.path().display()))?;
2324
2325    return Ok(());
2326
2327    #[cfg(unix)]
2328    fn set_permissions(file: &File, mode: u32) -> CargoResult<()> {
2329        use std::os::unix::fs::PermissionsExt;
2330
2331        let mut perms = file.metadata()?.permissions();
2332        perms.set_mode(mode);
2333        file.set_permissions(perms)?;
2334        Ok(())
2335    }
2336
2337    #[cfg(not(unix))]
2338    fn set_permissions(_file: &File, _mode: u32) -> CargoResult<()> {
2339        Ok(())
2340    }
2341}
2342
2343/// Represents a config-include value in the configuration.
2344///
2345/// This intentionally doesn't derive serde deserialization
2346/// to avoid any misuse of `GlobalContext::get::<ConfigInclude>()`,
2347/// which might lead to wrong config loading order.
2348struct ConfigInclude {
2349    /// Path to a config-include configuration file.
2350    /// Could be either relative or absolute.
2351    path: PathBuf,
2352    def: Definition,
2353    /// Whether this include is optional (missing files are silently ignored)
2354    optional: bool,
2355}
2356
2357impl ConfigInclude {
2358    fn new(p: impl Into<PathBuf>, def: Definition) -> Self {
2359        Self {
2360            path: p.into(),
2361            def,
2362            optional: false,
2363        }
2364    }
2365
2366    /// Resolves the absolute path for this include.
2367    ///
2368    /// For file based include,
2369    /// it is relative to parent directory of the config file includes it.
2370    /// For example, if `.cargo/config.toml has a `include = "foo.toml"`,
2371    /// Cargo will load `.cargo/foo.toml`.
2372    ///
2373    /// For CLI based include (e.g., `--config 'include = "foo.toml"'`),
2374    /// it is relative to the current working directory.
2375    ///
2376    /// Returns `None` if this is an optional include and the file doesn't exist.
2377    /// Otherwise returns `Some(PathBuf)` with the absolute path.
2378    fn resolve_path(&self, gctx: &GlobalContext) -> Option<PathBuf> {
2379        let abs_path = match &self.def {
2380            Definition::Path(p) | Definition::Cli(Some(p)) => p.parent().unwrap(),
2381            Definition::Environment(_) | Definition::Cli(None) | Definition::BuiltIn => gctx.cwd(),
2382        }
2383        .join(&self.path);
2384        let abs_path = paths::normalize_path(&abs_path);
2385
2386        if self.optional && !abs_path.exists() {
2387            tracing::info!(
2388                "skipping optional include `{}` in `{}`:  file not found at `{}`",
2389                self.path.display(),
2390                self.def,
2391                abs_path.display(),
2392            );
2393            None
2394        } else {
2395            Some(abs_path)
2396        }
2397    }
2398}
2399
2400fn toml_dotted_keys(arg: &str) -> CargoResult<toml_edit::DocumentMut> {
2401    // We only want to allow "dotted key" (see https://toml.io/en/v1.0.0#keys)
2402    // expressions followed by a value that's not an "inline table"
2403    // (https://toml.io/en/v1.0.0#inline-table). Easiest way to check for that is to
2404    // parse the value as a toml_edit::DocumentMut, and check that the (single)
2405    // inner-most table is set via dotted keys.
2406    let doc: toml_edit::DocumentMut = arg.parse().with_context(|| {
2407        format!("failed to parse value from --config argument `{arg}` as a dotted key expression")
2408    })?;
2409    fn non_empty(d: Option<&toml_edit::RawString>) -> bool {
2410        d.map_or(false, |p| !p.as_str().unwrap_or_default().trim().is_empty())
2411    }
2412    fn non_empty_decor(d: &toml_edit::Decor) -> bool {
2413        non_empty(d.prefix()) || non_empty(d.suffix())
2414    }
2415    fn non_empty_key_decor(k: &toml_edit::Key) -> bool {
2416        non_empty_decor(k.leaf_decor()) || non_empty_decor(k.dotted_decor())
2417    }
2418    let ok = {
2419        let mut got_to_value = false;
2420        let mut table = doc.as_table();
2421        let mut is_root = true;
2422        while table.is_dotted() || is_root {
2423            is_root = false;
2424            if table.len() != 1 {
2425                break;
2426            }
2427            let (k, n) = table.iter().next().expect("len() == 1 above");
2428            match n {
2429                Item::Table(nt) => {
2430                    if table.key(k).map_or(false, non_empty_key_decor)
2431                        || non_empty_decor(nt.decor())
2432                    {
2433                        bail!(
2434                            "--config argument `{arg}` \
2435                                includes non-whitespace decoration"
2436                        )
2437                    }
2438                    table = nt;
2439                }
2440                Item::Value(v) if v.is_inline_table() => {
2441                    bail!(
2442                        "--config argument `{arg}` \
2443                        sets a value to an inline table, which is not accepted"
2444                    );
2445                }
2446                Item::Value(v) => {
2447                    if table
2448                        .key(k)
2449                        .map_or(false, |k| non_empty(k.leaf_decor().prefix()))
2450                        || non_empty_decor(v.decor())
2451                    {
2452                        bail!(
2453                            "--config argument `{arg}` \
2454                                includes non-whitespace decoration"
2455                        )
2456                    }
2457                    got_to_value = true;
2458                    break;
2459                }
2460                Item::ArrayOfTables(_) => {
2461                    bail!(
2462                        "--config argument `{arg}` \
2463                        sets a value to an array of tables, which is not accepted"
2464                    );
2465                }
2466
2467                Item::None => {
2468                    bail!("--config argument `{arg}` doesn't provide a value")
2469                }
2470            }
2471        }
2472        got_to_value
2473    };
2474    if !ok {
2475        bail!(
2476            "--config argument `{arg}` was not a TOML dotted key expression (such as `build.jobs = 2`)"
2477        );
2478    }
2479    Ok(doc)
2480}
2481
2482/// A type to deserialize a list of strings from a toml file.
2483///
2484/// Supports deserializing either a whitespace-separated list of arguments in a
2485/// single string or a string list itself. For example these deserialize to
2486/// equivalent values:
2487///
2488/// ```toml
2489/// a = 'a b c'
2490/// b = ['a', 'b', 'c']
2491/// ```
2492#[derive(Debug, Deserialize, Clone)]
2493pub struct StringList(Vec<String>);
2494
2495impl StringList {
2496    pub fn as_slice(&self) -> &[String] {
2497        &self.0
2498    }
2499}
2500
2501#[macro_export]
2502macro_rules! __shell_print {
2503    ($config:expr, $which:ident, $newline:literal, $($arg:tt)*) => ({
2504        let mut shell = $config.shell();
2505        let out = shell.$which();
2506        drop(out.write_fmt(format_args!($($arg)*)));
2507        if $newline {
2508            drop(out.write_all(b"\n"));
2509        }
2510    });
2511}
2512
2513#[macro_export]
2514macro_rules! drop_println {
2515    ($config:expr) => ( $crate::drop_print!($config, "\n") );
2516    ($config:expr, $($arg:tt)*) => (
2517        $crate::__shell_print!($config, out, true, $($arg)*)
2518    );
2519}
2520
2521#[macro_export]
2522macro_rules! drop_eprintln {
2523    ($config:expr) => ( $crate::drop_eprint!($config, "\n") );
2524    ($config:expr, $($arg:tt)*) => (
2525        $crate::__shell_print!($config, err, true, $($arg)*)
2526    );
2527}
2528
2529#[macro_export]
2530macro_rules! drop_print {
2531    ($config:expr, $($arg:tt)*) => (
2532        $crate::__shell_print!($config, out, false, $($arg)*)
2533    );
2534}
2535
2536#[macro_export]
2537macro_rules! drop_eprint {
2538    ($config:expr, $($arg:tt)*) => (
2539        $crate::__shell_print!($config, err, false, $($arg)*)
2540    );
2541}
2542
2543enum Tool {
2544    Rustc,
2545    Rustdoc,
2546}
2547
2548impl Tool {
2549    fn as_str(&self) -> &str {
2550        match self {
2551            Tool::Rustc => "rustc",
2552            Tool::Rustdoc => "rustdoc",
2553        }
2554    }
2555}
2556
2557/// Disable HTTP/2 multiplexing for some broken versions of libcurl.
2558///
2559/// In certain versions of libcurl when proxy is in use with HTTP/2
2560/// multiplexing, connections will continue stacking up. This was
2561/// fixed in libcurl 8.0.0 in curl/curl@821f6e2a89de8aec1c7da3c0f381b92b2b801efc
2562///
2563/// However, Cargo can still link against old system libcurl if it is from a
2564/// custom built one or on macOS. For those cases, multiplexing needs to be
2565/// disabled when those versions are detected.
2566fn disables_multiplexing_for_bad_curl(
2567    curl_version: &str,
2568    http: &mut CargoHttpConfig,
2569    gctx: &GlobalContext,
2570) {
2571    use crate::util::network;
2572
2573    if network::proxy::http_proxy_exists(http, gctx) && http.multiplexing.is_none() {
2574        let bad_curl_versions = ["7.87.0", "7.88.0", "7.88.1"];
2575        if bad_curl_versions
2576            .iter()
2577            .any(|v| curl_version.starts_with(v))
2578        {
2579            tracing::info!("disabling multiplexing with proxy, curl version is {curl_version}");
2580            http.multiplexing = Some(false);
2581        }
2582    }
2583}
2584
2585#[cfg(test)]
2586mod tests {
2587    use super::CargoHttpConfig;
2588    use super::GlobalContext;
2589    use super::Shell;
2590    use super::disables_multiplexing_for_bad_curl;
2591
2592    #[test]
2593    fn disables_multiplexing() {
2594        let mut gctx = GlobalContext::new(Shell::new(), "".into(), "".into());
2595        gctx.set_search_stop_path(std::path::PathBuf::new());
2596        gctx.set_env(Default::default());
2597
2598        let mut http = CargoHttpConfig::default();
2599        http.proxy = Some("127.0.0.1:3128".into());
2600        disables_multiplexing_for_bad_curl("7.88.1", &mut http, &gctx);
2601        assert_eq!(http.multiplexing, Some(false));
2602
2603        let cases = [
2604            (None, None, "7.87.0", None),
2605            (None, None, "7.88.0", None),
2606            (None, None, "7.88.1", None),
2607            (None, None, "8.0.0", None),
2608            (Some("".into()), None, "7.87.0", Some(false)),
2609            (Some("".into()), None, "7.88.0", Some(false)),
2610            (Some("".into()), None, "7.88.1", Some(false)),
2611            (Some("".into()), None, "8.0.0", None),
2612            (Some("".into()), Some(false), "7.87.0", Some(false)),
2613            (Some("".into()), Some(false), "7.88.0", Some(false)),
2614            (Some("".into()), Some(false), "7.88.1", Some(false)),
2615            (Some("".into()), Some(false), "8.0.0", Some(false)),
2616        ];
2617
2618        for (proxy, multiplexing, curl_v, result) in cases {
2619            let mut http = CargoHttpConfig {
2620                multiplexing,
2621                proxy,
2622                ..Default::default()
2623            };
2624            disables_multiplexing_for_bad_curl(curl_v, &mut http, &gctx);
2625            assert_eq!(http.multiplexing, result);
2626        }
2627    }
2628
2629    #[test]
2630    fn sync_context() {
2631        fn assert_sync<S: Sync>() {}
2632        assert_sync::<GlobalContext>();
2633    }
2634}