]> git.lizzy.rs Git - rust.git/blob - src/main.rs
Include more information in --help
[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     --no-deps                Run Clippy only on the given crate, without linting the dependencies 
18     --fix                    Automatically apply lint suggestions. This flag implies `--no-deps`
19     -h, --help               Print this message
20     -V, --version            Print version info and exit
21
22 Note: --no-deps flag is used with `cargo clippy --`. Example: `cargo clippy -- --no-deps`
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 Err(code) = process(env::args().skip(2)) {
61         process::exit(code);
62     }
63 }
64
65 struct ClippyCmd {
66     cargo_subcommand: &'static str,
67     args: Vec<String>,
68     clippy_args: Vec<String>,
69 }
70
71 impl ClippyCmd {
72     fn new<I>(mut old_args: I) -> Self
73     where
74         I: Iterator<Item = String>,
75     {
76         let mut cargo_subcommand = "check";
77         let mut args = vec![];
78
79         for arg in old_args.by_ref() {
80             match arg.as_str() {
81                 "--fix" => {
82                     cargo_subcommand = "fix";
83                     continue;
84                 },
85                 "--" => break,
86                 _ => {},
87             }
88
89             args.push(arg);
90         }
91
92         let mut clippy_args: Vec<String> = old_args.collect();
93         if cargo_subcommand == "fix" && !clippy_args.iter().any(|arg| arg == "--no-deps") {
94             clippy_args.push("--no-deps".into());
95         }
96
97         ClippyCmd {
98             cargo_subcommand,
99             args,
100             clippy_args,
101         }
102     }
103
104     fn path() -> PathBuf {
105         let mut path = env::current_exe()
106             .expect("current executable path invalid")
107             .with_file_name("clippy-driver");
108
109         if cfg!(windows) {
110             path.set_extension("exe");
111         }
112
113         path
114     }
115
116     fn target_dir() -> Option<(&'static str, OsString)> {
117         env::var_os("CLIPPY_DOGFOOD")
118             .map(|_| {
119                 env::var_os("CARGO_MANIFEST_DIR").map_or_else(
120                     || std::ffi::OsString::from("clippy_dogfood"),
121                     |d| {
122                         std::path::PathBuf::from(d)
123                             .join("target")
124                             .join("dogfood")
125                             .into_os_string()
126                     },
127                 )
128             })
129             .map(|p| ("CARGO_TARGET_DIR", p))
130     }
131
132     fn into_std_cmd(self) -> Command {
133         let mut cmd = Command::new("cargo");
134         let clippy_args: String = self
135             .clippy_args
136             .iter()
137             .map(|arg| format!("{}__CLIPPY_HACKERY__", arg))
138             .collect();
139
140         cmd.env("RUSTC_WORKSPACE_WRAPPER", Self::path())
141             .envs(ClippyCmd::target_dir())
142             .env("CLIPPY_ARGS", clippy_args)
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 }