Skip to content

Commit 767c947

Browse files
committed
Pass Clippy args also trough RUSTFLAGS
1 parent 6c70133 commit 767c947

File tree

4 files changed

+165
-52
lines changed

4 files changed

+165
-52
lines changed

README.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,6 @@ the lint(s) you are interested in:
208208
```terminal
209209
cargo clippy -- -A clippy::all -W clippy::useless_format -W clippy::...
210210
```
211-
Note that if you've run clippy before, this may only take effect after you've modified a file or ran `cargo clean`.
212211

213212
### Specifying the minimum supported Rust version
214213

src/driver.rs

Lines changed: 87 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#![feature(rustc_private)]
22
#![feature(once_cell)]
3+
#![feature(bool_to_option)]
34
#![cfg_attr(feature = "deny-warnings", deny(warnings))]
45
// warn on lints, that are included in `rust-lang/rust`s bootstrap
56
#![warn(rust_2018_idioms, unused_lifetimes)]
@@ -19,6 +20,7 @@ use rustc_tools_util::VersionInfo;
1920

2021
use std::borrow::Cow;
2122
use std::env;
23+
use std::iter;
2224
use std::lazy::SyncLazy;
2325
use std::ops::Deref;
2426
use std::panic;
@@ -47,20 +49,6 @@ fn arg_value<'a, T: Deref<Target = str>>(
4749
None
4850
}
4951

50-
#[test]
51-
fn test_arg_value() {
52-
let args = &["--bar=bar", "--foobar", "123", "--foo"];
53-
54-
assert_eq!(arg_value(&[] as &[&str], "--foobar", |_| true), None);
55-
assert_eq!(arg_value(args, "--bar", |_| false), None);
56-
assert_eq!(arg_value(args, "--bar", |_| true), Some("bar"));
57-
assert_eq!(arg_value(args, "--bar", |p| p == "bar"), Some("bar"));
58-
assert_eq!(arg_value(args, "--bar", |p| p == "foo"), None);
59-
assert_eq!(arg_value(args, "--foobar", |p| p == "foo"), None);
60-
assert_eq!(arg_value(args, "--foobar", |p| p == "123"), Some("123"));
61-
assert_eq!(arg_value(args, "--foo", |_| true), None);
62-
}
63-
6452
struct DefaultCallbacks;
6553
impl rustc_driver::Callbacks for DefaultCallbacks {}
6654

@@ -182,6 +170,28 @@ fn toolchain_path(home: Option<String>, toolchain: Option<String>) -> Option<Pat
182170
})
183171
}
184172

173+
fn remove_clippy_args<'a, T, U, I>(args: &mut Vec<T>, clippy_args: I)
174+
where
175+
T: AsRef<str>,
176+
U: AsRef<str> + ?Sized + 'a,
177+
I: Iterator<Item = &'a U> + Clone,
178+
{
179+
let args_iter = clippy_args.map(AsRef::as_ref);
180+
let args_count = args_iter.clone().count();
181+
182+
if args_count > 0 {
183+
if let Some(start) = args.windows(args_count).enumerate().find_map(|(current, window)| {
184+
window
185+
.iter()
186+
.map(AsRef::as_ref)
187+
.eq(args_iter.clone())
188+
.then_some(current)
189+
}) {
190+
args.drain(start..start + args_count);
191+
}
192+
}
193+
}
194+
185195
#[allow(clippy::too_many_lines)]
186196
pub fn main() {
187197
rustc_driver::init_rustc_env_logger();
@@ -278,20 +288,9 @@ pub fn main() {
278288
args.extend(vec!["--sysroot".into(), sys_root]);
279289
};
280290

281-
let mut no_deps = false;
282-
let clippy_args = env::var("CLIPPY_ARGS")
283-
.unwrap_or_default()
284-
.split("__CLIPPY_HACKERY__")
285-
.filter_map(|s| match s {
286-
"" => None,
287-
"--no-deps" => {
288-
no_deps = true;
289-
None
290-
},
291-
_ => Some(s.to_string()),
292-
})
293-
.chain(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()])
294-
.collect::<Vec<String>>();
291+
let clippy_args = env::var("CLIPPY_ARGS").unwrap_or_default();
292+
let clippy_args = clippy_args.split_whitespace();
293+
let no_deps = clippy_args.clone().any(|flag| flag == "--no-deps");
295294

296295
// We enable Clippy if one of the following conditions is met
297296
// - IF Clippy is run on its test suite OR
@@ -304,7 +303,11 @@ pub fn main() {
304303

305304
let clippy_enabled = clippy_tests_set || (!cap_lints_allow && (!no_deps || in_primary_package));
306305
if clippy_enabled {
307-
args.extend(clippy_args);
306+
remove_clippy_args(&mut args, iter::once("--no-deps"));
307+
args.extend(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()]);
308+
} else {
309+
// Remove all flags passed through RUSTFLAGS if Clippy is not enabled.
310+
remove_clippy_args(&mut args, clippy_args);
308311
}
309312

310313
let mut clippy = ClippyCallbacks;
@@ -315,3 +318,58 @@ pub fn main() {
315318
rustc_driver::RunCompiler::new(&args, callbacks).run()
316319
}))
317320
}
321+
322+
#[cfg(test)]
323+
mod tests {
324+
use super::*;
325+
326+
#[test]
327+
fn test_arg_value() {
328+
let args = &["--bar=bar", "--foobar", "123", "--foo"];
329+
330+
assert_eq!(arg_value(&[] as &[&str], "--foobar", |_| true), None);
331+
assert_eq!(arg_value(args, "--bar", |_| false), None);
332+
assert_eq!(arg_value(args, "--bar", |_| true), Some("bar"));
333+
assert_eq!(arg_value(args, "--bar", |p| p == "bar"), Some("bar"));
334+
assert_eq!(arg_value(args, "--bar", |p| p == "foo"), None);
335+
assert_eq!(arg_value(args, "--foobar", |p| p == "foo"), None);
336+
assert_eq!(arg_value(args, "--foobar", |p| p == "123"), Some("123"));
337+
assert_eq!(arg_value(args, "--foo", |_| true), None);
338+
}
339+
340+
#[test]
341+
fn removes_clippy_args_from_start() {
342+
let mut args = vec!["-D", "clippy::await_holding_lock", "--cfg", r#"feature="some_feat""#];
343+
let clippy_args = ["-D", "clippy::await_holding_lock"].iter();
344+
345+
remove_clippy_args(&mut args, clippy_args);
346+
assert_eq!(args, &["--cfg", r#"feature="some_feat""#]);
347+
}
348+
349+
#[test]
350+
fn removes_clippy_args_from_end() {
351+
let mut args = vec!["-Zui-testing", "-A", "clippy::empty_loop", "--no-deps"];
352+
let clippy_args = ["-A", "clippy::empty_loop", "--no-deps"].iter();
353+
354+
remove_clippy_args(&mut args, clippy_args);
355+
assert_eq!(args, &["-Zui-testing"]);
356+
}
357+
358+
#[test]
359+
fn removes_clippy_args_from_middle() {
360+
let mut args = vec!["-Zui-testing", "-W", "clippy::filter_map", "-L", "serde"];
361+
let clippy_args = ["-W", "clippy::filter_map"].iter();
362+
363+
remove_clippy_args(&mut args, clippy_args);
364+
assert_eq!(args, &["-Zui-testing", "-L", "serde"]);
365+
}
366+
367+
#[test]
368+
fn no_clippy_args_to_remove() {
369+
let mut args = vec!["-Zui-testing", "-L", "serde"];
370+
let clippy_args: [&str; 0] = [];
371+
372+
remove_clippy_args(&mut args, clippy_args.iter());
373+
assert_eq!(args, &["-Zui-testing", "-L", "serde"]);
374+
}
375+
}

src/main.rs

Lines changed: 77 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#![feature(bool_to_option)]
12
#![cfg_attr(feature = "deny-warnings", deny(warnings))]
23
// warn on lints, that are included in `rust-lang/rust`s bootstrap
34
#![warn(rust_2018_idioms, unused_lifetimes)]
@@ -62,11 +63,12 @@ struct ClippyCmd {
6263
unstable_options: bool,
6364
cargo_subcommand: &'static str,
6465
args: Vec<String>,
65-
clippy_args: Vec<String>,
66+
rustflags: Option<String>,
67+
clippy_args: Option<String>,
6668
}
6769

6870
impl ClippyCmd {
69-
fn new<I>(mut old_args: I) -> Self
71+
fn new<I>(mut old_args: I, rustflags: Option<String>) -> Self
7072
where
7173
I: Iterator<Item = String>,
7274
{
@@ -99,16 +101,19 @@ impl ClippyCmd {
99101
args.insert(0, "+nightly".to_string());
100102
}
101103

102-
let mut clippy_args: Vec<String> = old_args.collect();
103-
if cargo_subcommand == "fix" && !clippy_args.iter().any(|arg| arg == "--no-deps") {
104-
clippy_args.push("--no-deps".into());
104+
let mut clippy_args = old_args.collect::<Vec<String>>().join(" ");
105+
if cargo_subcommand == "fix" && !clippy_args.contains("--no-deps") {
106+
clippy_args = format!("{} --no-deps", clippy_args);
105107
}
106108

109+
let has_args = !clippy_args.is_empty();
107110
ClippyCmd {
108111
unstable_options,
109112
cargo_subcommand,
110113
args,
111-
clippy_args,
114+
rustflags: has_args
115+
.then(|| rustflags.map_or_else(|| clippy_args.clone(), |flags| format!("{} {}", clippy_args, flags))),
116+
clippy_args: has_args.then_some(clippy_args),
112117
}
113118
}
114119

@@ -150,18 +155,19 @@ impl ClippyCmd {
150155

151156
fn into_std_cmd(self) -> Command {
152157
let mut cmd = Command::new("cargo");
153-
let clippy_args: String = self
154-
.clippy_args
155-
.iter()
156-
.map(|arg| format!("{}__CLIPPY_HACKERY__", arg))
157-
.collect();
158158

159159
cmd.env(self.path_env(), Self::path())
160160
.envs(ClippyCmd::target_dir())
161-
.env("CLIPPY_ARGS", clippy_args)
162161
.arg(self.cargo_subcommand)
163162
.args(&self.args);
164163

164+
// HACK: pass Clippy args to the driver *also* through RUSTFLAGS.
165+
// This guarantees that new builds will be triggered when Clippy flags change.
166+
if let (Some(clippy_args), Some(rustflags)) = (self.clippy_args, self.rustflags) {
167+
cmd.env("CLIPPY_ARGS", clippy_args);
168+
cmd.env("RUSTFLAGS", rustflags);
169+
}
170+
165171
cmd
166172
}
167173
}
@@ -170,7 +176,7 @@ fn process<I>(old_args: I) -> Result<(), i32>
170176
where
171177
I: Iterator<Item = String>,
172178
{
173-
let cmd = ClippyCmd::new(old_args);
179+
let cmd = ClippyCmd::new(old_args, env::var("RUSTFLAGS").ok());
174180

175181
let mut cmd = cmd.into_std_cmd();
176182

@@ -195,15 +201,16 @@ mod tests {
195201
#[should_panic]
196202
fn fix_without_unstable() {
197203
let args = "cargo clippy --fix".split_whitespace().map(ToString::to_string);
198-
let _ = ClippyCmd::new(args);
204+
let _ = ClippyCmd::new(args, None);
199205
}
200206

201207
#[test]
202208
fn fix_unstable() {
203209
let args = "cargo clippy --fix -Zunstable-options"
204210
.split_whitespace()
205211
.map(ToString::to_string);
206-
let cmd = ClippyCmd::new(args);
212+
let cmd = ClippyCmd::new(args, None);
213+
207214
assert_eq!("fix", cmd.cargo_subcommand);
208215
assert_eq!("RUSTC_WORKSPACE_WRAPPER", cmd.path_env());
209216
assert!(cmd.args.iter().any(|arg| arg.ends_with("unstable-options")));
@@ -214,23 +221,26 @@ mod tests {
214221
let args = "cargo clippy --fix -Zunstable-options"
215222
.split_whitespace()
216223
.map(ToString::to_string);
217-
let cmd = ClippyCmd::new(args);
218-
assert!(cmd.clippy_args.iter().any(|arg| arg == "--no-deps"));
224+
let cmd = ClippyCmd::new(args, None);
225+
226+
assert!(cmd.clippy_args.unwrap().contains("--no-deps"));
219227
}
220228

221229
#[test]
222230
fn no_deps_not_duplicated_with_fix() {
223231
let args = "cargo clippy --fix -Zunstable-options -- --no-deps"
224232
.split_whitespace()
225233
.map(ToString::to_string);
226-
let cmd = ClippyCmd::new(args);
227-
assert_eq!(cmd.clippy_args.iter().filter(|arg| *arg == "--no-deps").count(), 1);
234+
let cmd = ClippyCmd::new(args, None);
235+
236+
assert_eq!(1, cmd.clippy_args.unwrap().matches("--no-deps").count());
228237
}
229238

230239
#[test]
231240
fn check() {
232241
let args = "cargo clippy".split_whitespace().map(ToString::to_string);
233-
let cmd = ClippyCmd::new(args);
242+
let cmd = ClippyCmd::new(args, None);
243+
234244
assert_eq!("check", cmd.cargo_subcommand);
235245
assert_eq!("RUSTC_WRAPPER", cmd.path_env());
236246
}
@@ -240,8 +250,54 @@ mod tests {
240250
let args = "cargo clippy -Zunstable-options"
241251
.split_whitespace()
242252
.map(ToString::to_string);
243-
let cmd = ClippyCmd::new(args);
253+
let cmd = ClippyCmd::new(args, None);
254+
244255
assert_eq!("check", cmd.cargo_subcommand);
245256
assert_eq!("RUSTC_WORKSPACE_WRAPPER", cmd.path_env());
246257
}
258+
259+
#[test]
260+
fn clippy_args_into_rustflags() {
261+
let args = "cargo clippy -- -W clippy::as_conversions"
262+
.split_whitespace()
263+
.map(ToString::to_string);
264+
let rustflags = None;
265+
let cmd = ClippyCmd::new(args, rustflags);
266+
267+
assert_eq!("-W clippy::as_conversions", cmd.rustflags.unwrap());
268+
}
269+
270+
#[test]
271+
fn clippy_args_respect_existing_rustflags() {
272+
let args = "cargo clippy -- -D clippy::await_holding_lock"
273+
.split_whitespace()
274+
.map(ToString::to_string);
275+
let rustflags = Some(r#"--cfg feature="some_feat""#.into());
276+
let cmd = ClippyCmd::new(args, rustflags);
277+
278+
assert_eq!(
279+
r#"-D clippy::await_holding_lock --cfg feature="some_feat""#,
280+
cmd.rustflags.unwrap()
281+
);
282+
}
283+
284+
#[test]
285+
fn no_env_change_if_no_clippy_args() {
286+
let args = "cargo clippy".split_whitespace().map(ToString::to_string);
287+
let rustflags = Some(r#"--cfg feature="some_feat""#.into());
288+
let cmd = ClippyCmd::new(args, rustflags);
289+
290+
assert!(cmd.clippy_args.is_none());
291+
assert!(cmd.rustflags.is_none());
292+
}
293+
294+
#[test]
295+
fn no_env_change_if_no_clippy_args_nor_rustflags() {
296+
let args = "cargo clippy".split_whitespace().map(ToString::to_string);
297+
let rustflags = None;
298+
let cmd = ClippyCmd::new(args, rustflags);
299+
300+
assert!(cmd.clippy_args.is_none());
301+
assert!(cmd.rustflags.is_none());
302+
}
247303
}

tests/dogfood.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ fn dogfood_clippy() {
2323
.current_dir(root_dir)
2424
.env("CLIPPY_DOGFOOD", "1")
2525
.env("CARGO_INCREMENTAL", "0")
26-
.arg("clippy-preview")
26+
.arg("clippy")
2727
.arg("--all-targets")
2828
.arg("--all-features")
2929
.arg("--")

0 commit comments

Comments
 (0)