1use cargo_util::collections::{HashMap, HashSet};
69use std::env;
70use std::ffi::{OsStr, OsString};
71use std::fs::File;
72use std::io::SeekFrom;
73use std::io::prelude::*;
74use std::path::{Path, PathBuf};
75use std::sync::{Arc, LazyLock, Mutex, MutexGuard, OnceLock};
76use std::time::Instant;
77
78use self::ConfigValue as CV;
79use crate::ops::RegistryCredentialConfig;
80use crate::sources::CRATES_IO_INDEX;
81use crate::sources::CRATES_IO_REGISTRY;
82use crate::util::OnceExt as _;
83use crate::util::VersionReqMatchMode;
84use crate::util::cache_lock::{CacheLock, CacheLockMode, CacheLocker};
85use crate::util::errors::CargoResult;
86use crate::util::network::http::{HandleConfiguration, configure_http_handle, http_handle};
87use crate::util::network::http_async;
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::{Shell, Verbosity};
98use curl::easy::Easy;
99use itertools::Itertools;
100use jiff::Timestamp;
101use url::Url;
102
103use crate::config::ConfigLoader;
104use crate::config::ConfigReader;
105use crate::config::Env;
106pub use crate::config::{
107 ConfigError, ConfigKey, ConfigStore, ConfigValue, Definition, OptValue, Scope, Value,
108};
109
110mod target;
111pub use target::{TargetCfgConfig, TargetConfig};
112
113pub use crate::config::schema::*;
114
115pub const TOP_LEVEL_CONFIG_KEYS: &[&str] = &[
116 "paths",
117 "alias",
118 "build",
119 "credential-alias",
120 "doc",
121 "env",
122 "future-incompat-report",
123 "cache",
124 "cargo-new",
125 "http",
126 "install",
127 "net",
128 "patch",
129 "profile",
130 "resolver",
131 "registries",
132 "registry",
133 "source",
134 "target",
135 "term",
136];
137
138#[derive(Debug)]
140pub struct CredentialCacheValue {
141 pub token_value: Secret<String>,
142 pub expiration: Option<Timestamp>,
143 pub operation_independent: bool,
144}
145
146#[derive(Debug)]
149pub struct GlobalContext {
150 cargo_home: Filesystem,
152 shell: Mutex<Shell>,
154 config: OnceLock<ConfigStore>,
156 credentials_config: OnceLock<ConfigStore>,
158 cli_config: Option<Vec<String>>,
160 cwd: PathBuf,
162 search_stop_path: Option<PathBuf>,
164 cargo_exe: OnceLock<PathBuf>,
166 rustdoc: OnceLock<PathBuf>,
168 extra_verbose: bool,
170 frozen: bool,
173 locked: bool,
176 offline: bool,
179 jobserver: Option<&'static jobserver::Client>,
181 unstable_flags: CliUnstable,
183 unstable_flags_cli: Option<Vec<String>>,
185 easy: OnceLock<Mutex<Easy>>,
187 crates_io_source_id: OnceLock<SourceId>,
189 cache_rustc_info: bool,
191 invocation_instant: Instant,
193 invocation_time: jiff::Timestamp,
197 target_dir: Option<Filesystem>,
199 env: Env,
201 updated_sources: Mutex<HashSet<SourceId>>,
203 credential_cache: Mutex<HashMap<CanonicalUrl, CredentialCacheValue>>,
206 registry_config: Mutex<HashMap<SourceId, Option<RegistryConfig>>>,
208 package_cache_lock: CacheLocker,
210 http_config: OnceLock<CargoHttpConfig>,
212 http_async: OnceLock<http_async::Client>,
213 future_incompat_config: OnceLock<CargoFutureIncompatConfig>,
214 net_config: OnceLock<CargoNetConfig>,
215 build_config: OnceLock<CargoBuildConfig>,
216 target_cfgs: OnceLock<Vec<(String, TargetCfgConfig)>>,
217 doc_extern_map: OnceLock<RustdocExternMap>,
218 progress_config: ProgressConfig,
219 env_config: OnceLock<Arc<HashMap<String, OsString>>>,
220 pub nightly_features_allowed: bool,
236 ws_roots: Mutex<HashMap<PathBuf, WorkspaceRootConfig>>,
238 global_cache_tracker: OnceLock<Mutex<GlobalCacheTracker>>,
240 deferred_global_last_use: OnceLock<Mutex<DeferredGlobalLastUse>>,
243}
244
245impl GlobalContext {
246 pub fn new(mut shell: Shell, cwd: PathBuf, cargo_home: PathBuf) -> GlobalContext {
254 static GLOBAL_JOBSERVER: LazyLock<CargoResult<Option<jobserver::Client>>> = LazyLock::new(
255 || {
256 use jobserver::FromEnvErrorKind;
257 let jobserver::FromEnv { client, var } =
263 unsafe { jobserver::Client::from_env_ext(true) };
264
265 match client {
266 Ok(client) => return Ok(Some(client)),
267 Err(e)
268 if matches!(
269 e.kind(),
270 FromEnvErrorKind::NoEnvVar
271 | FromEnvErrorKind::NoJobserver
272 | FromEnvErrorKind::NegativeFd
273 | FromEnvErrorKind::Unsupported
274 ) =>
275 {
276 Ok(None)
277 }
278 Err(e) => {
279 let (name, value) = var.unwrap();
280 Err(anyhow::anyhow!(
281 "failed to connect to jobserver from environment variable `{name}={value:?}`: {e}"
282 ))
283 }
284 }
285 },
286 );
287 let jobserver = match &*GLOBAL_JOBSERVER {
288 Ok(jobserver) => jobserver.as_ref(),
289 Err(e) => {
290 let _ = shell.warn(e);
291 None
292 }
293 };
294
295 let env = Env::from_env();
296
297 let cache_key = "CARGO_CACHE_RUSTC_INFO";
298 let cache_rustc_info = match env.get_env_os(cache_key) {
299 Some(cache) => cache != "0",
300 _ => true,
301 };
302
303 #[expect(
304 clippy::disallowed_methods,
305 reason = "testing only, no reason for config support"
306 )]
307 let invocation_time = match env::var("__CARGO_TEST_INVOCATION_TIME") {
308 Ok(now) => now.parse().unwrap(),
309 Err(_) => jiff::Timestamp::now(),
310 };
311
312 GlobalContext {
313 cargo_home: Filesystem::new(cargo_home),
314 shell: Mutex::new(shell),
315 cwd,
316 search_stop_path: None,
317 config: Default::default(),
318 credentials_config: Default::default(),
319 cli_config: None,
320 cargo_exe: Default::default(),
321 rustdoc: Default::default(),
322 extra_verbose: false,
323 frozen: false,
324 locked: false,
325 offline: false,
326 jobserver,
327 unstable_flags: CliUnstable::default(),
328 unstable_flags_cli: None,
329 easy: Default::default(),
330 crates_io_source_id: Default::default(),
331 cache_rustc_info,
332 invocation_instant: Instant::now(),
333 invocation_time,
334 target_dir: None,
335 env,
336 updated_sources: Default::default(),
337 credential_cache: Default::default(),
338 registry_config: Default::default(),
339 package_cache_lock: CacheLocker::new(),
340 http_config: Default::default(),
341 http_async: Default::default(),
342 future_incompat_config: Default::default(),
343 net_config: Default::default(),
344 build_config: Default::default(),
345 target_cfgs: Default::default(),
346 doc_extern_map: Default::default(),
347 progress_config: ProgressConfig::default(),
348 env_config: Default::default(),
349 nightly_features_allowed: matches!(&*features::channel(), "nightly" | "dev"),
350 ws_roots: Default::default(),
351 global_cache_tracker: Default::default(),
352 deferred_global_last_use: Default::default(),
353 }
354 }
355
356 pub fn default() -> CargoResult<GlobalContext> {
361 let shell = Shell::new();
362 let cwd =
363 env::current_dir().context("couldn't get the current directory of the process")?;
364 let cargo_home = cargo_home(&cwd)?;
365 Ok(GlobalContext::new(shell, cwd, cargo_home))
366 }
367
368 pub fn cargo_home(&self) -> &Filesystem {
370 &self.cargo_home
371 }
372
373 pub fn diagnostic_home_config(&self) -> String {
377 let cargo_home = self.cargo_home.as_path_unlocked();
378 let path = match self
379 .config_loader()
380 .get_file_path(cargo_home, "config", false)
381 {
382 Ok(Some(existing_path)) => existing_path,
383 _ => cargo_home.join("config.toml"),
384 };
385 path.to_string_lossy().to_string()
386 }
387
388 pub fn git_path(&self) -> Filesystem {
390 self.cargo_home.join("git")
391 }
392
393 pub fn git_checkouts_path(&self) -> Filesystem {
396 self.git_path().join("checkouts")
397 }
398
399 pub fn git_db_path(&self) -> Filesystem {
402 self.git_path().join("db")
403 }
404
405 pub fn registry_base_path(&self) -> Filesystem {
407 self.cargo_home.join("registry")
408 }
409
410 pub fn registry_index_path(&self) -> Filesystem {
412 self.registry_base_path().join("index")
413 }
414
415 pub fn registry_cache_path(&self) -> Filesystem {
417 self.registry_base_path().join("cache")
418 }
419
420 pub fn registry_source_path(&self) -> Filesystem {
422 self.registry_base_path().join("src")
423 }
424
425 pub fn default_registry(&self) -> CargoResult<Option<String>> {
427 Ok(self
428 .get_string(["registry", "default"])?
429 .map(|registry| registry.val))
430 }
431
432 pub fn shell(&self) -> MutexGuard<'_, Shell> {
434 self.shell.lock().unwrap()
435 }
436
437 pub fn debug_assert_shell_not_borrowed(&self) {
443 if cfg!(debug_assertions) {
444 match self.shell.try_lock() {
445 Ok(_) | Err(std::sync::TryLockError::Poisoned(_)) => (),
446 Err(std::sync::TryLockError::WouldBlock) => panic!("shell is borrowed!"),
447 }
448 }
449 }
450
451 pub fn rustdoc(&self) -> CargoResult<&Path> {
453 self.rustdoc
454 .try_borrow_with(|| Ok(self.get_tool(Tool::Rustdoc, &self.build_config()?.rustdoc)))
455 .map(AsRef::as_ref)
456 }
457
458 pub fn load_global_rustc(&self, ws: Option<&Workspace<'_>>) -> CargoResult<Rustc> {
460 let cache_location =
461 ws.map(|ws| ws.build_dir().join(".rustc_info.json").into_path_unlocked());
462 let wrapper = self.maybe_get_tool("rustc_wrapper", &self.build_config()?.rustc_wrapper);
463 let rustc_workspace_wrapper = self.maybe_get_tool(
464 "rustc_workspace_wrapper",
465 &self.build_config()?.rustc_workspace_wrapper,
466 );
467
468 Rustc::new(
469 self.get_tool(Tool::Rustc, &self.build_config()?.rustc),
470 wrapper,
471 rustc_workspace_wrapper,
472 &self
473 .cargo_home()
474 .join("bin")
475 .join("rustc")
476 .into_path_unlocked()
477 .with_extension(env::consts::EXE_EXTENSION),
478 if self.cache_rustc_info {
479 cache_location
480 } else {
481 None
482 },
483 self,
484 )
485 }
486
487 pub fn cargo_exe(&self) -> CargoResult<&Path> {
489 self.cargo_exe
490 .try_borrow_with(|| {
491 let from_env = || -> CargoResult<PathBuf> {
492 let exe = self
497 .get_env_os(crate::CARGO_ENV)
498 .map(PathBuf::from)
499 .ok_or_else(|| anyhow!("$CARGO not set"))?;
500 Ok(exe)
501 };
502
503 fn from_current_exe() -> CargoResult<PathBuf> {
504 let exe = env::current_exe()?;
509 Ok(exe)
510 }
511
512 fn from_argv() -> CargoResult<PathBuf> {
513 let argv0 = env::args_os()
520 .map(PathBuf::from)
521 .next()
522 .ok_or_else(|| anyhow!("no argv[0]"))?;
523 paths::resolve_executable(&argv0)
524 }
525
526 fn is_cargo(path: &Path) -> bool {
529 path.file_stem() == Some(OsStr::new("cargo"))
530 }
531
532 let from_current_exe = from_current_exe();
533 if from_current_exe.as_deref().is_ok_and(is_cargo) {
534 return from_current_exe;
535 }
536
537 let from_argv = from_argv();
538 if from_argv.as_deref().is_ok_and(is_cargo) {
539 return from_argv;
540 }
541
542 let exe = from_env()
543 .or(from_current_exe)
544 .or(from_argv)
545 .context("couldn't get the path to cargo executable")?;
546 Ok(exe)
547 })
548 .map(AsRef::as_ref)
549 }
550
551 pub fn updated_sources(&self) -> MutexGuard<'_, HashSet<SourceId>> {
553 self.updated_sources.lock().unwrap()
554 }
555
556 pub fn credential_cache(&self) -> MutexGuard<'_, HashMap<CanonicalUrl, CredentialCacheValue>> {
558 self.credential_cache.lock().unwrap()
559 }
560
561 pub fn registry_config(&self, sid: &SourceId) -> CargoResult<Option<RegistryConfig>> {
570 let mut cache = self.registry_config.lock().unwrap();
571 if let Some(cfg) = cache.get(sid) {
572 return Ok(cfg.clone());
573 }
574 let cfg = registry_config_uncached(self, sid)?;
575 cache.insert(*sid, cfg.clone());
576 Ok(cfg)
577 }
578
579 pub fn registry_credentials(&self, sid: &SourceId) -> CargoResult<Option<RegistryCredential>> {
584 let credentials = self.credentials_config()?;
585 let mut key = if sid.is_crates_io() {
586 ConfigKey::from_parts(["registry"])
587 } else if let Some(name) = registry_name(self, sid)? {
588 ConfigKey::from_parts(["registries", &name])
589 } else {
590 return Ok(None);
591 };
592 let has_credentials = credentials.get_cv(&key)?.is_some();
593 key.push("token");
594 let credentials_token = match credentials.get_cv(&key)? {
595 Some(CV::String(val, definition)) => Some(Value {
596 val: Secret::from(val),
597 definition,
598 }),
599 Some(cv) => return Err(ConfigError::expected(&key, "a string", &cv).into()),
600 None => None,
601 };
602
603 let config = self.registry_config(sid)?;
604 let has_config = config.is_some();
605 let config_token = config.and_then(|config| {
606 #[expect(deprecated)]
607 config.token
608 });
609
610 let token = match (config_token, credentials_token) {
611 (Some(config_token), Some(credentials_token))
612 if config_token
613 .definition
614 .is_higher_priority(&credentials_token.definition) =>
615 {
616 Some(config_token)
617 }
618 (_, Some(credentials_token)) => Some(credentials_token),
619 (config_token, None) => config_token,
620 };
621
622 Ok((has_config || has_credentials).then_some(RegistryCredential { token }))
623 }
624
625 pub fn config(&self) -> CargoResult<&ConfigStore> {
631 self.config.try_borrow_with(|| self.load_config())
632 }
633
634 pub fn config_mut(&mut self) -> CargoResult<&mut ConfigStore> {
641 let _ = self.config()?;
642 Ok(self.config.get_mut().expect("already loaded config values"))
643 }
644
645 pub fn set_search_stop_path<P: Into<PathBuf>>(&mut self, path: P) {
648 let path = path.into();
649 debug_assert!(self.cwd.starts_with(&path));
650 self.search_stop_path = Some(path);
651 }
652
653 pub fn reload_cwd(&mut self) -> CargoResult<()> {
657 let cwd =
658 env::current_dir().context("couldn't get the current directory of the process")?;
659 let cargo_home = cargo_home(&cwd)?;
660
661 self.cwd = cwd;
662 self.cargo_home = Filesystem::new(cargo_home);
663 self.reload_rooted_at(self.cwd.clone())?;
664 Ok(())
665 }
666
667 pub fn reload_rooted_at<P: AsRef<Path>>(&mut self, path: P) -> CargoResult<()> {
670 let mut layers = self.config_loader().load_layers(path.as_ref())?;
671 layers.push(self.cli_args_to_config()?);
672 let config =
673 ConfigStore::from_layers(layers).context("could not load Cargo configuration")?;
674 self.config.replace(config);
675 self.load_unstable_flags_from_config()?;
676 Ok(())
677 }
678
679 pub fn cwd(&self) -> &Path {
681 &self.cwd
682 }
683
684 pub fn target_dir(&self) -> CargoResult<Option<Filesystem>> {
690 if let Some(dir) = &self.target_dir {
691 Ok(Some(dir.clone()))
692 } else if let Some(dir) = self.get_env_os("CARGO_TARGET_DIR") {
693 if dir.is_empty() {
695 bail!(
696 "the target directory is set to an empty string in the \
697 `CARGO_TARGET_DIR` environment variable"
698 )
699 }
700
701 Ok(Some(Filesystem::new(self.cwd.join(dir))))
702 } else if let Some(val) = &self.build_config()?.target_dir {
703 let path = val.resolve(self.cwd());
704
705 if val.is_empty() {
707 bail!(
708 "the target directory is set to an empty string in {}",
709 val.definition()
710 )
711 }
712
713 Ok(Some(Filesystem::new(path)))
714 } else {
715 Ok(None)
716 }
717 }
718
719 pub fn build_dir(&self, workspace_manifest_path: &Path) -> CargoResult<Option<Filesystem>> {
723 let Some(val) = &self.build_config()?.build_dir else {
724 return Ok(None);
725 };
726 self.custom_build_dir(val, workspace_manifest_path)
727 .map(Some)
728 }
729
730 pub fn custom_build_dir(
734 &self,
735 val: &ConfigRootRelativePathTemplate,
736 workspace_manifest_path: &Path,
737 ) -> CargoResult<Filesystem> {
738 let replacements = [
739 (
740 "{workspace-root}",
741 workspace_manifest_path
742 .parent()
743 .unwrap()
744 .to_str()
745 .context("workspace root was not valid utf-8")?
746 .to_string(),
747 ),
748 (
749 "{cargo-cache-home}",
750 self.cargo_home()
751 .as_path_unlocked()
752 .to_str()
753 .context("cargo home was not valid utf-8")?
754 .to_string(),
755 ),
756 ("{workspace-path-hash}", {
757 let real_path = std::fs::canonicalize(workspace_manifest_path)
758 .unwrap_or_else(|_err| workspace_manifest_path.to_owned());
759 let hash = crate::util::hex::short_hash(&real_path);
760 format!("{}{}{}", &hash[0..2], std::path::MAIN_SEPARATOR, &hash[2..])
761 }),
762 ];
763
764 let template_variables = replacements
765 .iter()
766 .map(|(key, _)| key[1..key.len() - 1].to_string())
767 .collect_vec();
768
769 let path = val
770 .resolve(self.cwd(), replacements)
771 .map_err(|e| match e {
772 ResolveTemplateError::UnexpectedVariable {
773 variable,
774 raw_template,
775 } => {
776 let mut suggestion = closest_msg(&variable, template_variables.iter(), |key| key, "template variable");
777 if suggestion == "" {
778 let variables = template_variables.iter().map(|v| format!("`{{{v}}}`")).join(", ");
779 suggestion = format!("\n\nhelp: available template variables are {variables}");
780 }
781 anyhow!(
782 "unexpected variable `{variable}` in build.build-dir path `{raw_template}`{suggestion}"
783 )
784 }
785 ResolveTemplateError::UnexpectedBracket { bracket_type, raw_template } => {
786 let (btype, literal) = match bracket_type {
787 BracketType::Opening => ("opening", "{"),
788 BracketType::Closing => ("closing", "}"),
789 };
790
791 anyhow!(
792 "unexpected {btype} bracket `{literal}` in build.build-dir path `{raw_template}`"
793 )
794 }
795 })?;
796
797 if val.is_empty() {
799 bail!(
800 "the build directory is set to an empty string in {}",
801 val.definition()
802 )
803 }
804
805 Ok(Filesystem::new(path))
806 }
807
808 fn config_reader(&self) -> CargoResult<ConfigReader<'_>> {
809 Ok(ConfigReader::new(&self.shell)
810 .config(self.config()?)
811 .env(&self.env)
812 .unstable_advanced_env(self.cli_unstable().advanced_env))
813 }
814
815 pub(crate) fn get_cv_with_env(&self, key: &ConfigKey) -> CargoResult<Option<CV>> {
816 self.config_reader()?.get_cv_with_env(key)
817 }
818
819 pub fn set_env(&mut self, env: HashMap<String, String>) {
821 self.env = Env::from_map(env);
822 }
823
824 pub(crate) fn env(&self) -> impl Iterator<Item = (&str, &str)> {
827 self.env.iter_str()
828 }
829
830 pub fn get_env(&self, key: impl AsRef<OsStr>) -> CargoResult<&str> {
835 self.env.get_env(key)
836 }
837
838 pub fn get_env_os(&self, key: impl AsRef<OsStr>) -> Option<&OsStr> {
843 self.env.get_env_os(key)
844 }
845
846 pub fn get_string(
850 &self,
851 key: impl IntoIterator<Item = impl AsRef<str>>,
852 ) -> CargoResult<OptValue<String>> {
853 self.get::<OptValue<String>>(key)
854 }
855
856 pub fn configure(
862 &mut self,
863 verbose: u32,
864 quiet: bool,
865 color: Option<&str>,
866 frozen: bool,
867 locked: bool,
868 offline: bool,
869 target_dir: &Option<PathBuf>,
870 unstable_flags: &[String],
871 cli_config: &[String],
872 ) -> CargoResult<()> {
873 for warning in self
874 .unstable_flags
875 .parse(unstable_flags, self.nightly_features_allowed)?
876 {
877 self.shell().warn(warning)?;
878 }
879 if !unstable_flags.is_empty() {
880 self.unstable_flags_cli = Some(unstable_flags.to_vec());
883 }
884 if !cli_config.is_empty() {
885 self.cli_config = Some(cli_config.iter().map(|s| s.to_string()).collect());
886 let cli_config = self.cli_args_to_config()?;
887 let files = std::mem::take(self.config_mut()?);
889 let config = ConfigStore::from_layers([files, cli_config])?;
890 self.config.replace(config);
891 }
892
893 self.load_unstable_flags_from_config()?;
894
895 let term = self.get::<TermConfig>(["term"]).unwrap_or_default();
899
900 let extra_verbose = verbose >= 2;
902 let verbose = verbose != 0;
903 let verbosity = match (verbose, quiet) {
904 (true, true) => bail!("cannot set both --verbose and --quiet"),
905 (true, false) => Verbosity::Verbose,
906 (false, true) => Verbosity::Quiet,
907 (false, false) => match (term.verbose, term.quiet) {
908 (Some(true), Some(true)) => {
909 bail!("cannot set both `term.verbose` and `term.quiet`")
910 }
911 (Some(true), _) => Verbosity::Verbose,
912 (_, Some(true)) => Verbosity::Quiet,
913 _ => Verbosity::Normal,
914 },
915 };
916 self.shell().set_verbosity(verbosity);
917 self.extra_verbose = extra_verbose;
918
919 let color = color.or_else(|| term.color.as_deref());
920 self.shell().set_color_choice(color)?;
921 if let Some(hyperlinks) = term.hyperlinks {
922 self.shell().set_hyperlinks(hyperlinks)?;
923 }
924 if let Some(unicode) = term.unicode {
925 self.shell().set_unicode(unicode)?;
926 }
927
928 self.progress_config = term.progress.unwrap_or_default();
929
930 self.frozen = frozen;
931 self.locked = locked;
932 self.offline = offline
933 || self
934 .net_config()
935 .ok()
936 .and_then(|n| n.offline)
937 .unwrap_or(false);
938 let cli_target_dir = target_dir.as_ref().map(|dir| Filesystem::new(dir.clone()));
939 self.target_dir = cli_target_dir;
940
941 self.shell()
942 .set_unstable_flags_rustc_unicode(self.unstable_flags.rustc_unicode)?;
943
944 if !self.unstable_flags.term_graphics {
947 self.shell().set_graphics(true)?;
948 }
949
950 if let Some(graphics) = term.graphics {
951 if self.unstable_flags.term_graphics {
952 self.shell().set_graphics(graphics)?;
953 } else {
954 self.shell()
955 .warn("ignoring `term.graphics` without `-Zterm-graphics`")?;
956 }
957 }
958
959 Ok(())
960 }
961
962 fn load_unstable_flags_from_config(&mut self) -> CargoResult<()> {
963 if self.nightly_features_allowed {
966 self.unstable_flags = self
967 .get::<Option<CliUnstable>>(["unstable"])?
968 .unwrap_or_default();
969 if let Some(unstable_flags_cli) = &self.unstable_flags_cli {
970 self.unstable_flags.parse(unstable_flags_cli, true)?;
975 }
976 }
977
978 Ok(())
979 }
980
981 pub fn cli_unstable(&self) -> &CliUnstable {
982 &self.unstable_flags
983 }
984
985 pub fn extra_verbose(&self) -> bool {
986 self.extra_verbose
987 }
988
989 pub fn network_allowed(&self) -> bool {
990 !self.offline_flag().is_some()
991 }
992
993 pub fn offline_flag(&self) -> Option<&'static str> {
994 if self.frozen {
995 Some("--frozen")
996 } else if self.offline {
997 Some("--offline")
998 } else {
999 None
1000 }
1001 }
1002
1003 pub fn set_locked(&mut self, locked: bool) {
1004 self.locked = locked;
1005 }
1006
1007 pub fn lock_update_allowed(&self) -> bool {
1008 !self.locked_flag().is_some()
1009 }
1010
1011 pub fn locked_flag(&self) -> Option<&'static str> {
1012 if self.frozen {
1013 Some("--frozen")
1014 } else if self.locked {
1015 Some("--locked")
1016 } else {
1017 None
1018 }
1019 }
1020
1021 pub fn load_config(&self) -> CargoResult<ConfigStore> {
1023 let layers = self.config_loader().load_layers(&self.cwd)?;
1024 ConfigStore::from_layers(layers).context("could not load Cargo configuration")
1025 }
1026
1027 pub(crate) fn cli_args_to_config(&self) -> CargoResult<ConfigStore> {
1029 let cli_args = self.cli_config.as_deref().unwrap_or_default();
1030 self.config_loader().load_cli_args_layer(cli_args)
1031 }
1032
1033 pub(crate) fn config_loader(&self) -> ConfigLoader<'_> {
1034 ConfigLoader::new(&self.shell, &self.cwd, self.cargo_home.as_path_unlocked())
1035 .search_stop_path(self.search_stop_path.as_deref())
1036 }
1037
1038 pub fn get_registry_index(&self, registry: &str) -> CargoResult<Url> {
1040 RegistryName::new(registry)?;
1041 if let Some(index) = self.get_string(["registries", registry, "index"])? {
1042 self.resolve_registry_index(&index).with_context(|| {
1043 format!(
1044 "invalid index URL for registry `{}` defined in {}",
1045 registry, index.definition
1046 )
1047 })
1048 } else {
1049 bail!(
1050 "registry index was not found in any configuration: `{}`",
1051 registry
1052 );
1053 }
1054 }
1055
1056 pub fn check_registry_index_not_set(&self) -> CargoResult<()> {
1058 if self.get_string(["registry", "index"])?.is_some() {
1059 bail!(
1060 "the `registry.index` config value is no longer supported\n\
1061 Use `[source]` replacement to alter the default index for crates.io."
1062 );
1063 }
1064 Ok(())
1065 }
1066
1067 fn resolve_registry_index(&self, index: &Value<String>) -> CargoResult<Url> {
1068 let base = index
1070 .definition
1071 .root(self.cwd())
1072 .join("truncated-by-url_with_base");
1073 let _parsed = index.val.into_url()?;
1075 let url = index.val.into_url_with_base(Some(&*base))?;
1076 if url.password().is_some() {
1077 bail!("registry URLs may not contain passwords");
1078 }
1079 Ok(url)
1080 }
1081
1082 fn credentials_config(&self) -> CargoResult<&ConfigStore> {
1084 self.credentials_config
1085 .try_borrow_with(|| self.config_loader().load_credentials())
1086 }
1087
1088 fn maybe_get_tool(
1091 &self,
1092 tool: &str,
1093 from_config: &Option<ConfigRootRelativeProgramPath>,
1094 ) -> Option<PathBuf> {
1095 let var = tool.to_uppercase();
1096
1097 match self.get_env_os(&var).as_ref().and_then(|s| s.to_str()) {
1098 Some(tool_path) => {
1099 let maybe_relative = tool_path.contains('/') || tool_path.contains('\\');
1100 let path = if maybe_relative {
1101 self.cwd.join(tool_path)
1102 } else {
1103 PathBuf::from(tool_path)
1104 };
1105 Some(path)
1106 }
1107
1108 None => from_config.as_ref().map(|p| p.resolve(self.cwd())),
1109 }
1110 }
1111
1112 fn get_tool(&self, tool: Tool, from_config: &Option<ConfigRootRelativeProgramPath>) -> PathBuf {
1123 let tool_str = tool.as_str();
1124 self.maybe_get_tool(tool_str, from_config)
1125 .or_else(|| {
1126 let toolchain = self.get_env_os("RUSTUP_TOOLCHAIN")?;
1140 let toolchain = toolchain.to_str()?;
1143 let toolchain_path = Path::new(toolchain);
1144 let toolchain_dir = if toolchain_path.is_absolute() {
1145 toolchain_path.to_path_buf()
1146 } else if !toolchain.contains(&['/', '\\']) {
1147 home::rustup_home().ok()?.join("toolchains").join(toolchain)
1148 } else {
1149 return None;
1150 };
1151 let tool_resolved = paths::resolve_executable(Path::new(tool_str)).ok()?;
1154 let rustup_resolved = paths::resolve_executable(Path::new("rustup")).ok()?;
1155 let tool_meta = tool_resolved.metadata().ok()?;
1156 let rustup_meta = rustup_resolved.metadata().ok()?;
1157 if tool_meta.len() != rustup_meta.len() {
1162 return None;
1163 }
1164 let tool_exe = Path::new(tool_str).with_extension(env::consts::EXE_EXTENSION);
1166 let toolchain_exe = toolchain_dir.join("bin").join(&tool_exe);
1167 toolchain_exe.exists().then_some(toolchain_exe)
1168 })
1169 .unwrap_or_else(|| PathBuf::from(tool_str))
1170 }
1171
1172 pub fn paths_overrides(&self) -> CargoResult<OptValue<Vec<(String, Definition)>>> {
1174 let key = ConfigKey::from_parts(["paths"]);
1175 match self.config()?.get_cv(&key)? {
1177 Some(CV::List(val, definition)) => {
1178 let val = val
1179 .into_iter()
1180 .map(|cv| match cv {
1181 CV::String(s, def) => Ok((s, def)),
1182 other => crate::config::expected("string", &key, &other),
1183 })
1184 .collect::<CargoResult<Vec<_>>>()?;
1185 Ok(Some(Value { val, definition }))
1186 }
1187 Some(val) => crate::config::expected("list", &key, &val),
1188 None => Ok(None),
1189 }
1190 }
1191
1192 pub fn jobserver_from_env(&self) -> Option<&jobserver::Client> {
1193 self.jobserver
1194 }
1195
1196 pub fn http(&self) -> CargoResult<&Mutex<Easy>> {
1197 let http = self
1198 .easy
1199 .try_borrow_with(|| http_handle(self).map(Into::into))?;
1200 {
1201 let mut http = http.lock().unwrap();
1202 http.reset();
1203 let timeout = configure_http_handle(self, &mut http)?;
1204 timeout.configure(&mut http)?;
1205 }
1206 Ok(http)
1207 }
1208
1209 pub fn http_async(&self) -> CargoResult<&http_async::Client> {
1210 self.http_async.try_borrow_with(|| {
1211 let handle_config = HandleConfiguration::new(&self)?;
1212 Ok(http_async::Client::new(handle_config))
1213 })
1214 }
1215
1216 pub fn http_config(&self) -> CargoResult<&CargoHttpConfig> {
1217 self.http_config.try_borrow_with(|| {
1218 let mut http = self.get::<CargoHttpConfig>(["http"])?;
1219 let curl_v = curl::Version::get();
1220 disables_multiplexing_for_bad_curl(curl_v.version(), &mut http, self);
1221 Ok(http)
1222 })
1223 }
1224
1225 pub fn future_incompat_config(&self) -> CargoResult<&CargoFutureIncompatConfig> {
1226 self.future_incompat_config
1227 .try_borrow_with(|| self.get::<CargoFutureIncompatConfig>(["future-incompat-report"]))
1228 }
1229
1230 pub fn net_config(&self) -> CargoResult<&CargoNetConfig> {
1231 self.net_config
1232 .try_borrow_with(|| self.get::<CargoNetConfig>(["net"]))
1233 }
1234
1235 pub fn build_config(&self) -> CargoResult<&CargoBuildConfig> {
1236 self.build_config
1237 .try_borrow_with(|| self.get::<CargoBuildConfig>(["build"]))
1238 }
1239
1240 pub fn progress_config(&self) -> &ProgressConfig {
1241 &self.progress_config
1242 }
1243
1244 pub fn env_config(&self) -> CargoResult<&Arc<HashMap<String, OsString>>> {
1247 let env_config = self.env_config.try_borrow_with(|| {
1248 CargoResult::Ok(Arc::new({
1249 let env_config = self.get::<EnvConfig>(["env"])?;
1250 for disallowed in &["CARGO_HOME", "RUSTUP_HOME", "RUSTUP_TOOLCHAIN"] {
1266 if env_config.contains_key(*disallowed) {
1267 bail!(
1268 "setting the `{disallowed}` environment variable is not supported \
1269 in the `[env]` configuration table"
1270 );
1271 }
1272 }
1273 env_config
1274 .into_iter()
1275 .filter_map(|(k, v)| {
1276 if v.is_force() || self.get_env_os(&k).is_none() {
1277 Some((k, v.resolve(self.cwd()).to_os_string()))
1278 } else {
1279 None
1280 }
1281 })
1282 .collect()
1283 }))
1284 })?;
1285
1286 Ok(env_config)
1287 }
1288
1289 pub fn validate_term_config(&self) -> CargoResult<()> {
1295 drop(self.get::<TermConfig>(["term"])?);
1296 Ok(())
1297 }
1298
1299 pub fn target_cfgs(&self) -> CargoResult<&Vec<(String, TargetCfgConfig)>> {
1303 self.target_cfgs
1304 .try_borrow_with(|| target::load_target_cfgs(self))
1305 }
1306
1307 pub fn doc_extern_map(&self) -> CargoResult<&RustdocExternMap> {
1308 self.doc_extern_map
1312 .try_borrow_with(|| self.get::<RustdocExternMap>(["doc", "extern-map"]))
1313 }
1314
1315 pub fn target_applies_to_host(&self) -> CargoResult<bool> {
1317 target::get_target_applies_to_host(self)
1318 }
1319
1320 pub fn host_cfg_tuple(&self, target: &str) -> CargoResult<TargetConfig> {
1322 target::load_host_tuple(self, target)
1323 }
1324
1325 pub fn target_cfg_tuple(&self, target: &str) -> CargoResult<TargetConfig> {
1327 target::load_target_tuple(self, target)
1328 }
1329
1330 pub fn crates_io_source_id(&self) -> CargoResult<SourceId> {
1335 let source_id = self.crates_io_source_id.try_borrow_with(|| {
1336 self.check_registry_index_not_set()?;
1337 let url = CRATES_IO_INDEX.into_url().unwrap();
1338 SourceId::for_alt_registry(&url, CRATES_IO_REGISTRY)
1339 })?;
1340 Ok(*source_id)
1341 }
1342
1343 pub fn invocation_instant(&self) -> Instant {
1344 self.invocation_instant
1345 }
1346
1347 pub fn invocation_time(&self) -> jiff::Timestamp {
1353 self.invocation_time
1354 }
1355
1356 pub fn get<'de, T: serde::de::Deserialize<'de>>(
1371 &self,
1372
1373 key: impl IntoIterator<Item = impl AsRef<str>>,
1374 ) -> CargoResult<T> {
1375 self.config_reader()?.get(ConfigKey::from_parts(key))
1376 }
1377
1378 #[track_caller]
1384 #[tracing::instrument(skip_all)]
1385 pub fn assert_package_cache_locked<'a>(
1386 &self,
1387 mode: CacheLockMode,
1388 f: &'a Filesystem,
1389 ) -> &'a Path {
1390 let ret = f.as_path_unlocked();
1391 assert!(
1392 self.package_cache_lock.is_locked(mode),
1393 "package cache lock is not currently held, Cargo forgot to call \
1394 `acquire_package_cache_lock` before we got to this stack frame",
1395 );
1396 assert!(ret.starts_with(self.cargo_home.as_path_unlocked()));
1397 ret
1398 }
1399
1400 #[tracing::instrument(skip_all)]
1406 pub fn acquire_package_cache_lock(&self, mode: CacheLockMode) -> CargoResult<CacheLock<'_>> {
1407 self.package_cache_lock.lock(self, mode)
1408 }
1409
1410 #[tracing::instrument(skip_all)]
1416 pub fn try_acquire_package_cache_lock(
1417 &self,
1418 mode: CacheLockMode,
1419 ) -> CargoResult<Option<CacheLock<'_>>> {
1420 self.package_cache_lock.try_lock(self, mode)
1421 }
1422
1423 pub fn global_cache_tracker(&self) -> CargoResult<MutexGuard<'_, GlobalCacheTracker>> {
1428 let tracker = self.global_cache_tracker.try_borrow_with(|| {
1429 Ok::<_, anyhow::Error>(Mutex::new(GlobalCacheTracker::new(self)?))
1430 })?;
1431 Ok(tracker.lock().unwrap())
1432 }
1433
1434 pub fn deferred_global_last_use(&self) -> CargoResult<MutexGuard<'_, DeferredGlobalLastUse>> {
1436 let deferred = self
1437 .deferred_global_last_use
1438 .try_borrow_with(|| Ok::<_, anyhow::Error>(Mutex::new(DeferredGlobalLastUse::new())))?;
1439 Ok(deferred.lock().unwrap())
1440 }
1441
1442 pub fn warning_handling(&self) -> CargoResult<WarningHandling> {
1444 Ok(self.build_config()?.warnings.unwrap_or_default())
1445 }
1446
1447 pub fn ws_roots(&self) -> MutexGuard<'_, HashMap<PathBuf, WorkspaceRootConfig>> {
1448 self.ws_roots.lock().unwrap()
1449 }
1450
1451 pub fn version_req_match_mode(&self) -> VersionReqMatchMode {
1457 if self.cli_unstable().prerelease {
1458 VersionReqMatchMode::Prerelease
1459 } else {
1460 VersionReqMatchMode::Default
1461 }
1462 }
1463}
1464
1465fn registry_config_uncached(
1466 gctx: &GlobalContext,
1467 sid: &SourceId,
1468) -> CargoResult<Option<RegistryConfig>> {
1469 tracing::trace!("loading registry config for {}", sid);
1470 if !sid.is_remote_registry() {
1471 bail!(
1472 "{} does not support API commands.\n\
1473 Check for a source-replacement in .cargo/config.",
1474 sid
1475 );
1476 }
1477
1478 if sid.is_crates_io() {
1480 gctx.check_registry_index_not_set()?;
1481 return Ok(gctx
1482 .get::<Option<GlobalRegistryConfig>>(["registry"])?
1483 .map(|c| c.to_registry_config()));
1484 }
1485
1486 let name = registry_name(gctx, sid)?;
1487
1488 if let Some(name) = name.as_deref() {
1493 if Some(name) != sid.alt_registry_key() {
1494 gctx.shell().note(format!(
1495 "name of alternative registry `{}` set to `{name}`",
1496 sid.url()
1497 ))?
1498 }
1499 }
1500
1501 if let Some(name) = &name {
1502 tracing::debug!("found alternative registry name `{name}` for {sid}");
1503 gctx.get::<Option<RegistryConfig>>(["registries", name.as_str()])
1504 } else {
1505 tracing::debug!("no registry name found for {sid}");
1506 Ok(None)
1507 }
1508}
1509
1510fn registry_name(gctx: &GlobalContext, sid: &SourceId) -> CargoResult<Option<String>> {
1511 let name = {
1524 let index = sid.canonical_url();
1526 let mut names: Vec<_> = gctx
1527 .env()
1528 .filter_map(|(k, v)| {
1529 Some((
1530 k.strip_prefix("CARGO_REGISTRIES_")?
1531 .strip_suffix("_INDEX")?,
1532 v,
1533 ))
1534 })
1535 .filter_map(|(k, v)| Some((k, CanonicalUrl::new(&v.into_url().ok()?).ok()?)))
1536 .filter(|(_, v)| v == index)
1537 .map(|(k, _)| k.to_lowercase())
1538 .collect();
1539
1540 if names.len() == 0 {
1542 if let Some(registries) = gctx.config()?.values().get("registries") {
1543 let (registries, _) = registries.table("registries")?;
1544 for (name, value) in registries {
1545 if let Some(v) = value.table(&format!("registries.{name}"))?.0.get("index") {
1546 let (v, _) = v.string(&format!("registries.{name}.index"))?;
1547 if index == &CanonicalUrl::new(&v.into_url()?)? {
1548 names.push(name.clone());
1549 }
1550 }
1551 }
1552 }
1553 }
1554 names.sort();
1555 match names.len() {
1556 0 => None,
1557 1 => Some(std::mem::take(&mut names[0])),
1558 _ => anyhow::bail!(
1559 "multiple registries are configured with the same index url '{}': {}",
1560 &sid.as_url(),
1561 names.join(", ")
1562 ),
1563 }
1564 };
1565
1566 Ok(name)
1567}
1568
1569pub fn cargo_home(cwd: &Path) -> CargoResult<PathBuf> {
1570 let cargo_home = ::home::cargo_home_with_cwd(cwd).map_err(|_| {
1571 anyhow!(
1572 "Cargo couldn't find your home directory. \
1573 This probably means that $HOME was not set."
1574 )
1575 })?;
1576 Ok(paths::normalize_path(&cargo_home))
1580}
1581
1582pub fn save_credentials(
1583 gctx: &GlobalContext,
1584 token: Option<RegistryCredentialConfig>,
1585 registry: &SourceId,
1586) -> CargoResult<()> {
1587 let registry = if registry.is_crates_io() {
1588 None
1589 } else {
1590 let name = registry
1591 .alt_registry_key()
1592 .ok_or_else(|| internal("can't save credentials for anonymous registry"))?;
1593 Some(name)
1594 };
1595
1596 let cargo_home = gctx.cargo_home.clone().into_path_unlocked();
1600 let filename = match gctx
1601 .config_loader()
1602 .get_file_path(&cargo_home, "credentials", false)?
1603 {
1604 Some(path) => match path.file_name() {
1605 Some(filename) => Path::new(filename).to_owned(),
1606 None => Path::new("credentials.toml").to_owned(),
1607 },
1608 None => Path::new("credentials.toml").to_owned(),
1609 };
1610
1611 let mut file = {
1612 gctx.cargo_home.create_dir()?;
1613 gctx.cargo_home
1614 .open_rw_exclusive_create(filename, gctx, "credentials' config file")?
1615 };
1616
1617 let mut contents = String::new();
1618 file.read_to_string(&mut contents).with_context(|| {
1619 format!(
1620 "failed to read configuration file `{}`",
1621 file.path().display()
1622 )
1623 })?;
1624
1625 let mut toml = contents.parse::<toml::Table>()?;
1626
1627 if let Some(token) = toml.remove("token") {
1629 #[expect(
1630 clippy::disallowed_types,
1631 reason = "need stdlib's HashMap because of TOML compatibility"
1632 )]
1633 let map = std::collections::HashMap::from([("token".to_string(), token)]);
1634 toml.insert("registry".into(), map.into());
1635 }
1636
1637 if let Some(token) = token {
1638 let path_def = Definition::path(file.path().to_path_buf());
1641 let (key, mut value) = match token {
1642 RegistryCredentialConfig::Token(token) => {
1643 let key = "token".to_string();
1646 let value = ConfigValue::String(token.expose(), path_def.clone());
1647 let map = HashMap::from_iter([(key, value)]);
1648 let table = CV::Table(map, path_def.clone());
1649
1650 if let Some(registry) = registry {
1651 let map = HashMap::from_iter([(registry.to_string(), table)]);
1652 ("registries".into(), CV::Table(map, path_def.clone()))
1653 } else {
1654 ("registry".into(), table)
1655 }
1656 }
1657 _ => unreachable!(),
1658 };
1659
1660 if registry.is_some() {
1661 if let Some(table) = toml.remove("registries") {
1662 let v = CV::from_toml(path_def, table)?;
1663 value.merge(v)?;
1664 }
1665 }
1666 toml.insert(key, value.into_toml());
1667 } else {
1668 if let Some(registry) = registry {
1670 if let Some(registries) = toml.get_mut("registries") {
1671 if let Some(reg) = registries.get_mut(registry) {
1672 let rtable = reg.as_table_mut().ok_or_else(|| {
1673 format_err!("expected `[registries.{}]` to be a table", registry)
1674 })?;
1675 rtable.remove("token");
1676 }
1677 }
1678 } else if let Some(registry) = toml.get_mut("registry") {
1679 let reg_table = registry
1680 .as_table_mut()
1681 .ok_or_else(|| format_err!("expected `[registry]` to be a table"))?;
1682 reg_table.remove("token");
1683 }
1684 }
1685
1686 let contents = toml.to_string();
1687 file.seek(SeekFrom::Start(0))?;
1688 file.write_all(contents.as_bytes())
1689 .with_context(|| format!("failed to write to `{}`", file.path().display()))?;
1690 file.file().set_len(contents.len() as u64)?;
1691 set_permissions(file.file(), 0o600)
1692 .with_context(|| format!("failed to set permissions of `{}`", file.path().display()))?;
1693
1694 return Ok(());
1695
1696 #[cfg(unix)]
1697 fn set_permissions(file: &File, mode: u32) -> CargoResult<()> {
1698 use std::os::unix::fs::PermissionsExt;
1699
1700 let mut perms = file.metadata()?.permissions();
1701 perms.set_mode(mode);
1702 file.set_permissions(perms)?;
1703 Ok(())
1704 }
1705
1706 #[cfg(not(unix))]
1707 fn set_permissions(_file: &File, _mode: u32) -> CargoResult<()> {
1708 Ok(())
1709 }
1710}
1711
1712#[macro_export]
1713macro_rules! __shell_print {
1714 ($config:expr, $which:ident, $newline:literal, $($arg:tt)*) => ({
1715 let mut shell = $config.shell();
1716 let out = shell.$which();
1717 drop(out.write_fmt(format_args!($($arg)*)));
1718 if $newline {
1719 drop(out.write_all(b"\n"));
1720 }
1721 });
1722}
1723
1724#[macro_export]
1725macro_rules! drop_println {
1726 ($config:expr) => ( $crate::drop_print!($config, "\n") );
1727 ($config:expr, $($arg:tt)*) => (
1728 $crate::__shell_print!($config, out, true, $($arg)*)
1729 );
1730}
1731
1732#[macro_export]
1733macro_rules! drop_eprintln {
1734 ($config:expr) => ( $crate::drop_eprint!($config, "\n") );
1735 ($config:expr, $($arg:tt)*) => (
1736 $crate::__shell_print!($config, err, true, $($arg)*)
1737 );
1738}
1739
1740#[macro_export]
1741macro_rules! drop_print {
1742 ($config:expr, $($arg:tt)*) => (
1743 $crate::__shell_print!($config, out, false, $($arg)*)
1744 );
1745}
1746
1747#[macro_export]
1748macro_rules! drop_eprint {
1749 ($config:expr, $($arg:tt)*) => (
1750 $crate::__shell_print!($config, err, false, $($arg)*)
1751 );
1752}
1753
1754enum Tool {
1755 Rustc,
1756 Rustdoc,
1757}
1758
1759impl Tool {
1760 fn as_str(&self) -> &str {
1761 match self {
1762 Tool::Rustc => "rustc",
1763 Tool::Rustdoc => "rustdoc",
1764 }
1765 }
1766}
1767
1768fn disables_multiplexing_for_bad_curl(
1778 curl_version: &str,
1779 http: &mut CargoHttpConfig,
1780 gctx: &GlobalContext,
1781) {
1782 use crate::util::network;
1783
1784 if network::proxy::http_proxy_exists(http, gctx) && http.multiplexing.is_none() {
1785 let bad_curl_versions = ["7.87.0", "7.88.0", "7.88.1"];
1786 if bad_curl_versions
1787 .iter()
1788 .any(|v| curl_version.starts_with(v))
1789 {
1790 tracing::info!("disabling multiplexing with proxy, curl version is {curl_version}");
1791 http.multiplexing = Some(false);
1792 }
1793 }
1794}
1795
1796#[cfg(test)]
1797mod tests {
1798 use super::CargoHttpConfig;
1799 use super::GlobalContext;
1800 use super::Shell;
1801 use super::disables_multiplexing_for_bad_curl;
1802
1803 #[test]
1804 fn disables_multiplexing() {
1805 let mut gctx = GlobalContext::new(Shell::new(), "".into(), "".into());
1806 gctx.set_search_stop_path(std::path::PathBuf::new());
1807 gctx.set_env(Default::default());
1808
1809 let mut http = CargoHttpConfig::default();
1810 http.proxy = Some("127.0.0.1:3128".into());
1811 disables_multiplexing_for_bad_curl("7.88.1", &mut http, &gctx);
1812 assert_eq!(http.multiplexing, Some(false));
1813
1814 let cases = [
1815 (None, None, "7.87.0", None),
1816 (None, None, "7.88.0", None),
1817 (None, None, "7.88.1", None),
1818 (None, None, "8.0.0", None),
1819 (Some("".into()), None, "7.87.0", Some(false)),
1820 (Some("".into()), None, "7.88.0", Some(false)),
1821 (Some("".into()), None, "7.88.1", Some(false)),
1822 (Some("".into()), None, "8.0.0", None),
1823 (Some("".into()), Some(false), "7.87.0", Some(false)),
1824 (Some("".into()), Some(false), "7.88.0", Some(false)),
1825 (Some("".into()), Some(false), "7.88.1", Some(false)),
1826 (Some("".into()), Some(false), "8.0.0", Some(false)),
1827 ];
1828
1829 for (proxy, multiplexing, curl_v, result) in cases {
1830 let mut http = CargoHttpConfig {
1831 multiplexing,
1832 proxy,
1833 ..Default::default()
1834 };
1835 disables_multiplexing_for_bad_curl(curl_v, &mut http, &gctx);
1836 assert_eq!(http.multiplexing, result);
1837 }
1838 }
1839
1840 #[test]
1841 fn sync_context() {
1842 fn assert_sync<S: Sync>() {}
1843 assert_sync::<GlobalContext>();
1844 }
1845}