]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/lintcheck/src/main.rs
Add 'library/portable-simd/' from commit '1ce1c645cf27c4acdefe6ec8a11d1f0491954a99'
[rust.git] / src / tools / clippy / lintcheck / src / main.rs
1 // Run clippy on a fixed set of crates and collect the warnings.
2 // This helps observing the impact clippy changes have on a set of real-world code (and not just our
3 // testsuite).
4 //
5 // When a new lint is introduced, we can search the results for new warnings and check for false
6 // positives.
7
8 #![allow(clippy::collapsible_else_if)]
9
10 use std::ffi::OsStr;
11 use std::process::Command;
12 use std::sync::atomic::{AtomicUsize, Ordering};
13 use std::{collections::HashMap, io::ErrorKind};
14 use std::{
15     env, fmt,
16     fs::write,
17     path::{Path, PathBuf},
18     thread,
19     time::Duration,
20 };
21
22 use clap::{App, Arg, ArgMatches};
23 use rayon::prelude::*;
24 use serde::{Deserialize, Serialize};
25 use serde_json::Value;
26 use walkdir::{DirEntry, WalkDir};
27
28 #[cfg(not(windows))]
29 const CLIPPY_DRIVER_PATH: &str = "target/debug/clippy-driver";
30 #[cfg(not(windows))]
31 const CARGO_CLIPPY_PATH: &str = "target/debug/cargo-clippy";
32
33 #[cfg(windows)]
34 const CLIPPY_DRIVER_PATH: &str = "target/debug/clippy-driver.exe";
35 #[cfg(windows)]
36 const CARGO_CLIPPY_PATH: &str = "target/debug/cargo-clippy.exe";
37
38 const LINTCHECK_DOWNLOADS: &str = "target/lintcheck/downloads";
39 const LINTCHECK_SOURCES: &str = "target/lintcheck/sources";
40
41 /// List of sources to check, loaded from a .toml file
42 #[derive(Debug, Serialize, Deserialize)]
43 struct SourceList {
44     crates: HashMap<String, TomlCrate>,
45 }
46
47 /// A crate source stored inside the .toml
48 /// will be translated into on one of the `CrateSource` variants
49 #[derive(Debug, Serialize, Deserialize)]
50 struct TomlCrate {
51     name: String,
52     versions: Option<Vec<String>>,
53     git_url: Option<String>,
54     git_hash: Option<String>,
55     path: Option<String>,
56     options: Option<Vec<String>>,
57 }
58
59 /// Represents an archive we download from crates.io, or a git repo, or a local repo/folder
60 /// Once processed (downloaded/extracted/cloned/copied...), this will be translated into a `Crate`
61 #[derive(Debug, Serialize, Deserialize, Eq, Hash, PartialEq, Ord, PartialOrd)]
62 enum CrateSource {
63     CratesIo {
64         name: String,
65         version: String,
66         options: Option<Vec<String>>,
67     },
68     Git {
69         name: String,
70         url: String,
71         commit: String,
72         options: Option<Vec<String>>,
73     },
74     Path {
75         name: String,
76         path: PathBuf,
77         options: Option<Vec<String>>,
78     },
79 }
80
81 /// Represents the actual source code of a crate that we ran "cargo clippy" on
82 #[derive(Debug)]
83 struct Crate {
84     version: String,
85     name: String,
86     // path to the extracted sources that clippy can check
87     path: PathBuf,
88     options: Option<Vec<String>>,
89 }
90
91 /// A single warning that clippy issued while checking a `Crate`
92 #[derive(Debug)]
93 struct ClippyWarning {
94     crate_name: String,
95     crate_version: String,
96     file: String,
97     line: String,
98     column: String,
99     linttype: String,
100     message: String,
101     is_ice: bool,
102 }
103
104 impl std::fmt::Display for ClippyWarning {
105     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106         writeln!(
107             f,
108             r#"target/lintcheck/sources/{}-{}/{}:{}:{} {} "{}""#,
109             &self.crate_name, &self.crate_version, &self.file, &self.line, &self.column, &self.linttype, &self.message
110         )
111     }
112 }
113
114 fn get(path: &str) -> Result<ureq::Response, ureq::Error> {
115     const MAX_RETRIES: u8 = 4;
116     let mut retries = 0;
117     loop {
118         match ureq::get(path).call() {
119             Ok(res) => return Ok(res),
120             Err(e) if retries >= MAX_RETRIES => return Err(e),
121             Err(ureq::Error::Transport(e)) => eprintln!("Error: {}", e),
122             Err(e) => return Err(e),
123         }
124         eprintln!("retrying in {} seconds...", retries);
125         thread::sleep(Duration::from_secs(retries as u64));
126         retries += 1;
127     }
128 }
129
130 impl CrateSource {
131     /// Makes the sources available on the disk for clippy to check.
132     /// Clones a git repo and checks out the specified commit or downloads a crate from crates.io or
133     /// copies a local folder
134     fn download_and_extract(&self) -> Crate {
135         match self {
136             CrateSource::CratesIo { name, version, options } => {
137                 let extract_dir = PathBuf::from(LINTCHECK_SOURCES);
138                 let krate_download_dir = PathBuf::from(LINTCHECK_DOWNLOADS);
139
140                 // url to download the crate from crates.io
141                 let url = format!("https://crates.io/api/v1/crates/{}/{}/download", name, version);
142                 println!("Downloading and extracting {} {} from {}", name, version, url);
143                 create_dirs(&krate_download_dir, &extract_dir);
144
145                 let krate_file_path = krate_download_dir.join(format!("{}-{}.crate.tar.gz", name, version));
146                 // don't download/extract if we already have done so
147                 if !krate_file_path.is_file() {
148                     // create a file path to download and write the crate data into
149                     let mut krate_dest = std::fs::File::create(&krate_file_path).unwrap();
150                     let mut krate_req = get(&url).unwrap().into_reader();
151                     // copy the crate into the file
152                     std::io::copy(&mut krate_req, &mut krate_dest).unwrap();
153
154                     // unzip the tarball
155                     let ungz_tar = flate2::read::GzDecoder::new(std::fs::File::open(&krate_file_path).unwrap());
156                     // extract the tar archive
157                     let mut archive = tar::Archive::new(ungz_tar);
158                     archive.unpack(&extract_dir).expect("Failed to extract!");
159                 }
160                 // crate is extracted, return a new Krate object which contains the path to the extracted
161                 // sources that clippy can check
162                 Crate {
163                     version: version.clone(),
164                     name: name.clone(),
165                     path: extract_dir.join(format!("{}-{}/", name, version)),
166                     options: options.clone(),
167                 }
168             },
169             CrateSource::Git {
170                 name,
171                 url,
172                 commit,
173                 options,
174             } => {
175                 let repo_path = {
176                     let mut repo_path = PathBuf::from(LINTCHECK_SOURCES);
177                     // add a -git suffix in case we have the same crate from crates.io and a git repo
178                     repo_path.push(format!("{}-git", name));
179                     repo_path
180                 };
181                 // clone the repo if we have not done so
182                 if !repo_path.is_dir() {
183                     println!("Cloning {} and checking out {}", url, commit);
184                     if !Command::new("git")
185                         .arg("clone")
186                         .arg(url)
187                         .arg(&repo_path)
188                         .status()
189                         .expect("Failed to clone git repo!")
190                         .success()
191                     {
192                         eprintln!("Failed to clone {} into {}", url, repo_path.display())
193                     }
194                 }
195                 // check out the commit/branch/whatever
196                 if !Command::new("git")
197                     .arg("checkout")
198                     .arg(commit)
199                     .current_dir(&repo_path)
200                     .status()
201                     .expect("Failed to check out commit")
202                     .success()
203                 {
204                     eprintln!("Failed to checkout {} of repo at {}", commit, repo_path.display())
205                 }
206
207                 Crate {
208                     version: commit.clone(),
209                     name: name.clone(),
210                     path: repo_path,
211                     options: options.clone(),
212                 }
213             },
214             CrateSource::Path { name, path, options } => {
215                 // copy path into the dest_crate_root but skip directories that contain a CACHEDIR.TAG file.
216                 // The target/ directory contains a CACHEDIR.TAG file so it is the most commonly skipped directory
217                 // as a result of this filter.
218                 let dest_crate_root = PathBuf::from(LINTCHECK_SOURCES).join(name);
219                 if dest_crate_root.exists() {
220                     println!("Deleting existing directory at {:?}", dest_crate_root);
221                     std::fs::remove_dir_all(&dest_crate_root).unwrap();
222                 }
223
224                 println!("Copying {:?} to {:?}", path, dest_crate_root);
225
226                 fn is_cache_dir(entry: &DirEntry) -> bool {
227                     std::fs::read(entry.path().join("CACHEDIR.TAG"))
228                         .map(|x| x.starts_with(b"Signature: 8a477f597d28d172789f06886806bc55"))
229                         .unwrap_or(false)
230                 }
231
232                 for entry in WalkDir::new(path).into_iter().filter_entry(|e| !is_cache_dir(e)) {
233                     let entry = entry.unwrap();
234                     let entry_path = entry.path();
235                     let relative_entry_path = entry_path.strip_prefix(path).unwrap();
236                     let dest_path = dest_crate_root.join(relative_entry_path);
237                     let metadata = entry_path.symlink_metadata().unwrap();
238
239                     if metadata.is_dir() {
240                         std::fs::create_dir(dest_path).unwrap();
241                     } else if metadata.is_file() {
242                         std::fs::copy(entry_path, dest_path).unwrap();
243                     }
244                 }
245
246                 Crate {
247                     version: String::from("local"),
248                     name: name.clone(),
249                     path: dest_crate_root,
250                     options: options.clone(),
251                 }
252             },
253         }
254     }
255 }
256
257 impl Crate {
258     /// Run `cargo clippy` on the `Crate` and collect and return all the lint warnings that clippy
259     /// issued
260     fn run_clippy_lints(
261         &self,
262         cargo_clippy_path: &Path,
263         target_dir_index: &AtomicUsize,
264         thread_limit: usize,
265         total_crates_to_lint: usize,
266         fix: bool,
267     ) -> Vec<ClippyWarning> {
268         // advance the atomic index by one
269         let index = target_dir_index.fetch_add(1, Ordering::SeqCst);
270         // "loop" the index within 0..thread_limit
271         let thread_index = index % thread_limit;
272         let perc = (index * 100) / total_crates_to_lint;
273
274         if thread_limit == 1 {
275             println!(
276                 "{}/{} {}% Linting {} {}",
277                 index, total_crates_to_lint, perc, &self.name, &self.version
278             );
279         } else {
280             println!(
281                 "{}/{} {}% Linting {} {} in target dir {:?}",
282                 index, total_crates_to_lint, perc, &self.name, &self.version, thread_index
283             );
284         }
285
286         let cargo_clippy_path = std::fs::canonicalize(cargo_clippy_path).unwrap();
287
288         let shared_target_dir = clippy_project_root().join("target/lintcheck/shared_target_dir");
289
290         let mut args = if fix {
291             vec!["--fix", "--allow-no-vcs", "--", "--cap-lints=warn"]
292         } else {
293             vec!["--", "--message-format=json", "--", "--cap-lints=warn"]
294         };
295
296         if let Some(options) = &self.options {
297             for opt in options {
298                 args.push(opt);
299             }
300         } else {
301             args.extend(&["-Wclippy::pedantic", "-Wclippy::cargo"])
302         }
303
304         let all_output = std::process::Command::new(&cargo_clippy_path)
305             // use the looping index to create individual target dirs
306             .env(
307                 "CARGO_TARGET_DIR",
308                 shared_target_dir.join(format!("_{:?}", thread_index)),
309             )
310             // lint warnings will look like this:
311             // src/cargo/ops/cargo_compile.rs:127:35: warning: usage of `FromIterator::from_iter`
312             .args(&args)
313             .current_dir(&self.path)
314             .output()
315             .unwrap_or_else(|error| {
316                 panic!(
317                     "Encountered error:\n{:?}\ncargo_clippy_path: {}\ncrate path:{}\n",
318                     error,
319                     &cargo_clippy_path.display(),
320                     &self.path.display()
321                 );
322             });
323         let stdout = String::from_utf8_lossy(&all_output.stdout);
324         let stderr = String::from_utf8_lossy(&all_output.stderr);
325         let status = &all_output.status;
326
327         if !status.success() {
328             eprintln!(
329                 "\nWARNING: bad exit status after checking {} {} \n",
330                 self.name, self.version
331             );
332         }
333
334         if fix {
335             if let Some(stderr) = stderr
336                 .lines()
337                 .find(|line| line.contains("failed to automatically apply fixes suggested by rustc to crate"))
338             {
339                 let subcrate = &stderr[63..];
340                 println!(
341                     "ERROR: failed to apply some suggetion to {} / to (sub)crate {}",
342                     self.name, subcrate
343                 );
344             }
345             // fast path, we don't need the warnings anyway
346             return Vec::new();
347         }
348
349         let output_lines = stdout.lines();
350         let warnings: Vec<ClippyWarning> = output_lines
351             .into_iter()
352             // get all clippy warnings and ICEs
353             .filter(|line| filter_clippy_warnings(&line))
354             .map(|json_msg| parse_json_message(json_msg, &self))
355             .collect();
356
357         warnings
358     }
359 }
360
361 #[derive(Debug)]
362 struct LintcheckConfig {
363     // max number of jobs to spawn (default 1)
364     max_jobs: usize,
365     // we read the sources to check from here
366     sources_toml_path: PathBuf,
367     // we save the clippy lint results here
368     lintcheck_results_path: PathBuf,
369     // whether to just run --fix and not collect all the warnings
370     fix: bool,
371 }
372
373 impl LintcheckConfig {
374     fn from_clap(clap_config: &ArgMatches) -> Self {
375         // first, check if we got anything passed via the LINTCHECK_TOML env var,
376         // if not, ask clap if we got any value for --crates-toml  <foo>
377         // if not, use the default "lintcheck/lintcheck_crates.toml"
378         let sources_toml = env::var("LINTCHECK_TOML").unwrap_or_else(|_| {
379             clap_config
380                 .value_of("crates-toml")
381                 .clone()
382                 .unwrap_or("lintcheck/lintcheck_crates.toml")
383                 .to_string()
384         });
385
386         let sources_toml_path = PathBuf::from(sources_toml);
387
388         // for the path where we save the lint results, get the filename without extension (so for
389         // wasd.toml, use "wasd"...)
390         let filename: PathBuf = sources_toml_path.file_stem().unwrap().into();
391         let lintcheck_results_path = PathBuf::from(format!("lintcheck-logs/{}_logs.txt", filename.display()));
392
393         // look at the --threads arg, if 0 is passed, ask rayon rayon how many threads it would spawn and
394         // use half of that for the physical core count
395         // by default use a single thread
396         let max_jobs = match clap_config.value_of("threads") {
397             Some(threads) => {
398                 let threads: usize = threads
399                     .parse()
400                     .unwrap_or_else(|_| panic!("Failed to parse '{}' to a digit", threads));
401                 if threads == 0 {
402                     // automatic choice
403                     // Rayon seems to return thread count so half that for core count
404                     (rayon::current_num_threads() / 2) as usize
405                 } else {
406                     threads
407                 }
408             },
409             // no -j passed, use a single thread
410             None => 1,
411         };
412         let fix: bool = clap_config.is_present("fix");
413
414         LintcheckConfig {
415             max_jobs,
416             sources_toml_path,
417             lintcheck_results_path,
418             fix,
419         }
420     }
421 }
422
423 /// takes a single json-formatted clippy warnings and returns true (we are interested in that line)
424 /// or false (we aren't)
425 fn filter_clippy_warnings(line: &str) -> bool {
426     // we want to collect ICEs because clippy might have crashed.
427     // these are summarized later
428     if line.contains("internal compiler error: ") {
429         return true;
430     }
431     // in general, we want all clippy warnings
432     // however due to some kind of bug, sometimes there are absolute paths
433     // to libcore files inside the message
434     // or we end up with cargo-metadata output (https://github.com/rust-lang/rust-clippy/issues/6508)
435
436     // filter out these message to avoid unnecessary noise in the logs
437     if line.contains("clippy::")
438         && !(line.contains("could not read cargo metadata")
439             || (line.contains(".rustup") && line.contains("toolchains")))
440     {
441         return true;
442     }
443     false
444 }
445
446 /// Builds clippy inside the repo to make sure we have a clippy executable we can use.
447 fn build_clippy() {
448     let status = Command::new("cargo")
449         .arg("build")
450         .status()
451         .expect("Failed to build clippy!");
452     if !status.success() {
453         eprintln!("Error: Failed to compile Clippy!");
454         std::process::exit(1);
455     }
456 }
457
458 /// Read a `toml` file and return a list of `CrateSources` that we want to check with clippy
459 fn read_crates(toml_path: &Path) -> Vec<CrateSource> {
460     let toml_content: String =
461         std::fs::read_to_string(&toml_path).unwrap_or_else(|_| panic!("Failed to read {}", toml_path.display()));
462     let crate_list: SourceList =
463         toml::from_str(&toml_content).unwrap_or_else(|e| panic!("Failed to parse {}: \n{}", toml_path.display(), e));
464     // parse the hashmap of the toml file into a list of crates
465     let tomlcrates: Vec<TomlCrate> = crate_list
466         .crates
467         .into_iter()
468         .map(|(_cratename, tomlcrate)| tomlcrate)
469         .collect();
470
471     // flatten TomlCrates into CrateSources (one TomlCrates may represent several versions of a crate =>
472     // multiple Cratesources)
473     let mut crate_sources = Vec::new();
474     tomlcrates.into_iter().for_each(|tk| {
475         if let Some(ref path) = tk.path {
476             crate_sources.push(CrateSource::Path {
477                 name: tk.name.clone(),
478                 path: PathBuf::from(path),
479                 options: tk.options.clone(),
480             });
481         }
482
483         // if we have multiple versions, save each one
484         if let Some(ref versions) = tk.versions {
485             versions.iter().for_each(|ver| {
486                 crate_sources.push(CrateSource::CratesIo {
487                     name: tk.name.clone(),
488                     version: ver.to_string(),
489                     options: tk.options.clone(),
490                 });
491             })
492         }
493         // otherwise, we should have a git source
494         if tk.git_url.is_some() && tk.git_hash.is_some() {
495             crate_sources.push(CrateSource::Git {
496                 name: tk.name.clone(),
497                 url: tk.git_url.clone().unwrap(),
498                 commit: tk.git_hash.clone().unwrap(),
499                 options: tk.options.clone(),
500             });
501         }
502         // if we have a version as well as a git data OR only one git data, something is funky
503         if tk.versions.is_some() && (tk.git_url.is_some() || tk.git_hash.is_some())
504             || tk.git_hash.is_some() != tk.git_url.is_some()
505         {
506             eprintln!("tomlkrate: {:?}", tk);
507             if tk.git_hash.is_some() != tk.git_url.is_some() {
508                 panic!("Error: Encountered TomlCrate with only one of git_hash and git_url!");
509             }
510             if tk.path.is_some() && (tk.git_hash.is_some() || tk.versions.is_some()) {
511                 panic!("Error: TomlCrate can only have one of 'git_.*', 'version' or 'path' fields");
512             }
513             unreachable!("Failed to translate TomlCrate into CrateSource!");
514         }
515     });
516     // sort the crates
517     crate_sources.sort();
518
519     crate_sources
520 }
521
522 /// Parse the json output of clippy and return a `ClippyWarning`
523 fn parse_json_message(json_message: &str, krate: &Crate) -> ClippyWarning {
524     let jmsg: Value = serde_json::from_str(&json_message).unwrap_or_else(|e| panic!("Failed to parse json:\n{:?}", e));
525
526     let file: String = jmsg["message"]["spans"][0]["file_name"]
527         .to_string()
528         .trim_matches('"')
529         .into();
530
531     let file = if file.contains(".cargo") {
532         // if we deal with macros, a filename may show the origin of a macro which can be inside a dep from
533         // the registry.
534         // don't show the full path in that case.
535
536         // /home/matthias/.cargo/registry/src/github.com-1ecc6299db9ec823/syn-1.0.63/src/custom_keyword.rs
537         let path = PathBuf::from(file);
538         let mut piter = path.iter();
539         // consume all elements until we find ".cargo", so that "/home/matthias" is skipped
540         let _: Option<&OsStr> = piter.find(|x| x == &std::ffi::OsString::from(".cargo"));
541         // collect the remaining segments
542         let file = piter.collect::<PathBuf>();
543         format!("{}", file.display())
544     } else {
545         file
546     };
547
548     ClippyWarning {
549         crate_name: krate.name.to_string(),
550         crate_version: krate.version.to_string(),
551         file,
552         line: jmsg["message"]["spans"][0]["line_start"]
553             .to_string()
554             .trim_matches('"')
555             .into(),
556         column: jmsg["message"]["spans"][0]["text"][0]["highlight_start"]
557             .to_string()
558             .trim_matches('"')
559             .into(),
560         linttype: jmsg["message"]["code"]["code"].to_string().trim_matches('"').into(),
561         message: jmsg["message"]["message"].to_string().trim_matches('"').into(),
562         is_ice: json_message.contains("internal compiler error: "),
563     }
564 }
565
566 /// Generate a short list of occuring lints-types and their count
567 fn gather_stats(clippy_warnings: &[ClippyWarning]) -> (String, HashMap<&String, usize>) {
568     // count lint type occurrences
569     let mut counter: HashMap<&String, usize> = HashMap::new();
570     clippy_warnings
571         .iter()
572         .for_each(|wrn| *counter.entry(&wrn.linttype).or_insert(0) += 1);
573
574     // collect into a tupled list for sorting
575     let mut stats: Vec<(&&String, &usize)> = counter.iter().map(|(lint, count)| (lint, count)).collect();
576     // sort by "000{count} {clippy::lintname}"
577     // to not have a lint with 200 and 2 warnings take the same spot
578     stats.sort_by_key(|(lint, count)| format!("{:0>4}, {}", count, lint));
579
580     let stats_string = stats
581         .iter()
582         .map(|(lint, count)| format!("{} {}\n", lint, count))
583         .collect::<String>();
584
585     (stats_string, counter)
586 }
587
588 /// check if the latest modification of the logfile is older than the modification date of the
589 /// clippy binary, if this is true, we should clean the lintchec shared target directory and recheck
590 fn lintcheck_needs_rerun(lintcheck_logs_path: &Path) -> bool {
591     if !lintcheck_logs_path.exists() {
592         return true;
593     }
594
595     let clippy_modified: std::time::SystemTime = {
596         let mut times = [CLIPPY_DRIVER_PATH, CARGO_CLIPPY_PATH].iter().map(|p| {
597             std::fs::metadata(p)
598                 .expect("failed to get metadata of file")
599                 .modified()
600                 .expect("failed to get modification date")
601         });
602         // the oldest modification of either of the binaries
603         std::cmp::max(times.next().unwrap(), times.next().unwrap())
604     };
605
606     let logs_modified: std::time::SystemTime = std::fs::metadata(lintcheck_logs_path)
607         .expect("failed to get metadata of file")
608         .modified()
609         .expect("failed to get modification date");
610
611     // time is represented in seconds since X
612     // logs_modified 2 and clippy_modified 5 means clippy binary is older and we need to recheck
613     logs_modified < clippy_modified
614 }
615
616 fn is_in_clippy_root() -> bool {
617     if let Ok(pb) = std::env::current_dir() {
618         if let Some(file) = pb.file_name() {
619             return file == PathBuf::from("rust-clippy");
620         }
621     }
622
623     false
624 }
625
626 /// lintchecks `main()` function
627 ///
628 /// # Panics
629 ///
630 /// This function panics if the clippy binaries don't exist
631 /// or if lintcheck is executed from the wrong directory (aka none-repo-root)
632 pub fn main() {
633     // assert that we launch lintcheck from the repo root (via cargo lintcheck)
634     if !is_in_clippy_root() {
635         eprintln!("lintcheck needs to be run from clippys repo root!\nUse `cargo lintcheck` alternatively.");
636         std::process::exit(3);
637     }
638
639     let clap_config = &get_clap_config();
640
641     let config = LintcheckConfig::from_clap(clap_config);
642
643     println!("Compiling clippy...");
644     build_clippy();
645     println!("Done compiling");
646
647     // if the clippy bin is newer than our logs, throw away target dirs to force clippy to
648     // refresh the logs
649     if lintcheck_needs_rerun(&config.lintcheck_results_path) {
650         let shared_target_dir = "target/lintcheck/shared_target_dir";
651         // if we get an Err here, the shared target dir probably does simply not exist
652         if let Ok(metadata) = std::fs::metadata(&shared_target_dir) {
653             if metadata.is_dir() {
654                 println!("Clippy is newer than lint check logs, clearing lintcheck shared target dir...");
655                 std::fs::remove_dir_all(&shared_target_dir)
656                     .expect("failed to remove target/lintcheck/shared_target_dir");
657             }
658         }
659     }
660
661     let cargo_clippy_path: PathBuf = PathBuf::from(CARGO_CLIPPY_PATH)
662         .canonicalize()
663         .expect("failed to canonicalize path to clippy binary");
664
665     // assert that clippy is found
666     assert!(
667         cargo_clippy_path.is_file(),
668         "target/debug/cargo-clippy binary not found! {}",
669         cargo_clippy_path.display()
670     );
671
672     let clippy_ver = std::process::Command::new(CARGO_CLIPPY_PATH)
673         .arg("--version")
674         .output()
675         .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
676         .expect("could not get clippy version!");
677
678     // download and extract the crates, then run clippy on them and collect clippys warnings
679     // flatten into one big list of warnings
680
681     let crates = read_crates(&config.sources_toml_path);
682     let old_stats = read_stats_from_file(&config.lintcheck_results_path);
683
684     let counter = AtomicUsize::new(1);
685
686     let clippy_warnings: Vec<ClippyWarning> = if let Some(only_one_crate) = clap_config.value_of("only") {
687         // if we don't have the specified crate in the .toml, throw an error
688         if !crates.iter().any(|krate| {
689             let name = match krate {
690                 CrateSource::CratesIo { name, .. } | CrateSource::Git { name, .. } | CrateSource::Path { name, .. } => {
691                     name
692                 },
693             };
694             name == only_one_crate
695         }) {
696             eprintln!(
697                 "ERROR: could not find crate '{}' in lintcheck/lintcheck_crates.toml",
698                 only_one_crate
699             );
700             std::process::exit(1);
701         }
702
703         // only check a single crate that was passed via cmdline
704         crates
705             .into_iter()
706             .map(|krate| krate.download_and_extract())
707             .filter(|krate| krate.name == only_one_crate)
708             .flat_map(|krate| krate.run_clippy_lints(&cargo_clippy_path, &AtomicUsize::new(0), 1, 1, config.fix))
709             .collect()
710     } else {
711         if config.max_jobs > 1 {
712             // run parallel with rayon
713
714             // Ask rayon for thread count. Assume that half of that is the number of physical cores
715             // Use one target dir for each core so that we can run N clippys in parallel.
716             // We need to use different target dirs because cargo would lock them for a single build otherwise,
717             // killing the parallelism. However this also means that deps will only be reused half/a
718             // quarter of the time which might result in a longer wall clock runtime
719
720             // This helps when we check many small crates with dep-trees that don't have a lot of branches in
721             // order to achive some kind of parallelism
722
723             // by default, use a single thread
724             let num_cpus = config.max_jobs;
725             let num_crates = crates.len();
726
727             // check all crates (default)
728             crates
729                 .into_par_iter()
730                 .map(|krate| krate.download_and_extract())
731                 .flat_map(|krate| {
732                     krate.run_clippy_lints(&cargo_clippy_path, &counter, num_cpus, num_crates, config.fix)
733                 })
734                 .collect()
735         } else {
736             // run sequential
737             let num_crates = crates.len();
738             crates
739                 .into_iter()
740                 .map(|krate| krate.download_and_extract())
741                 .flat_map(|krate| krate.run_clippy_lints(&cargo_clippy_path, &counter, 1, num_crates, config.fix))
742                 .collect()
743         }
744     };
745
746     // if we are in --fix mode, don't change the log files, terminate here
747     if config.fix {
748         return;
749     }
750
751     // generate some stats
752     let (stats_formatted, new_stats) = gather_stats(&clippy_warnings);
753
754     // grab crashes/ICEs, save the crate name and the ice message
755     let ices: Vec<(&String, &String)> = clippy_warnings
756         .iter()
757         .filter(|warning| warning.is_ice)
758         .map(|w| (&w.crate_name, &w.message))
759         .collect();
760
761     let mut all_msgs: Vec<String> = clippy_warnings.iter().map(ToString::to_string).collect();
762     all_msgs.sort();
763     all_msgs.push("\n\n\n\nStats:\n".into());
764     all_msgs.push(stats_formatted);
765
766     // save the text into lintcheck-logs/logs.txt
767     let mut text = clippy_ver; // clippy version number on top
768     text.push_str(&format!("\n{}", all_msgs.join("")));
769     text.push_str("ICEs:\n");
770     ices.iter()
771         .for_each(|(cratename, msg)| text.push_str(&format!("{}: '{}'", cratename, msg)));
772
773     println!("Writing logs to {}", config.lintcheck_results_path.display());
774     write(&config.lintcheck_results_path, text).unwrap();
775
776     print_stats(old_stats, new_stats);
777 }
778
779 /// read the previous stats from the lintcheck-log file
780 fn read_stats_from_file(file_path: &Path) -> HashMap<String, usize> {
781     let file_content: String = match std::fs::read_to_string(file_path).ok() {
782         Some(content) => content,
783         None => {
784             return HashMap::new();
785         },
786     };
787
788     let lines: Vec<String> = file_content.lines().map(ToString::to_string).collect();
789
790     // search for the beginning "Stats:" and the end "ICEs:" of the section we want
791     let start = lines.iter().position(|line| line == "Stats:").unwrap();
792     let end = lines.iter().position(|line| line == "ICEs:").unwrap();
793
794     let stats_lines = &lines[start + 1..end];
795
796     stats_lines
797         .iter()
798         .map(|line| {
799             let mut spl = line.split(' ');
800             (
801                 spl.next().unwrap().to_string(),
802                 spl.next().unwrap().parse::<usize>().unwrap(),
803             )
804         })
805         .collect::<HashMap<String, usize>>()
806 }
807
808 /// print how lint counts changed between runs
809 fn print_stats(old_stats: HashMap<String, usize>, new_stats: HashMap<&String, usize>) {
810     let same_in_both_hashmaps = old_stats
811         .iter()
812         .filter(|(old_key, old_val)| new_stats.get::<&String>(&old_key) == Some(old_val))
813         .map(|(k, v)| (k.to_string(), *v))
814         .collect::<Vec<(String, usize)>>();
815
816     let mut old_stats_deduped = old_stats;
817     let mut new_stats_deduped = new_stats;
818
819     // remove duplicates from both hashmaps
820     same_in_both_hashmaps.iter().for_each(|(k, v)| {
821         assert!(old_stats_deduped.remove(k) == Some(*v));
822         assert!(new_stats_deduped.remove(k) == Some(*v));
823     });
824
825     println!("\nStats:");
826
827     // list all new counts  (key is in new stats but not in old stats)
828     new_stats_deduped
829         .iter()
830         .filter(|(new_key, _)| old_stats_deduped.get::<str>(&new_key).is_none())
831         .for_each(|(new_key, new_value)| {
832             println!("{} 0 => {}", new_key, new_value);
833         });
834
835     // list all changed counts (key is in both maps but value differs)
836     new_stats_deduped
837         .iter()
838         .filter(|(new_key, _new_val)| old_stats_deduped.get::<str>(&new_key).is_some())
839         .for_each(|(new_key, new_val)| {
840             let old_val = old_stats_deduped.get::<str>(&new_key).unwrap();
841             println!("{} {} => {}", new_key, old_val, new_val);
842         });
843
844     // list all gone counts (key is in old status but not in new stats)
845     old_stats_deduped
846         .iter()
847         .filter(|(old_key, _)| new_stats_deduped.get::<&String>(&old_key).is_none())
848         .for_each(|(old_key, old_value)| {
849             println!("{} {} => 0", old_key, old_value);
850         });
851 }
852
853 /// Create necessary directories to run the lintcheck tool.
854 ///
855 /// # Panics
856 ///
857 /// This function panics if creating one of the dirs fails.
858 fn create_dirs(krate_download_dir: &Path, extract_dir: &Path) {
859     std::fs::create_dir("target/lintcheck/").unwrap_or_else(|err| {
860         if err.kind() != ErrorKind::AlreadyExists {
861             panic!("cannot create lintcheck target dir");
862         }
863     });
864     std::fs::create_dir(&krate_download_dir).unwrap_or_else(|err| {
865         if err.kind() != ErrorKind::AlreadyExists {
866             panic!("cannot create crate download dir");
867         }
868     });
869     std::fs::create_dir(&extract_dir).unwrap_or_else(|err| {
870         if err.kind() != ErrorKind::AlreadyExists {
871             panic!("cannot create crate extraction dir");
872         }
873     });
874 }
875
876 fn get_clap_config<'a>() -> ArgMatches<'a> {
877     App::new("lintcheck")
878         .about("run clippy on a set of crates and check output")
879         .arg(
880             Arg::with_name("only")
881                 .takes_value(true)
882                 .value_name("CRATE")
883                 .long("only")
884                 .help("only process a single crate of the list"),
885         )
886         .arg(
887             Arg::with_name("crates-toml")
888                 .takes_value(true)
889                 .value_name("CRATES-SOURCES-TOML-PATH")
890                 .long("crates-toml")
891                 .help("set the path for a crates.toml where lintcheck should read the sources from"),
892         )
893         .arg(
894             Arg::with_name("threads")
895                 .takes_value(true)
896                 .value_name("N")
897                 .short("j")
898                 .long("jobs")
899                 .help("number of threads to use, 0 automatic choice"),
900         )
901         .arg(
902             Arg::with_name("fix")
903                 .long("--fix")
904                 .help("runs cargo clippy --fix and checks if all suggestions apply"),
905         )
906         .get_matches()
907 }
908
909 /// Returns the path to the Clippy project directory
910 ///
911 /// # Panics
912 ///
913 /// Panics if the current directory could not be retrieved, there was an error reading any of the
914 /// Cargo.toml files or ancestor directory is the clippy root directory
915 #[must_use]
916 pub fn clippy_project_root() -> PathBuf {
917     let current_dir = std::env::current_dir().unwrap();
918     for path in current_dir.ancestors() {
919         let result = std::fs::read_to_string(path.join("Cargo.toml"));
920         if let Err(err) = &result {
921             if err.kind() == std::io::ErrorKind::NotFound {
922                 continue;
923             }
924         }
925
926         let content = result.unwrap();
927         if content.contains("[package]\nname = \"clippy\"") {
928             return path.to_path_buf();
929         }
930     }
931     panic!("error: Can't determine root of project. Please run inside a Clippy working dir.");
932 }
933
934 #[test]
935 fn lintcheck_test() {
936     let args = [
937         "run",
938         "--target-dir",
939         "lintcheck/target",
940         "--manifest-path",
941         "./lintcheck/Cargo.toml",
942         "--",
943         "--crates-toml",
944         "lintcheck/test_sources.toml",
945     ];
946     let status = std::process::Command::new("cargo")
947         .args(&args)
948         .current_dir("..") // repo root
949         .status();
950     //.output();
951
952     assert!(status.unwrap().success());
953 }