]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/src/main.rs
Merge commit '9809f5d21990d9e24b3e9876ea7da756fd4e9def' into libgccjit-codegen
[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     --no-deps                Run Clippy only on the given crate, without linting the dependencies 
18     --fix                    Automatically apply lint suggestions. This flag implies `--no-deps`
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     cargo_subcommand: &'static str,
65     args: Vec<String>,
66     clippy_args: Vec<String>,
67 }
68
69 impl ClippyCmd {
70     fn new<I>(mut old_args: I) -> Self
71     where
72         I: Iterator<Item = String>,
73     {
74         let mut cargo_subcommand = "check";
75         let mut args = vec![];
76         let mut clippy_args: Vec<String> = vec![];
77
78         for arg in old_args.by_ref() {
79             match arg.as_str() {
80                 "--fix" => {
81                     cargo_subcommand = "fix";
82                     continue;
83                 },
84                 "--no-deps" => {
85                     clippy_args.push("--no-deps".into());
86                     continue;
87                 },
88                 "--" => break,
89                 _ => {},
90             }
91
92             args.push(arg);
93         }
94
95         clippy_args.append(&mut (old_args.collect()));
96         if cargo_subcommand == "fix" && !clippy_args.iter().any(|arg| arg == "--no-deps") {
97             clippy_args.push("--no-deps".into());
98         }
99
100         ClippyCmd {
101             cargo_subcommand,
102             args,
103             clippy_args,
104         }
105     }
106
107     fn path() -> PathBuf {
108         let mut path = env::current_exe()
109             .expect("current executable path invalid")
110             .with_file_name("clippy-driver");
111
112         if cfg!(windows) {
113             path.set_extension("exe");
114         }
115
116         path
117     }
118
119     fn target_dir() -> Option<(&'static str, OsString)> {
120         env::var_os("CLIPPY_DOGFOOD")
121             .map(|_| {
122                 env::var_os("CARGO_MANIFEST_DIR").map_or_else(
123                     || std::ffi::OsString::from("clippy_dogfood"),
124                     |d| {
125                         std::path::PathBuf::from(d)
126                             .join("target")
127                             .join("dogfood")
128                             .into_os_string()
129                     },
130                 )
131             })
132             .map(|p| ("CARGO_TARGET_DIR", p))
133     }
134
135     fn into_std_cmd(self) -> Command {
136         let mut cmd = Command::new("cargo");
137         let clippy_args: String = self
138             .clippy_args
139             .iter()
140             .map(|arg| format!("{}__CLIPPY_HACKERY__", arg))
141             .collect();
142
143         cmd.env("RUSTC_WORKSPACE_WRAPPER", Self::path())
144             .envs(ClippyCmd::target_dir())
145             .env("CLIPPY_ARGS", clippy_args)
146             .arg(self.cargo_subcommand)
147             .args(&self.args);
148
149         cmd
150     }
151 }
152
153 fn process<I>(old_args: I) -> Result<(), i32>
154 where
155     I: Iterator<Item = String>,
156 {
157     let cmd = ClippyCmd::new(old_args);
158
159     let mut cmd = cmd.into_std_cmd();
160
161     let exit_status = cmd
162         .spawn()
163         .expect("could not run cargo")
164         .wait()
165         .expect("failed to wait for cargo?");
166
167     if exit_status.success() {
168         Ok(())
169     } else {
170         Err(exit_status.code().unwrap_or(-1))
171     }
172 }
173
174 #[cfg(test)]
175 mod tests {
176     use super::ClippyCmd;
177
178     #[test]
179     fn fix() {
180         let args = "cargo clippy --fix".split_whitespace().map(ToString::to_string);
181         let cmd = ClippyCmd::new(args);
182         assert_eq!("fix", cmd.cargo_subcommand);
183         assert!(!cmd.args.iter().any(|arg| arg.ends_with("unstable-options")));
184     }
185
186     #[test]
187     fn fix_implies_no_deps() {
188         let args = "cargo clippy --fix".split_whitespace().map(ToString::to_string);
189         let cmd = ClippyCmd::new(args);
190         assert!(cmd.clippy_args.iter().any(|arg| arg == "--no-deps"));
191     }
192
193     #[test]
194     fn no_deps_not_duplicated_with_fix() {
195         let args = "cargo clippy --fix -- --no-deps"
196             .split_whitespace()
197             .map(ToString::to_string);
198         let cmd = ClippyCmd::new(args);
199         assert_eq!(cmd.clippy_args.iter().filter(|arg| *arg == "--no-deps").count(), 1);
200     }
201
202     #[test]
203     fn check() {
204         let args = "cargo clippy".split_whitespace().map(ToString::to_string);
205         let cmd = ClippyCmd::new(args);
206         assert_eq!("check", cmd.cargo_subcommand);
207     }
208 }