]> git.lizzy.rs Git - rust.git/blob - src/main.rs
Add help text for `--all`
[rust.git] / src / main.rs
1 // error-pattern:yummy
2 #![feature(box_syntax)]
3 #![feature(rustc_private)]
4 #![allow(unknown_lints, missing_docs_in_private_items)]
5
6 extern crate clippy_lints;
7 extern crate getopts;
8 extern crate rustc;
9 extern crate rustc_driver;
10 extern crate rustc_errors;
11 extern crate rustc_plugin;
12 extern crate syntax;
13
14 use rustc_driver::{driver, Compilation, CompilerCalls, RustcDefaultCalls};
15 use rustc::session::{config, CompileIncomplete, Session};
16 use rustc::session::config::{ErrorOutputType, Input};
17 use std::collections::HashMap;
18 use std::path::PathBuf;
19 use std::process::{self, Command};
20 use syntax::ast;
21 use std::io::{self, Write};
22
23 extern crate cargo_metadata;
24
25 struct ClippyCompilerCalls {
26     default: RustcDefaultCalls,
27     run_lints: bool,
28 }
29
30 impl ClippyCompilerCalls {
31     fn new(run_lints: bool) -> Self {
32         ClippyCompilerCalls {
33             default: RustcDefaultCalls,
34             run_lints: run_lints,
35         }
36     }
37 }
38
39 impl<'a> CompilerCalls<'a> for ClippyCompilerCalls {
40     fn early_callback(
41         &mut self,
42         matches: &getopts::Matches,
43         sopts: &config::Options,
44         cfg: &ast::CrateConfig,
45         descriptions: &rustc_errors::registry::Registry,
46         output: ErrorOutputType,
47     ) -> Compilation {
48         self.default.early_callback(
49             matches,
50             sopts,
51             cfg,
52             descriptions,
53             output,
54         )
55     }
56     fn no_input(
57         &mut self,
58         matches: &getopts::Matches,
59         sopts: &config::Options,
60         cfg: &ast::CrateConfig,
61         odir: &Option<PathBuf>,
62         ofile: &Option<PathBuf>,
63         descriptions: &rustc_errors::registry::Registry,
64     ) -> Option<(Input, Option<PathBuf>)> {
65         self.default.no_input(
66             matches,
67             sopts,
68             cfg,
69             odir,
70             ofile,
71             descriptions,
72         )
73     }
74     fn late_callback(
75         &mut self,
76         matches: &getopts::Matches,
77         sess: &Session,
78         input: &Input,
79         odir: &Option<PathBuf>,
80         ofile: &Option<PathBuf>,
81     ) -> Compilation {
82         self.default.late_callback(
83             matches,
84             sess,
85             input,
86             odir,
87             ofile,
88         )
89     }
90     fn build_controller(&mut self, sess: &Session, matches: &getopts::Matches) -> driver::CompileController<'a> {
91         let mut control = self.default.build_controller(sess, matches);
92
93         if self.run_lints {
94             let old = std::mem::replace(&mut control.after_parse.callback, box |_| {});
95             control.after_parse.callback = Box::new(move |state| {
96                 {
97                     let mut registry = rustc_plugin::registry::Registry::new(
98                         state.session,
99                         state
100                             .krate
101                             .as_ref()
102                             .expect(
103                                 "at this compilation stage \
104                                                                                           the krate must be parsed",
105                             )
106                             .span,
107                     );
108                     registry.args_hidden = Some(Vec::new());
109                     clippy_lints::register_plugins(&mut registry);
110
111                     let rustc_plugin::registry::Registry {
112                         early_lint_passes,
113                         late_lint_passes,
114                         lint_groups,
115                         llvm_passes,
116                         attributes,
117                         ..
118                     } = registry;
119                     let sess = &state.session;
120                     let mut ls = sess.lint_store.borrow_mut();
121                     for pass in early_lint_passes {
122                         ls.register_early_pass(Some(sess), true, pass);
123                     }
124                     for pass in late_lint_passes {
125                         ls.register_late_pass(Some(sess), true, pass);
126                     }
127
128                     for (name, to) in lint_groups {
129                         ls.register_group(Some(sess), true, name, to);
130                     }
131
132                     sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
133                     sess.plugin_attributes.borrow_mut().extend(attributes);
134                 }
135                 old(state);
136             });
137         }
138
139         control
140     }
141 }
142
143 use std::path::Path;
144
145 const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code.
146
147 Usage:
148     cargo clippy [options] [--] [<opts>...]
149
150 Common options:
151     -h, --help               Print this message
152     --features               Features to compile for the package
153     -V, --version            Print version info and exit
154     --all                    Run over all packages in the current workspace
155
156 Other options are the same as `cargo rustc`.
157
158 To allow or deny a lint from the command line you can use `cargo clippy --`
159 with:
160
161     -W --warn OPT       Set lint warnings
162     -A --allow OPT      Set lint allowed
163     -D --deny OPT       Set lint denied
164     -F --forbid OPT     Set lint forbidden
165
166 The feature `cargo-clippy` is automatically defined for convenience. You can use
167 it to allow or deny lints from the code, eg.:
168
169     #[cfg_attr(feature = "cargo-clippy", allow(needless_lifetimes))]
170 "#;
171
172 #[allow(print_stdout)]
173 fn show_help() {
174     println!("{}", CARGO_CLIPPY_HELP);
175 }
176
177 #[allow(print_stdout)]
178 fn show_version() {
179     println!("{}", env!("CARGO_PKG_VERSION"));
180 }
181
182 pub fn main() {
183     use std::env;
184
185     if env::var("CLIPPY_DOGFOOD").map(|_| true).unwrap_or(false) {
186         panic!("yummy");
187     }
188
189     // Check for version and help flags even when invoked as 'cargo-clippy'
190     if std::env::args().any(|a| a == "--help" || a == "-h") {
191         show_help();
192         return;
193     }
194     if std::env::args().any(|a| a == "--version" || a == "-V") {
195         show_version();
196         return;
197     }
198
199     if let Some("clippy") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
200         // this arm is executed on the initial call to `cargo clippy`
201
202         let manifest_path_arg = std::env::args()
203             .skip(2)
204             .find(|val| val.starts_with("--manifest-path="));
205
206         let mut metadata =
207             if let Ok(metadata) = cargo_metadata::metadata(manifest_path_arg.as_ref().map(AsRef::as_ref)) {
208                 metadata
209             } else {
210                 let _ = io::stderr().write_fmt(format_args!("error: Could not obtain cargo metadata.\n"));
211                 process::exit(101);
212             };
213
214         let manifest_path = manifest_path_arg.map(|arg| {
215             Path::new(&arg["--manifest-path=".len()..])
216                 .canonicalize()
217                 .expect("manifest path could not be canonicalized")
218         });
219
220         let packages = if std::env::args().any(|a| a == "--all") {
221             metadata.packages
222         } else {
223             let package_index = {
224                 if let Some(manifest_path) = manifest_path {
225                     metadata.packages.iter().position(|package| {
226                         let package_manifest_path = Path::new(&package.manifest_path)
227                             .canonicalize()
228                             .expect("package manifest path could not be canonicalized");
229                         package_manifest_path == manifest_path
230                     })
231                 } else {
232                     let package_manifest_paths: HashMap<_, _> = metadata
233                         .packages
234                         .iter()
235                         .enumerate()
236                         .map(|(i, package)| {
237                             let package_manifest_path = Path::new(&package.manifest_path)
238                                 .parent()
239                                 .expect("could not find parent directory of package manifest")
240                                 .canonicalize()
241                                 .expect("package directory cannot be canonicalized");
242                             (package_manifest_path, i)
243                         })
244                         .collect();
245
246                     let current_dir = std::env::current_dir()
247                         .expect("could not read current directory")
248                         .canonicalize()
249                         .expect("current directory cannot be canonicalized");
250
251                     let mut current_path: &Path = &current_dir;
252
253                     // This gets the most-recent parent (the one that takes the fewest `cd ..`s to
254                     // reach).
255                     loop {
256                         if let Some(&package_index) = package_manifest_paths.get(current_path) {
257                             break Some(package_index);
258                         } else {
259                             // We'll never reach the filesystem root, because to get to this point in the
260                             // code
261                             // the call to `cargo_metadata::metadata` must have succeeded. So it's okay to
262                             // unwrap the current path's parent.
263                             current_path = current_path
264                                 .parent()
265                                 .unwrap_or_else(|| panic!("could not find parent of path {}", current_path.display()));
266                         }
267                     }
268                 }
269             }.expect("could not find matching package");
270
271             vec![metadata.packages.remove(package_index)]
272         };
273
274         for package in packages {
275             let manifest_path = package.manifest_path;
276
277             for target in package.targets {
278                 let args = std::env::args()
279                     .skip(2)
280                     .filter(|a| a != "--all" && !a.starts_with("--manifest-path="));
281
282                 let args = std::iter::once(format!("--manifest-path={}", manifest_path)).chain(args);
283                 if let Some(first) = target.kind.get(0) {
284                     if target.kind.len() > 1 || first.ends_with("lib") {
285                         if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args)) {
286                             std::process::exit(code);
287                         }
288                     } else if ["bin", "example", "test", "bench"].contains(&&**first) {
289                         if let Err(code) = process(
290                             vec![format!("--{}", first), target.name]
291                                 .into_iter()
292                                 .chain(args),
293                         ) {
294                             std::process::exit(code);
295                         }
296                     }
297                 } else {
298                     panic!("badly formatted cargo metadata: target::kind is an empty array");
299                 }
300             }
301         }
302     } else {
303         // this arm is executed when cargo-clippy runs `cargo rustc` with the `RUSTC`
304         // env var set to itself
305
306         let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
307         let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
308         let sys_root = if let (Some(home), Some(toolchain)) = (home, toolchain) {
309             format!("{}/toolchains/{}", home, toolchain)
310         } else {
311             option_env!("SYSROOT")
312                 .map(|s| s.to_owned())
313                 .or_else(|| {
314                     Command::new("rustc")
315                         .arg("--print")
316                         .arg("sysroot")
317                         .output()
318                         .ok()
319                         .and_then(|out| String::from_utf8(out.stdout).ok())
320                         .map(|s| s.trim().to_owned())
321                 })
322                 .expect(
323                     "need to specify SYSROOT env var during clippy compilation, or use rustup or multirust",
324                 )
325         };
326
327         rustc_driver::in_rustc_thread(|| {
328             // this conditional check for the --sysroot flag is there so users can call
329             // `cargo-clippy` directly
330             // without having to pass --sysroot or anything
331             let mut args: Vec<String> = if env::args().any(|s| s == "--sysroot") {
332                 env::args().collect()
333             } else {
334                 env::args()
335                     .chain(Some("--sysroot".to_owned()))
336                     .chain(Some(sys_root))
337                     .collect()
338             };
339
340             // this check ensures that dependencies are built but not linted and the final
341             // crate is
342             // linted but not built
343             let clippy_enabled = env::args().any(|s| s == "--emit=metadata");
344
345             if clippy_enabled {
346                 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
347             }
348
349             let mut ccc = ClippyCompilerCalls::new(clippy_enabled);
350             let (result, _) = rustc_driver::run_compiler(&args, &mut ccc, None, None);
351             if let Err(CompileIncomplete::Errored(_)) = result {
352                 std::process::exit(1);
353             }
354         }).expect("rustc_thread failed");
355     }
356 }
357
358 fn process<I>(old_args: I) -> Result<(), i32>
359 where
360     I: Iterator<Item = String>,
361 {
362
363     let mut args = vec!["rustc".to_owned()];
364
365     let mut found_dashes = false;
366     for arg in old_args {
367         found_dashes |= arg == "--";
368         args.push(arg);
369     }
370     if !found_dashes {
371         args.push("--".to_owned());
372     }
373     args.push("--emit=metadata".to_owned());
374     args.push("--cfg".to_owned());
375     args.push(r#"feature="cargo-clippy""#.to_owned());
376
377     let path = std::env::current_exe().expect("current executable path invalid");
378     let exit_status = std::process::Command::new("cargo")
379         .args(&args)
380         .env("RUSTC", path)
381         .spawn()
382         .expect("could not run cargo")
383         .wait()
384         .expect("failed to wait for cargo?");
385
386     if exit_status.success() {
387         Ok(())
388     } else {
389         Err(exit_status.code().unwrap_or(-1))
390     }
391 }