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