]> git.lizzy.rs Git - rust.git/blob - src/main.rs
Merge pull request #2202 from topecongiro/format
[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     use std::env;
53
54     if env::var("CLIPPY_DOGFOOD").is_ok() {
55         panic!("yummy");
56     }
57
58     // Check for version and help flags even when invoked as 'cargo-clippy'
59     if std::env::args().any(|a| a == "--help" || a == "-h") {
60         show_help();
61         return;
62     }
63     if std::env::args().any(|a| a == "--version" || a == "-V") {
64         show_version();
65         return;
66     }
67
68     let manifest_path_arg = std::env::args()
69         .skip(2)
70         .find(|val| val.starts_with("--manifest-path="));
71
72     let mut metadata = if let Ok(metadata) = cargo_metadata::metadata(manifest_path_arg.as_ref().map(AsRef::as_ref)) {
73         metadata
74     } else {
75         let _ = io::stderr().write_fmt(format_args!("error: Could not obtain cargo metadata.\n"));
76         process::exit(101);
77     };
78
79     let manifest_path = manifest_path_arg.map(|arg| {
80         Path::new(&arg["--manifest-path=".len()..])
81             .canonicalize()
82             .expect("manifest path could not be canonicalized")
83     });
84
85     let packages = if std::env::args().any(|a| a == "--all") {
86         metadata.packages
87     } else {
88         let package_index = {
89             if let Some(manifest_path) = manifest_path {
90                 metadata.packages.iter().position(|package| {
91                     let package_manifest_path = Path::new(&package.manifest_path)
92                         .canonicalize()
93                         .expect("package manifest path could not be canonicalized");
94                     package_manifest_path == manifest_path
95                 })
96             } else {
97                 let package_manifest_paths: HashMap<_, _> = metadata
98                     .packages
99                     .iter()
100                     .enumerate()
101                     .map(|(i, package)| {
102                         let package_manifest_path = Path::new(&package.manifest_path)
103                             .parent()
104                             .expect("could not find parent directory of package manifest")
105                             .canonicalize()
106                             .expect("package directory cannot be canonicalized");
107                         (package_manifest_path, i)
108                     })
109                     .collect();
110
111                 let current_dir = std::env::current_dir()
112                     .expect("could not read current directory")
113                     .canonicalize()
114                     .expect("current directory cannot be canonicalized");
115
116                 let mut current_path: &Path = &current_dir;
117
118                 // This gets the most-recent parent (the one that takes the fewest `cd ..`s to
119                 // reach).
120                 loop {
121                     if let Some(&package_index) = package_manifest_paths.get(current_path) {
122                         break Some(package_index);
123                     } else {
124                         // We'll never reach the filesystem root, because to get to this point in the
125                         // code
126                         // the call to `cargo_metadata::metadata` must have succeeded. So it's okay to
127                         // unwrap the current path's parent.
128                         current_path = current_path
129                             .parent()
130                             .unwrap_or_else(|| panic!("could not find parent of path {}", current_path.display()));
131                     }
132                 }
133             }
134         }.expect("could not find matching package");
135
136         vec![metadata.packages.remove(package_index)]
137     };
138
139     for package in packages {
140         let manifest_path = package.manifest_path;
141
142         for target in package.targets {
143             let args = std::env::args()
144                 .skip(2)
145                 .filter(|a| a != "--all" && !a.starts_with("--manifest-path="));
146
147             let args = std::iter::once(format!("--manifest-path={}", manifest_path)).chain(args);
148             if let Some(first) = target.kind.get(0) {
149                 if target.kind.len() > 1 || first.ends_with("lib") {
150                     if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args)) {
151                         std::process::exit(code);
152                     }
153                 } else if ["bin", "example", "test", "bench"].contains(&&**first) {
154                     if let Err(code) = process(
155                         vec![format!("--{}", first), target.name]
156                             .into_iter()
157                             .chain(args),
158                     ) {
159                         std::process::exit(code);
160                     }
161                 }
162             } else {
163                 panic!("badly formatted cargo metadata: target::kind is an empty array");
164             }
165         }
166     }
167 }
168
169 fn process<I>(old_args: I) -> Result<(), i32>
170 where
171     I: Iterator<Item = String>,
172 {
173     let mut args = vec!["rustc".to_owned()];
174
175     let mut found_dashes = false;
176     for arg in old_args {
177         found_dashes |= arg == "--";
178         args.push(arg);
179     }
180     if !found_dashes {
181         args.push("--".to_owned());
182     }
183     args.push("--emit=metadata".to_owned());
184     args.push("--cfg".to_owned());
185     args.push(r#"feature="cargo-clippy""#.to_owned());
186
187     let path = std::env::current_exe()
188         .expect("current executable path invalid")
189         .with_file_name("clippy-driver");
190     let exit_status = std::process::Command::new("cargo")
191         .args(&args)
192         .env("RUSTC_WRAPPER", path)
193         .spawn()
194         .expect("could not run cargo")
195         .wait()
196         .expect("failed to wait for cargo?");
197
198     if exit_status.success() {
199         Ok(())
200     } else {
201         Err(exit_status.code().unwrap_or(-1))
202     }
203 }