Skip to content

Commit f364c80

Browse files
committed
feat: add build.warnings config option to control rustc warnings
1 parent 4d16e0e commit f364c80

File tree

9 files changed

+164
-28
lines changed

9 files changed

+164
-28
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
@@ -90,6 +90,7 @@ pub use crate::core::compiler::unit::{Unit, UnitInterner};
9090
use crate::core::manifest::TargetSourcePath;
9191
use crate::core::profiles::{PanicStrategy, Profile, StripInner};
9292
use crate::core::{Feature, PackageId, Target, Verbosity};
93+
use crate::util::context::WarningHandling;
9394
use crate::util::errors::{CargoResult, VerboseError};
9495
use crate::util::interning::InternedString;
9596
use crate::util::machine_message::{self, Message};
@@ -201,13 +202,15 @@ fn compile<'gctx>(
201202
} else {
202203
// We always replay the output cache,
203204
// since it might contain future-incompat-report messages
205+
let show_diagnostics = unit.show_warnings(bcx.gctx)
206+
&& build_runner.bcx.gctx.warning_handling()? != WarningHandling::Allow;
204207
let work = replay_output_cache(
205208
unit.pkg.package_id(),
206209
PathBuf::from(unit.pkg.manifest_path()),
207210
&unit.target,
208211
build_runner.files().message_cache_path(unit),
209212
build_runner.bcx.build_config.message_format,
210-
unit.show_warnings(bcx.gctx),
213+
show_diagnostics,
211214
);
212215
// Need to link targets on both the dirty and fresh.
213216
work.then(link_targets(build_runner, unit, true)?)
@@ -1638,10 +1641,12 @@ impl OutputOptions {
16381641
// Remove old cache, ignore ENOENT, which is the common case.
16391642
drop(fs::remove_file(&path));
16401643
let cache_cell = Some((path, LazyCell::new()));
1644+
let show_diagnostics =
1645+
build_runner.bcx.gctx.warning_handling().unwrap_or_default() != WarningHandling::Allow;
16411646
OutputOptions {
16421647
format: build_runner.bcx.build_config.message_format,
16431648
cache_cell,
1644-
show_diagnostics: true,
1649+
show_diagnostics,
16451650
warnings_seen: 0,
16461651
errors_seen: 0,
16471652
}

src/cargo/core/features.rs

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

795796
const STABILIZED_COMPILE_PROGRESS: &str = "The progress bar is now always \
@@ -1293,6 +1294,7 @@ impl CliUnstable {
12931294
"script" => self.script = parse_empty(k, v)?,
12941295
"target-applies-to-host" => self.target_applies_to_host = parse_empty(k, v)?,
12951296
"unstable-options" => self.unstable_options = parse_empty(k, v)?,
1297+
"warnings" => self.warnings = parse_empty(k, v)?,
12961298
_ => bail!("\
12971299
unknown `-Z` flag specified: {k}\n\n\
12981300
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
@@ -2004,6 +2004,15 @@ impl GlobalContext {
20042004
})?;
20052005
Ok(deferred.borrow_mut())
20062006
}
2007+
2008+
/// Get the global [`WarningHandling`] configuration.
2009+
pub fn warning_handling(&self) -> CargoResult<WarningHandling> {
2010+
if self.unstable_flags.warnings {
2011+
Ok(self.build_config()?.warnings.unwrap_or_default())
2012+
} else {
2013+
Ok(Default::default())
2014+
}
2015+
}
20072016
}
20082017

20092018
/// Internal error for serde errors.
@@ -2615,6 +2624,20 @@ pub struct CargoBuildConfig {
26152624
// deprecated alias for artifact-dir
26162625
pub out_dir: Option<ConfigRelativePath>,
26172626
pub artifact_dir: Option<ConfigRelativePath>,
2627+
pub warnings: Option<WarningHandling>,
2628+
}
2629+
2630+
/// Whether warnings should warn, be allowed, or cause an error.
2631+
#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize, Default)]
2632+
#[serde(rename_all = "kebab-case")]
2633+
pub enum WarningHandling {
2634+
#[default]
2635+
/// Output warnings.
2636+
Warn,
2637+
/// Allow warnings (do not output them).
2638+
Allow,
2639+
/// Error if warnings are emitted.
2640+
Deny,
26182641
}
26192642

26202643
/// Configuration for `build.target`.

src/doc/src/reference/unstable.md

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

122123
## allow-features
123124

@@ -1974,3 +1975,22 @@ default behavior.
19741975

19751976
See the [build script documentation](build-scripts.md#rustc-check-cfg) for information
19761977
about specifying custom cfgs.
1978+
1979+
## warnings
1980+
1981+
The `-Z warnings` feature enables the `build.warnings` configuration option to control how
1982+
Cargo handles warnings. If the `-Z warnings` unstable flag is not enabled, then
1983+
the `build.warnings` config will be ignored.
1984+
1985+
This setting currently only applies to rustc warnings. It may apply to additional warnings (such as Cargo lints or Cargo warnings)
1986+
in the future.
1987+
1988+
### `build.warnings`
1989+
* Type: string
1990+
* Default: `warn`
1991+
* Environment: `CARGO_BUILD_WARNINGS`
1992+
1993+
Controls how Cargo handles warnings. Allowed values are:
1994+
* `warn`: warnings are emitted as warnings (default).
1995+
* `allow`: warnings are hidden.
1996+
* `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

0 commit comments

Comments
 (0)