1use std::collections::BTreeSet;
122use std::env;
123use std::fmt::{self, Write};
124use std::path::PathBuf;
125use std::str::FromStr;
126
127use anyhow::{Error, bail};
128use cargo_util::ProcessBuilder;
129use serde::{Deserialize, Serialize};
130use tracing::debug;
131
132use crate::GlobalContext;
133use crate::resolver::ResolveBehavior;
134use crate::util::errors::CargoResult;
135use crate::util::indented_lines;
136
137pub const SEE_CHANNELS: &str = "See https://doc.rust-lang.org/book/appendix-07-nightly-rust.html for more information \
138 about Rust release channels.";
139
140pub type AllowFeatures = BTreeSet<String>;
142
143#[derive(
181 Default, Clone, Copy, Debug, Hash, PartialOrd, Ord, Eq, PartialEq, Serialize, Deserialize,
182)]
183pub enum Edition {
184 #[default]
186 Edition2015,
187 Edition2018,
189 Edition2021,
191 Edition2024,
193 EditionFuture,
195}
196
197impl Edition {
198 pub const LATEST_UNSTABLE: Option<Edition> = None;
205 pub const LATEST_STABLE: Edition = Edition::Edition2024;
207 pub const ALL: &'static [Edition] = &[
208 Self::Edition2015,
209 Self::Edition2018,
210 Self::Edition2021,
211 Self::Edition2024,
212 Self::EditionFuture,
213 ];
214 pub const CLI_VALUES: [&'static str; 4] = ["2015", "2018", "2021", "2024"];
222
223 pub(crate) fn first_version(&self) -> Option<semver::Version> {
226 use Edition::*;
227 match self {
228 Edition2015 => None,
229 Edition2018 => Some(semver::Version::new(1, 31, 0)),
230 Edition2021 => Some(semver::Version::new(1, 56, 0)),
231 Edition2024 => Some(semver::Version::new(1, 85, 0)),
232 EditionFuture => None,
233 }
234 }
235
236 pub fn is_stable(&self) -> bool {
238 use Edition::*;
239 match self {
240 Edition2015 => true,
241 Edition2018 => true,
242 Edition2021 => true,
243 Edition2024 => true,
244 EditionFuture => false,
245 }
246 }
247
248 pub fn previous(&self) -> Option<Edition> {
252 use Edition::*;
253 match self {
254 Edition2015 => None,
255 Edition2018 => Some(Edition2015),
256 Edition2021 => Some(Edition2018),
257 Edition2024 => Some(Edition2021),
258 EditionFuture => panic!("future does not have a previous edition"),
259 }
260 }
261
262 pub fn saturating_next(&self) -> Edition {
265 use Edition::*;
266 match self {
268 Edition2015 => Edition2018,
269 Edition2018 => Edition2021,
270 Edition2021 => Edition2024,
271 Edition2024 => Edition2024,
272 EditionFuture => EditionFuture,
273 }
274 }
275
276 pub(crate) fn cmd_edition_arg(&self, cmd: &mut ProcessBuilder) {
279 cmd.arg(format!("--edition={}", self));
280 if !self.is_stable() {
281 cmd.arg("-Z").arg("unstable-options");
282 }
283 }
284
285 pub(crate) fn force_warn_arg(&self, cmd: &mut ProcessBuilder) {
287 use Edition::*;
288 match self {
289 Edition2015 => {}
290 EditionFuture => {
291 cmd.arg("--force-warn=edition_future_compatibility");
292 }
293 e => {
294 cmd.arg(format!("--force-warn=rust-{e}-compatibility"));
301 }
302 }
303 }
304
305 pub(crate) fn supports_idiom_lint(&self) -> bool {
309 use Edition::*;
310 match self {
311 Edition2015 => false,
312 Edition2018 => true,
313 Edition2021 => false,
314 Edition2024 => false,
315 EditionFuture => false,
316 }
317 }
318
319 pub(crate) fn default_resolve_behavior(&self) -> ResolveBehavior {
320 if *self >= Edition::Edition2024 {
321 ResolveBehavior::V3
322 } else if *self >= Edition::Edition2021 {
323 ResolveBehavior::V2
324 } else {
325 ResolveBehavior::V1
326 }
327 }
328}
329
330impl fmt::Display for Edition {
331 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
332 match *self {
333 Edition::Edition2015 => f.write_str("2015"),
334 Edition::Edition2018 => f.write_str("2018"),
335 Edition::Edition2021 => f.write_str("2021"),
336 Edition::Edition2024 => f.write_str("2024"),
337 Edition::EditionFuture => f.write_str("future"),
338 }
339 }
340}
341
342impl FromStr for Edition {
343 type Err = Error;
344 fn from_str(s: &str) -> Result<Self, Error> {
345 match s {
346 "2015" => Ok(Edition::Edition2015),
347 "2018" => Ok(Edition::Edition2018),
348 "2021" => Ok(Edition::Edition2021),
349 "2024" => Ok(Edition::Edition2024),
350 "future" => Ok(Edition::EditionFuture),
351 s if s.parse().map_or(false, |y: u16| y > 2024 && y < 2050) => bail!(
352 "this version of Cargo is older than the `{}` edition, \
353 and only supports `2015`, `2018`, `2021`, and `2024` editions.",
354 s
355 ),
356 s => bail!(
357 "supported edition values are `2015`, `2018`, `2021`, or `2024`, \
358 but `{}` is unknown",
359 s
360 ),
361 }
362 }
363}
364
365#[derive(Debug, Deserialize)]
367pub enum FixEdition {
368 Start(Edition),
375 End { initial: Edition, next: Edition },
383}
384
385impl FromStr for FixEdition {
386 type Err = anyhow::Error;
387 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
388 if let Some(start) = s.strip_prefix("start=") {
389 Ok(FixEdition::Start(start.parse()?))
390 } else if let Some(end) = s.strip_prefix("end=") {
391 let (initial, next) = end
392 .split_once(',')
393 .ok_or_else(|| anyhow::format_err!("expected `initial,next`"))?;
394 Ok(FixEdition::End {
395 initial: initial.parse()?,
396 next: next.parse()?,
397 })
398 } else {
399 bail!("invalid `-Zfix-edition, expected start= or end=, got `{s}`");
400 }
401 }
402}
403
404#[derive(Debug, PartialEq)]
405enum Status {
406 Stable,
407 Unstable,
408 Removed,
409}
410
411macro_rules! features {
423 (
424 $(
425 $(#[$attr:meta])*
426 ($stab:ident, $feature:ident, $version:expr, $docs:expr),
427 )*
428 ) => (
429 #[derive(Default, Clone, Debug)]
434 pub struct Features {
435 $($feature: bool,)*
436 activated: Vec<String>,
438 nightly_features_allowed: bool,
440 is_local: bool,
442 }
443
444 impl Feature {
445 $(
446 $(#[$attr])*
447 #[doc = concat!("\n\n\nSee <https://doc.rust-lang.org/nightly/cargo/", $docs, ">.")]
448 pub const fn $feature() -> &'static Feature {
449 fn get(features: &Features) -> bool {
450 stab!($stab) == Status::Stable || features.$feature
451 }
452 const FEAT: Feature = Feature {
453 name: stringify!($feature),
454 stability: stab!($stab),
455 version: $version,
456 docs: $docs,
457 get,
458 };
459 &FEAT
460 }
461 )*
462
463 fn is_enabled(&self, features: &Features) -> bool {
465 (self.get)(features)
466 }
467
468 pub(crate) fn name(&self) -> &str {
469 self.name
470 }
471 }
472
473 impl Features {
474 fn status(&mut self, feature: &str) -> Option<(&mut bool, &'static Feature)> {
475 if feature.contains("_") {
476 return None;
477 }
478 let feature = feature.replace("-", "_");
479 $(
480 if feature == stringify!($feature) {
481 return Some((&mut self.$feature, Feature::$feature()));
482 }
483 )*
484 None
485 }
486 }
487 )
488}
489
490macro_rules! stab {
491 (stable) => {
492 Status::Stable
493 };
494 (unstable) => {
495 Status::Unstable
496 };
497 (removed) => {
498 Status::Removed
499 };
500}
501
502features! {
504 (stable, test_dummy_stable, "1.0", ""),
507
508 (unstable, test_dummy_unstable, "", "reference/unstable.html"),
511
512 (stable, alternative_registries, "1.34", "reference/registries.html"),
514
515 (stable, edition, "1.31", "reference/manifest.html#the-edition-field"),
517
518 (stable, rename_dependency, "1.31", "reference/specifying-dependencies.html#renaming-dependencies-in-cargotoml"),
520
521 (removed, publish_lockfile, "1.37", "reference/unstable.html#publish-lockfile"),
523
524 (stable, profile_overrides, "1.41", "reference/profiles.html#overrides"),
526
527 (stable, default_run, "1.37", "reference/manifest.html#the-default-run-field"),
529
530 (unstable, metabuild, "", "reference/unstable.html#metabuild"),
532
533 (unstable, public_dependency, "", "reference/unstable.html#public-dependency"),
535
536 (stable, named_profiles, "1.57", "reference/profiles.html#custom-profiles"),
538
539 (stable, resolver, "1.51", "reference/resolver.html#resolver-versions"),
541
542 (stable, strip, "1.58", "reference/profiles.html#strip-option"),
544
545 (stable, rust_version, "1.56", "reference/manifest.html#the-rust-version-field"),
547
548 (stable, edition2021, "1.56", "reference/manifest.html#the-edition-field"),
550
551 (unstable, per_package_target, "", "reference/unstable.html#per-package-target"),
553
554 (unstable, codegen_backend, "", "reference/unstable.html#codegen-backend"),
556
557 (unstable, different_binary_name, "", "reference/unstable.html#different-binary-name"),
559
560 (unstable, profile_rustflags, "", "reference/unstable.html#profile-rustflags-option"),
562
563 (stable, workspace_inheritance, "1.64", "reference/unstable.html#workspace-inheritance"),
565
566 (stable, edition2024, "1.85", "reference/manifest.html#the-edition-field"),
568
569 (stable, trim_paths, "1.101", "reference/profiles.html#trim-paths"),
571
572 (unstable, open_namespaces, "", "reference/unstable.html#open-namespaces"),
574
575 (unstable, path_bases, "", "reference/unstable.html#path-bases"),
577
578 (unstable, unstable_editions, "", "reference/unstable.html#unstable-editions"),
580
581 (unstable, multiple_build_scripts, "", "reference/unstable.html#multiple-build-scripts"),
583
584 (unstable, panic_immediate_abort, "", "reference/unstable.html#panic-immediate-abort"),
586
587 (unstable, feature_metadata, "", "reference/unstable.html#feature_metadata"),
589
590 (unstable, builtin_dependencies, "", "reference/unstable.html#builtin-dependencies"),
592}
593
594#[derive(Debug)]
596pub struct Feature {
597 name: &'static str,
599 stability: Status,
600 version: &'static str,
602 docs: &'static str,
604 get: fn(&Features) -> bool,
605}
606
607impl Features {
608 pub fn new(
610 features: &[String],
611 gctx: &GlobalContext,
612 warnings: &mut Vec<String>,
613 is_local: bool,
614 ) -> CargoResult<Features> {
615 let mut ret = Features::default();
616 ret.nightly_features_allowed = gctx.nightly_features_allowed;
617 ret.is_local = is_local;
618 for feature in features {
619 ret.add(feature, gctx, warnings)?;
620 ret.activated.push(feature.to_string());
621 }
622 Ok(ret)
623 }
624
625 fn add(
626 &mut self,
627 feature_name: &str,
628 gctx: &GlobalContext,
629 warnings: &mut Vec<String>,
630 ) -> CargoResult<()> {
631 let nightly_features_allowed = self.nightly_features_allowed;
632 let Some((slot, feature)) = self.status(feature_name) else {
633 let mut msg = format!("unknown Cargo.toml feature `{feature_name}`\n\n");
634 let mut append_see_docs = true;
635
636 if feature_name.contains('_') {
637 let _ = writeln!(msg, "Feature names must use '-' instead of '_'.");
638 append_see_docs = false;
639 } else {
640 let underscore_name = feature_name.replace('-', "_");
641 if CliUnstable::help()
642 .iter()
643 .any(|(option, _)| *option == underscore_name)
644 {
645 let _ = writeln!(
646 msg,
647 "This feature can be enabled via -Z{feature_name} or the `[unstable]` section in config.toml."
648 );
649 }
650 }
651
652 if append_see_docs {
653 let _ = writeln!(
654 msg,
655 "See https://doc.rust-lang.org/nightly/cargo/reference/unstable.html for more information."
656 );
657 }
658 bail!(msg)
659 };
660
661 if *slot {
662 bail!(
663 "the cargo feature `{}` has already been activated",
664 feature_name
665 );
666 }
667
668 let see_docs = || {
669 format!(
670 "See {} for more information about using this feature.",
671 cargo_docs_link(feature.docs)
672 )
673 };
674
675 match feature.stability {
676 Status::Stable => {
677 let warning = format!(
678 "the cargo feature `{}` has been stabilized in the {} \
679 release and is no longer necessary to be listed in the \
680 manifest\n {}",
681 feature_name,
682 feature.version,
683 see_docs()
684 );
685 warnings.push(warning);
686 }
687 Status::Unstable if !nightly_features_allowed => bail!(
688 "the cargo feature `{}` requires a nightly version of \
689 Cargo, but this is the `{}` channel\n\
690 {}\n{}",
691 feature_name,
692 channel(),
693 SEE_CHANNELS,
694 see_docs()
695 ),
696 Status::Unstable => {
697 if let Some(allow) = &gctx.cli_unstable().allow_features {
698 if !allow.contains(feature_name) {
699 bail!(
700 "the feature `{}` is not in the list of allowed features: [{}]",
701 feature_name,
702 itertools::join(allow, ", "),
703 );
704 }
705 }
706 }
707 Status::Removed => {
708 let mut msg = format!(
709 "the cargo feature `{}` has been removed in the {} release\n\n",
710 feature_name, feature.version
711 );
712 if self.is_local {
713 let _ = writeln!(
714 msg,
715 "Remove the feature from Cargo.toml to remove this error."
716 );
717 } else {
718 let _ = writeln!(
719 msg,
720 "This package cannot be used with this version of Cargo, \
721 as the unstable feature `{}` is no longer supported.",
722 feature_name
723 );
724 }
725 let _ = writeln!(msg, "{}", see_docs());
726 bail!(msg);
727 }
728 }
729
730 *slot = true;
731
732 Ok(())
733 }
734
735 pub fn activated(&self) -> &[String] {
737 &self.activated
738 }
739
740 pub fn require(&self, feature: &Feature) -> CargoResult<()> {
742 self.require_with_hint(feature, None)
743 }
744
745 pub(crate) fn require_with_hint(
751 &self,
752 feature: &Feature,
753 hint: Option<&str>,
754 ) -> CargoResult<()> {
755 if feature.is_enabled(self) {
756 return Ok(());
757 }
758 let feature_name = feature.name.replace("_", "-");
759 let mut msg = format!(
760 "feature `{}` is required\n\
761 \n\
762 The package requires the Cargo feature called `{}`, but \
763 that feature is not stabilized in this version of Cargo ({}).\n\
764 ",
765 feature_name,
766 feature_name,
767 crate::version(),
768 );
769
770 if self.nightly_features_allowed {
771 if self.is_local {
772 let _ = writeln!(
773 msg,
774 "Consider adding `cargo-features = [\"{}\"]` \
775 to the top of Cargo.toml (above the [package] table) \
776 to tell Cargo you are opting in to use this unstable feature.",
777 feature_name
778 );
779 } else {
780 let _ = writeln!(msg, "Consider trying a more recent nightly release.");
781 }
782 } else {
783 let _ = writeln!(
784 msg,
785 "Consider trying a newer version of Cargo \
786 (this may require the nightly release)."
787 );
788 }
789 let _ = writeln!(
790 msg,
791 "See https://doc.rust-lang.org/nightly/cargo/{} for more information \
792 about the status of this feature.",
793 feature.docs
794 );
795 if let Some(hint) = hint {
796 let _ = writeln!(msg, "{hint}");
797 }
798
799 bail!("{}", msg);
800 }
801
802 pub fn is_enabled(&self, feature: &Feature) -> bool {
804 feature.is_enabled(self)
805 }
806}
807
808macro_rules! unstable_cli_options {
812 (
813 $(
814 $(#[$meta:meta])?
815 $element: ident: $ty: ty$( = ($help:literal))?,
816 )*
817 ) => {
818 #[derive(Debug, Deserialize)]
824 #[serde(default, rename_all = "kebab-case")]
825 pub struct CliUnstable {
826 $(
827 $(#[doc = $help])?
828 $(#[$meta])?
829 pub $element: $ty
830 ),*
831 }
832 impl CliUnstable {
833 pub fn help() -> Vec<(&'static str, Option<&'static str>)> {
835 let fields = vec![$((stringify!($element), None$(.or(Some($help)))?)),*];
836 fields
837 }
838 }
839 impl Default for CliUnstable {
840 fn default() -> Self {
841 let mut unstable = Self {
842 $(
843 $element: Default::default()
844 ),*
845 };
846
847 unstable.build_dir_new_layout = !is_new_build_dir_layout_opt_out();
848
849 return unstable;
850 }
851 }
852
853 #[cfg(test)]
854 mod test {
855 #[test]
856 fn ensure_sorted() {
857 let location = std::panic::Location::caller();
859 println!(
860 "\nTo fix this test, sort the features inside the macro at {}:{}\n",
861 location.file(),
862 location.line()
863 );
864 let mut expected = vec![$(stringify!($element)),*];
865 expected[3..].sort();
867 let expected = format!("{:#?}", expected);
868 let actual = format!("{:#?}", vec![$(stringify!($element)),*]);
869 snapbox::assert_data_eq!(actual, expected);
870 }
871 }
872 }
873}
874
875unstable_cli_options!(
876 allow_features: Option<AllowFeatures> = ("Allow *only* the listed unstable features"),
878 embed_metadata: Option<bool> = ("Avoid embedding metadata in library artifacts"),
879 print_im_a_teapot: bool,
880
881 advanced_env: bool,
884 any_build_script_metadata: bool = ("Allow any build script to specify env vars via cargo::metadata=key=value"),
885 avoid_dev_deps: bool = ("Avoid installing dev-dependencies if possible"),
886 binary_dep_depinfo: bool = ("Track changes to dependency artifacts"),
887 bindeps: bool = ("Allow Cargo packages to depend on bin, cdylib, and staticlib crates, and use the artifacts built by those crates"),
888 build_analysis: bool = ("Record and persist build metrics across runs, with commands to query past builds."),
889 build_dir_new_layout: bool = ("Use the new build-dir filesystem layout"),
890 #[serde(deserialize_with = "deserialize_comma_separated_list")]
891 build_std: Option<Vec<String>> = ("Enable Cargo to compile the standard library itself as part of a crate graph compilation"),
892 #[serde(deserialize_with = "deserialize_comma_separated_list")]
893 build_std_features: Option<Vec<String>> = ("Configure features enabled for the standard library itself when building the standard library"),
894 checksum_freshness: bool = ("Use a checksum to determine if output is fresh rather than filesystem mtime"),
895 codegen_backend: bool = ("Enable the `codegen-backend` option in profiles in .cargo/config.toml file"),
896 direct_minimal_versions: bool = ("Resolve minimal dependency versions instead of maximum (direct dependencies only)"),
897 dual_proc_macros: bool = ("Build proc-macros for both the host and the target"),
898 feature_unification: bool = ("Enable new feature unification modes in workspaces"),
899 features: Option<Vec<String>>,
900 fine_grain_locking: bool = ("Use fine grain locking instead of locking the entire build cache"),
901 fix_edition: Option<FixEdition> = ("Permanently unstable edition migration helper"),
902 gc: bool = ("Track cache usage and \"garbage collect\" unused files"),
903 #[serde(deserialize_with = "deserialize_git_features")]
904 git: Option<GitFeatures> = ("Enable support for shallow git fetch operations"),
905 #[serde(deserialize_with = "deserialize_gitoxide_features")]
906 gitoxide: Option<GitoxideFeatures> = ("Use gitoxide for the given git interactions, or all of them if no argument is given"),
907 hint_min_opt_level: bool = ("Enable the `hints.min-opt-level` manifest key"),
908 hint_msrv: bool = ("Enable passing `package.rust-version` to rustc for lints"),
909 host_config: bool = ("Enable the `[host]` section in the .cargo/config.toml file"),
910 json_target_spec: bool = ("Enable `.json` target spec files"),
911 mem_stats: bool = ("Report peak memory usage per build unit in --timings output"),
912 minimal_versions: bool = ("Resolve minimal dependency versions instead of maximum"),
913 msrv_policy: bool = ("Enable rust-version aware policy within cargo"),
914 mtime_on_use: bool = ("Configure Cargo to update the mtime of used files"),
915 next_lockfile_bump: bool,
916 no_index_update: bool = ("Do not update the registry index even if the cache is outdated"),
917 panic_abort_tests: bool = ("Enable support to run tests with -Cpanic=abort"),
918 panic_immediate_abort: bool = ("Enable setting `panic = \"immediate-abort\"` in profiles"),
919 prerelease: bool = ("Allow selecting pre-release versions with `update --precise`"),
920 profile_hint_mostly_unused: bool = ("Enable the `hint-mostly-unused` setting in profiles to mark a crate as mostly unused."),
921 profile_rustflags: bool = ("Enable the `rustflags` option in profiles in .cargo/config.toml file"),
922 public_dependency: bool = ("Respect a dependency's `public` field in Cargo.toml to control public/private dependencies"),
923 publish_timeout: bool = ("Enable the `publish.timeout` key in .cargo/config.toml file"),
924 root_dir: Option<PathBuf> = ("Set the root directory relative to which paths are printed (defaults to workspace root)"),
925 rustc_unicode: bool = ("Enable `rustc`'s unicode error format in Cargo's error messages"),
926 rustdoc_depinfo: bool = ("Use dep-info files in rustdoc rebuild detection"),
927 rustdoc_map: bool = ("Allow passing external documentation mappings to rustdoc"),
928 rustdoc_mergeable_info: bool = ("Use rustdoc mergeable cross-crate-info files"),
929 rustdoc_scrape_examples: bool = ("Allows Rustdoc to scrape code examples from reverse-dependencies"),
930 sbom: bool = ("Enable the `sbom` option in build config in .cargo/config.toml file"),
931 script: bool = ("Enable support for single-file, `.rs` packages"),
932 section_timings: bool = ("Enable support for extended compilation sections in --timings output"),
933 separate_nightlies: bool,
934 skip_rustdoc_fingerprint: bool,
935 target_applies_to_host: bool = ("Enable the `target-applies-to-host` key in the .cargo/config.toml file"),
936 unstable_options: bool = ("Allow the usage of unstable options"),
937);
938
939const STABILIZED_COMPILE_PROGRESS: &str = "The progress bar is now always \
940 enabled when used on an interactive console.\n\
941 See https://doc.rust-lang.org/cargo/reference/config.html#termprogresswhen \
942 for information on controlling the progress bar.";
943
944const STABILIZED_OFFLINE: &str = "Offline mode is now available via the \
945 --offline CLI option";
946
947const STABILIZED_CACHE_MESSAGES: &str = "Message caching is now always enabled.";
948
949const STABILIZED_INSTALL_UPGRADE: &str = "Packages are now always upgraded if \
950 they appear out of date.\n\
951 See https://doc.rust-lang.org/cargo/commands/cargo-install.html for more \
952 information on how upgrading works.";
953
954const STABILIZED_CONFIG_PROFILE: &str = "See \
955 https://doc.rust-lang.org/cargo/reference/config.html#profile for more \
956 information about specifying profiles in config.";
957
958const STABILIZED_CRATE_VERSIONS: &str = "The crate version is now \
959 automatically added to the documentation.";
960
961const STABILIZED_PACKAGE_FEATURES: &str = "Enhanced feature flag behavior is now \
962 available in virtual workspaces, and `member/feature-name` syntax is also \
963 always available. Other extensions require setting `resolver = \"2\"` in \
964 Cargo.toml.\n\
965 See https://doc.rust-lang.org/nightly/cargo/reference/features.html#resolver-version-2-command-line-flags \
966 for more information.";
967
968const STABILIZED_FEATURES: &str = "The new feature resolver is now available \
969 by specifying `resolver = \"2\"` in Cargo.toml.\n\
970 See https://doc.rust-lang.org/nightly/cargo/reference/features.html#feature-resolver-version-2 \
971 for more information.";
972
973const STABILIZED_EXTRA_LINK_ARG: &str = "Additional linker arguments are now \
974 supported without passing this flag.";
975
976const STABILIZED_CONFIGURABLE_ENV: &str = "The [env] section is now always enabled.";
977
978const STABILIZED_PATCH_IN_CONFIG: &str = "The patch-in-config feature is now always enabled.";
979
980const STABILIZED_NAMED_PROFILES: &str = "The named-profiles feature is now always enabled.\n\
981 See https://doc.rust-lang.org/nightly/cargo/reference/profiles.html#custom-profiles \
982 for more information";
983
984const STABILIZED_DOCTEST_IN_WORKSPACE: &str =
985 "The doctest-in-workspace feature is now always enabled.";
986
987const STABILIZED_FUTURE_INCOMPAT_REPORT: &str =
988 "The future-incompat-report feature is now always enabled.";
989
990const STABILIZED_WEAK_DEP_FEATURES: &str = "Weak dependency features are now always available.";
991
992const STABILISED_NAMESPACED_FEATURES: &str = "Namespaced features are now always available.";
993
994const STABILIZED_TIMINGS: &str = "The -Ztimings option has been stabilized as --timings.";
995
996const STABILISED_MULTITARGET: &str = "Multiple `--target` options are now always available.";
997
998const STABILIZED_TERMINAL_WIDTH: &str =
999 "The -Zterminal-width option is now always enabled for terminal output.";
1000
1001const STABILISED_SPARSE_REGISTRY: &str = "The sparse protocol is now the default for crates.io";
1002
1003const STABILIZED_CREDENTIAL_PROCESS: &str =
1004 "Authentication with a credential provider is always available.";
1005
1006const STABILIZED_REGISTRY_AUTH: &str =
1007 "Authenticated registries are available if a credential provider is configured.";
1008
1009const STABILIZED_LINTS: &str = "The `[lints]` table is now always available.";
1010
1011const STABILIZED_CARGO_LINTS: &str = "The `[lints.cargo]` table is now always available.";
1012
1013const STABILIZED_CHECK_CFG: &str =
1014 "Compile-time checking of conditional (a.k.a. `-Zcheck-cfg`) is now always enabled.";
1015
1016const STABILIZED_DOCTEST_XCOMPILE: &str = "Doctest cross-compiling is now always enabled.";
1017
1018const STABILIZED_PACKAGE_WORKSPACE: &str =
1019 "Workspace packaging and publishing (a.k.a. `-Zpackage-workspace`) is now always enabled.";
1020
1021const STABILIZED_BUILD_DIR: &str = "build.build-dir is now always enabled.";
1022
1023const STABILIZED_CONFIG_INCLUDE: &str = "The `include` config key is now always available";
1024
1025const STABILIZED_LOCKFILE_PATH: &str = "The `lockfile-path` config key is now always available";
1026
1027const STABILIZED_WARNINGS: &str = "The `build.warnings` config key is now always available";
1028
1029const STABILIZED_BUILD_DIR_NEW_LAYOUT: &str = "build.build-dir-new-layout is now always enabled.";
1030
1031const STABILIZED_MIN_PUBLISH_AGE: &str =
1032 "The `min-publish-age` configuration is now always available.";
1033
1034const STABILIZED_TRIM_PATHS: &str = "The `trim-paths` profile option is now always available.";
1035
1036fn deserialize_comma_separated_list<'de, D>(
1037 deserializer: D,
1038) -> Result<Option<Vec<String>>, D::Error>
1039where
1040 D: serde::Deserializer<'de>,
1041{
1042 let Some(list) = <Option<Vec<String>>>::deserialize(deserializer)? else {
1043 return Ok(None);
1044 };
1045 let v = list
1046 .iter()
1047 .flat_map(|s| s.split(','))
1048 .filter(|s| !s.is_empty())
1049 .map(String::from)
1050 .collect();
1051 Ok(Some(v))
1052}
1053
1054#[derive(Debug, Copy, Clone, Default, Deserialize, Ord, PartialOrd, Eq, PartialEq)]
1055#[serde(default)]
1056pub struct GitFeatures {
1057 pub shallow_index: bool,
1059 pub shallow_deps: bool,
1061}
1062
1063impl GitFeatures {
1064 pub fn all() -> Self {
1065 GitFeatures {
1066 shallow_index: true,
1067 shallow_deps: true,
1068 }
1069 }
1070
1071 fn expecting() -> String {
1072 let fields = ["`shallow-index`", "`shallow-deps`"];
1073 format!(
1074 "unstable 'git' only takes {} as valid inputs",
1075 fields.join(" and ")
1076 )
1077 }
1078}
1079
1080fn deserialize_git_features<'de, D>(deserializer: D) -> Result<Option<GitFeatures>, D::Error>
1081where
1082 D: serde::de::Deserializer<'de>,
1083{
1084 struct GitFeaturesVisitor;
1085
1086 impl<'de> serde::de::Visitor<'de> for GitFeaturesVisitor {
1087 type Value = Option<GitFeatures>;
1088
1089 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1090 formatter.write_str(&GitFeatures::expecting())
1091 }
1092
1093 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1094 where
1095 E: serde::de::Error,
1096 {
1097 if v {
1098 Ok(Some(GitFeatures::all()))
1099 } else {
1100 Ok(None)
1101 }
1102 }
1103
1104 fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
1105 where
1106 E: serde::de::Error,
1107 {
1108 Ok(parse_git(s.split(",")).map_err(serde::de::Error::custom)?)
1109 }
1110
1111 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1112 where
1113 D: serde::de::Deserializer<'de>,
1114 {
1115 let git = GitFeatures::deserialize(deserializer)?;
1116 Ok(Some(git))
1117 }
1118
1119 fn visit_map<V>(self, map: V) -> Result<Self::Value, V::Error>
1120 where
1121 V: serde::de::MapAccess<'de>,
1122 {
1123 let mvd = serde::de::value::MapAccessDeserializer::new(map);
1124 Ok(Some(GitFeatures::deserialize(mvd)?))
1125 }
1126 }
1127
1128 deserializer.deserialize_any(GitFeaturesVisitor)
1129}
1130
1131fn parse_git(it: impl Iterator<Item = impl AsRef<str>>) -> CargoResult<Option<GitFeatures>> {
1132 let mut out = GitFeatures::default();
1133 let GitFeatures {
1134 shallow_index,
1135 shallow_deps,
1136 } = &mut out;
1137
1138 for e in it {
1139 match e.as_ref() {
1140 "shallow-index" => *shallow_index = true,
1141 "shallow-deps" => *shallow_deps = true,
1142 _ => {
1143 bail!(GitFeatures::expecting())
1144 }
1145 }
1146 }
1147 Ok(Some(out))
1148}
1149
1150#[derive(Debug, Copy, Clone, Default, Deserialize, Ord, PartialOrd, Eq, PartialEq)]
1151#[serde(default)]
1152pub struct GitoxideFeatures {
1153 pub fetch: bool,
1155 pub checkout: bool,
1158}
1159
1160impl GitoxideFeatures {
1161 pub fn all() -> Self {
1162 GitoxideFeatures {
1163 fetch: true,
1164 checkout: true,
1165 }
1166 }
1167
1168 fn expecting() -> String {
1169 let fields = ["`fetch`", "`checkout`"];
1170 format!(
1171 "unstable 'gitoxide' only takes {} as valid inputs, for shallow fetches see `-Zgit=shallow-index,shallow-deps`",
1172 fields.join(" and ")
1173 )
1174 }
1175}
1176
1177fn deserialize_gitoxide_features<'de, D>(
1178 deserializer: D,
1179) -> Result<Option<GitoxideFeatures>, D::Error>
1180where
1181 D: serde::de::Deserializer<'de>,
1182{
1183 struct GitoxideFeaturesVisitor;
1184
1185 impl<'de> serde::de::Visitor<'de> for GitoxideFeaturesVisitor {
1186 type Value = Option<GitoxideFeatures>;
1187
1188 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1189 formatter.write_str(&GitoxideFeatures::expecting())
1190 }
1191
1192 fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
1193 where
1194 E: serde::de::Error,
1195 {
1196 Ok(parse_gitoxide(s.split(",")).map_err(serde::de::Error::custom)?)
1197 }
1198
1199 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1200 where
1201 E: serde::de::Error,
1202 {
1203 if v {
1204 Ok(Some(GitoxideFeatures::all()))
1205 } else {
1206 Ok(None)
1207 }
1208 }
1209
1210 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1211 where
1212 D: serde::de::Deserializer<'de>,
1213 {
1214 let gitoxide = GitoxideFeatures::deserialize(deserializer)?;
1215 Ok(Some(gitoxide))
1216 }
1217
1218 fn visit_map<V>(self, map: V) -> Result<Self::Value, V::Error>
1219 where
1220 V: serde::de::MapAccess<'de>,
1221 {
1222 let mvd = serde::de::value::MapAccessDeserializer::new(map);
1223 Ok(Some(GitoxideFeatures::deserialize(mvd)?))
1224 }
1225 }
1226
1227 deserializer.deserialize_any(GitoxideFeaturesVisitor)
1228}
1229
1230fn parse_gitoxide(
1231 it: impl Iterator<Item = impl AsRef<str>>,
1232) -> CargoResult<Option<GitoxideFeatures>> {
1233 let mut out = GitoxideFeatures::default();
1234 let GitoxideFeatures { fetch, checkout } = &mut out;
1235
1236 for e in it {
1237 match e.as_ref() {
1238 "fetch" => *fetch = true,
1239 "checkout" => *checkout = true,
1240 _ => {
1241 bail!(GitoxideFeatures::expecting())
1242 }
1243 }
1244 }
1245 Ok(Some(out))
1246}
1247
1248impl CliUnstable {
1249 pub fn parse(
1252 &mut self,
1253 flags: &[String],
1254 nightly_features_allowed: bool,
1255 ) -> CargoResult<Vec<String>> {
1256 if !flags.is_empty() && !nightly_features_allowed {
1257 bail!(
1258 "the `-Z` flag is only accepted on the nightly channel of Cargo, \
1259 but this is the `{}` channel\n\
1260 {}",
1261 channel(),
1262 SEE_CHANNELS
1263 );
1264 }
1265 let mut warnings = Vec::new();
1266 for flag in flags {
1269 if flag.starts_with("allow-features=") {
1270 self.add(flag, &mut warnings)?;
1271 }
1272 }
1273 for flag in flags {
1274 self.add(flag, &mut warnings)?;
1275 }
1276
1277 self.implicitly_enable_features_if_needed();
1278
1279 Ok(warnings)
1280 }
1281
1282 fn add(&mut self, flag: &str, warnings: &mut Vec<String>) -> CargoResult<()> {
1283 let mut parts = flag.splitn(2, '=');
1284 let k = parts.next().unwrap();
1285 let v = parts.next();
1286
1287 fn parse_bool(key: &str, value: Option<&str>) -> CargoResult<bool> {
1288 match value {
1289 None | Some("yes") => Ok(true),
1290 Some("no") => Ok(false),
1291 Some(s) => bail!("flag -Z{} expected `no` or `yes`, found: `{}`", key, s),
1292 }
1293 }
1294
1295 fn parse_option_bool(key: &str, value: Option<&str>) -> CargoResult<Option<bool>> {
1296 match value {
1297 None => Ok(None),
1298 Some("yes") => Ok(Some(true)),
1299 Some("no") => Ok(Some(false)),
1300 Some(s) => bail!("flag -Z{key} expected `no` or `yes`, found: `{s}`"),
1301 }
1302 }
1303
1304 fn parse_list(value: Option<&str>) -> Vec<String> {
1306 match value {
1307 None => Vec::new(),
1308 Some("") => Vec::new(),
1309 Some(v) => v.split(',').map(|s| s.to_string()).collect(),
1310 }
1311 }
1312
1313 fn parse_empty(key: &str, value: Option<&str>) -> CargoResult<bool> {
1315 if let Some(v) = value {
1316 bail!("flag -Z{} does not take a value, found: `{}`", key, v);
1317 }
1318 Ok(true)
1319 }
1320
1321 let mut stabilized_warn = |key: &str, version: &str, message: &str| {
1322 warnings.push(format!(
1323 "flag `-Z {}` has been stabilized in the {} release, \
1324 and is no longer necessary\n{}",
1325 key,
1326 version,
1327 indented_lines(message)
1328 ));
1329 };
1330
1331 let stabilized_err = |key: &str, version: &str, message: &str| {
1333 Err(anyhow::format_err!(
1334 "flag `-Z {}` has been stabilized in the {} release\n{}",
1335 key,
1336 version,
1337 indented_lines(message)
1338 ))
1339 };
1340
1341 if let Some(allowed) = &self.allow_features {
1342 if k != "allow-features" && !allowed.contains(k) {
1343 bail!(
1344 "the feature `{}` is not in the list of allowed features: [{}]",
1345 k,
1346 itertools::join(allowed, ", ")
1347 );
1348 }
1349 }
1350
1351 match k {
1352 "allow-features" => self.allow_features = Some(parse_list(v).into_iter().collect()),
1355 "embed-metadata" => self.embed_metadata = parse_option_bool(k, v)?,
1356 "print-im-a-teapot" => self.print_im_a_teapot = parse_bool(k, v)?,
1357
1358 "compile-progress" => stabilized_warn(k, "1.30", STABILIZED_COMPILE_PROGRESS),
1361 "offline" => stabilized_err(k, "1.36", STABILIZED_OFFLINE)?,
1362 "cache-messages" => stabilized_warn(k, "1.40", STABILIZED_CACHE_MESSAGES),
1363 "install-upgrade" => stabilized_warn(k, "1.41", STABILIZED_INSTALL_UPGRADE),
1364 "config-profile" => stabilized_warn(k, "1.43", STABILIZED_CONFIG_PROFILE),
1365 "crate-versions" => stabilized_warn(k, "1.47", STABILIZED_CRATE_VERSIONS),
1366 "features" => {
1367 let feats = parse_list(v);
1375 let stab_is_not_empty = feats.iter().any(|feat| {
1376 matches!(
1377 feat.as_str(),
1378 "build_dep" | "host_dep" | "dev_dep" | "itarget" | "all"
1379 )
1380 });
1381 if stab_is_not_empty || feats.is_empty() {
1382 stabilized_warn(k, "1.51", STABILIZED_FEATURES);
1384 }
1385 self.features = Some(feats);
1386 }
1387 "package-features" => stabilized_warn(k, "1.51", STABILIZED_PACKAGE_FEATURES),
1388 "configurable-env" => stabilized_warn(k, "1.56", STABILIZED_CONFIGURABLE_ENV),
1389 "extra-link-arg" => stabilized_warn(k, "1.56", STABILIZED_EXTRA_LINK_ARG),
1390 "patch-in-config" => stabilized_warn(k, "1.56", STABILIZED_PATCH_IN_CONFIG),
1391 "named-profiles" => stabilized_warn(k, "1.57", STABILIZED_NAMED_PROFILES),
1392 "future-incompat-report" => {
1393 stabilized_warn(k, "1.59.0", STABILIZED_FUTURE_INCOMPAT_REPORT)
1394 }
1395 "namespaced-features" => stabilized_warn(k, "1.60", STABILISED_NAMESPACED_FEATURES),
1396 "timings" => stabilized_warn(k, "1.60", STABILIZED_TIMINGS),
1397 "weak-dep-features" => stabilized_warn(k, "1.60", STABILIZED_WEAK_DEP_FEATURES),
1398 "multitarget" => stabilized_warn(k, "1.64", STABILISED_MULTITARGET),
1399 "sparse-registry" => stabilized_warn(k, "1.68", STABILISED_SPARSE_REGISTRY),
1400 "terminal-width" => stabilized_warn(k, "1.68", STABILIZED_TERMINAL_WIDTH),
1401 "doctest-in-workspace" => stabilized_warn(k, "1.72", STABILIZED_DOCTEST_IN_WORKSPACE),
1402 "credential-process" => stabilized_warn(k, "1.74", STABILIZED_CREDENTIAL_PROCESS),
1403 "lints" => stabilized_warn(k, "1.74", STABILIZED_LINTS),
1404 "registry-auth" => stabilized_warn(k, "1.74", STABILIZED_REGISTRY_AUTH),
1405 "check-cfg" => stabilized_warn(k, "1.80", STABILIZED_CHECK_CFG),
1406 "doctest-xcompile" => stabilized_warn(k, "1.89", STABILIZED_DOCTEST_XCOMPILE),
1407 "package-workspace" => stabilized_warn(k, "1.89", STABILIZED_PACKAGE_WORKSPACE),
1408 "build-dir" => stabilized_warn(k, "1.91", STABILIZED_BUILD_DIR),
1409 "config-include" => stabilized_warn(k, "1.93", STABILIZED_CONFIG_INCLUDE),
1410 "lockfile-path" => stabilized_warn(k, "1.97", STABILIZED_LOCKFILE_PATH),
1411 "warnings" => stabilized_warn(k, "1.97", STABILIZED_WARNINGS),
1412 "build-dir-new-layout" => stabilized_warn(k, "1.100", STABILIZED_BUILD_DIR_NEW_LAYOUT),
1413 "cargo-lints" => stabilized_warn(k, "1.100", STABILIZED_CARGO_LINTS),
1414 "min-publish-age" => stabilized_warn(k, "1.100", STABILIZED_MIN_PUBLISH_AGE),
1415 "trim-paths" => stabilized_warn(k, "1.101", STABILIZED_TRIM_PATHS),
1416
1417 "advanced-env" => self.advanced_env = parse_empty(k, v)?,
1420 "any-build-script-metadata" => self.any_build_script_metadata = parse_empty(k, v)?,
1421 "avoid-dev-deps" => self.avoid_dev_deps = parse_empty(k, v)?,
1422 "binary-dep-depinfo" => self.binary_dep_depinfo = parse_empty(k, v)?,
1423 "bindeps" => self.bindeps = parse_empty(k, v)?,
1424 "build-analysis" => self.build_analysis = parse_empty(k, v)?,
1425 "build-std" => self.build_std = Some(parse_list(v)),
1426 "build-std-features" => self.build_std_features = Some(parse_list(v)),
1427 "codegen-backend" => self.codegen_backend = parse_empty(k, v)?,
1428 "direct-minimal-versions" => self.direct_minimal_versions = parse_empty(k, v)?,
1429 "dual-proc-macros" => self.dual_proc_macros = parse_empty(k, v)?,
1430 "feature-unification" => self.feature_unification = parse_empty(k, v)?,
1431 "fine-grain-locking" => self.fine_grain_locking = parse_empty(k, v)?,
1432 "fix-edition" => {
1433 let fe = v
1434 .ok_or_else(|| anyhow::anyhow!("-Zfix-edition expected a value"))?
1435 .parse()?;
1436 self.fix_edition = Some(fe);
1437 }
1438 "gc" => self.gc = parse_empty(k, v)?,
1439 "git" => {
1440 self.git =
1441 v.map_or_else(|| Ok(Some(GitFeatures::all())), |v| parse_git(v.split(',')))?
1442 }
1443 "gitoxide" => {
1444 self.gitoxide = v.map_or_else(
1445 || Ok(Some(GitoxideFeatures::all())),
1446 |v| parse_gitoxide(v.split(',')),
1447 )?
1448 }
1449 "hint-min-opt-level" => self.hint_min_opt_level = parse_empty(k, v)?,
1450 "host-config" => self.host_config = parse_empty(k, v)?,
1451 "json-target-spec" => self.json_target_spec = parse_empty(k, v)?,
1452 "hint-msrv" => self.hint_msrv = parse_empty(k, v)?,
1453 "next-lockfile-bump" => self.next_lockfile_bump = parse_empty(k, v)?,
1454 "mem-stats" => self.mem_stats = parse_empty(k, v)?,
1455 "minimal-versions" => self.minimal_versions = parse_empty(k, v)?,
1456 "msrv-policy" => self.msrv_policy = parse_empty(k, v)?,
1457 "mtime-on-use" => self.mtime_on_use = parse_empty(k, v)?,
1459 "no-index-update" => self.no_index_update = parse_empty(k, v)?,
1460 "panic-abort-tests" => self.panic_abort_tests = parse_empty(k, v)?,
1461 "prerelease" => self.prerelease = parse_empty(k, v)?,
1462 "public-dependency" => self.public_dependency = parse_empty(k, v)?,
1463 "profile-hint-mostly-unused" => self.profile_hint_mostly_unused = parse_empty(k, v)?,
1464 "profile-rustflags" => self.profile_rustflags = parse_empty(k, v)?,
1465 "publish-timeout" => self.publish_timeout = parse_empty(k, v)?,
1466 "root-dir" => self.root_dir = v.map(|v| v.into()),
1467 "rustc-unicode" => self.rustc_unicode = parse_empty(k, v)?,
1468 "rustdoc-depinfo" => self.rustdoc_depinfo = parse_empty(k, v)?,
1469 "rustdoc-map" => self.rustdoc_map = parse_empty(k, v)?,
1470 "rustdoc-mergeable-info" => self.rustdoc_mergeable_info = parse_empty(k, v)?,
1471 "rustdoc-scrape-examples" => self.rustdoc_scrape_examples = parse_empty(k, v)?,
1472 "sbom" => self.sbom = parse_empty(k, v)?,
1473 "section-timings" => self.section_timings = parse_empty(k, v)?,
1474 "separate-nightlies" => self.separate_nightlies = parse_empty(k, v)?,
1475 "checksum-freshness" => self.checksum_freshness = parse_empty(k, v)?,
1476 "skip-rustdoc-fingerprint" => self.skip_rustdoc_fingerprint = parse_empty(k, v)?,
1477 "script" => self.script = parse_empty(k, v)?,
1478 "target-applies-to-host" => self.target_applies_to_host = parse_empty(k, v)?,
1479 "panic-immediate-abort" => self.panic_immediate_abort = parse_empty(k, v)?,
1480 "unstable-options" => self.unstable_options = parse_empty(k, v)?,
1481 _ => bail!(
1482 "\
1483 unknown `-Z` flag specified: {k}\n\n\
1484 For available unstable features, see \
1485 https://doc.rust-lang.org/nightly/cargo/reference/unstable.html\n\
1486 If you intended to use an unstable rustc feature, try setting `RUSTFLAGS=\"-Z{k}\"`"
1487 ),
1488 }
1489
1490 Ok(())
1491 }
1492
1493 pub fn fail_if_stable_opt(&self, flag: &str, issue: u32) -> CargoResult<()> {
1496 self.fail_if_stable_opt_custom_z(flag, issue, "unstable-options", self.unstable_options)
1497 }
1498
1499 pub fn fail_if_stable_opt_custom_z(
1500 &self,
1501 flag: &str,
1502 issue: u32,
1503 z_name: &str,
1504 enabled: bool,
1505 ) -> CargoResult<()> {
1506 if !enabled {
1507 let see = format!(
1508 "See https://github.com/rust-lang/cargo/issues/{issue} for more \
1509 information about the `{flag}` flag."
1510 );
1511 let channel = channel();
1513 if channel == "nightly" || channel == "dev" {
1514 bail!(
1515 "the `{flag}` flag is unstable, pass `-Z {z_name}` to enable it\n\
1516 {see}"
1517 );
1518 } else {
1519 bail!(
1520 "the `{flag}` flag is unstable, and only available on the nightly channel \
1521 of Cargo, but this is the `{channel}` channel\n\
1522 {SEE_CHANNELS}\n\
1523 {see}"
1524 );
1525 }
1526 }
1527 Ok(())
1528 }
1529
1530 pub fn fail_if_stable_command(
1533 &self,
1534 gctx: &GlobalContext,
1535 command: &str,
1536 issue: u32,
1537 z_name: &str,
1538 enabled: bool,
1539 ) -> CargoResult<()> {
1540 if enabled {
1541 return Ok(());
1542 }
1543 let see = format!(
1544 "See https://github.com/rust-lang/cargo/issues/{} for more \
1545 information about the `cargo {}` command.",
1546 issue, command
1547 );
1548 if gctx.nightly_features_allowed {
1549 bail!(
1550 "the `cargo {command}` command is unstable, pass `-Z {z_name}` \
1551 to enable it\n\
1552 {see}",
1553 );
1554 } else {
1555 bail!(
1556 "the `cargo {}` command is unstable, and only available on the \
1557 nightly channel of Cargo, but this is the `{}` channel\n\
1558 {}\n\
1559 {}",
1560 command,
1561 channel(),
1562 SEE_CHANNELS,
1563 see
1564 );
1565 }
1566 }
1567
1568 fn implicitly_enable_features_if_needed(&mut self) {
1569 if self.fine_grain_locking && !self.build_dir_new_layout {
1570 debug!("-Zbuild-dir-new-layout implicitly enabled by -Zfine-grain-locking");
1571 self.build_dir_new_layout = true;
1572 }
1573 }
1574}
1575
1576pub fn channel() -> String {
1578 #[expect(
1579 clippy::disallowed_methods,
1580 reason = "testing only, no reason for config support"
1581 )]
1582 if let Ok(override_channel) = env::var("__CARGO_TEST_CHANNEL_OVERRIDE_DO_NOT_USE_THIS") {
1583 return override_channel;
1584 }
1585 #[expect(
1586 clippy::disallowed_methods,
1587 reason = "consistency with rustc, not specified behavior"
1588 )]
1589 if let Ok(staging) = env::var("RUSTC_BOOTSTRAP") {
1590 if staging == "1" {
1591 return "dev".to_string();
1592 }
1593 }
1594 crate::version()
1595 .release_channel
1596 .unwrap_or_else(|| String::from("dev"))
1597}
1598
1599#[expect(
1600 clippy::disallowed_methods,
1601 reason = "Temporary opt out that is not part of the public interface"
1602)]
1603fn is_new_build_dir_layout_opt_out() -> bool {
1604 std::env::var("__CARGO_TEMPORARY_BUILD_DIR_NEW_LAYOUT_OPT_OUT").as_deref() == Ok("1")
1605}
1606
1607pub fn cargo_docs_link(path: &str) -> String {
1610 let version = crate::version().version;
1611 let url_channel = match channel().as_str() {
1612 "dev" | "nightly" => "nightly",
1613 "beta" => "beta",
1614 _ => version.as_str(),
1615 };
1616 format!("https://doc.rust-lang.org/{url_channel}/cargo/{path}")
1617}