mirror of
https://github.com/rust-lang/cargo.git
synced 2025-09-28 11:20:36 +00:00
Merge pull request #14388 from arlosi/warnings2
feat(warnings): add build.warnings option
This commit is contained in:
commit
d8cb5fb7f8
@ -122,6 +122,9 @@ pub struct Compilation<'gctx> {
|
||||
target_runners: HashMap<CompileKind, Option<(PathBuf, Vec<String>)>>,
|
||||
/// The linker to use for each host or target.
|
||||
target_linkers: HashMap<CompileKind, Option<PathBuf>>,
|
||||
|
||||
/// The total number of warnings emitted by the compilation.
|
||||
pub warning_count: usize,
|
||||
}
|
||||
|
||||
impl<'gctx> Compilation<'gctx> {
|
||||
@ -169,6 +172,7 @@ impl<'gctx> Compilation<'gctx> {
|
||||
.chain(Some(&CompileKind::Host))
|
||||
.map(|kind| Ok((*kind, target_linker(bcx, *kind)?)))
|
||||
.collect::<CargoResult<HashMap<_, _>>>()?,
|
||||
warning_count: 0,
|
||||
})
|
||||
}
|
||||
|
||||
|
@ -141,6 +141,7 @@ use crate::core::compiler::future_incompat::{
|
||||
};
|
||||
use crate::core::resolver::ResolveBehavior;
|
||||
use crate::core::{PackageId, Shell, TargetKind};
|
||||
use crate::util::context::WarningHandling;
|
||||
use crate::util::diagnostic_server::{self, DiagnosticPrinter};
|
||||
use crate::util::errors::AlreadyPrintedError;
|
||||
use crate::util::machine_message::{self, Message as _};
|
||||
@ -602,6 +603,7 @@ impl<'gctx> DrainState<'gctx> {
|
||||
plan: &mut BuildPlan,
|
||||
event: Message,
|
||||
) -> Result<(), ErrorToHandle> {
|
||||
let warning_handling = build_runner.bcx.gctx.warning_handling()?;
|
||||
match event {
|
||||
Message::Run(id, cmd) => {
|
||||
build_runner
|
||||
@ -639,7 +641,9 @@ impl<'gctx> DrainState<'gctx> {
|
||||
}
|
||||
}
|
||||
Message::Warning { id, warning } => {
|
||||
build_runner.bcx.gctx.shell().warn(warning)?;
|
||||
if warning_handling != WarningHandling::Allow {
|
||||
build_runner.bcx.gctx.shell().warn(warning)?;
|
||||
}
|
||||
self.bump_warning_count(id, true, false);
|
||||
}
|
||||
Message::WarningCount {
|
||||
@ -660,7 +664,7 @@ impl<'gctx> DrainState<'gctx> {
|
||||
trace!("end: {:?}", id);
|
||||
self.finished += 1;
|
||||
self.report_warning_count(
|
||||
build_runner.bcx.gctx,
|
||||
build_runner,
|
||||
id,
|
||||
&build_runner.bcx.rustc().workspace_wrapper,
|
||||
);
|
||||
@ -964,7 +968,7 @@ impl<'gctx> DrainState<'gctx> {
|
||||
}
|
||||
|
||||
fn emit_log_messages(
|
||||
&mut self,
|
||||
&self,
|
||||
unit: &Unit,
|
||||
build_runner: &mut BuildRunner<'_, '_>,
|
||||
show_warnings: bool,
|
||||
@ -1024,17 +1028,19 @@ impl<'gctx> DrainState<'gctx> {
|
||||
/// Displays a final report of the warnings emitted by a particular job.
|
||||
fn report_warning_count(
|
||||
&mut self,
|
||||
gctx: &GlobalContext,
|
||||
runner: &mut BuildRunner<'_, '_>,
|
||||
id: JobId,
|
||||
rustc_workspace_wrapper: &Option<PathBuf>,
|
||||
) {
|
||||
let count = match self.warning_count.remove(&id) {
|
||||
let gctx = runner.bcx.gctx;
|
||||
let count = match self.warning_count.get(&id) {
|
||||
// An error could add an entry for a `Unit`
|
||||
// with 0 warnings but having fixable
|
||||
// warnings be disallowed
|
||||
Some(count) if count.total > 0 => count,
|
||||
None | Some(_) => return,
|
||||
};
|
||||
runner.compilation.warning_count += count.total;
|
||||
let unit = &self.active[&id];
|
||||
let mut message = descriptive_pkg_name(&unit.pkg.name(), &unit.target, &unit.mode);
|
||||
message.push_str(" generated ");
|
||||
|
@ -91,6 +91,7 @@ pub use crate::core::compiler::unit::{Unit, UnitInterner};
|
||||
use crate::core::manifest::TargetSourcePath;
|
||||
use crate::core::profiles::{PanicStrategy, Profile, StripInner};
|
||||
use crate::core::{Feature, PackageId, Target, Verbosity};
|
||||
use crate::util::context::WarningHandling;
|
||||
use crate::util::errors::{CargoResult, VerboseError};
|
||||
use crate::util::interning::InternedString;
|
||||
use crate::util::machine_message::{self, Message};
|
||||
@ -202,13 +203,15 @@ fn compile<'gctx>(
|
||||
} else {
|
||||
// We always replay the output cache,
|
||||
// since it might contain future-incompat-report messages
|
||||
let show_diagnostics = unit.show_warnings(bcx.gctx)
|
||||
&& build_runner.bcx.gctx.warning_handling()? != WarningHandling::Allow;
|
||||
let work = replay_output_cache(
|
||||
unit.pkg.package_id(),
|
||||
PathBuf::from(unit.pkg.manifest_path()),
|
||||
&unit.target,
|
||||
build_runner.files().message_cache_path(unit),
|
||||
build_runner.bcx.build_config.message_format,
|
||||
unit.show_warnings(bcx.gctx),
|
||||
show_diagnostics,
|
||||
);
|
||||
// Need to link targets on both the dirty and fresh.
|
||||
work.then(link_targets(build_runner, unit, true)?)
|
||||
@ -1648,10 +1651,12 @@ impl OutputOptions {
|
||||
// Remove old cache, ignore ENOENT, which is the common case.
|
||||
drop(fs::remove_file(&path));
|
||||
let cache_cell = Some((path, LazyCell::new()));
|
||||
let show_diagnostics =
|
||||
build_runner.bcx.gctx.warning_handling().unwrap_or_default() != WarningHandling::Allow;
|
||||
OutputOptions {
|
||||
format: build_runner.bcx.build_config.message_format,
|
||||
cache_cell,
|
||||
show_diagnostics: true,
|
||||
show_diagnostics,
|
||||
warnings_seen: 0,
|
||||
errors_seen: 0,
|
||||
}
|
||||
|
@ -793,6 +793,7 @@ unstable_cli_options!(
|
||||
target_applies_to_host: bool = ("Enable the `target-applies-to-host` key in the .cargo/config.toml file"),
|
||||
trim_paths: bool = ("Enable the `trim-paths` option in profiles"),
|
||||
unstable_options: bool = ("Allow the usage of unstable options"),
|
||||
warnings: bool = ("Allow use of the build.warnings config key"),
|
||||
);
|
||||
|
||||
const STABILIZED_COMPILE_PROGRESS: &str = "The progress bar is now always \
|
||||
@ -1298,6 +1299,7 @@ impl CliUnstable {
|
||||
"script" => self.script = parse_empty(k, v)?,
|
||||
"target-applies-to-host" => self.target_applies_to_host = parse_empty(k, v)?,
|
||||
"unstable-options" => self.unstable_options = parse_empty(k, v)?,
|
||||
"warnings" => self.warnings = parse_empty(k, v)?,
|
||||
_ => bail!("\
|
||||
unknown `-Z` flag specified: {k}\n\n\
|
||||
For available unstable features, see https://doc.rust-lang.org/nightly/cargo/reference/unstable.html\n\
|
||||
|
@ -52,7 +52,7 @@ use crate::core::{PackageId, PackageSet, SourceId, TargetKind, Workspace};
|
||||
use crate::drop_println;
|
||||
use crate::ops;
|
||||
use crate::ops::resolve::WorkspaceResolve;
|
||||
use crate::util::context::GlobalContext;
|
||||
use crate::util::context::{GlobalContext, WarningHandling};
|
||||
use crate::util::interning::InternedString;
|
||||
use crate::util::{CargoResult, StableHasher};
|
||||
|
||||
@ -138,7 +138,11 @@ pub fn compile_with_exec<'a>(
|
||||
exec: &Arc<dyn Executor>,
|
||||
) -> CargoResult<Compilation<'a>> {
|
||||
ws.emit_warnings()?;
|
||||
compile_ws(ws, options, exec)
|
||||
let compilation = compile_ws(ws, options, exec)?;
|
||||
if ws.gctx().warning_handling()? == WarningHandling::Deny && compilation.warning_count > 0 {
|
||||
anyhow::bail!("warnings are denied by `build.warnings` configuration")
|
||||
}
|
||||
Ok(compilation)
|
||||
}
|
||||
|
||||
/// Like [`compile_with_exec`] but without warnings from manifest parsing.
|
||||
|
@ -2022,6 +2022,15 @@ impl GlobalContext {
|
||||
})?;
|
||||
Ok(deferred.borrow_mut())
|
||||
}
|
||||
|
||||
/// Get the global [`WarningHandling`] configuration.
|
||||
pub fn warning_handling(&self) -> CargoResult<WarningHandling> {
|
||||
if self.unstable_flags.warnings {
|
||||
Ok(self.build_config()?.warnings.unwrap_or_default())
|
||||
} else {
|
||||
Ok(WarningHandling::default())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal error for serde errors.
|
||||
@ -2633,6 +2642,20 @@ pub struct CargoBuildConfig {
|
||||
// deprecated alias for artifact-dir
|
||||
pub out_dir: Option<ConfigRelativePath>,
|
||||
pub artifact_dir: Option<ConfigRelativePath>,
|
||||
pub warnings: Option<WarningHandling>,
|
||||
}
|
||||
|
||||
/// Whether warnings should warn, be allowed, or cause an error.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize, Default)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum WarningHandling {
|
||||
#[default]
|
||||
/// Output warnings.
|
||||
Warn,
|
||||
/// Allow warnings (do not output them).
|
||||
Allow,
|
||||
/// Error if warnings are emitted.
|
||||
Deny,
|
||||
}
|
||||
|
||||
/// Configuration for `build.target`.
|
||||
|
@ -120,6 +120,7 @@ Each new feature described below should explain how to use it.
|
||||
* [lockfile-path](#lockfile-path) --- Allows to specify a path to lockfile other than the default path `<workspace_root>/Cargo.lock`.
|
||||
* [package-workspace](#package-workspace) --- Allows for packaging and publishing multiple crates in a workspace.
|
||||
* [native-completions](#native-completions) --- Move cargo shell completions to native completions.
|
||||
* [warnings](#warnings) --- controls warning behavior; options for allowing or denying warnings.
|
||||
|
||||
## allow-features
|
||||
|
||||
@ -1991,3 +1992,22 @@ default behavior.
|
||||
|
||||
See the [build script documentation](build-scripts.md#rustc-check-cfg) for information
|
||||
about specifying custom cfgs.
|
||||
|
||||
## warnings
|
||||
|
||||
The `-Z warnings` feature enables the `build.warnings` configuration option to control how
|
||||
Cargo handles warnings. If the `-Z warnings` unstable flag is not enabled, then
|
||||
the `build.warnings` config will be ignored.
|
||||
|
||||
This setting currently only applies to rustc warnings. It may apply to additional warnings (such as Cargo lints or Cargo warnings)
|
||||
in the future.
|
||||
|
||||
### `build.warnings`
|
||||
* Type: string
|
||||
* Default: `warn`
|
||||
* Environment: `CARGO_BUILD_WARNINGS`
|
||||
|
||||
Controls how Cargo handles warnings. Allowed values are:
|
||||
* `warn`: warnings are emitted as warnings (default).
|
||||
* `allow`: warnings are hidden.
|
||||
* `deny`: if warnings are emitted, an error will be raised at the end of the operation and the process will exit with a failure exit code.
|
||||
|
@ -1,4 +1,4 @@
|
||||
<svg width="1230px" height="758px" xmlns="http://www.w3.org/2000/svg">
|
||||
<svg width="1230px" height="776px" xmlns="http://www.w3.org/2000/svg">
|
||||
<style>
|
||||
.fg { fill: #AAAAAA }
|
||||
.bg { background: #000000 }
|
||||
@ -88,15 +88,17 @@
|
||||
</tspan>
|
||||
<tspan x="10px" y="658px"><tspan> -Z unstable-options Allow the usage of unstable options</tspan>
|
||||
</tspan>
|
||||
<tspan x="10px" y="676px">
|
||||
<tspan x="10px" y="676px"><tspan> -Z warnings Allow use of the build.warnings config key</tspan>
|
||||
</tspan>
|
||||
<tspan x="10px" y="694px"><tspan>Run with `cargo -Z [FLAG] [COMMAND]`</tspan>
|
||||
<tspan x="10px" y="694px">
|
||||
</tspan>
|
||||
<tspan x="10px" y="712px">
|
||||
<tspan x="10px" y="712px"><tspan>Run with `cargo -Z [FLAG] [COMMAND]`</tspan>
|
||||
</tspan>
|
||||
<tspan x="10px" y="730px"><tspan>See https://doc.rust-lang.org/nightly/cargo/reference/unstable.html for more information about these flags.</tspan>
|
||||
<tspan x="10px" y="730px">
|
||||
</tspan>
|
||||
<tspan x="10px" y="748px">
|
||||
<tspan x="10px" y="748px"><tspan>See https://doc.rust-lang.org/nightly/cargo/reference/unstable.html for more information about these flags.</tspan>
|
||||
</tspan>
|
||||
<tspan x="10px" y="766px">
|
||||
</tspan>
|
||||
</text>
|
||||
|
||||
|
Before Width: | Height: | Size: 5.9 KiB After Width: | Height: | Size: 6.0 KiB |
@ -182,6 +182,7 @@ mod vendor;
|
||||
mod verify_project;
|
||||
mod version;
|
||||
mod warn_on_failure;
|
||||
mod warning_override;
|
||||
mod weak_dep_features;
|
||||
mod workspaces;
|
||||
mod yank;
|
||||
|
221
tests/testsuite/warning_override.rs
Normal file
221
tests/testsuite/warning_override.rs
Normal file
@ -0,0 +1,221 @@
|
||||
//! Tests for overriding warning behavior using `build.warnings` config option.
|
||||
|
||||
use cargo_test_support::{cargo_test, project, str, tools, Project};
|
||||
|
||||
fn make_project_with_rustc_warning() -> Project {
|
||||
project()
|
||||
.file(
|
||||
"Cargo.toml",
|
||||
&format!(
|
||||
r#"
|
||||
[package]
|
||||
name = "foo"
|
||||
version = "0.0.1"
|
||||
edition = "2021"
|
||||
"#
|
||||
),
|
||||
)
|
||||
.file("src/main.rs", "fn main() { let x = 3; }")
|
||||
.build()
|
||||
}
|
||||
|
||||
#[cargo_test]
|
||||
fn rustc_caching_allow_first() {
|
||||
let p = make_project_with_rustc_warning();
|
||||
p.cargo("check")
|
||||
.masquerade_as_nightly_cargo(&["warnings"])
|
||||
.arg("-Zwarnings")
|
||||
.arg("--config")
|
||||
.arg("build.warnings='allow'")
|
||||
.with_stderr_data(str![[r#"
|
||||
[CHECKING] foo v0.0.1 ([ROOT]/foo)
|
||||
[FINISHED] `dev` profile [unoptimized + debuginfo] target(s) in [ELAPSED]s
|
||||
|
||||
"#]])
|
||||
.run();
|
||||
|
||||
p.cargo("check")
|
||||
.masquerade_as_nightly_cargo(&["warnings"])
|
||||
.arg("-Zwarnings")
|
||||
.arg("--config")
|
||||
.arg("build.warnings='deny'")
|
||||
.with_stderr_data(str![[r#"
|
||||
[WARNING] unused variable: `x`
|
||||
--> src/main.rs:1:17
|
||||
|
|
||||
1 | fn main() { let x = 3; }
|
||||
| ^ [HELP] if this is intentional, prefix it with an underscore: `_x`
|
||||
|
|
||||
= [NOTE] `#[warn(unused_variables)]` on by default
|
||||
|
||||
[WARNING] `foo` (bin "foo") generated 1 warning
|
||||
[FINISHED] `dev` profile [unoptimized + debuginfo] target(s) in [ELAPSED]s
|
||||
[ERROR] warnings are denied by `build.warnings` configuration
|
||||
|
||||
"#]])
|
||||
.with_status(101)
|
||||
.run();
|
||||
}
|
||||
|
||||
#[cargo_test]
|
||||
fn rustc_caching_deny_first() {
|
||||
let p = make_project_with_rustc_warning();
|
||||
p.cargo("check")
|
||||
.masquerade_as_nightly_cargo(&["warnings"])
|
||||
.arg("-Zwarnings")
|
||||
.arg("--config")
|
||||
.arg("build.warnings='deny'")
|
||||
.with_stderr_data(str![[r#"
|
||||
[CHECKING] foo v0.0.1 ([ROOT]/foo)
|
||||
[WARNING] unused variable: `x`
|
||||
--> src/main.rs:1:17
|
||||
|
|
||||
1 | fn main() { let x = 3; }
|
||||
| ^ [HELP] if this is intentional, prefix it with an underscore: `_x`
|
||||
|
|
||||
= [NOTE] `#[warn(unused_variables)]` on by default
|
||||
|
||||
[WARNING] `foo` (bin "foo") generated 1 warning
|
||||
[FINISHED] `dev` profile [unoptimized + debuginfo] target(s) in [ELAPSED]s
|
||||
[ERROR] warnings are denied by `build.warnings` configuration
|
||||
|
||||
"#]])
|
||||
.with_status(101)
|
||||
.run();
|
||||
|
||||
p.cargo("check")
|
||||
.masquerade_as_nightly_cargo(&["warnings"])
|
||||
.arg("-Zwarnings")
|
||||
.arg("--config")
|
||||
.arg("build.warnings='allow'")
|
||||
.with_stderr_data(str![[r#"
|
||||
[FINISHED] `dev` profile [unoptimized + debuginfo] target(s) in [ELAPSED]s
|
||||
|
||||
"#]])
|
||||
.run();
|
||||
}
|
||||
|
||||
#[cargo_test]
|
||||
fn config() {
|
||||
let p = make_project_with_rustc_warning();
|
||||
p.cargo("check")
|
||||
.masquerade_as_nightly_cargo(&["warnings"])
|
||||
.arg("-Zwarnings")
|
||||
.env("CARGO_BUILD_WARNINGS", "deny")
|
||||
.with_stderr_data(str![[r#"
|
||||
[CHECKING] foo v0.0.1 ([ROOT]/foo)
|
||||
[WARNING] unused variable: `x`
|
||||
--> src/main.rs:1:17
|
||||
|
|
||||
1 | fn main() { let x = 3; }
|
||||
| ^ [HELP] if this is intentional, prefix it with an underscore: `_x`
|
||||
|
|
||||
= [NOTE] `#[warn(unused_variables)]` on by default
|
||||
|
||||
[WARNING] `foo` (bin "foo") generated 1 warning
|
||||
[FINISHED] `dev` profile [unoptimized + debuginfo] target(s) in [ELAPSED]s
|
||||
[ERROR] warnings are denied by `build.warnings` configuration
|
||||
|
||||
"#]])
|
||||
.with_status(101)
|
||||
.run();
|
||||
|
||||
// CLI has precedence over env
|
||||
p.cargo("check")
|
||||
.masquerade_as_nightly_cargo(&["warnings"])
|
||||
.arg("-Zwarnings")
|
||||
.arg("--config")
|
||||
.arg("build.warnings='warn'")
|
||||
.env("CARGO_BUILD_WARNINGS", "deny")
|
||||
.with_stderr_data(str![[r#"
|
||||
[WARNING] unused variable: `x`
|
||||
--> src/main.rs:1:17
|
||||
|
|
||||
1 | fn main() { let x = 3; }
|
||||
| ^ [HELP] if this is intentional, prefix it with an underscore: `_x`
|
||||
|
|
||||
= [NOTE] `#[warn(unused_variables)]` on by default
|
||||
|
||||
[WARNING] `foo` (bin "foo") generated 1 warning
|
||||
[FINISHED] `dev` profile [unoptimized + debuginfo] target(s) in [ELAPSED]s
|
||||
|
||||
"#]])
|
||||
.run();
|
||||
}
|
||||
|
||||
#[cargo_test]
|
||||
fn requires_nightly() {
|
||||
// build.warnings has no effect without -Zwarnings.
|
||||
let p = make_project_with_rustc_warning();
|
||||
p.cargo("check")
|
||||
.arg("--config")
|
||||
.arg("build.warnings='deny'")
|
||||
.with_stderr_data(str![[r#"
|
||||
[CHECKING] foo v0.0.1 ([ROOT]/foo)
|
||||
[WARNING] unused variable: `x`
|
||||
--> src/main.rs:1:17
|
||||
|
|
||||
1 | fn main() { let x = 3; }
|
||||
| ^ [HELP] if this is intentional, prefix it with an underscore: `_x`
|
||||
|
|
||||
= [NOTE] `#[warn(unused_variables)]` on by default
|
||||
|
||||
[WARNING] `foo` (bin "foo") generated 1 warning
|
||||
[FINISHED] `dev` profile [unoptimized + debuginfo] target(s) in [ELAPSED]s
|
||||
|
||||
"#]])
|
||||
.run();
|
||||
}
|
||||
|
||||
#[cargo_test]
|
||||
fn clippy() {
|
||||
let p = project()
|
||||
.file(
|
||||
"Cargo.toml",
|
||||
r#"
|
||||
[package]
|
||||
name = "foo"
|
||||
version = "0.0.1"
|
||||
edition = "2015"
|
||||
"#,
|
||||
)
|
||||
.file("src/lib.rs", "use std::io;") // <-- unused import
|
||||
.build();
|
||||
|
||||
p.cargo("check")
|
||||
.masquerade_as_nightly_cargo(&["warnings"])
|
||||
.arg("-Zwarnings")
|
||||
.arg("--config")
|
||||
.arg("build.warnings='deny'")
|
||||
.env("RUSTC_WORKSPACE_WRAPPER", tools::wrapped_clippy_driver())
|
||||
.with_stderr_data(str![[r#"
|
||||
[CHECKING] foo v0.0.1 ([ROOT]/foo)
|
||||
[WARNING] unused import: `std::io`
|
||||
...
|
||||
[WARNING] `foo` (lib) generated 1 warning (run `cargo clippy --fix --lib -p foo` to apply 1 suggestion)
|
||||
[FINISHED] `dev` profile [unoptimized + debuginfo] target(s) in [ELAPSED]s
|
||||
[ERROR] warnings are denied by `build.warnings` configuration
|
||||
|
||||
"#]])
|
||||
.with_status(101)
|
||||
.run();
|
||||
}
|
||||
|
||||
#[cargo_test]
|
||||
fn unknown_value() {
|
||||
let p = make_project_with_rustc_warning();
|
||||
p.cargo("check")
|
||||
.masquerade_as_nightly_cargo(&["warnings"])
|
||||
.arg("-Zwarnings")
|
||||
.arg("--config")
|
||||
.arg("build.warnings='forbid'")
|
||||
.with_stderr_data(str![[r#"
|
||||
[ERROR] error in --config cli option: could not load config key `build.warnings`
|
||||
|
||||
Caused by:
|
||||
unknown variant `forbid`, expected one of `warn`, `allow`, `deny`
|
||||
|
||||
"#]])
|
||||
.with_status(101)
|
||||
.run();
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user