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