]> git.lizzy.rs Git - rust.git/blob - src/main.rs
Auto merge of #6318 - camsteffen:article-description, r=Manishearth
[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::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     unstable_options: bool,
63     cargo_subcommand: &'static str,
64     args: Vec<String>,
65     clippy_args: Vec<String>,
66 }
67
68 impl ClippyCmd {
69     fn new<I>(mut old_args: I) -> Self
70     where
71         I: Iterator<Item = String>,
72     {
73         let mut cargo_subcommand = "check";
74         let mut unstable_options = false;
75         let mut args = vec![];
76
77         for arg in old_args.by_ref() {
78             match arg.as_str() {
79                 "--fix" => {
80                     cargo_subcommand = "fix";
81                     continue;
82                 },
83                 "--" => break,
84                 // Cover -Zunstable-options and -Z unstable-options
85                 s if s.ends_with("unstable-options") => unstable_options = true,
86                 _ => {},
87             }
88
89             args.push(arg);
90         }
91
92         if cargo_subcommand == "fix" && !unstable_options {
93             panic!("Usage of `--fix` requires `-Z unstable-options`");
94         }
95
96         // Run the dogfood tests directly on nightly cargo. This is required due
97         // to a bug in rustup.rs when running cargo on custom toolchains. See issue #3118.
98         if env::var_os("CLIPPY_DOGFOOD").is_some() && cfg!(windows) {
99             args.insert(0, "+nightly".to_string());
100         }
101
102         let mut clippy_args: Vec<String> = old_args.collect();
103         if cargo_subcommand == "fix" && !clippy_args.iter().any(|arg| arg == "--no-deps") {
104             clippy_args.push("--no-deps".into());
105         }
106
107         ClippyCmd {
108             unstable_options,
109             cargo_subcommand,
110             args,
111             clippy_args,
112         }
113     }
114
115     fn path_env(&self) -> &'static str {
116         if self.unstable_options {
117             "RUSTC_WORKSPACE_WRAPPER"
118         } else {
119             "RUSTC_WRAPPER"
120         }
121     }
122
123     fn path() -> PathBuf {
124         let mut path = env::current_exe()
125             .expect("current executable path invalid")
126             .with_file_name("clippy-driver");
127
128         if cfg!(windows) {
129             path.set_extension("exe");
130         }
131
132         path
133     }
134
135     fn target_dir() -> Option<(&'static str, OsString)> {
136         env::var_os("CLIPPY_DOGFOOD")
137             .map(|_| {
138                 env::var_os("CARGO_MANIFEST_DIR").map_or_else(
139                     || std::ffi::OsString::from("clippy_dogfood"),
140                     |d| {
141                         std::path::PathBuf::from(d)
142                             .join("target")
143                             .join("dogfood")
144                             .into_os_string()
145                     },
146                 )
147             })
148             .map(|p| ("CARGO_TARGET_DIR", p))
149     }
150
151     fn into_std_cmd(self) -> Command {
152         let mut cmd = Command::new("cargo");
153         let clippy_args: String = self
154             .clippy_args
155             .iter()
156             .map(|arg| format!("{}__CLIPPY_HACKERY__", arg))
157             .collect();
158
159         cmd.env(self.path_env(), Self::path())
160             .envs(ClippyCmd::target_dir())
161             .env("CLIPPY_ARGS", clippy_args)
162             .arg(self.cargo_subcommand)
163             .args(&self.args);
164
165         cmd
166     }
167 }
168
169 fn process<I>(old_args: I) -> Result<(), i32>
170 where
171     I: Iterator<Item = String>,
172 {
173     let cmd = ClippyCmd::new(old_args);
174
175     let mut cmd = cmd.into_std_cmd();
176
177     let exit_status = cmd
178         .spawn()
179         .expect("could not run cargo")
180         .wait()
181         .expect("failed to wait for cargo?");
182
183     if exit_status.success() {
184         Ok(())
185     } else {
186         Err(exit_status.code().unwrap_or(-1))
187     }
188 }
189
190 #[cfg(test)]
191 mod tests {
192     use super::ClippyCmd;
193
194     #[test]
195     #[should_panic]
196     fn fix_without_unstable() {
197         let args = "cargo clippy --fix".split_whitespace().map(ToString::to_string);
198         let _ = ClippyCmd::new(args);
199     }
200
201     #[test]
202     fn fix_unstable() {
203         let args = "cargo clippy --fix -Zunstable-options"
204             .split_whitespace()
205             .map(ToString::to_string);
206         let cmd = ClippyCmd::new(args);
207         assert_eq!("fix", cmd.cargo_subcommand);
208         assert_eq!("RUSTC_WORKSPACE_WRAPPER", cmd.path_env());
209         assert!(cmd.args.iter().any(|arg| arg.ends_with("unstable-options")));
210     }
211
212     #[test]
213     fn fix_implies_no_deps() {
214         let args = "cargo clippy --fix -Zunstable-options"
215             .split_whitespace()
216             .map(ToString::to_string);
217         let cmd = ClippyCmd::new(args);
218         assert!(cmd.clippy_args.iter().any(|arg| arg == "--no-deps"));
219     }
220
221     #[test]
222     fn no_deps_not_duplicated_with_fix() {
223         let args = "cargo clippy --fix -Zunstable-options -- --no-deps"
224             .split_whitespace()
225             .map(ToString::to_string);
226         let cmd = ClippyCmd::new(args);
227         assert_eq!(cmd.clippy_args.iter().filter(|arg| *arg == "--no-deps").count(), 1);
228     }
229
230     #[test]
231     fn check() {
232         let args = "cargo clippy".split_whitespace().map(ToString::to_string);
233         let cmd = ClippyCmd::new(args);
234         assert_eq!("check", cmd.cargo_subcommand);
235         assert_eq!("RUSTC_WRAPPER", cmd.path_env());
236     }
237
238     #[test]
239     fn check_unstable() {
240         let args = "cargo clippy -Zunstable-options"
241             .split_whitespace()
242             .map(ToString::to_string);
243         let cmd = ClippyCmd::new(args);
244         assert_eq!("check", cmd.cargo_subcommand);
245         assert_eq!("RUSTC_WORKSPACE_WRAPPER", cmd.path_env());
246     }
247 }