Skip to content

Commit a2d9925

Browse files
committedDec 9, 2020
Auto merge of #6188 - ebroto:primary_package, r=flip1995
Add --no-deps option to avoid running on path dependencies in workspaces Since rust-lang/cargo#8758 has hit nightly, this allows us to address the second bullet point and [the concern related to `--fix`](rust-lang/cargo#8143 (comment)) in the [RUSTC_WORKSPACE_WRAPPER tracking issue](rust-lang/cargo#8143). As a reminder stabilizing that env var will solve #4612 (Clippy not running after `cargo check` in stable) and would allow to stabilize the `--fix` option in Clippy. changelog: Add `--no-deps` option to avoid running on path dependencies in workspaces Fixes #3025
2 parents b02b0c7 + 952b731 commit a2d9925

File tree

7 files changed

+156
-19
lines changed

7 files changed

+156
-19
lines changed
 

‎README.md

+16
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,22 @@ Note that this is still experimental and only supported on the nightly channel:
8282
cargo clippy --fix -Z unstable-options
8383
```
8484

85+
#### Workspaces
86+
87+
All the usual workspace options should work with Clippy. For example the following command
88+
will run Clippy on the `example` crate:
89+
90+
```terminal
91+
cargo clippy -p example
92+
```
93+
94+
As with `cargo check`, this includes dependencies that are members of the workspace, like path dependencies.
95+
If you want to run Clippy **only** on the given crate, use the `--no-deps` option like this:
96+
97+
```terminal
98+
cargo clippy -p example -- --no-deps
99+
```
100+
85101
### Running Clippy from the command line without installing it
86102

87103
To have cargo compile your crate with Clippy without Clippy installation
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
[package]
2+
name = "path_dep"
3+
version = "0.1.0"
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
#![deny(clippy::empty_loop)]
2+
3+
#[cfg(feature = "primary_package_test")]
4+
pub fn lint_me() {
5+
loop {}
6+
}
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
11
[package]
22
name = "subcrate"
33
version = "0.1.0"
4+
5+
[dependencies]
6+
path_dep = { path = "../path_dep" }

‎src/driver.rs

+29-15
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,7 @@ fn toolchain_path(home: Option<String>, toolchain: Option<String>) -> Option<Pat
182182
})
183183
}
184184

185+
#[allow(clippy::too_many_lines)]
185186
pub fn main() {
186187
rustc_driver::init_rustc_env_logger();
187188
SyncLazy::force(&ICE_HOOK);
@@ -277,27 +278,40 @@ pub fn main() {
277278
args.extend(vec!["--sysroot".into(), sys_root]);
278279
};
279280

280-
// this check ensures that dependencies are built but not linted and the final
281-
// crate is linted but not built
282-
let clippy_enabled = env::var("CLIPPY_TESTS").map_or(false, |val| val == "true")
283-
|| arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_none();
284-
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>>();
295+
296+
// We enable Clippy if one of the following conditions is met
297+
// - IF Clippy is run on its test suite OR
298+
// - IF Clippy is run on the main crate, not on deps (`!cap_lints_allow`) THEN
299+
// - IF `--no-deps` is not set (`!no_deps`) OR
300+
// - IF `--no-deps` is set and Clippy is run on the specified primary package
301+
let clippy_tests_set = env::var("CLIPPY_TESTS").map_or(false, |val| val == "true");
302+
let cap_lints_allow = arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_some();
303+
let in_primary_package = env::var("CARGO_PRIMARY_PACKAGE").is_ok();
304+
305+
let clippy_enabled = clippy_tests_set || (!cap_lints_allow && (!no_deps || in_primary_package));
285306
if clippy_enabled {
286-
args.extend(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()]);
287-
if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
288-
args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
289-
if s.is_empty() {
290-
None
291-
} else {
292-
Some(s.to_string())
293-
}
294-
}));
295-
}
307+
args.extend(clippy_args);
296308
}
309+
297310
let mut clippy = ClippyCallbacks;
298311
let mut default = DefaultCallbacks;
299312
let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
300313
if clippy_enabled { &mut clippy } else { &mut default };
314+
301315
rustc_driver::RunCompiler::new(&args, callbacks).run()
302316
}))
303317
}

‎src/main.rs

+29-3
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ struct ClippyCmd {
6262
unstable_options: bool,
6363
cargo_subcommand: &'static str,
6464
args: Vec<String>,
65-
clippy_args: String,
65+
clippy_args: Vec<String>,
6666
}
6767

6868
impl ClippyCmd {
@@ -99,7 +99,10 @@ impl ClippyCmd {
9999
args.insert(0, "+nightly".to_string());
100100
}
101101

102-
let clippy_args: String = old_args.map(|arg| format!("{}__CLIPPY_HACKERY__", arg)).collect();
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());
105+
}
103106

104107
ClippyCmd {
105108
unstable_options,
@@ -147,10 +150,15 @@ impl ClippyCmd {
147150

148151
fn into_std_cmd(self) -> Command {
149152
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();
150158

151159
cmd.env(self.path_env(), Self::path())
152160
.envs(ClippyCmd::target_dir())
153-
.env("CLIPPY_ARGS", self.clippy_args)
161+
.env("CLIPPY_ARGS", clippy_args)
154162
.arg(self.cargo_subcommand)
155163
.args(&self.args);
156164

@@ -201,6 +209,24 @@ mod tests {
201209
assert!(cmd.args.iter().any(|arg| arg.ends_with("unstable-options")));
202210
}
203211

212+
#[test]
213+
fn fix_implies_no_deps() {
214+
let args = "cargo clippy --fix -Zunstable-options"
215+
.split_whitespace()
216+
.map(ToString::to_string);
217+
let cmd = ClippyCmd::new(args);
218+
assert!(cmd.clippy_args.iter().any(|arg| arg == "--no-deps"));
219+
}
220+
221+
#[test]
222+
fn no_deps_not_duplicated_with_fix() {
223+
let args = "cargo clippy --fix -Zunstable-options -- --no-deps"
224+
.split_whitespace()
225+
.map(ToString::to_string);
226+
let cmd = ClippyCmd::new(args);
227+
assert_eq!(cmd.clippy_args.iter().filter(|arg| *arg == "--no-deps").count(), 1);
228+
}
229+
204230
#[test]
205231
fn check() {
206232
let args = "cargo clippy".split_whitespace().map(ToString::to_string);

‎tests/dogfood.rs

+70-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
#![feature(once_cell)]
44

55
use std::lazy::SyncLazy;
6-
use std::path::PathBuf;
6+
use std::path::{Path, PathBuf};
77
use std::process::Command;
88

99
mod cargo;
@@ -47,12 +47,77 @@ fn dogfood_clippy() {
4747

4848
#[test]
4949
fn dogfood_subprojects() {
50+
fn test_no_deps_ignores_path_deps_in_workspaces() {
51+
fn clean(cwd: &Path, target_dir: &Path) {
52+
Command::new("cargo")
53+
.current_dir(cwd)
54+
.env("CARGO_TARGET_DIR", target_dir)
55+
.arg("clean")
56+
.args(&["-p", "subcrate"])
57+
.args(&["-p", "path_dep"])
58+
.output()
59+
.unwrap();
60+
}
61+
62+
if cargo::is_rustc_test_suite() {
63+
return;
64+
}
65+
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
66+
let target_dir = root.join("target").join("dogfood");
67+
let cwd = root.join("clippy_workspace_tests");
68+
69+
// Make sure we start with a clean state
70+
clean(&cwd, &target_dir);
71+
72+
// `path_dep` is a path dependency of `subcrate` that would trigger a denied lint.
73+
// Make sure that with the `--no-deps` argument Clippy does not run on `path_dep`.
74+
let output = Command::new(&*CLIPPY_PATH)
75+
.current_dir(&cwd)
76+
.env("CLIPPY_DOGFOOD", "1")
77+
.env("CARGO_INCREMENTAL", "0")
78+
.arg("clippy")
79+
.args(&["-p", "subcrate"])
80+
.arg("--")
81+
.arg("--no-deps")
82+
.arg("-Cdebuginfo=0") // disable debuginfo to generate less data in the target dir
83+
.args(&["--cfg", r#"feature="primary_package_test""#])
84+
.output()
85+
.unwrap();
86+
println!("status: {}", output.status);
87+
println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
88+
println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
89+
90+
assert!(output.status.success());
91+
92+
// Make sure we start with a clean state
93+
clean(&cwd, &target_dir);
94+
95+
// Test that without the `--no-deps` argument, `path_dep` is linted.
96+
let output = Command::new(&*CLIPPY_PATH)
97+
.current_dir(&cwd)
98+
.env("CLIPPY_DOGFOOD", "1")
99+
.env("CARGO_INCREMENTAL", "0")
100+
.arg("clippy")
101+
.args(&["-p", "subcrate"])
102+
.arg("--")
103+
.arg("-Cdebuginfo=0") // disable debuginfo to generate less data in the target dir
104+
.args(&["--cfg", r#"feature="primary_package_test""#])
105+
.output()
106+
.unwrap();
107+
println!("status: {}", output.status);
108+
println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
109+
println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
110+
111+
assert!(!output.status.success());
112+
}
113+
50114
// run clippy on remaining subprojects and fail the test if lint warnings are reported
51115
if cargo::is_rustc_test_suite() {
52116
return;
53117
}
54118
let root_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
55119

120+
// NOTE: `path_dep` crate is omitted on purpose here
56121
for d in &[
57122
"clippy_workspace_tests",
58123
"clippy_workspace_tests/src",
@@ -78,4 +143,8 @@ fn dogfood_subprojects() {
78143

79144
assert!(output.status.success());
80145
}
146+
147+
// NOTE: Since tests run in parallel we can't run cargo commands on the same workspace at the
148+
// same time, so we test this immediately after the dogfood for workspaces.
149+
test_no_deps_ignores_path_deps_in_workspaces();
81150
}

0 commit comments

Comments
 (0)
Please sign in to comment.