]> git.lizzy.rs Git - rust.git/blob - src/main.rs
Merge remote-tracking branch 'upstream/master' into rustup
[rust.git] / src / main.rs
1 #![feature(bool_to_option)]
2 #![feature(command_access)]
3 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
4 // warn on lints, that are included in `rust-lang/rust`s bootstrap
5 #![warn(rust_2018_idioms, unused_lifetimes)]
6
7 use rustc_tools_util::VersionInfo;
8 use std::env;
9 use std::ffi::OsString;
10 use std::path::PathBuf;
11 use std::process::{self, Command};
12
13 const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code.
14
15 Usage:
16     cargo clippy [options] [--] [<opts>...]
17
18 Common options:
19     -h, --help               Print this message
20     -V, --version            Print version info and exit
21
22 Other options are the same as `cargo check`.
23
24 To allow or deny a lint from the command line you can use `cargo clippy --`
25 with:
26
27     -W --warn OPT       Set lint warnings
28     -A --allow OPT      Set lint allowed
29     -D --deny OPT       Set lint denied
30     -F --forbid OPT     Set lint forbidden
31
32 You can use tool lints to allow or deny lints from your code, eg.:
33
34     #[allow(clippy::needless_lifetimes)]
35 "#;
36
37 fn show_help() {
38     println!("{}", CARGO_CLIPPY_HELP);
39 }
40
41 fn show_version() {
42     let version_info = rustc_tools_util::get_version_info!();
43     println!("{}", version_info);
44 }
45
46 pub fn main() {
47     // Check for version and help flags even when invoked as 'cargo-clippy'
48     if env::args().any(|a| a == "--help" || a == "-h") {
49         show_help();
50         return;
51     }
52
53     if env::args().any(|a| a == "--version" || a == "-V") {
54         show_version();
55         return;
56     }
57
58     if let Err(code) = process(env::args().skip(2)) {
59         process::exit(code);
60     }
61 }
62
63 struct ClippyCmd {
64     unstable_options: bool,
65     cargo_subcommand: &'static str,
66     args: Vec<String>,
67     clippy_args: Option<String>,
68 }
69
70 impl ClippyCmd {
71     fn new<I>(mut old_args: I) -> Self
72     where
73         I: Iterator<Item = String>,
74     {
75         let mut cargo_subcommand = "check";
76         let mut unstable_options = false;
77         let mut args = vec![];
78
79         for arg in old_args.by_ref() {
80             match arg.as_str() {
81                 "--fix" => {
82                     cargo_subcommand = "fix";
83                     continue;
84                 },
85                 "--" => break,
86                 // Cover -Zunstable-options and -Z unstable-options
87                 s if s.ends_with("unstable-options") => unstable_options = true,
88                 _ => {},
89             }
90
91             args.push(arg);
92         }
93
94         if cargo_subcommand == "fix" && !unstable_options {
95             panic!("Usage of `--fix` requires `-Z unstable-options`");
96         }
97
98         // Run the dogfood tests directly on nightly cargo. This is required due
99         // to a bug in rustup.rs when running cargo on custom toolchains. See issue #3118.
100         if env::var_os("CLIPPY_DOGFOOD").is_some() && cfg!(windows) {
101             args.insert(0, "+nightly".to_string());
102         }
103
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);
107         }
108
109         let has_args = !clippy_args.is_empty();
110         ClippyCmd {
111             unstable_options,
112             cargo_subcommand,
113             args,
114             clippy_args: has_args.then_some(clippy_args),
115         }
116     }
117
118     fn path_env(&self) -> &'static str {
119         if self.unstable_options {
120             "RUSTC_WORKSPACE_WRAPPER"
121         } else {
122             "RUSTC_WRAPPER"
123         }
124     }
125
126     fn path() -> PathBuf {
127         let mut path = env::current_exe()
128             .expect("current executable path invalid")
129             .with_file_name("clippy-driver");
130
131         if cfg!(windows) {
132             path.set_extension("exe");
133         }
134
135         path
136     }
137
138     fn target_dir() -> Option<(&'static str, OsString)> {
139         env::var_os("CLIPPY_DOGFOOD")
140             .map(|_| {
141                 env::var_os("CARGO_MANIFEST_DIR").map_or_else(
142                     || std::ffi::OsString::from("clippy_dogfood"),
143                     |d| {
144                         std::path::PathBuf::from(d)
145                             .join("target")
146                             .join("dogfood")
147                             .into_os_string()
148                     },
149                 )
150             })
151             .map(|p| ("CARGO_TARGET_DIR", p))
152     }
153
154     fn into_std_cmd(self, rustflags: Option<String>) -> Command {
155         let mut cmd = Command::new("cargo");
156
157         cmd.env(self.path_env(), Self::path())
158             .envs(ClippyCmd::target_dir())
159             .arg(self.cargo_subcommand)
160             .args(&self.args);
161
162         // HACK: pass Clippy args to the driver *also* through RUSTFLAGS.
163         // This guarantees that new builds will be triggered when Clippy flags change.
164         if let Some(clippy_args) = self.clippy_args {
165             cmd.env(
166                 "RUSTFLAGS",
167                 rustflags.map_or(clippy_args.clone(), |flags| format!("{} {}", clippy_args, flags)),
168             );
169             cmd.env("CLIPPY_ARGS", clippy_args);
170         }
171
172         cmd
173     }
174 }
175
176 fn process<I>(old_args: I) -> Result<(), i32>
177 where
178     I: Iterator<Item = String>,
179 {
180     let cmd = ClippyCmd::new(old_args);
181
182     let mut cmd = cmd.into_std_cmd(env::var("RUSTFLAGS").ok());
183
184     let exit_status = cmd
185         .spawn()
186         .expect("could not run cargo")
187         .wait()
188         .expect("failed to wait for cargo?");
189
190     if exit_status.success() {
191         Ok(())
192     } else {
193         Err(exit_status.code().unwrap_or(-1))
194     }
195 }
196
197 #[cfg(test)]
198 mod tests {
199     use super::ClippyCmd;
200     use std::ffi::OsStr;
201
202     #[test]
203     #[should_panic]
204     fn fix_without_unstable() {
205         let args = "cargo clippy --fix".split_whitespace().map(ToString::to_string);
206         let _ = ClippyCmd::new(args);
207     }
208
209     #[test]
210     fn fix_unstable() {
211         let args = "cargo clippy --fix -Zunstable-options"
212             .split_whitespace()
213             .map(ToString::to_string);
214         let cmd = ClippyCmd::new(args);
215
216         assert_eq!("fix", cmd.cargo_subcommand);
217         assert_eq!("RUSTC_WORKSPACE_WRAPPER", cmd.path_env());
218         assert!(cmd.args.iter().any(|arg| arg.ends_with("unstable-options")));
219     }
220
221     #[test]
222     fn fix_implies_no_deps() {
223         let args = "cargo clippy --fix -Zunstable-options"
224             .split_whitespace()
225             .map(ToString::to_string);
226         let cmd = ClippyCmd::new(args);
227
228         assert!(cmd.clippy_args.unwrap().contains("--no-deps"));
229     }
230
231     #[test]
232     fn no_deps_not_duplicated_with_fix() {
233         let args = "cargo clippy --fix -Zunstable-options -- --no-deps"
234             .split_whitespace()
235             .map(ToString::to_string);
236         let cmd = ClippyCmd::new(args);
237
238         assert_eq!(1, cmd.clippy_args.unwrap().matches("--no-deps").count());
239     }
240
241     #[test]
242     fn check() {
243         let args = "cargo clippy".split_whitespace().map(ToString::to_string);
244         let cmd = ClippyCmd::new(args);
245
246         assert_eq!("check", cmd.cargo_subcommand);
247         assert_eq!("RUSTC_WRAPPER", cmd.path_env());
248     }
249
250     #[test]
251     fn check_unstable() {
252         let args = "cargo clippy -Zunstable-options"
253             .split_whitespace()
254             .map(ToString::to_string);
255         let cmd = ClippyCmd::new(args);
256
257         assert_eq!("check", cmd.cargo_subcommand);
258         assert_eq!("RUSTC_WORKSPACE_WRAPPER", cmd.path_env());
259     }
260
261     #[test]
262     fn clippy_args_into_rustflags() {
263         let args = "cargo clippy -- -W clippy::as_conversions"
264             .split_whitespace()
265             .map(ToString::to_string);
266         let cmd = ClippyCmd::new(args);
267
268         let rustflags = None;
269         let cmd = cmd.into_std_cmd(rustflags);
270
271         assert!(cmd
272             .get_envs()
273             .any(|(key, val)| key == "RUSTFLAGS" && val == Some(OsStr::new("-W clippy::as_conversions"))));
274     }
275
276     #[test]
277     fn clippy_args_respect_existing_rustflags() {
278         let args = "cargo clippy -- -D clippy::await_holding_lock"
279             .split_whitespace()
280             .map(ToString::to_string);
281         let cmd = ClippyCmd::new(args);
282
283         let rustflags = Some(r#"--cfg feature="some_feat""#.into());
284         let cmd = cmd.into_std_cmd(rustflags);
285
286         assert!(cmd.get_envs().any(|(key, val)| key == "RUSTFLAGS"
287             && val == Some(OsStr::new(r#"-D clippy::await_holding_lock --cfg feature="some_feat""#))));
288     }
289
290     #[test]
291     fn no_env_change_if_no_clippy_args() {
292         let args = "cargo clippy".split_whitespace().map(ToString::to_string);
293         let cmd = ClippyCmd::new(args);
294
295         let rustflags = Some(r#"--cfg feature="some_feat""#.into());
296         let cmd = cmd.into_std_cmd(rustflags);
297
298         assert!(!cmd
299             .get_envs()
300             .any(|(key, _)| key == "RUSTFLAGS" || key == "CLIPPY_ARGS"));
301     }
302
303     #[test]
304     fn no_env_change_if_no_clippy_args_nor_rustflags() {
305         let args = "cargo clippy".split_whitespace().map(ToString::to_string);
306         let cmd = ClippyCmd::new(args);
307
308         let rustflags = None;
309         let cmd = cmd.into_std_cmd(rustflags);
310
311         assert!(!cmd
312             .get_envs()
313             .any(|(key, _)| key == "RUSTFLAGS" || key == "CLIPPY_ARGS"))
314     }
315 }