]> git.lizzy.rs Git - rust.git/blob - src/main.rs
Auto merge of #9712 - Alexendoo:old-generated-files, r=flip1995
[rust.git] / 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 const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code.
11
12 Usage:
13     cargo clippy [options] [--] [<opts>...]
14
15 Common options:
16     --no-deps                Run Clippy only on the given crate, without linting the dependencies
17     --fix                    Automatically apply lint suggestions. This flag implies `--no-deps`
18     -h, --help               Print this message
19     -V, --version            Print version info and exit
20     --explain LINT           Print the documentation for a given lint
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 Some(pos) = env::args().position(|a| a == "--explain") {
59         if let Some(mut lint) = env::args().nth(pos + 1) {
60             lint.make_ascii_lowercase();
61             clippy_lints::explain(&lint.strip_prefix("clippy::").unwrap_or(&lint).replace('-', "_"));
62         } else {
63             show_help();
64         }
65         return;
66     }
67
68     if let Err(code) = process(env::args().skip(2)) {
69         process::exit(code);
70     }
71 }
72
73 struct ClippyCmd {
74     cargo_subcommand: &'static str,
75     args: Vec<String>,
76     clippy_args: Vec<String>,
77 }
78
79 impl ClippyCmd {
80     fn new<I>(mut old_args: I) -> Self
81     where
82         I: Iterator<Item = String>,
83     {
84         let mut cargo_subcommand = "check";
85         let mut args = vec![];
86         let mut clippy_args: Vec<String> = vec![];
87
88         for arg in old_args.by_ref() {
89             match arg.as_str() {
90                 "--fix" => {
91                     cargo_subcommand = "fix";
92                     continue;
93                 },
94                 "--no-deps" => {
95                     clippy_args.push("--no-deps".into());
96                     continue;
97                 },
98                 "--" => break,
99                 _ => {},
100             }
101
102             args.push(arg);
103         }
104
105         clippy_args.append(&mut (old_args.collect()));
106         if cargo_subcommand == "fix" && !clippy_args.iter().any(|arg| arg == "--no-deps") {
107             clippy_args.push("--no-deps".into());
108         }
109
110         Self {
111             cargo_subcommand,
112             args,
113             clippy_args,
114         }
115     }
116
117     fn path() -> PathBuf {
118         let mut path = env::current_exe()
119             .expect("current executable path invalid")
120             .with_file_name("clippy-driver");
121
122         if cfg!(windows) {
123             path.set_extension("exe");
124         }
125
126         path
127     }
128
129     fn into_std_cmd(self) -> Command {
130         let mut cmd = Command::new("cargo");
131         let clippy_args: String = self
132             .clippy_args
133             .iter()
134             .map(|arg| format!("{arg}__CLIPPY_HACKERY__"))
135             .collect();
136
137         // Currently, `CLIPPY_TERMINAL_WIDTH` is used only to format "unknown field" error messages.
138         let terminal_width = termize::dimensions().map_or(0, |(w, _)| w);
139
140         cmd.env("RUSTC_WORKSPACE_WRAPPER", Self::path())
141             .env("CLIPPY_ARGS", clippy_args)
142             .env("CLIPPY_TERMINAL_WIDTH", terminal_width.to_string())
143             .arg(self.cargo_subcommand)
144             .args(&self.args);
145
146         cmd
147     }
148 }
149
150 fn process<I>(old_args: I) -> Result<(), i32>
151 where
152     I: Iterator<Item = String>,
153 {
154     let cmd = ClippyCmd::new(old_args);
155
156     let mut cmd = cmd.into_std_cmd();
157
158     let exit_status = cmd
159         .spawn()
160         .expect("could not run cargo")
161         .wait()
162         .expect("failed to wait for cargo?");
163
164     if exit_status.success() {
165         Ok(())
166     } else {
167         Err(exit_status.code().unwrap_or(-1))
168     }
169 }
170
171 #[cfg(test)]
172 mod tests {
173     use super::ClippyCmd;
174
175     #[test]
176     fn fix() {
177         let args = "cargo clippy --fix".split_whitespace().map(ToString::to_string);
178         let cmd = ClippyCmd::new(args);
179         assert_eq!("fix", cmd.cargo_subcommand);
180         assert!(!cmd.args.iter().any(|arg| arg.ends_with("unstable-options")));
181     }
182
183     #[test]
184     fn fix_implies_no_deps() {
185         let args = "cargo clippy --fix".split_whitespace().map(ToString::to_string);
186         let cmd = ClippyCmd::new(args);
187         assert!(cmd.clippy_args.iter().any(|arg| arg == "--no-deps"));
188     }
189
190     #[test]
191     fn no_deps_not_duplicated_with_fix() {
192         let args = "cargo clippy --fix -- --no-deps"
193             .split_whitespace()
194             .map(ToString::to_string);
195         let cmd = ClippyCmd::new(args);
196         assert_eq!(cmd.clippy_args.iter().filter(|arg| *arg == "--no-deps").count(), 1);
197     }
198
199     #[test]
200     fn check() {
201         let args = "cargo clippy".split_whitespace().map(ToString::to_string);
202         let cmd = ClippyCmd::new(args);
203         assert_eq!("check", cmd.cargo_subcommand);
204     }
205 }