Skip to content

Commit ff472b6

Browse files
committed
feat: add build.warnings config option to control rustc warnings
1 parent 41820c3 commit ff472b6

File tree

10 files changed

+176
-40
lines changed

10 files changed

+176
-40
lines changed

src/cargo/core/compiler/compilation.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,9 @@ pub struct Compilation<'gctx> {
122122
target_runners: HashMap<CompileKind, Option<(PathBuf, Vec<String>)>>,
123123
/// The linker to use for each host or target.
124124
target_linkers: HashMap<CompileKind, Option<PathBuf>>,
125+
126+
/// The total number of warnings emitted by the compilation.
127+
pub warning_count: usize,
125128
}
126129

127130
impl<'gctx> Compilation<'gctx> {
@@ -169,6 +172,7 @@ impl<'gctx> Compilation<'gctx> {
169172
.chain(Some(&CompileKind::Host))
170173
.map(|kind| Ok((*kind, target_linker(bcx, *kind)?)))
171174
.collect::<CargoResult<HashMap<_, _>>>()?,
175+
warning_count: 0,
172176
})
173177
}
174178

src/cargo/core/compiler/job_queue/mod.rs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,7 @@ use crate::core::compiler::future_incompat::{
140140
};
141141
use crate::core::resolver::ResolveBehavior;
142142
use crate::core::{PackageId, Shell, TargetKind};
143+
use crate::util::context::WarningHandling;
143144
use crate::util::diagnostic_server::{self, DiagnosticPrinter};
144145
use crate::util::errors::AlreadyPrintedError;
145146
use crate::util::machine_message::{self, Message as _};
@@ -601,6 +602,7 @@ impl<'gctx> DrainState<'gctx> {
601602
plan: &mut BuildPlan,
602603
event: Message,
603604
) -> Result<(), ErrorToHandle> {
605+
let warning_handling = build_runner.bcx.gctx.warning_handling()?;
604606
match event {
605607
Message::Run(id, cmd) => {
606608
build_runner
@@ -638,7 +640,9 @@ impl<'gctx> DrainState<'gctx> {
638640
}
639641
}
640642
Message::Warning { id, warning } => {
641-
build_runner.bcx.gctx.shell().warn(warning)?;
643+
if warning_handling != WarningHandling::Allow {
644+
build_runner.bcx.gctx.shell().warn(warning)?;
645+
}
642646
self.bump_warning_count(id, true, false);
643647
}
644648
Message::WarningCount {
@@ -659,7 +663,7 @@ impl<'gctx> DrainState<'gctx> {
659663
trace!("end: {:?}", id);
660664
self.finished += 1;
661665
self.report_warning_count(
662-
build_runner.bcx.gctx,
666+
build_runner,
663667
id,
664668
&build_runner.bcx.rustc().workspace_wrapper,
665669
);
@@ -1019,17 +1023,19 @@ impl<'gctx> DrainState<'gctx> {
10191023
/// Displays a final report of the warnings emitted by a particular job.
10201024
fn report_warning_count(
10211025
&mut self,
1022-
gctx: &GlobalContext,
1026+
runner: &mut BuildRunner<'_, '_>,
10231027
id: JobId,
10241028
rustc_workspace_wrapper: &Option<PathBuf>,
10251029
) {
1026-
let count = match self.warning_count.remove(&id) {
1030+
let gctx = runner.bcx.gctx;
1031+
let count = match self.warning_count.get(&id) {
10271032
// An error could add an entry for a `Unit`
10281033
// with 0 warnings but having fixable
10291034
// warnings be disallowed
10301035
Some(count) if count.total > 0 => count,
10311036
None | Some(_) => return,
10321037
};
1038+
runner.compilation.warning_count += count.total;
10331039
let unit = &self.active[&id];
10341040
let mut message = descriptive_pkg_name(&unit.pkg.name(), &unit.target, &unit.mode);
10351041
message.push_str(" generated ");

src/cargo/core/compiler/mod.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ pub use crate::core::compiler::unit::{Unit, UnitInterner};
9191
use crate::core::manifest::TargetSourcePath;
9292
use crate::core::profiles::{PanicStrategy, Profile, StripInner};
9393
use crate::core::{Feature, PackageId, Target, Verbosity};
94+
use crate::util::context::WarningHandling;
9495
use crate::util::errors::{CargoResult, VerboseError};
9596
use crate::util::interning::InternedString;
9697
use crate::util::machine_message::{self, Message};
@@ -202,13 +203,15 @@ fn compile<'gctx>(
202203
} else {
203204
// We always replay the output cache,
204205
// since it might contain future-incompat-report messages
206+
let show_diagnostics = unit.show_warnings(bcx.gctx)
207+
&& build_runner.bcx.gctx.warning_handling()? != WarningHandling::Allow;
205208
let work = replay_output_cache(
206209
unit.pkg.package_id(),
207210
PathBuf::from(unit.pkg.manifest_path()),
208211
&unit.target,
209212
build_runner.files().message_cache_path(unit),
210213
build_runner.bcx.build_config.message_format,
211-
unit.show_warnings(bcx.gctx),
214+
show_diagnostics,
212215
);
213216
// Need to link targets on both the dirty and fresh.
214217
work.then(link_targets(build_runner, unit, true)?)
@@ -1657,10 +1660,12 @@ impl OutputOptions {
16571660
// Remove old cache, ignore ENOENT, which is the common case.
16581661
drop(fs::remove_file(&path));
16591662
let cache_cell = Some((path, LazyCell::new()));
1663+
let show_diagnostics =
1664+
build_runner.bcx.gctx.warning_handling().unwrap_or_default() != WarningHandling::Allow;
16601665
OutputOptions {
16611666
format: build_runner.bcx.build_config.message_format,
16621667
cache_cell,
1663-
show_diagnostics: true,
1668+
show_diagnostics,
16641669
warnings_seen: 0,
16651670
errors_seen: 0,
16661671
}

src/cargo/core/features.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -791,6 +791,7 @@ unstable_cli_options!(
791791
target_applies_to_host: bool = ("Enable the `target-applies-to-host` key in the .cargo/config.toml file"),
792792
trim_paths: bool = ("Enable the `trim-paths` option in profiles"),
793793
unstable_options: bool = ("Allow the usage of unstable options"),
794+
warnings: bool = ("Allow use of the build.warnings config key"),
794795
);
795796

796797
const STABILIZED_COMPILE_PROGRESS: &str = "The progress bar is now always \
@@ -1295,6 +1296,7 @@ impl CliUnstable {
12951296
"script" => self.script = parse_empty(k, v)?,
12961297
"target-applies-to-host" => self.target_applies_to_host = parse_empty(k, v)?,
12971298
"unstable-options" => self.unstable_options = parse_empty(k, v)?,
1299+
"warnings" => self.warnings = parse_empty(k, v)?,
12981300
_ => bail!("\
12991301
unknown `-Z` flag specified: {k}\n\n\
13001302
For available unstable features, see https://doc.rust-lang.org/nightly/cargo/reference/unstable.html\n\

src/cargo/ops/cargo_compile/mod.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ use crate::core::{PackageId, PackageSet, SourceId, TargetKind, Workspace};
5252
use crate::drop_println;
5353
use crate::ops;
5454
use crate::ops::resolve::WorkspaceResolve;
55-
use crate::util::context::GlobalContext;
55+
use crate::util::context::{GlobalContext, WarningHandling};
5656
use crate::util::interning::InternedString;
5757
use crate::util::{CargoResult, StableHasher};
5858

@@ -138,7 +138,11 @@ pub fn compile_with_exec<'a>(
138138
exec: &Arc<dyn Executor>,
139139
) -> CargoResult<Compilation<'a>> {
140140
ws.emit_warnings()?;
141-
compile_ws(ws, options, exec)
141+
let compilation = compile_ws(ws, options, exec)?;
142+
if ws.gctx().warning_handling()? == WarningHandling::Deny && compilation.warning_count > 0 {
143+
anyhow::bail!("warnings are denied by `build.warnings` configuration")
144+
}
145+
Ok(compilation)
142146
}
143147

144148
/// Like [`compile_with_exec`] but without warnings from manifest parsing.

src/cargo/util/context/mod.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2009,6 +2009,15 @@ impl GlobalContext {
20092009
})?;
20102010
Ok(deferred.borrow_mut())
20112011
}
2012+
2013+
/// Get the global [`WarningHandling`] configuration.
2014+
pub fn warning_handling(&self) -> CargoResult<WarningHandling> {
2015+
if self.unstable_flags.warnings {
2016+
Ok(self.build_config()?.warnings.unwrap_or_default())
2017+
} else {
2018+
Ok(Default::default())
2019+
}
2020+
}
20122021
}
20132022

20142023
/// Internal error for serde errors.
@@ -2620,6 +2629,20 @@ pub struct CargoBuildConfig {
26202629
// deprecated alias for artifact-dir
26212630
pub out_dir: Option<ConfigRelativePath>,
26222631
pub artifact_dir: Option<ConfigRelativePath>,
2632+
pub warnings: Option<WarningHandling>,
2633+
}
2634+
2635+
/// Whether warnings should warn, be allowed, or cause an error.
2636+
#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize, Default)]
2637+
#[serde(rename_all = "kebab-case")]
2638+
pub enum WarningHandling {
2639+
#[default]
2640+
/// Output warnings.
2641+
Warn,
2642+
/// Allow warnings (do not output them).
2643+
Allow,
2644+
/// Error if warnings are emitted.
2645+
Deny,
26232646
}
26242647

26252648
/// Configuration for `build.target`.

src/doc/src/reference/unstable.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@ Each new feature described below should explain how to use it.
119119
* [lockfile-path](#lockfile-path) --- Allows to specify a path to lockfile other than the default path `<workspace_root>/Cargo.lock`.
120120
* [package-workspace](#package-workspace) --- Allows for packaging and publishing multiple crates in a workspace.
121121
* [native-completions](#native-completions) --- Move cargo shell completions to native completions.
122+
* [warnings](#warnings) --- controls warning behavior; options for allowing or denying warnings.
122123

123124
## allow-features
124125

@@ -2012,3 +2013,22 @@ default behavior.
20122013

20132014
See the [build script documentation](build-scripts.md#rustc-check-cfg) for information
20142015
about specifying custom cfgs.
2016+
2017+
## warnings
2018+
2019+
The `-Z warnings` feature enables the `build.warnings` configuration option to control how
2020+
Cargo handles warnings. If the `-Z warnings` unstable flag is not enabled, then
2021+
the `build.warnings` config will be ignored.
2022+
2023+
This setting currently only applies to rustc warnings. It may apply to additional warnings (such as Cargo lints or Cargo warnings)
2024+
in the future.
2025+
2026+
### `build.warnings`
2027+
* Type: string
2028+
* Default: `warn`
2029+
* Environment: `CARGO_BUILD_WARNINGS`
2030+
2031+
Controls how Cargo handles warnings. Allowed values are:
2032+
* `warn`: warnings are emitted as warnings (default).
2033+
* `allow`: warnings are hidden.
2034+
* `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.

tests/testsuite/cargo/z_help/stdout.term.svg

Lines changed: 8 additions & 6 deletions
Loading

tests/testsuite/fix.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1677,13 +1677,13 @@ fn abnormal_exit() {
16771677
)
16781678
// "signal: 6, SIGABRT: process abort signal" on some platforms
16791679
.with_stderr_data(str![[r#"
1680-
...
1681-
[WARNING] failed to automatically apply fixes suggested by rustc to crate `foo`
1682-
...
1680+
[LOCKING] 1 package to latest compatible version
1681+
[COMPILING] pm v0.1.0 ([ROOT]/foo/pm)
1682+
[CHECKING] foo v0.1.0 ([ROOT]/foo)
1683+
[FIXED] src/lib.rs (1 fix)
16831684
I'm not a diagnostic.
1684-
rustc exited abnormally: [..]
1685-
Original diagnostics will follow.
1686-
...
1685+
[FINISHED] `dev` profile [unoptimized + debuginfo] target(s) in [ELAPSED]s
1686+
16871687
"#]])
16881688
.run();
16891689
}

0 commit comments

Comments
 (0)