]> git.lizzy.rs Git - rust.git/blob - src/main.rs
Merge pull request #2362 from flip1995/master
[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 use std::collections::HashMap;
7 use std::process;
8 use std::io::{self, Write};
9
10 extern crate cargo_metadata;
11
12 use std::path::Path;
13
14 const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code.
15
16 Usage:
17     cargo clippy [options] [--] [<opts>...]
18
19 Common options:
20     -h, --help               Print this message
21     --features               Features to compile for the package
22     -V, --version            Print version info and exit
23     --all                    Run over all packages in the current workspace
24
25 Other options are the same as `cargo rustc`.
26
27 To allow or deny a lint from the command line you can use `cargo clippy --`
28 with:
29
30     -W --warn OPT       Set lint warnings
31     -A --allow OPT      Set lint allowed
32     -D --deny OPT       Set lint denied
33     -F --forbid OPT     Set lint forbidden
34
35 The feature `cargo-clippy` is automatically defined for convenience. You can use
36 it to allow or deny lints from the code, eg.:
37
38     #[cfg_attr(feature = "cargo-clippy", allow(needless_lifetimes))]
39 "#;
40
41 #[allow(print_stdout)]
42 fn show_help() {
43     println!("{}", CARGO_CLIPPY_HELP);
44 }
45
46 #[allow(print_stdout)]
47 fn show_version() {
48     println!("{}", env!("CARGO_PKG_VERSION"));
49 }
50
51 pub fn main() {
52     // Check for version and help flags even when invoked as 'cargo-clippy'
53     if std::env::args().any(|a| a == "--help" || a == "-h") {
54         show_help();
55         return;
56     }
57     if std::env::args().any(|a| a == "--version" || a == "-V") {
58         show_version();
59         return;
60     }
61
62     let manifest_path_arg = std::env::args()
63         .skip(2)
64         .find(|val| val.starts_with("--manifest-path="));
65
66     let mut metadata = if let Ok(metadata) = cargo_metadata::metadata(manifest_path_arg.as_ref().map(AsRef::as_ref)) {
67         metadata
68     } else {
69         let _ = io::stderr().write_fmt(format_args!("error: Could not obtain cargo metadata.\n"));
70         process::exit(101);
71     };
72
73     let manifest_path = manifest_path_arg.map(|arg| {
74         Path::new(&arg["--manifest-path=".len()..])
75             .canonicalize()
76             .expect("manifest path could not be canonicalized")
77     });
78
79     let packages = if std::env::args().any(|a| a == "--all") {
80         metadata.packages
81     } else {
82         let package_index = {
83             if let Some(manifest_path) = manifest_path {
84                 metadata.packages.iter().position(|package| {
85                     let package_manifest_path = Path::new(&package.manifest_path)
86                         .canonicalize()
87                         .expect("package manifest path could not be canonicalized");
88                     package_manifest_path == manifest_path
89                 })
90             } else {
91                 let package_manifest_paths: HashMap<_, _> = metadata
92                     .packages
93                     .iter()
94                     .enumerate()
95                     .map(|(i, package)| {
96                         let package_manifest_path = Path::new(&package.manifest_path)
97                             .parent()
98                             .expect("could not find parent directory of package manifest")
99                             .canonicalize()
100                             .expect("package directory cannot be canonicalized");
101                         (package_manifest_path, i)
102                     })
103                     .collect();
104
105                 let current_dir = std::env::current_dir()
106                     .expect("could not read current directory")
107                     .canonicalize()
108                     .expect("current directory cannot be canonicalized");
109
110                 let mut current_path: &Path = &current_dir;
111
112                 // This gets the most-recent parent (the one that takes the fewest `cd ..`s to
113                 // reach).
114                 loop {
115                     if let Some(&package_index) = package_manifest_paths.get(current_path) {
116                         break Some(package_index);
117                     } else {
118                         // We'll never reach the filesystem root, because to get to this point in the
119                         // code
120                         // the call to `cargo_metadata::metadata` must have succeeded. So it's okay to
121                         // unwrap the current path's parent.
122                         current_path = current_path
123                             .parent()
124                             .unwrap_or_else(|| panic!("could not find parent of path {}", current_path.display()));
125                     }
126                 }
127             }
128         }.expect("could not find matching package");
129
130         vec![metadata.packages.remove(package_index)]
131     };
132
133     for package in packages {
134         let manifest_path = package.manifest_path;
135
136         for target in package.targets {
137             let args = std::env::args()
138                 .skip(2)
139                 .filter(|a| a != "--all" && !a.starts_with("--manifest-path="));
140
141             let args = std::iter::once(format!("--manifest-path={}", manifest_path)).chain(args);
142             if let Some(first) = target.kind.get(0) {
143                 if target.kind.len() > 1 || first.ends_with("lib") {
144                     println!("lib: {}", target.name);
145                     if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args)) {
146                         std::process::exit(code);
147                     }
148                 } else if ["bin", "example", "test", "bench"].contains(&&**first) {
149                     println!("{}: {}", first, target.name);
150                     if let Err(code) = process(
151                         vec![format!("--{}", first), target.name]
152                             .into_iter()
153                             .chain(args),
154                     ) {
155                         std::process::exit(code);
156                     }
157                 }
158             } else {
159                 panic!("badly formatted cargo metadata: target::kind is an empty array");
160             }
161         }
162     }
163 }
164
165 fn process<I>(old_args: I) -> Result<(), i32>
166 where
167     I: Iterator<Item = String>,
168 {
169     let mut args = vec!["rustc".to_owned()];
170
171     let mut found_dashes = false;
172     for arg in old_args {
173         found_dashes |= arg == "--";
174         args.push(arg);
175     }
176     if !found_dashes {
177         args.push("--".to_owned());
178     }
179     args.push("--emit=metadata".to_owned());
180     args.push("--cfg".to_owned());
181     args.push(r#"feature="cargo-clippy""#.to_owned());
182
183     let mut path = std::env::current_exe()
184         .expect("current executable path invalid")
185         .with_file_name("clippy-driver");
186     if cfg!(windows) {
187         path.set_extension("exe");
188     }
189     let exit_status = std::process::Command::new("cargo")
190         .args(&args)
191         .env("RUSTC_WRAPPER", path)
192         .spawn()
193         .expect("could not run cargo")
194         .wait()
195         .expect("failed to wait for cargo?");
196
197     if exit_status.success() {
198         Ok(())
199     } else {
200         Err(exit_status.code().unwrap_or(-1))
201     }
202 }