]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/src/main.rs
Auto merge of #86778 - tmiasko:fast-multiline, r=davidtwco
[rust.git] / src / tools / clippy / src / main.rs
1 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
2 // warn on lints, that are included in `rust-lang/rust`s bootstrap
3 #![warn(rust_2018_idioms, unused_lifetimes)]
4
5 use rustc_tools_util::VersionInfo;
6 use std::env;
7 use std::ffi::OsString;
8 use std::path::PathBuf;
9 use std::process::{self, Command};
10
11 const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code.
12
13 Usage:
14     cargo clippy [options] [--] [<opts>...]
15
16 Common options:
17     -h, --help               Print this message
18     -V, --version            Print version info and exit
19
20 Other options are the same as `cargo check`.
21
22 To allow or deny a lint from the command line you can use `cargo clippy --`
23 with:
24
25     -W --warn OPT       Set lint warnings
26     -A --allow OPT      Set lint allowed
27     -D --deny OPT       Set lint denied
28     -F --forbid OPT     Set lint forbidden
29
30 You can use tool lints to allow or deny lints from your code, eg.:
31
32     #[allow(clippy::needless_lifetimes)]
33 "#;
34
35 fn show_help() {
36     println!("{}", CARGO_CLIPPY_HELP);
37 }
38
39 fn show_version() {
40     let version_info = rustc_tools_util::get_version_info!();
41     println!("{}", version_info);
42 }
43
44 pub fn main() {
45     // Check for version and help flags even when invoked as 'cargo-clippy'
46     if env::args().any(|a| a == "--help" || a == "-h") {
47         show_help();
48         return;
49     }
50
51     if env::args().any(|a| a == "--version" || a == "-V") {
52         show_version();
53         return;
54     }
55
56     if let Err(code) = process(env::args().skip(2)) {
57         process::exit(code);
58     }
59 }
60
61 struct ClippyCmd {
62     cargo_subcommand: &'static str,
63     args: Vec<String>,
64     clippy_args: Vec<String>,
65 }
66
67 impl ClippyCmd {
68     fn new<I>(mut old_args: I) -> Self
69     where
70         I: Iterator<Item = String>,
71     {
72         let mut cargo_subcommand = "check";
73         let mut args = vec![];
74
75         for arg in old_args.by_ref() {
76             match arg.as_str() {
77                 "--fix" => {
78                     cargo_subcommand = "fix";
79                     continue;
80                 },
81                 "--" => break,
82                 _ => {},
83             }
84
85             args.push(arg);
86         }
87
88         let mut clippy_args: Vec<String> = old_args.collect();
89         if cargo_subcommand == "fix" && !clippy_args.iter().any(|arg| arg == "--no-deps") {
90             clippy_args.push("--no-deps".into());
91         }
92
93         ClippyCmd {
94             cargo_subcommand,
95             args,
96             clippy_args,
97         }
98     }
99
100     fn path() -> PathBuf {
101         let mut path = env::current_exe()
102             .expect("current executable path invalid")
103             .with_file_name("clippy-driver");
104
105         if cfg!(windows) {
106             path.set_extension("exe");
107         }
108
109         path
110     }
111
112     fn target_dir() -> Option<(&'static str, OsString)> {
113         env::var_os("CLIPPY_DOGFOOD")
114             .map(|_| {
115                 env::var_os("CARGO_MANIFEST_DIR").map_or_else(
116                     || std::ffi::OsString::from("clippy_dogfood"),
117                     |d| {
118                         std::path::PathBuf::from(d)
119                             .join("target")
120                             .join("dogfood")
121                             .into_os_string()
122                     },
123                 )
124             })
125             .map(|p| ("CARGO_TARGET_DIR", p))
126     }
127
128     fn into_std_cmd(self) -> Command {
129         let mut cmd = Command::new("cargo");
130         let clippy_args: String = self
131             .clippy_args
132             .iter()
133             .map(|arg| format!("{}__CLIPPY_HACKERY__", arg))
134             .collect();
135
136         cmd.env("RUSTC_WORKSPACE_WRAPPER", Self::path())
137             .envs(ClippyCmd::target_dir())
138             .env("CLIPPY_ARGS", clippy_args)
139             .arg(self.cargo_subcommand)
140             .args(&self.args);
141
142         cmd
143     }
144 }
145
146 fn process<I>(old_args: I) -> Result<(), i32>
147 where
148     I: Iterator<Item = String>,
149 {
150     let cmd = ClippyCmd::new(old_args);
151
152     let mut cmd = cmd.into_std_cmd();
153
154     let exit_status = cmd
155         .spawn()
156         .expect("could not run cargo")
157         .wait()
158         .expect("failed to wait for cargo?");
159
160     if exit_status.success() {
161         Ok(())
162     } else {
163         Err(exit_status.code().unwrap_or(-1))
164     }
165 }
166
167 #[cfg(test)]
168 mod tests {
169     use super::ClippyCmd;
170
171     #[test]
172     fn fix() {
173         let args = "cargo clippy --fix".split_whitespace().map(ToString::to_string);
174         let cmd = ClippyCmd::new(args);
175         assert_eq!("fix", cmd.cargo_subcommand);
176         assert!(!cmd.args.iter().any(|arg| arg.ends_with("unstable-options")));
177     }
178
179     #[test]
180     fn fix_implies_no_deps() {
181         let args = "cargo clippy --fix".split_whitespace().map(ToString::to_string);
182         let cmd = ClippyCmd::new(args);
183         assert!(cmd.clippy_args.iter().any(|arg| arg == "--no-deps"));
184     }
185
186     #[test]
187     fn no_deps_not_duplicated_with_fix() {
188         let args = "cargo clippy --fix -- --no-deps"
189             .split_whitespace()
190             .map(ToString::to_string);
191         let cmd = ClippyCmd::new(args);
192         assert_eq!(cmd.clippy_args.iter().filter(|arg| *arg == "--no-deps").count(), 1);
193     }
194
195     #[test]
196     fn check() {
197         let args = "cargo clippy".split_whitespace().map(ToString::to_string);
198         let cmd = ClippyCmd::new(args);
199         assert_eq!("check", cmd.cargo_subcommand);
200     }
201 }