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