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