]> git.lizzy.rs Git - rust.git/blob - src/main.rs
Auto merge of #6389 - giraffate:sync-from-rust, r=llogiq
[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: 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 clippy_args: String = old_args.map(|arg| format!("{}__CLIPPY_HACKERY__", arg)).collect();
103
104         ClippyCmd {
105             unstable_options,
106             cargo_subcommand,
107             args,
108             clippy_args,
109         }
110     }
111
112     fn path_env(&self) -> &'static str {
113         if self.unstable_options {
114             "RUSTC_WORKSPACE_WRAPPER"
115         } else {
116             "RUSTC_WRAPPER"
117         }
118     }
119
120     fn path() -> PathBuf {
121         let mut path = env::current_exe()
122             .expect("current executable path invalid")
123             .with_file_name("clippy-driver");
124
125         if cfg!(windows) {
126             path.set_extension("exe");
127         }
128
129         path
130     }
131
132     fn target_dir() -> Option<(&'static str, OsString)> {
133         env::var_os("CLIPPY_DOGFOOD")
134             .map(|_| {
135                 env::var_os("CARGO_MANIFEST_DIR").map_or_else(
136                     || std::ffi::OsString::from("clippy_dogfood"),
137                     |d| {
138                         std::path::PathBuf::from(d)
139                             .join("target")
140                             .join("dogfood")
141                             .into_os_string()
142                     },
143                 )
144             })
145             .map(|p| ("CARGO_TARGET_DIR", p))
146     }
147
148     fn into_std_cmd(self) -> Command {
149         let mut cmd = Command::new("cargo");
150
151         cmd.env(self.path_env(), Self::path())
152             .envs(ClippyCmd::target_dir())
153             .env("CLIPPY_ARGS", self.clippy_args)
154             .arg(self.cargo_subcommand)
155             .args(&self.args);
156
157         cmd
158     }
159 }
160
161 fn process<I>(old_args: I) -> Result<(), i32>
162 where
163     I: Iterator<Item = String>,
164 {
165     let cmd = ClippyCmd::new(old_args);
166
167     let mut cmd = cmd.into_std_cmd();
168
169     let exit_status = cmd
170         .spawn()
171         .expect("could not run cargo")
172         .wait()
173         .expect("failed to wait for cargo?");
174
175     if exit_status.success() {
176         Ok(())
177     } else {
178         Err(exit_status.code().unwrap_or(-1))
179     }
180 }
181
182 #[cfg(test)]
183 mod tests {
184     use super::ClippyCmd;
185
186     #[test]
187     #[should_panic]
188     fn fix_without_unstable() {
189         let args = "cargo clippy --fix".split_whitespace().map(ToString::to_string);
190         let _ = ClippyCmd::new(args);
191     }
192
193     #[test]
194     fn fix_unstable() {
195         let args = "cargo clippy --fix -Zunstable-options"
196             .split_whitespace()
197             .map(ToString::to_string);
198         let cmd = ClippyCmd::new(args);
199         assert_eq!("fix", cmd.cargo_subcommand);
200         assert_eq!("RUSTC_WORKSPACE_WRAPPER", cmd.path_env());
201         assert!(cmd.args.iter().any(|arg| arg.ends_with("unstable-options")));
202     }
203
204     #[test]
205     fn check() {
206         let args = "cargo clippy".split_whitespace().map(ToString::to_string);
207         let cmd = ClippyCmd::new(args);
208         assert_eq!("check", cmd.cargo_subcommand);
209         assert_eq!("RUSTC_WRAPPER", cmd.path_env());
210     }
211
212     #[test]
213     fn check_unstable() {
214         let args = "cargo clippy -Zunstable-options"
215             .split_whitespace()
216             .map(ToString::to_string);
217         let cmd = ClippyCmd::new(args);
218         assert_eq!("check", cmd.cargo_subcommand);
219         assert_eq!("RUSTC_WORKSPACE_WRAPPER", cmd.path_env());
220     }
221 }