1use 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
134macro_rules! get_value_typed {
136 ($name:ident, $ty:ty, $variant:ident, $expected:expr) => {
137 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#[derive(Debug)]
183pub struct CredentialCacheValue {
184 pub token_value: Secret<String>,
185 pub expiration: Option<OffsetDateTime>,
186 pub operation_independent: bool,
187}
188
189#[derive(Debug)]
192pub struct GlobalContext {
193 home_path: Filesystem,
195 shell: Mutex<Shell>,
197 config: OnceLock<ConfigStore>,
199 credentials_config: OnceLock<ConfigStore>,
201 cli_config: Option<Vec<String>>,
203 cwd: PathBuf,
205 search_stop_path: Option<PathBuf>,
207 cargo_exe: OnceLock<PathBuf>,
209 rustdoc: OnceLock<PathBuf>,
211 extra_verbose: bool,
213 frozen: bool,
216 locked: bool,
219 offline: bool,
222 jobserver: Option<&'static jobserver::Client>,
224 unstable_flags: CliUnstable,
226 unstable_flags_cli: Option<Vec<String>>,
228 easy: OnceLock<Mutex<Easy>>,
230 crates_io_source_id: OnceLock<SourceId>,
232 cache_rustc_info: bool,
234 invocation_instant: Instant,
236 invocation_time: jiff::Timestamp,
240 target_dir: Option<Filesystem>,
242 env: Env,
244 updated_sources: Mutex<HashSet<SourceId>>,
246 credential_cache: Mutex<HashMap<CanonicalUrl, CredentialCacheValue>>,
249 registry_config: Mutex<HashMap<SourceId, Option<RegistryConfig>>>,
251 package_cache_lock: CacheLocker,
253 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 pub nightly_features_allowed: bool,
279 ws_roots: Mutex<HashMap<PathBuf, WorkspaceRootConfig>>,
281 global_cache_tracker: OnceLock<Mutex<GlobalCacheTracker>>,
283 deferred_global_last_use: OnceLock<Mutex<DeferredGlobalLastUse>>,
286}
287
288impl GlobalContext {
289 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 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 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 pub fn home(&self) -> &Filesystem {
418 &self.home_path
419 }
420
421 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 pub fn git_path(&self) -> Filesystem {
435 self.home_path.join("git")
436 }
437
438 pub fn git_checkouts_path(&self) -> Filesystem {
441 self.git_path().join("checkouts")
442 }
443
444 pub fn git_db_path(&self) -> Filesystem {
447 self.git_path().join("db")
448 }
449
450 pub fn registry_base_path(&self) -> Filesystem {
452 self.home_path.join("registry")
453 }
454
455 pub fn registry_index_path(&self) -> Filesystem {
457 self.registry_base_path().join("index")
458 }
459
460 pub fn registry_cache_path(&self) -> Filesystem {
462 self.registry_base_path().join("cache")
463 }
464
465 pub fn registry_source_path(&self) -> Filesystem {
467 self.registry_base_path().join("src")
468 }
469
470 pub fn default_registry(&self) -> CargoResult<Option<String>> {
472 Ok(self
473 .get_string(["registry", "default"])?
474 .map(|registry| registry.val))
475 }
476
477 pub fn shell(&self) -> MutexGuard<'_, Shell> {
479 self.shell.lock().unwrap()
480 }
481
482 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 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 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 pub fn cargo_exe(&self) -> CargoResult<&Path> {
534 self.cargo_exe
535 .try_borrow_with(|| {
536 let from_env = || -> CargoResult<PathBuf> {
537 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 let exe = env::current_exe()?;
554 Ok(exe)
555 }
556
557 fn from_argv() -> CargoResult<PathBuf> {
558 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 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 pub fn updated_sources(&self) -> MutexGuard<'_, HashSet<SourceId>> {
598 self.updated_sources.lock().unwrap()
599 }
600
601 pub fn credential_cache(&self) -> MutexGuard<'_, HashMap<CanonicalUrl, CredentialCacheValue>> {
603 self.credential_cache.lock().unwrap()
604 }
605
606 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 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 pub fn config(&self) -> CargoResult<&ConfigStore> {
676 self.config.try_borrow_with(|| self.load_config())
677 }
678
679 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 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 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 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 pub fn cwd(&self) -> &Path {
729 &self.cwd
730 }
731
732 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 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 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 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 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 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 pub(crate) fn get_cv_with_env(&self, key: &ConfigKey) -> CargoResult<Option<CV>> {
858 let cv = self.config()?.get_cv(key)?;
861 if key.is_root() {
862 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 (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 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 self.get_env_list(key, &mut cv_list)?;
894 Ok(Some(CV::List(cv_list, cv_def)))
895 }
896 Some(cv) => {
897 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 match cv {
918 Some(CV::List(mut cv_list, cv_def)) => {
919 self.get_env_list(key, &mut cv_list)?;
921 Ok(Some(CV::List(cv_list, cv_def)))
922 }
923 _ => {
924 Ok(Some(CV::String(env.to_string(), env_def)))
929 }
930 }
931 }
932 }
933
934 pub fn set_env(&mut self, env: HashMap<String, String>) {
936 self.env = Env::from_map(env);
937 }
938
939 pub(crate) fn env(&self) -> impl Iterator<Item = (&str, &str)> {
942 self.env.iter_str()
943 }
944
945 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 pub fn get_env(&self, key: impl AsRef<OsStr>) -> CargoResult<&str> {
977 self.env.get_env(key)
978 }
979
980 pub fn get_env_os(&self, key: impl AsRef<OsStr>) -> Option<&OsStr> {
985 self.env.get_env_os(key)
986 }
987
988 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 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 PathBuf::from(value)
1036 }
1037 }
1038
1039 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 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 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 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 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 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 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 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 let term = self.get::<TermConfig>(["term"]).unwrap_or_default();
1158
1159 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 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 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 pub fn load_config(&self) -> CargoResult<ConfigStore> {
1267 self.load_config_from(&self.cwd)
1268 }
1269
1270 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 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 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 fn load_file(&self, path: &Path) -> CargoResult<ConfigStore> {
1338 self._load_file(path, &mut HashSet::default(), true, DefinitionKind::Path)
1339 }
1340
1341 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 fn load_includes(
1379 &self,
1380 mut config: ConfigStore,
1381 seen: &mut HashSet<PathBuf>,
1382 definition_kind: DefinitionKind,
1383 ) -> CargoResult<ConfigStore> {
1384 let includes = self.include_paths(&mut config, true)?;
1386
1387 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 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 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 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 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 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 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 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 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 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 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 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 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 let base = index
1679 .definition
1680 .root(self.cwd())
1681 .join("truncated-by-url_with_base");
1682 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 fn credentials_config(&self) -> CargoResult<&ConfigStore> {
1693 self.credentials_config
1694 .try_borrow_with(|| self.load_credentials())
1695 }
1696
1697 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 {
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 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 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 let toolchain = self.get_env_os("RUSTUP_TOOLCHAIN")?;
1773 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 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 if tool_meta.len() != rustup_meta.len() {
1795 return None;
1796 }
1797 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 pub fn paths_overrides(&self) -> CargoResult<OptValue<Vec<(String, Definition)>>> {
1807 let key = ConfigKey::from_parts(["paths"]);
1808 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 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 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 pub fn validate_term_config(&self) -> CargoResult<()> {
1928 drop(self.get::<TermConfig>(["term"])?);
1929 Ok(())
1930 }
1931
1932 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 self.doc_extern_map
1945 .try_borrow_with(|| self.get::<RustdocExternMap>(["doc", "extern-map"]))
1946 }
1947
1948 pub fn target_applies_to_host(&self) -> CargoResult<bool> {
1950 target::get_target_applies_to_host(self)
1951 }
1952
1953 pub fn host_cfg_tuple(&self, target: &str) -> CargoResult<TargetConfig> {
1955 target::load_host_tuple(self, target)
1956 }
1957
1958 pub fn target_cfg_tuple(&self, target: &str) -> CargoResult<TargetConfig> {
1960 target::load_target_tuple(self, target)
1961 }
1962
1963 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 pub fn invocation_time(&self) -> jiff::Timestamp {
1986 self.invocation_time
1987 }
1988
1989 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 #[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 #[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 #[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 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 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 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 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 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 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 let name = {
2162 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 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 .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 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 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 let path_def = Definition::Path(file.path().to_path_buf());
2272 let (key, mut value) = match token {
2273 RegistryCredentialConfig::Token(token) => {
2274 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 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
2343struct ConfigInclude {
2349 path: PathBuf,
2352 def: Definition,
2353 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 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 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#[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
2557fn 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}