diff --git a/crates/xtask-bump-check/src/xtask.rs b/crates/xtask-bump-check/src/xtask.rs index f891523315d..cba5ed68a56 100644 --- a/crates/xtask-bump-check/src/xtask.rs +++ b/crates/xtask-bump-check/src/xtask.rs @@ -219,7 +219,7 @@ fn get_base_commit<'a>( let upstream_ref = upstream_branches[0].get(); if upstream_branches.len() > 1 { let name = upstream_ref.name().expect("name is valid UTF-8"); - let _ = config.shell().warn(format!( + let _ = config.emit_diagnostic(format!( "multiple `{UPSTREAM_BRANCH}` found, picking {name}" )); } diff --git a/src/bin/cargo/cli.rs b/src/bin/cargo/cli.rs index eb337d681ce..0fbbd4dcf0f 100644 --- a/src/bin/cargo/cli.rs +++ b/src/bin/cargo/cli.rs @@ -266,7 +266,7 @@ fn expand_aliases( match (exec, aliased_cmd) { (Some(_), Ok(Some(_))) => { // User alias conflicts with a built-in subcommand - config.shell().warn(format!( + config.emit_diagnostic(format!( "user-defined alias `{}` is ignored, because it is shadowed by a built-in command", cmd, ))?; @@ -296,7 +296,7 @@ To pass the arguments to the subcommand, remove `--`", // a hard error. if super::builtin_aliases_execs(cmd).is_none() { if let Some(path) = super::find_external_subcommand(config, cmd) { - config.shell().warn(format!( + config.emit_diagnostic(format!( "\ user-defined alias `{}` is shadowing an external subcommand found at: `{}` This was previously accepted but is being phased out; it will become a hard error in a future release. @@ -310,7 +310,7 @@ For more information, see issue #10049 { let ext_path = super::find_external_subcommand(config, &cmd); if !config.cli_unstable().script && ext_path.is_some() { - config.shell().warn(format_args!( + config.emit_diagnostic(format_args!( "\ external subcommand `{cmd}` has the appearance of a manfiest-command This was previously accepted but will be phased out when `-Zscript` is stabilized. diff --git a/src/bin/cargo/commands/metadata.rs b/src/bin/cargo/commands/metadata.rs index 54257dee3db..7c4e6ca3d06 100644 --- a/src/bin/cargo/commands/metadata.rs +++ b/src/bin/cargo/commands/metadata.rs @@ -34,7 +34,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult { let version = match args.get_one::("format-version") { None => { - config.shell().warn( + config.emit_diagnostic( "please specify `--format-version` flag explicitly \ to avoid compatibility problems", )?; diff --git a/src/bin/cargo/commands/tree.rs b/src/bin/cargo/commands/tree.rs index 4472765a92d..0eeee49db24 100644 --- a/src/bin/cargo/commands/tree.rs +++ b/src/bin/cargo/commands/tree.rs @@ -107,14 +107,10 @@ pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult { return Ok(()); } let prefix = if args.flag("no-indent") { - config - .shell() - .warn("the --no-indent flag has been changed to --prefix=none")?; + config.emit_diagnostic("the --no-indent flag has been changed to --prefix=none")?; "none" } else if args.flag("prefix-depth") { - config - .shell() - .warn("the --prefix-depth flag has been changed to --prefix=depth")?; + config.emit_diagnostic("the --prefix-depth flag has been changed to --prefix=depth")?; "depth" } else { args.get_one::("prefix").unwrap().as_str() @@ -123,7 +119,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult { let no_dedupe = args.flag("no-dedupe") || args.flag("all"); if args.flag("all") { - config.shell().warn( + config.emit_diagnostic( "The `cargo tree` --all flag has been changed to --no-dedupe, \ and may be removed in a future version.\n\ If you are looking to display all workspace members, use the --workspace flag.", @@ -131,9 +127,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult { } let targets = if args.flag("all-targets") { - config - .shell() - .warn("the --all-targets flag has been changed to --target=all")?; + config.emit_diagnostic("the --all-targets flag has been changed to --target=all")?; vec!["all".to_string()] } else { args._values_of("target") @@ -228,9 +222,7 @@ fn parse_edge_kinds(config: &Config, args: &ArgMatches) -> CargoResult<(HashSet< ); if args.flag("no-dev-dependencies") { - config - .shell() - .warn("the --no-dev-dependencies flag has changed to -e=no-dev")?; + config.emit_diagnostic("the --no-dev-dependencies flag has changed to -e=no-dev")?; kinds.push("no-dev"); } diff --git a/src/cargo/core/compiler/build_config.rs b/src/cargo/core/compiler/build_config.rs index 5d4d754bff1..c9668423e19 100644 --- a/src/cargo/core/compiler/build_config.rs +++ b/src/cargo/core/compiler/build_config.rs @@ -73,7 +73,7 @@ impl BuildConfig { let cfg = config.build_config()?; let requested_kinds = CompileKind::from_requested_targets(config, requested_targets)?; if jobs.is_some() && config.jobserver_from_env().is_some() { - config.shell().warn( + config.emit_diagnostic( "a `-j` argument was passed to Cargo but Cargo is \ also configured with an external jobserver in \ its environment, ignoring the `-j` parameter", diff --git a/src/cargo/core/compiler/build_context/target_info.rs b/src/cargo/core/compiler/build_context/target_info.rs index 754adcf3cd0..ecb03178e4e 100644 --- a/src/cargo/core/compiler/build_context/target_info.rs +++ b/src/cargo/core/compiler/build_context/target_info.rs @@ -302,7 +302,7 @@ impl TargetInfo { continue; } if !reached_fixed_point { - config.shell().warn("non-trivial mutual dependency between target-specific configuration and RUSTFLAGS")?; + config.emit_diagnostic("non-trivial mutual dependency between target-specific configuration and RUSTFLAGS")?; } return Ok(TargetInfo { diff --git a/src/cargo/core/compiler/context/mod.rs b/src/cargo/core/compiler/context/mod.rs index 3f13f086c95..58a9522902c 100644 --- a/src/cargo/core/compiler/context/mod.rs +++ b/src/cargo/core/compiler/context/mod.rs @@ -465,7 +465,7 @@ impl<'a, 'cfg> Context<'a, 'cfg> { suggestion: &str| -> CargoResult<()> { if unit.target.name() == other_unit.target.name() { - self.bcx.config.shell().warn(format!( + self.bcx.config.emit_diagnostic(format!( "output filename collision.\n\ {}\ The targets should have unique names.\n\ @@ -474,7 +474,7 @@ impl<'a, 'cfg> Context<'a, 'cfg> { suggestion )) } else { - self.bcx.config.shell().warn(format!( + self.bcx.config.emit_diagnostic(format!( "output filename collision.\n\ {}\ The output filenames should be unique.\n\ @@ -560,7 +560,7 @@ impl<'a, 'cfg> Context<'a, 'cfg> { } if let Some(ref export_path) = output.export_path { if let Some(other_unit) = output_collisions.insert(export_path.clone(), unit) { - self.bcx.config.shell().warn(format!( + self.bcx.config.emit_diagnostic(format!( "`--out-dir` filename collision.\n\ {}\ The exported filenames should be unique.\n\ diff --git a/src/cargo/core/compiler/future_incompat.rs b/src/cargo/core/compiler/future_incompat.rs index ccea28b9416..4df8aacc510 100644 --- a/src/cargo/core/compiler/future_incompat.rs +++ b/src/cargo/core/compiler/future_incompat.rs @@ -180,7 +180,7 @@ impl OnDiskReports { crate::display_warning_with_error( "failed to write on-disk future incompatible report", &e, - &mut ws.config().shell(), + ws.config(), ); } @@ -395,7 +395,7 @@ pub fn save_and_display_report( crate::display_warning_with_error( "failed to read future-incompat config from disk", &e, - &mut bcx.config.shell(), + bcx.config, ); true } @@ -434,7 +434,7 @@ pub fn save_and_display_report( let package_vers: Vec<_> = package_ids.iter().map(|pid| pid.to_string()).collect(); if should_display_message || bcx.build_config.future_incompat_report { - drop(bcx.config.shell().warn(&format!( + drop(bcx.config.emit_diagnostic(&format!( "the following packages contain code that will be rejected by a future \ version of Rust: {}", package_vers.join(", ") diff --git a/src/cargo/core/compiler/job_queue/mod.rs b/src/cargo/core/compiler/job_queue/mod.rs index 26fcd482692..6230a7216dd 100644 --- a/src/cargo/core/compiler/job_queue/mod.rs +++ b/src/cargo/core/compiler/job_queue/mod.rs @@ -139,7 +139,7 @@ use crate::core::compiler::future_incompat::{ self, FutureBreakageItem, FutureIncompatReportPackage, }; use crate::core::resolver::ResolveBehavior; -use crate::core::{PackageId, Shell, TargetKind}; +use crate::core::{PackageId, TargetKind}; use crate::util::diagnostic_server::{self, DiagnosticPrinter}; use crate::util::errors::AlreadyPrintedError; use crate::util::machine_message::{self, Message as _}; @@ -619,7 +619,7 @@ impl<'cfg> DrainState<'cfg> { } } Message::Warning { id, warning } => { - cx.bcx.config.shell().warn(warning)?; + cx.bcx.config.emit_diagnostic(warning)?; self.bump_warning_count(id, true, false); } Message::WarningCount { @@ -745,7 +745,7 @@ impl<'cfg> DrainState<'cfg> { loop { if errors.count == 0 || cx.bcx.build_config.keep_going { if let Err(e) = self.spawn_work_if_possible(cx, jobserver_helper, scope) { - self.handle_error(&mut cx.bcx.config.shell(), &mut errors, e); + self.handle_error(cx.bcx.config, &mut errors, e); } } @@ -762,7 +762,7 @@ impl<'cfg> DrainState<'cfg> { // to the jobserver itself. for event in self.wait_for_events() { if let Err(event_err) = self.handle_event(cx, plan, event) { - self.handle_error(&mut cx.bcx.config.shell(), &mut errors, event_err); + self.handle_error(cx.bcx.config, &mut errors, event_err); } } } @@ -788,7 +788,7 @@ impl<'cfg> DrainState<'cfg> { let time_elapsed = util::elapsed(cx.bcx.config.creation_time().elapsed()); if let Err(e) = self.timings.finished(cx, &errors.to_error()) { - self.handle_error(&mut cx.bcx.config.shell(), &mut errors, e); + self.handle_error(cx.bcx.config, &mut errors, e); } if cx.bcx.build_config.emit_json() { let mut shell = cx.bcx.config.shell(); @@ -797,7 +797,7 @@ impl<'cfg> DrainState<'cfg> { } .to_json_string(); if let Err(e) = writeln!(shell.out(), "{}", msg) { - self.handle_error(&mut shell, &mut errors, e); + self.handle_error(cx.bcx.config, &mut errors, e); } } @@ -828,15 +828,15 @@ impl<'cfg> DrainState<'cfg> { fn handle_error( &self, - shell: &mut Shell, + config: &Config, err_state: &mut ErrorsDuringDrain, new_err: impl Into, ) { let new_err = new_err.into(); if new_err.print_always || err_state.count == 0 { - crate::display_error(&new_err.error, shell); + crate::display_error(&new_err.error, &mut config.shell()); if err_state.count == 0 && !self.active.is_empty() { - let _ = shell.warn("build failed, waiting for other jobs to finish..."); + let _ = config.emit_diagnostic("build failed, waiting for other jobs to finish..."); } err_state.count += 1; } else { @@ -953,7 +953,7 @@ impl<'cfg> DrainState<'cfg> { } for warning in output.warnings.iter() { - bcx.config.shell().warn(warning)?; + bcx.config.emit_diagnostic(warning)?; } if msg.is_some() { @@ -1058,7 +1058,7 @@ impl<'cfg> DrainState<'cfg> { } // Errors are ignored here because it is tricky to handle them // correctly, and they aren't important. - let _ = config.shell().warn(message); + let _ = config.emit_diagnostic(message); } fn finish( diff --git a/src/cargo/core/compiler/mod.rs b/src/cargo/core/compiler/mod.rs index 7024a2ac561..9e9d3b5ce4f 100644 --- a/src/cargo/core/compiler/mod.rs +++ b/src/cargo/core/compiler/mod.rs @@ -1272,7 +1272,7 @@ fn build_deps_args(cmd: &mut ProcessBuilder, cx: &Context<'_, '_>, unit: &Unit) if let Some(dep) = deps.iter().find(|dep| { !dep.unit.mode.is_doc() && dep.unit.target.is_lib() && !dep.unit.artifact.is_true() }) { - bcx.config.shell().warn(format!( + bcx.config.emit_diagnostic(format!( "The package `{}` \ provides no linkable target. The compiler might raise an error while compiling \ `{}`. Consider adding 'dylib' or 'rlib' to key `crate-type` in `{}`'s \ diff --git a/src/cargo/core/compiler/standard_lib.rs b/src/cargo/core/compiler/standard_lib.rs index c456c58d530..00afd0c3dd7 100644 --- a/src/cargo/core/compiler/standard_lib.rs +++ b/src/cargo/core/compiler/standard_lib.rs @@ -68,8 +68,7 @@ pub fn resolve_std<'cfg>( ) -> CargoResult<(PackageSet<'cfg>, Resolve, ResolvedFeatures)> { if build_config.build_plan { ws.config() - .shell() - .warn("-Zbuild-std does not currently fully support --build-plan")?; + .emit_diagnostic("-Zbuild-std does not currently fully support --build-plan")?; } let src_path = detect_sysroot_src_path(target_data)?; diff --git a/src/cargo/core/package.rs b/src/cargo/core/package.rs index c84941462b4..6aa8cb585db 100644 --- a/src/cargo/core/package.rs +++ b/src/cargo/core/package.rs @@ -597,7 +597,7 @@ impl<'cfg> PackageSet<'cfg> { .map(|artifact| artifact.is_lib()) .unwrap_or(true) }) { - ws.config().shell().warn(&format!( + ws.config().emit_diagnostic(&format!( "{} ignoring invalid dependency `{}` which is missing a lib target", pkg_id, dep.name_in_toml(), diff --git a/src/cargo/core/profiles.rs b/src/cargo/core/profiles.rs index 5c7d3e2488e..7c13c9d44ad 100644 --- a/src/cargo/core/profiles.rs +++ b/src/cargo/core/profiles.rs @@ -24,7 +24,7 @@ use crate::core::compiler::{CompileKind, CompileTarget, Unit}; use crate::core::dependency::Artifact; use crate::core::resolver::features::FeaturesFor; -use crate::core::{PackageId, PackageIdSpec, Resolve, Shell, Target, Workspace}; +use crate::core::{PackageId, PackageIdSpec, Resolve, Target, Workspace}; use crate::util::interning::InternedString; use crate::util::toml::{ ProfilePackageSpec, StringOrBool, TomlDebugInfo, TomlProfile, TomlProfiles, @@ -341,7 +341,7 @@ impl Profiles { pub fn validate_packages( &self, profiles: Option<&TomlProfiles>, - shell: &mut Shell, + config: &Config, resolve: &Resolve, ) -> CargoResult<()> { for (name, profile) in &self.by_name { @@ -364,7 +364,7 @@ impl Profiles { // iterates over the manifest profiles only. if let Some(profiles) = profiles { if let Some(toml_profile) = profiles.get(name) { - validate_packages_unmatched(shell, resolve, name, toml_profile, &found)?; + validate_packages_unmatched(config, resolve, name, toml_profile, &found)?; } } } @@ -1225,7 +1225,7 @@ fn get_config_profile(ws: &Workspace<'_>, name: &str) -> CargoResult PackageRegistry<'cfg> { ); if dep.features().len() != 0 || !dep.uses_default_features() { - self.source_config.config().shell().warn(format!( + self.source_config.config().emit_diagnostic(format!( "patch for `{}` uses the features mechanism. \ default-features and features will not take effect because the patch dependency does not support this mechanism", dep.package_name() @@ -546,7 +546,7 @@ https://doc.rust-lang.org/cargo/reference/overriding-dependencies.html dep.package_name(), boilerplate ); - self.source_config.config().shell().warn(&msg)?; + self.source_config.config().emit_diagnostic(&msg)?; return Ok(()); } @@ -559,7 +559,7 @@ https://doc.rust-lang.org/cargo/reference/overriding-dependencies.html dep.package_name(), boilerplate ); - self.source_config.config().shell().warn(&msg)?; + self.source_config.config().emit_diagnostic(&msg)?; return Ok(()); } diff --git a/src/cargo/core/shell.rs b/src/cargo/core/shell.rs index 4d45e609889..0edc5e024bd 100644 --- a/src/cargo/core/shell.rs +++ b/src/cargo/core/shell.rs @@ -2,7 +2,7 @@ use std::fmt; use std::io::prelude::*; use std::io::IsTerminal; -use termcolor::Color::{Cyan, Green, Red, Yellow}; +use termcolor::Color::{Cyan, Green, Red}; use termcolor::{self, Color, ColorSpec, StandardStream, WriteColor}; use crate::util::errors::CargoResult; @@ -126,7 +126,7 @@ impl Shell { /// Prints a message, where the status will have `color` color, and can be justified. The /// messages follows without color. - fn print( + pub(crate) fn print( &mut self, status: &dyn fmt::Display, message: Option<&dyn fmt::Display>, @@ -258,14 +258,6 @@ impl Shell { .message_stderr(&"error", Some(&message), Red, false) } - /// Prints an amber 'warning' message. - pub fn warn(&mut self, message: T) -> CargoResult<()> { - match self.verbosity { - Verbosity::Quiet => Ok(()), - _ => self.print(&"warning", Some(&message), Yellow, false), - } - } - /// Prints a cyan 'note' message. pub fn note(&mut self, message: T) -> CargoResult<()> { self.print(&"note", Some(&message), Cyan, false) diff --git a/src/cargo/core/workspace.rs b/src/cargo/core/workspace.rs index 9ee0cbe0430..fa64d5c015b 100644 --- a/src/cargo/core/workspace.rs +++ b/src/cargo/core/workspace.rs @@ -454,8 +454,7 @@ impl<'cfg> Workspace<'cfg> { for message in warnings { self.config - .shell() - .warn(format!("[patch] in cargo config: {}", message))? + .emit_diagnostic(format!("[patch] in cargo config: {}", message))? } Ok(patch) @@ -993,7 +992,7 @@ impl<'cfg> Workspace<'cfg> { pkg.manifest_path().display(), root_manifest.display(), ); - self.config.shell().warn(&msg) + self.config.emit_diagnostic(&msg) }; if manifest.original().has_profiles() { emit_warning("profiles")?; @@ -1021,7 +1020,7 @@ impl<'cfg> Workspace<'cfg> { .max() { let resolver = edition.default_resolve_behavior().to_manifest(); - self.config.shell().warn(format_args!("some crates are on edition {edition} which defaults to `resolver = \"{resolver}\"`, but virtual workspaces default to `resolver = \"1\"`"))?; + self.config.emit_diagnostic(format_args!("some crates are on edition {edition} which defaults to `resolver = \"{resolver}\"`, but virtual workspaces default to `resolver = \"1\"`"))?; self.config.shell().note( "to keep the current resolver, specify `workspace.resolver = \"1\"` in the workspace root's manifest", )?; @@ -1098,7 +1097,7 @@ impl<'cfg> Workspace<'cfg> { // originated, so include the path. format!("{}: {}", path.display(), warning.message) }; - self.config.shell().warn(msg)? + self.config.emit_diagnostic(msg)? } } } diff --git a/src/cargo/lib.rs b/src/cargo/lib.rs index 9f6edf80d2a..4e828f508f9 100644 --- a/src/cargo/lib.rs +++ b/src/cargo/lib.rs @@ -205,10 +205,11 @@ pub fn display_error(err: &Error, shell: &mut Shell) { /// Displays a warning, with an error object providing detailed information /// and context. -pub fn display_warning_with_error(warning: &str, err: &Error, shell: &mut Shell) { - drop(shell.warn(warning)); +pub fn display_warning_with_error(warning: &str, err: &Error, config: &Config) { + drop(config.emit_diagnostic(warning)); + let mut shell = config.shell(); drop(writeln!(shell.err())); - _display_error(err, shell, false); + _display_error(err, &mut shell, false); } fn _display_error(err: &Error, shell: &mut Shell, as_err: bool) -> bool { diff --git a/src/cargo/ops/cargo_add/mod.rs b/src/cargo/ops/cargo_add/mod.rs index 11ca282ee42..16883011a0c 100644 --- a/src/cargo/ops/cargo_add/mod.rs +++ b/src/cargo/ops/cargo_add/mod.rs @@ -217,7 +217,9 @@ pub fn add(workspace: &Workspace<'_>, options: &AddOptions<'_>) -> CargoResult<( } if options.dry_run { - options.config.shell().warn("aborting add due to dry run")?; + options + .config + .emit_diagnostic("aborting add due to dry run")?; } else { manifest.write()?; } @@ -291,7 +293,7 @@ fn resolve_dependency( let dependency = crate_spec.to_dependency()?.set_source(src); let selected = select_package(&dependency, config, registry)?; if dependency.name != selected.name { - config.shell().warn(format!( + config.emit_diagnostic(format!( "translating `{}` to `{}`", dependency.name, selected.name, ))?; @@ -316,7 +318,7 @@ fn resolve_dependency( let dependency = crate_spec.to_dependency()?.set_source(src); let selected = select_package(&dependency, config, registry)?; if dependency.name != selected.name { - config.shell().warn(format!( + config.emit_diagnostic(format!( "translating `{}` to `{}`", dependency.name, selected.name, ))?; @@ -384,7 +386,7 @@ fn resolve_dependency( )?; if dependency.name != latest.name { - config.shell().warn(format!( + config.emit_diagnostic(format!( "translating `{}` to `{}`", dependency.name, latest.name, ))?; @@ -611,7 +613,7 @@ fn get_latest_dependency( })?; if latest_msrv.version() < latest.version() { - config.shell().warn(format_args!( + config.emit_diagnostic(format_args!( "ignoring `{dependency}@{latest_version}` (which has a rust-version of \ {latest_rust_version}) to satisfy this package's rust-version of \ {rust_version} (use `--ignore-rust-version` to override)", diff --git a/src/cargo/ops/cargo_clean.rs b/src/cargo/ops/cargo_clean.rs index b9b33690e45..73611c48394 100644 --- a/src/cargo/ops/cargo_clean.rs +++ b/src/cargo/ops/cargo_clean.rs @@ -100,7 +100,7 @@ pub fn clean(ws: &Workspace<'_>, opts: &CleanOptions<'_>) -> CargoResult<()> { // Translate the spec to a Package. let spec = PackageIdSpec::parse(spec_str)?; if spec.version().is_some() { - config.shell().warn(&format!( + config.emit_diagnostic(&format!( "version qualifier in `-p {}` is ignored, \ cleaning all versions of `{}` found", spec_str, @@ -108,7 +108,7 @@ pub fn clean(ws: &Workspace<'_>, opts: &CleanOptions<'_>) -> CargoResult<()> { ))?; } if spec.url().is_some() { - config.shell().warn(&format!( + config.emit_diagnostic(&format!( "url qualifier in `-p {}` ignored, \ cleaning all versions of `{}` found", spec_str, diff --git a/src/cargo/ops/cargo_compile/mod.rs b/src/cargo/ops/cargo_compile/mod.rs index 9287fdf4fc5..248d94a3f8f 100644 --- a/src/cargo/ops/cargo_compile/mod.rs +++ b/src/cargo/ops/cargo_compile/mod.rs @@ -222,14 +222,14 @@ pub fn create_bcx<'a, 'cfg>( | CompileMode::Bench | CompileMode::RunCustomBuild => { if ws.config().get_env("RUST_FLAGS").is_ok() { - config.shell().warn( + config.emit_diagnostic( "Cargo does not read `RUST_FLAGS` environment variable. Did you mean `RUSTFLAGS`?", )?; } } CompileMode::Doc { .. } | CompileMode::Doctest | CompileMode::Docscrape => { if ws.config().get_env("RUSTDOC_FLAGS").is_ok() { - config.shell().warn( + config.emit_diagnostic( "Cargo does not read `RUSTDOC_FLAGS` environment variable. Did you mean `RUSTDOCFLAGS`?" )?; } @@ -331,7 +331,7 @@ pub fn create_bcx<'a, 'cfg>( let profiles = Profiles::new(ws, build_config.requested_profile)?; profiles.validate_packages( ws.profiles(), - &mut config.shell(), + config, workspace_resolve.as_ref().unwrap_or(&resolve), )?; diff --git a/src/cargo/ops/cargo_compile/packages.rs b/src/cargo/ops/cargo_compile/packages.rs index 2d14d60a69c..e8aa3208e4d 100644 --- a/src/cargo/ops/cargo_compile/packages.rs +++ b/src/cargo/ops/cargo_compile/packages.rs @@ -59,7 +59,7 @@ impl Packages { .map(Package::package_id) .map(PackageIdSpec::from_package_id) .collect(); - let warn = |e| ws.config().shell().warn(e); + let warn = |e| ws.config().emit_diagnostic(e); emit_package_not_found(ws, names, true).or_else(warn)?; emit_pattern_not_found(ws, patterns, true).or_else(warn)?; specs diff --git a/src/cargo/ops/cargo_compile/unit_generator.rs b/src/cargo/ops/cargo_compile/unit_generator.rs index ce5a825fe3a..ef736af1570 100644 --- a/src/cargo/ops/cargo_compile/unit_generator.rs +++ b/src/cargo/ops/cargo_compile/unit_generator.rs @@ -361,7 +361,7 @@ impl<'a> UnitGenerator<'a, '_> { if self.mode.is_doc_test() && !target.doctestable() { let types = target.rustc_crate_types(); let types_str: Vec<&str> = types.iter().map(|t| t.as_str()).collect(); - self.ws.config().shell().warn(format!( + self.ws.config().emit_diagnostic(format!( "doc tests are not supported for crate type(s) `{}` in package `{}`", types_str.join(", "), pkg.name() @@ -487,9 +487,8 @@ impl<'a> UnitGenerator<'a, '_> { let skipped_examples = skipped_examples.into_inner(); if !skipped_examples.is_empty() { - let mut shell = self.ws.config().shell(); let example_str = skipped_examples.join(", "); - shell.warn(format!( + self.ws.config().emit_diagnostic(format!( "\ Rustdoc did not scrape the following examples because they require dev-dependencies: {example_str} If you want Rustdoc to scrape these examples, then add `doc-scrape-examples = true` @@ -505,7 +504,6 @@ Rustdoc did not scrape the following examples because they require dev-dependenc /// We want to emit a warning to make sure the user knows that this run is a no-op, /// and their code remains unchecked despite cargo not returning any errors fn unmatched_target_filters(&self, units: &[Unit]) -> CargoResult<()> { - let mut shell = self.ws.config().shell(); if let CompileFilter::Only { all_targets, lib: _, @@ -536,7 +534,7 @@ Rustdoc did not scrape the following examples because they require dev-dependenc filters.pop(); } - return shell.warn(format!( + return self.ws.config().emit_diagnostic(format!( "Target {}{} specified, but no targets matched. This is a no-op", if miss_count > 1 { "filters" } else { "filter" }, filters, @@ -562,13 +560,12 @@ Rustdoc did not scrape the following examples because they require dev-dependenc Some(resolve) => resolve, }; - let mut shell = self.ws.config().shell(); for feature in required_features { let fv = FeatureValue::new(feature.into()); match &fv { FeatureValue::Feature(f) => { if !summary.features().contains_key(f) { - shell.warn(format!( + self.ws.config().emit_diagnostic(format!( "invalid feature `{}` in required-features of target `{}`: \ `{}` is not present in [features] section", fv, target_name, fv @@ -607,7 +604,7 @@ Rustdoc did not scrape the following examples because they require dev-dependenc dep.name_in_toml() == *dep_feature && dep.is_optional() }) { - shell.warn(format!( + self.ws.config().emit_diagnostic(format!( "invalid feature `{}` in required-features of target `{}`: \ feature `{}` does not exist in package `{}`", fv, target_name, dep_feature, dep_id @@ -615,7 +612,7 @@ Rustdoc did not scrape the following examples because they require dev-dependenc } } None => { - shell.warn(format!( + self.ws.config().emit_diagnostic(format!( "invalid feature `{}` in required-features of target `{}`: \ dependency `{}` does not exist", fv, target_name, dep_name diff --git a/src/cargo/ops/cargo_doc.rs b/src/cargo/ops/cargo_doc.rs index afa6ac327d8..aa90f0ca786 100644 --- a/src/cargo/ops/cargo_doc.rs +++ b/src/cargo/ops/cargo_doc.rs @@ -1,4 +1,4 @@ -use crate::core::{Shell, Workspace}; +use crate::core::Workspace; use crate::ops; use crate::util::config::{Config, PathAndArgs}; use crate::util::CargoResult; @@ -35,9 +35,8 @@ pub fn doc(ws: &Workspace<'_>, options: &DocOptions) -> CargoResult<()> { cfg.map(|path_args| (path_args.path.resolve_program(ws.config()), path_args.args)) }; - let mut shell = ws.config().shell(); - shell.status("Opening", path.display())?; - open_docs(&path, &mut shell, config_browser, ws.config())?; + ws.config().shell().status("Opening", path.display())?; + open_docs(&path, config_browser, ws.config())?; } } @@ -46,7 +45,6 @@ pub fn doc(ws: &Workspace<'_>, options: &DocOptions) -> CargoResult<()> { fn open_docs( path: &Path, - shell: &mut Shell, config_browser: Option<(PathBuf, Vec)>, config: &Config, ) -> CargoResult<()> { @@ -56,7 +54,7 @@ fn open_docs( match browser { Some((browser, initial_args)) => { if let Err(e) = Command::new(&browser).args(initial_args).arg(path).status() { - shell.warn(format!( + config.emit_diagnostic(format!( "Couldn't open docs with {}: {}", browser.to_string_lossy(), e @@ -66,7 +64,7 @@ fn open_docs( None => { if let Err(e) = opener::open(&path) { let e = e.into(); - crate::display_warning_with_error("couldn't open docs", &e, shell); + crate::display_warning_with_error("couldn't open docs", &e, config); } } }; diff --git a/src/cargo/ops/cargo_generate_lockfile.rs b/src/cargo/ops/cargo_generate_lockfile.rs index fddf83f1998..585e77c62a3 100644 --- a/src/cargo/ops/cargo_generate_lockfile.rs +++ b/src/cargo/ops/cargo_generate_lockfile.rs @@ -159,8 +159,7 @@ pub fn update_lockfile(ws: &Workspace<'_>, opts: &UpdateOptions<'_>) -> CargoRes } if opts.dry_run { opts.config - .shell() - .warn("not updating lockfile due to dry run")?; + .emit_diagnostic("not updating lockfile due to dry run")?; } else { ops::write_pkg_lockfile(ws, &mut resolve)?; } diff --git a/src/cargo/ops/cargo_install.rs b/src/cargo/ops/cargo_install.rs index 8ddfa4fab3d..4ea95c55a0e 100644 --- a/src/cargo/ops/cargo_install.rs +++ b/src/cargo/ops/cargo_install.rs @@ -175,7 +175,7 @@ impl<'cfg, 'a> InstallablePackage<'cfg, 'a> { // If we're installing in --locked mode and there's no `Cargo.lock` published // ie. the bin was published before https://github.com/rust-lang/cargo/pull/7026 if config.locked() && !ws.root().join("Cargo.lock").exists() { - config.shell().warn(format!( + config.emit_diagnostic(format!( "no Cargo.lock file published in {}", pkg.to_string() ))?; @@ -201,7 +201,7 @@ impl<'cfg, 'a> InstallablePackage<'cfg, 'a> { if from_cwd { if pkg.manifest().edition() == Edition::Edition2015 { - config.shell().warn( + config.emit_diagnostic( "Using `cargo install` to install the binaries for the \ package in current working directory is deprecated, \ use `cargo install --path .` instead. \ @@ -378,8 +378,7 @@ impl<'cfg, 'a> InstallablePackage<'cfg, 'a> { .collect(); if !binaries.is_empty() { self.config - .shell() - .warn(make_warning_about_missing_features(&binaries))?; + .emit_diagnostic(make_warning_about_missing_features(&binaries))?; } return Ok(false); @@ -472,8 +471,7 @@ impl<'cfg, 'a> InstallablePackage<'cfg, 'a> { { // Don't hard error on remove. self.config - .shell() - .warn(format!("failed to remove orphan: {:?}", e))?; + .emit_diagnostic(format!("failed to remove orphan: {:?}", e))?; } match tracker.save() { @@ -717,7 +715,7 @@ pub fn install( let dst_in_path = env::split_paths(&path).any(|path| path == dst); if !dst_in_path { - config.shell().warn(&format!( + config.emit_diagnostic(&format!( "be sure to add `{}` to your PATH to be \ able to run the installed binaries", dst.display() diff --git a/src/cargo/ops/cargo_new.rs b/src/cargo/ops/cargo_new.rs index 0809cefc373..6b4424ffb55 100644 --- a/src/cargo/ops/cargo_new.rs +++ b/src/cargo/ops/cargo_new.rs @@ -1,4 +1,4 @@ -use crate::core::{Edition, Shell, Workspace}; +use crate::core::{Edition, Workspace}; use crate::util::errors::CargoResult; use crate::util::important_paths::find_root_manifest_for_wd; use crate::util::{existing_vcs_repo, FossilRepo, GitRepo, HgRepo, PijulRepo}; @@ -164,12 +164,7 @@ fn get_name<'a>(path: &'a Path, opts: &'a NewOptions) -> CargoResult<&'a str> { } /// See also `util::toml::embedded::sanitize_name` -fn check_name( - name: &str, - show_name_help: bool, - has_bin: bool, - shell: &mut Shell, -) -> CargoResult<()> { +fn check_name(name: &str, show_name_help: bool, has_bin: bool, config: &Config) -> CargoResult<()> { // If --name is already used to override, no point in suggesting it // again as a fix. let name_help = if show_name_help { @@ -214,7 +209,7 @@ fn check_name( name_help ); } else { - shell.warn(format!( + config.emit_diagnostic(format!( "the name `{}` will not support binary \ executables with that name, \ it conflicts with cargo's build directory names", @@ -230,7 +225,7 @@ fn check_name( ); } if ["core", "std", "alloc", "proc_macro", "proc-macro"].contains(&name) { - shell.warn(format!( + config.emit_diagnostic(format!( "the name `{}` is part of Rust's standard library\n\ It is recommended to use a different name to avoid problems.{}", name, @@ -245,7 +240,7 @@ fn check_name( name_help ); } else { - shell.warn(format!( + config.emit_diagnostic(format!( "the name `{}` is a reserved Windows filename\n\ This package will not work on Windows platforms.", name @@ -253,7 +248,7 @@ fn check_name( } } if restricted_names::is_non_ascii_name(name) { - shell.warn(format!( + config.emit_diagnostic(format!( "the name `{}` contains non-ASCII characters\n\ Non-ASCII crate names are not supported by Rust.", name @@ -264,11 +259,11 @@ fn check_name( } /// Checks if the path contains any invalid PATH env characters. -fn check_path(path: &Path, shell: &mut Shell) -> CargoResult<()> { +fn check_path(path: &Path, config: &Config) -> CargoResult<()> { // warn if the path contains characters that will break `env::join_paths` if let Err(_) = paths::join_paths(slice::from_ref(&OsStr::new(path)), "") { let path = path.to_string_lossy(); - shell.warn(format!( + config.emit_diagnostic(format!( "the path `{path}` contains invalid PATH characters (usually `:`, `;`, or `\"`)\n\ It is recommended to use a different name to avoid problems." ))?; @@ -436,12 +431,12 @@ pub fn new(opts: &NewOptions, config: &Config) -> CargoResult<()> { ) } - check_path(path, &mut config.shell())?; + check_path(path, config)?; let is_bin = opts.kind.is_bin(); let name = get_name(path, opts)?; - check_name(name, opts.name.is_none(), is_bin, &mut config.shell())?; + check_name(name, opts.name.is_none(), is_bin, config)?; let mkopts = MkOptions { version_control: opts.version_control, @@ -475,7 +470,7 @@ pub fn init(opts: &NewOptions, config: &Config) -> CargoResult { anyhow::bail!("`cargo init` cannot be run on existing Cargo packages") } - check_path(path, &mut config.shell())?; + check_path(path, config)?; let name = get_name(path, opts)?; @@ -495,7 +490,7 @@ pub fn init(opts: &NewOptions, config: &Config) -> CargoResult { } else { NewProjectKind::Lib }; - config.shell().warn(format!( + config.emit_diagnostic(format!( "file `{}` seems to be a {} file", src_paths_types[0].relative_path, file_type ))?; @@ -511,7 +506,7 @@ pub fn init(opts: &NewOptions, config: &Config) -> CargoResult { ) } - check_name(name, opts.name.is_none(), has_bin, &mut config.shell())?; + check_name(name, opts.name.is_none(), has_bin, config)?; let mut version_control = opts.version_control; @@ -889,7 +884,7 @@ mod tests { "compiling this new package may not work due to invalid \ workspace configuration", &e, - &mut config.shell(), + config, ); } diff --git a/src/cargo/ops/cargo_package.rs b/src/cargo/ops/cargo_package.rs index 93469607bc8..daf8790ef3a 100644 --- a/src/cargo/ops/cargo_package.rs +++ b/src/cargo/ops/cargo_package.rs @@ -10,7 +10,7 @@ use std::task::Poll; use crate::core::compiler::{BuildConfig, CompileMode, DefaultExecutor, Executor}; use crate::core::resolver::CliFeatures; use crate::core::{registry::PackageRegistry, resolver::HasDevUnits}; -use crate::core::{Feature, Shell, Verbosity, Workspace}; +use crate::core::{Feature, Verbosity, Workspace}; use crate::core::{Package, PackageId, PackageSet, Resolve, SourceId}; use crate::sources::PathSource; use crate::util::config::JobsConfig; @@ -95,7 +95,7 @@ pub fn package_one( } if !pkg.manifest().exclude().is_empty() && !pkg.manifest().include().is_empty() { - config.shell().warn( + config.emit_diagnostic( "both package.include and package.exclude are specified; \ the exclude list will be ignored", )?; @@ -233,7 +233,7 @@ fn build_ar_list( for src_file in &src_files { let rel_path = src_file.strip_prefix(&root)?; - check_filename(rel_path, &mut ws.config().shell())?; + check_filename(rel_path, ws.config())?; let rel_str = rel_path.to_str().ok_or_else(|| { anyhow::format_err!("non-utf8 path in source directory: {}", rel_path.display()) })?; @@ -276,7 +276,7 @@ fn build_ar_list( contents: FileContents::Generated(GeneratedFile::Manifest), }); } else { - ws.config().shell().warn(&format!( + ws.config().emit_diagnostic(&format!( "no `Cargo.toml` file found when packaging `{}` (note the case of the file name).", pkg.name() ))?; @@ -361,7 +361,7 @@ fn check_for_file_and_add( // The file exists somewhere outside of the package. let file_name = file_path.file_name().unwrap(); if result.iter().any(|ar| ar.rel_path == file_name) { - ws.config().shell().warn(&format!( + ws.config().emit_diagnostic(&format!( "{} `{}` appears to be a path outside of the package, \ but there is already a file named `{}` in the root of the package. \ The archived crate will contain the copy in the root of the package. \ @@ -395,7 +395,7 @@ fn warn_on_nonexistent_file( } else { format!(" (relative to `{}`)", pkg.root().display()) }; - ws.config().shell().warn(&format!( + ws.config().emit_diagnostic(&format!( "{manifest_key_name} `{}` does not appear to exist{}.\n\ Please update the {manifest_key_name} setting in the manifest at `{}`\n\ This may become a hard error in the future.", @@ -482,7 +482,7 @@ fn check_metadata(pkg: &Package, config: &Config) -> CargoResult<()> { } things.push_str(missing.last().unwrap()); - config.shell().warn(&format!( + config.emit_diagnostic(&format!( "manifest has no {things}.\n\ See https://doc.rust-lang.org/cargo/reference/manifest.html#package-metadata for more info.", things = things @@ -523,18 +523,15 @@ fn check_repo_state( })); } } - config.shell().verbose(|shell| { - shell.warn(format!( - "No (git) Cargo.toml found at `{}` in workdir `{}`", - path.display(), - workdir.display() - )) - })?; + config.emit_verbose_diagnostic(format!( + "No (git) Cargo.toml found at `{}` in workdir `{}`", + path.display(), + workdir.display() + ))?; } } else { - config.shell().verbose(|shell| { - shell.warn(format!("No (git) VCS found for `{}`", p.root().display())) - })?; + config + .emit_verbose_diagnostic(format!("No (git) VCS found for `{}`", p.root().display()))?; } // No VCS with a checked in `Cargo.toml` found, so we don't know if the @@ -828,7 +825,7 @@ pub fn check_yanked( for (pkg_id, is_yanked) in results { if is_yanked? { - config.shell().warn(format!( + config.emit_diagnostic(format!( "package `{}` in Cargo.lock is yanked in registry `{}`, {}", pkg_id, pkg_id.source_id().display_registry_name(), @@ -990,7 +987,7 @@ fn report_hash_difference(orig: &HashMap, after: &HashMap CargoResult<()> { +fn check_filename(file: &Path, config: &Config) -> CargoResult<()> { let name = match file.file_name() { Some(name) => name, None => return Ok(()), @@ -1012,7 +1009,7 @@ fn check_filename(file: &Path, shell: &mut Shell) -> CargoResult<()> { ) } if restricted_names::is_windows_reserved_path(file) { - shell.warn(format!( + config.emit_diagnostic(format!( "file {} is a reserved Windows filename, \ it will not work on Windows platforms", file.display() diff --git a/src/cargo/ops/cargo_read_manifest.rs b/src/cargo/ops/cargo_read_manifest.rs index d9daea5da2c..6bce1af243d 100644 --- a/src/cargo/ops/cargo_read_manifest.rs +++ b/src/cargo/ops/cargo_read_manifest.rs @@ -187,7 +187,7 @@ fn read_nested_packages( // by users so we can hide the warning about those since the user is unlikely // to care about those cases. if pkg.publish().is_none() { - let _ = config.shell().warn(format!( + let _ = config.emit_diagnostic(format!( "skipping duplicate package `{}` found at `{}`", pkg.name(), path.display() diff --git a/src/cargo/ops/cargo_remove.rs b/src/cargo/ops/cargo_remove.rs index 4866caeddac..3973ff5423b 100644 --- a/src/cargo/ops/cargo_remove.rs +++ b/src/cargo/ops/cargo_remove.rs @@ -55,8 +55,7 @@ pub fn remove(options: &RemoveOptions<'_>) -> CargoResult<()> { if options.dry_run { options .config - .shell() - .warn("aborting remove due to dry run")?; + .emit_diagnostic("aborting remove due to dry run")?; } else { manifest.write()?; } diff --git a/src/cargo/ops/registry/publish.rs b/src/cargo/ops/registry/publish.rs index 40ca9fd16f5..f3c63ccc808 100644 --- a/src/cargo/ops/registry/publish.rs +++ b/src/cargo/ops/registry/publish.rs @@ -250,7 +250,7 @@ fn wait_for_publish( let elapsed = now.elapsed(); if timeout < elapsed { - config.shell().warn(format!( + config.emit_diagnostic(format!( "timed out waiting for `{short_pkg_description}` to be available in {source_description}", ))?; config.shell().note( @@ -387,7 +387,7 @@ fn transmit( // Do not upload if performing a dry run if dry_run { - config.shell().warn("aborting upload due to dry run")?; + config.emit_diagnostic("aborting upload due to dry run")?; return Ok(()); } @@ -438,7 +438,7 @@ fn transmit( ", warnings.invalid_categories.join(", ") ); - config.shell().warn(&msg)?; + config.emit_diagnostic(&msg)?; } if !warnings.invalid_badges.is_empty() { @@ -450,12 +450,12 @@ fn transmit( for valid badge types and their required attributes.", warnings.invalid_badges.join(", ") ); - config.shell().warn(&msg)?; + config.emit_diagnostic(&msg)?; } if !warnings.other.is_empty() { for msg in warnings.other { - config.shell().warn(&msg)?; + config.emit_diagnostic(&msg)?; } } diff --git a/src/cargo/ops/resolve.rs b/src/cargo/ops/resolve.rs index 6246311a5c5..d4f4656c093 100644 --- a/src/cargo/ops/resolve.rs +++ b/src/cargo/ops/resolve.rs @@ -155,14 +155,11 @@ pub fn resolve_ws_with_opts<'cfg>( .any(|r| replace_spec.matches(r) && !dep.matches_id(r)) { ws.config() - .shell() - .warn(format!("package replacement is not used: {}", replace_spec))? + .emit_diagnostic(format!("package replacement is not used: {}", replace_spec))? } if dep.features().len() != 0 || !dep.uses_default_features() { - ws.config() - .shell() - .warn(format!( + ws.config().emit_diagnostic(format!( "replacement for `{}` uses the features mechanism. \ default-features and features will not take effect because the replacement dependency does not support this mechanism", dep.package_name() @@ -845,7 +842,7 @@ fn emit_warnings_of_unused_patches( for id in ids.iter() { write!(msg, "\n {}", id.display_registry_name())?; } - ws.config().shell().warn(msg)?; + ws.config().emit_diagnostic(msg)?; } _ => unemitted_unused_patches.push(unused), } @@ -857,9 +854,11 @@ fn emit_warnings_of_unused_patches( .iter() .map(|pkgid| format!("Patch `{}` {}", pkgid, MESSAGE)) .collect(); - ws.config() - .shell() - .warn(format!("{}\n{}", warnings.join("\n"), UNUSED_PATCH_WARNING))?; + ws.config().emit_diagnostic(format!( + "{}\n{}", + warnings.join("\n"), + UNUSED_PATCH_WARNING + ))?; } return Ok(()); diff --git a/src/cargo/ops/tree/mod.rs b/src/cargo/ops/tree/mod.rs index f397b95af6f..5715e132f6b 100644 --- a/src/cargo/ops/tree/mod.rs +++ b/src/cargo/ops/tree/mod.rs @@ -214,7 +214,7 @@ pub fn build_and_print(ws: &Workspace<'_>, opts: &TreeOptions) -> CargoResult<() .collect::>>()?; if root_indexes.len() == 0 { - ws.config().shell().warn( + ws.config().emit_diagnostic( "nothing to print.\n\n\ To find dependencies that require specific target platforms, \ try to use option `--target all` first, and then narrow your search scope accordingly.", diff --git a/src/cargo/sources/path.rs b/src/cargo/sources/path.rs index 1d8ffc35c8b..37a3747b537 100644 --- a/src/cargo/sources/path.rs +++ b/src/cargo/sources/path.rs @@ -462,7 +462,7 @@ impl<'cfg> PathSource<'cfg> { } } Err(err) if err.loop_ancestor().is_some() => { - self.config.shell().warn(err)?; + self.config.emit_diagnostic(err)?; } Err(err) => match err.path() { // If an error occurs with a path, filter it again. diff --git a/src/cargo/util/auth/mod.rs b/src/cargo/util/auth/mod.rs index 60a356fa093..6175a6dc214 100644 --- a/src/cargo/util/auth/mod.rs +++ b/src/cargo/util/auth/mod.rs @@ -110,14 +110,14 @@ fn credential_provider(config: &Config, sid: &SourceId) -> CargoResult { if let Some(token) = token { - config.shell().warn(format!( + config.emit_diagnostic(format!( "{sid} has a token configured in {} that will be ignored \ because a credential-provider is configured for this registry`", token.definition ))?; } if let Some(secret_key) = secret_key { - config.shell().warn(format!( + config.emit_diagnostic(format!( "{sid} has a secret-key configured in {} that will be ignored \ because a credential-provider is configured for this registry`", secret_key.definition @@ -141,14 +141,14 @@ fn credential_provider(config: &Config, sid: &SourceId) -> CargoResult { if token_pos < paseto_pos { - config.shell().warn(format!( + config.emit_diagnostic(format!( "{sid} has a `secret_key` configured in {} that will be ignored \ because a `token` is also configured, and the `cargo:token` provider is \ configured with higher precedence", secret_key.definition ))?; } else { - config.shell().warn(format!("{sid} has a `token` configured in {} that will be ignored \ + config.emit_diagnostic(format!("{sid} has a `token` configured in {} that will be ignored \ because a `secret_key` is also configured, and the `cargo:paseto` provider is \ configured with higher precedence", token.definition))?; } @@ -168,7 +168,7 @@ fn credential_provider(config: &Config, sid: &SourceId) -> CargoResult CargoResult { if self.flag("release") { - config.shell().warn( + config.emit_diagnostic( "the `--release` flag should not be specified with the `--profile` flag\n\ The `--release` flag will be ignored.\n\ This was historically accepted, but will become an error \ diff --git a/src/cargo/util/config/de.rs b/src/cargo/util/config/de.rs index a9147ab0306..9d1ba5f489a 100644 --- a/src/cargo/util/config/de.rs +++ b/src/cargo/util/config/de.rs @@ -249,7 +249,7 @@ impl<'config> ConfigMapAccess<'config> { .iter() .filter(|(k, _v)| !given_fields.iter().any(|gk| gk == k)); for (unused_key, unused_value) in unused_keys { - de.config.shell().warn(format!( + de.config.emit_diagnostic(format!( "unused config key `{}.{}` in `{}`", de.key, unused_key, diff --git a/src/cargo/util/config/mod.rs b/src/cargo/util/config/mod.rs index cf977d38d13..e460a1e2529 100644 --- a/src/cargo/util/config/mod.rs +++ b/src/cargo/util/config/mod.rs @@ -807,7 +807,7 @@ impl Config { fn check_environment_key_case_mismatch(&self, key: &ConfigKey) { if let Some(env_key) = self.env.get_normalized(key.as_env_key()) { - let _ = self.shell().warn(format!( + let _ = self.emit_diagnostic(format!( "Environment variables are expected to use uppercase letters and underscores, \ the variable `{}` will be ignored and have no effect", env_key @@ -983,7 +983,7 @@ impl Config { .unstable_flags .parse(unstable_flags, self.nightly_features_allowed)? { - self.shell().warn(warning)?; + self.emit_diagnostic(warning)?; } if !unstable_flags.is_empty() { // store a copy of the cli flags separately for `load_unstable_flags_from_config` @@ -1498,7 +1498,7 @@ impl Config { }; if !skip_warning { - self.shell().warn(format!( + self.emit_diagnostic(format!( "Both `{}` and `{}` exist. Using `{}`", possible.display(), possible_with_extension.display(), @@ -1949,6 +1949,33 @@ impl Config { } pub fn release_package_cache_lock(&self) {} + + /// Emit a diagnostic to the console. + pub fn emit_diagnostic(&self, diagnostic: T) -> CargoResult<()> { + let mut shell = self.shell(); + match shell.verbosity() { + Verbosity::Quiet => Ok(()), + _ => shell.print( + &"warning", + Some(&diagnostic), + termcolor::Color::Yellow, + false, + ), + } + } + + /// Emits a diagnostic only if the verbosity level is `Verbose`. This uses + /// [Config::emit_diagnostic] internally. + pub fn emit_verbose_diagnostic(&self, diagnostic: T) -> CargoResult<()> { + // If this is moved to the match statement below, it will cause an + // error, as shell will still be mutably borrowed, when calling + // `emit_diagnostic` below. + let verbosity = self.shell().verbosity(); + match verbosity { + Verbosity::Verbose => self.emit_diagnostic(diagnostic), + _ => Ok(()), + } + } } /// Internal error for serde errors. diff --git a/src/cargo/util/config/target.rs b/src/cargo/util/config/target.rs index b8aaf906d6f..0bfe9ea9602 100644 --- a/src/cargo/util/config/target.rs +++ b/src/cargo/util/config/target.rs @@ -53,7 +53,7 @@ pub(super) fn load_target_cfgs(config: &Config) -> CargoResult DiagnosticPrinter<'a> { } Message::ReplaceFailed { file, message } => { let msg = format!("error applying suggestions to `{}`\n", file); - self.config.shell().warn(&msg)?; + self.config.emit_diagnostic(&msg)?; write!( self.config.shell().err(), "The full error message was:\n\n> {}\n\n", @@ -146,15 +146,15 @@ impl<'a> DiagnosticPrinter<'a> { abnormal_exit, } => { if let Some(ref krate) = *krate { - self.config.shell().warn(&format!( + self.config.emit_diagnostic(&format!( "failed to automatically apply fixes suggested by rustc \ to crate `{}`", krate, ))?; } else { - self.config - .shell() - .warn("failed to automatically apply fixes suggested by rustc")?; + self.config.emit_diagnostic( + "failed to automatically apply fixes suggested by rustc", + )?; } if !files.is_empty() { writeln!( @@ -207,7 +207,7 @@ impl<'a> DiagnosticPrinter<'a> { message: "".to_string(), // Dummy, so that this only long-warns once. edition: *edition, }) { - self.config.shell().warn(&format!("\ + self.config.emit_diagnostic(&format!("\ {} If you are trying to migrate from the previous edition ({prev_edition}), the @@ -224,7 +224,7 @@ https://doc.rust-lang.org/edition-guide/editions/transitioning-an-existing-proje message, this_edition=edition, prev_edition=edition.previous().unwrap() )) } else { - self.config.shell().warn(message) + self.config.emit_diagnostic(message) } } } diff --git a/src/cargo/util/network/retry.rs b/src/cargo/util/network/retry.rs index 5cb7d1e4fbd..35261e522e2 100644 --- a/src/cargo/util/network/retry.rs +++ b/src/cargo/util/network/retry.rs @@ -52,7 +52,7 @@ impl<'a> Retry<'a> { "spurious network error ({} tries remaining): {err_msg}", self.max_retries - self.retries, ); - if let Err(e) = self.config.shell().warn(msg) { + if let Err(e) = self.config.emit_diagnostic(msg) { return RetryResult::Err(e); } self.retries += 1; diff --git a/src/cargo/util/toml/embedded.rs b/src/cargo/util/toml/embedded.rs index 395430c1b58..b9623686b74 100644 --- a/src/cargo/util/toml/embedded.rs +++ b/src/cargo/util/toml/embedded.rs @@ -83,7 +83,7 @@ fn expand_manifest_( .entry("version".to_owned()) .or_insert_with(|| toml::Value::String(DEFAULT_VERSION.to_owned())); package.entry("edition".to_owned()).or_insert_with(|| { - let _ = config.shell().warn(format_args!( + let _ = config.emit_diagnostic(format_args!( "`package.edition` is unspecified, defaulting to `{}`", DEFAULT_EDITION )); diff --git a/src/cargo/util/toml/mod.rs b/src/cargo/util/toml/mod.rs index 963c4afaa92..9bc4e1de201 100644 --- a/src/cargo/util/toml/mod.rs +++ b/src/cargo/util/toml/mod.rs @@ -1952,7 +1952,7 @@ impl TomlManifest { let mut package = match (&me.package, &me.project) { (Some(_), Some(project)) => { if source_id.is_path() { - config.shell().warn(format!( + config.emit_diagnostic(format!( "manifest at `{}` contains both `project` and `package`, \ this could become a hard error in the future", package_root.display() @@ -1963,7 +1963,7 @@ impl TomlManifest { (Some(package), None) => package.clone(), (None, Some(project)) => { if source_id.is_path() { - config.shell().warn(format!( + config.emit_diagnostic(format!( "manifest at `{}` contains `[project]` instead of `[package]`, \ this could become a hard error in the future", package_root.display()