]> git.lizzy.rs Git - rust.git/blobdiff - src/main.rs
Fix small nits on the help message
[rust.git] / src / main.rs
index 9541e70ecc0ba9c7792d18aced8405be59d443dd..44c3b61d22cc181fd35ec65a663e221f18d01440 100644 (file)
@@ -1,6 +1,9 @@
 // error-pattern:yummy
 #![feature(box_syntax)]
 #![feature(rustc_private)]
+#![feature(static_in_const)]
+
+#![allow(unknown_lints, missing_docs_in_private_items)]
 
 extern crate clippy_lints;
 extern crate getopts;
@@ -15,6 +18,7 @@
 use rustc::session::config::{Input, ErrorOutputType};
 use std::path::PathBuf;
 use std::process::Command;
+use syntax::ast;
 
 use clippy_lints::utils::cargo;
 
@@ -36,28 +40,31 @@ impl<'a> CompilerCalls<'a> for ClippyCompilerCalls {
     fn early_callback(&mut self,
                       matches: &getopts::Matches,
                       sopts: &config::Options,
+                      cfg: &ast::CrateConfig,
                       descriptions: &rustc_errors::registry::Registry,
                       output: ErrorOutputType)
                       -> Compilation {
-        self.default.early_callback(matches, sopts, descriptions, output)
+        self.default.early_callback(matches, sopts, cfg, descriptions, output)
     }
     fn no_input(&mut self,
                 matches: &getopts::Matches,
                 sopts: &config::Options,
+                cfg: &ast::CrateConfig,
                 odir: &Option<PathBuf>,
                 ofile: &Option<PathBuf>,
                 descriptions: &rustc_errors::registry::Registry)
                 -> Option<(Input, Option<PathBuf>)> {
-        self.default.no_input(matches, sopts, odir, ofile, descriptions)
+        self.default.no_input(matches, sopts, cfg, odir, ofile, descriptions)
     }
     fn late_callback(&mut self,
                      matches: &getopts::Matches,
                      sess: &Session,
+                     cfg: &ast::CrateConfig,
                      input: &Input,
                      odir: &Option<PathBuf>,
                      ofile: &Option<PathBuf>)
                      -> Compilation {
-        self.default.late_callback(matches, sess, input, odir, ofile)
+        self.default.late_callback(matches, sess, cfg, input, odir, ofile)
     }
     fn build_controller(&mut self, sess: &Session, matches: &getopts::Matches) -> driver::CompileController<'a> {
         let mut control = self.default.build_controller(sess, matches);
@@ -66,7 +73,7 @@ fn build_controller(&mut self, sess: &Session, matches: &getopts::Matches) -> dr
             let old = std::mem::replace(&mut control.after_parse.callback, box |_| {});
             control.after_parse.callback = Box::new(move |state| {
                 {
-                    let mut registry = rustc_plugin::registry::Registry::new(state.session, state.krate.as_ref().expect("at this compilation stage the krate must be parsed"));
+                    let mut registry = rustc_plugin::registry::Registry::new(state.session, state.krate.as_ref().expect("at this compilation stage the krate must be parsed").span);
                     registry.args_hidden = Some(Vec::new());
                     clippy_lints::register_plugins(&mut registry);
 
@@ -104,6 +111,36 @@ fn build_controller(&mut self, sess: &Session, matches: &getopts::Matches) -> dr
 
 use std::path::Path;
 
+const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code.
+
+Usage:
+    cargo clippy [options] [--] [<opts>...]
+
+Common options:
+    -h, --help               Print this message
+    --features               Features to compile for the package
+
+Other options are the same as `cargo rustc`.
+
+To allow or deny a lint from the command line you can use `cargo clippy --`
+with:
+
+    -W --warn OPT       Set lint warnings
+    -A --allow OPT      Set lint allowed
+    -D --deny OPT       Set lint denied
+    -F --forbid OPT     Set lint forbidden
+
+The feature `cargo-clippy` is automatically defined for convenience. You can use
+it to allow or deny lints from the code, eg.:
+
+    #[cfg_attr(feature = "cargo-clippy", allow(needless_lifetimes))]
+"#;
+
+#[allow(print_stdout)]
+fn show_help() {
+    println!("{}", CARGO_CLIPPY_HELP);
+}
+
 pub fn main() {
     use std::env;
 
@@ -132,18 +169,44 @@ pub fn main() {
 
     if let Some("clippy") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
         // this arm is executed on the initial call to `cargo clippy`
-        let manifest_path = std::env::args().skip(2).find(|val| val.starts_with("--manifest-path="));
-        let mut metadata = cargo::metadata(manifest_path).expect("could not obtain cargo metadata");
+
+        if std::env::args().any(|a| a == "--help" || a == "-h") {
+            show_help();
+            return;
+        }
+
+        let manifest_path_arg = std::env::args().skip(2).find(|val| val.starts_with("--manifest-path="));
+
+        let mut metadata = cargo::metadata(manifest_path_arg.as_ref().map(AsRef::as_ref)).expect("could not obtain cargo metadata");
+
         assert_eq!(metadata.version, 1);
-        for target in metadata.packages.remove(0).targets {
+
+        let manifest_path = manifest_path_arg.map(|arg| PathBuf::from(Path::new(&arg["--manifest-path=".len()..])));
+
+        let current_dir = std::env::current_dir();
+
+        let package_index = metadata.packages.iter()
+            .position(|package| {
+                let package_manifest_path = Path::new(&package.manifest_path);
+                if let Some(ref manifest_path) = manifest_path {
+                    package_manifest_path == manifest_path
+                } else {
+                    let current_dir = current_dir.as_ref().expect("could not read current directory");
+                    let package_manifest_directory = package_manifest_path.parent().expect("could not find parent directory of package manifest");
+                    package_manifest_directory == current_dir
+                }
+            })
+            .expect("could not find matching package");
+        let package = metadata.packages.remove(package_index);
+        for target in package.targets {
             let args = std::env::args().skip(2);
             if let Some(first) = target.kind.get(0) {
                 if target.kind.len() > 1 || first.ends_with("lib") {
                     if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args), &dep_path, &sys_root) {
                         std::process::exit(code);
                     }
-                } else if first == "bin" {
-                    if let Err(code) = process(vec!["--bin".to_owned(), target.name].into_iter().chain(args), &dep_path, &sys_root) {
+                } else if ["bin", "example", "test", "bench"].contains(&&**first) {
+                    if let Err(code) = process(vec![format!("--{}", first), target.name].into_iter().chain(args), &dep_path, &sys_root) {
                         std::process::exit(code);
                     }
                 }
@@ -156,15 +219,18 @@ pub fn main() {
 
         // this conditional check for the --sysroot flag is there so users can call `cargo-clippy` directly
         // without having to pass --sysroot or anything
-        let args: Vec<String> = if env::args().any(|s| s == "--sysroot") {
+        let mut args: Vec<String> = if env::args().any(|s| s == "--sysroot") {
             env::args().collect()
         } else {
             env::args().chain(Some("--sysroot".to_owned())).chain(Some(sys_root)).collect()
         };
+
         // this check ensures that dependencies are built but not linted and the final crate is
         // linted but not built
+        args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
+
         let mut ccc = ClippyCompilerCalls::new(env::args().any(|s| s == "-Zno-trans"));
-        let (result, _) = rustc_driver::run_compiler(&args, &mut ccc);
+        let (result, _) = rustc_driver::run_compiler(&args, &mut ccc, None, None);
 
         if let Err(err_count) = result {
             if err_count > 0 {
@@ -194,6 +260,8 @@ fn process<P, I>(old_args: I, dep_path: P, sysroot: &str) -> Result<(), i32>
     args.push(String::from("--sysroot"));
     args.push(sysroot.to_owned());
     args.push("-Zno-trans".to_owned());
+    args.push("--cfg".to_owned());
+    args.push(r#"feature="cargo-clippy""#.to_owned());
 
     let path = std::env::current_exe().expect("current executable path invalid");
     let exit_status = std::process::Command::new("cargo")