]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/lintcheck/src/main.rs
Merge commit 'ac0e10aa68325235069a842f47499852b2dee79e' into clippyup
[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 mod config;
11 mod driver;
12 mod recursive;
13
14 use crate::config::LintcheckConfig;
15 use crate::recursive::LintcheckServer;
16
17 use std::collections::{HashMap, HashSet};
18 use std::env;
19 use std::env::consts::EXE_SUFFIX;
20 use std::fmt::Write as _;
21 use std::fs;
22 use std::io::ErrorKind;
23 use std::path::{Path, PathBuf};
24 use std::process::Command;
25 use std::sync::atomic::{AtomicUsize, Ordering};
26 use std::thread;
27 use std::time::Duration;
28
29 use cargo_metadata::diagnostic::{Diagnostic, DiagnosticLevel};
30 use cargo_metadata::Message;
31 use rayon::prelude::*;
32 use serde::{Deserialize, Serialize};
33 use walkdir::{DirEntry, WalkDir};
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     #[serde(default)]
43     recursive: RecursiveOptions,
44 }
45
46 #[derive(Debug, Serialize, Deserialize, Default)]
47 struct RecursiveOptions {
48     ignore: HashSet<String>,
49 }
50
51 /// A crate source stored inside the .toml
52 /// will be translated into on one of the `CrateSource` variants
53 #[derive(Debug, Serialize, Deserialize)]
54 struct TomlCrate {
55     name: String,
56     versions: Option<Vec<String>>,
57     git_url: Option<String>,
58     git_hash: Option<String>,
59     path: Option<String>,
60     options: Option<Vec<String>>,
61 }
62
63 /// Represents an archive we download from crates.io, or a git repo, or a local repo/folder
64 /// Once processed (downloaded/extracted/cloned/copied...), this will be translated into a `Crate`
65 #[derive(Debug, Serialize, Deserialize, Eq, Hash, PartialEq, Ord, PartialOrd)]
66 enum CrateSource {
67     CratesIo {
68         name: String,
69         version: String,
70         options: Option<Vec<String>>,
71     },
72     Git {
73         name: String,
74         url: String,
75         commit: String,
76         options: Option<Vec<String>>,
77     },
78     Path {
79         name: String,
80         path: PathBuf,
81         options: Option<Vec<String>>,
82     },
83 }
84
85 /// Represents the actual source code of a crate that we ran "cargo clippy" on
86 #[derive(Debug)]
87 struct Crate {
88     version: String,
89     name: String,
90     // path to the extracted sources that clippy can check
91     path: PathBuf,
92     options: Option<Vec<String>>,
93 }
94
95 /// A single warning that clippy issued while checking a `Crate`
96 #[derive(Debug)]
97 struct ClippyWarning {
98     crate_name: String,
99     file: String,
100     line: usize,
101     column: usize,
102     lint_type: String,
103     message: String,
104     is_ice: bool,
105 }
106
107 #[allow(unused)]
108 impl ClippyWarning {
109     fn new(diag: Diagnostic, crate_name: &str, crate_version: &str) -> Option<Self> {
110         let lint_type = diag.code?.code;
111         if !(lint_type.contains("clippy") || diag.message.contains("clippy"))
112             || diag.message.contains("could not read cargo metadata")
113         {
114             return None;
115         }
116
117         let span = diag.spans.into_iter().find(|span| span.is_primary)?;
118
119         let file = match Path::new(&span.file_name).strip_prefix(env!("CARGO_HOME")) {
120             Ok(stripped) => format!("$CARGO_HOME/{}", stripped.display()),
121             Err(_) => format!(
122                 "target/lintcheck/sources/{}-{}/{}",
123                 crate_name, crate_version, span.file_name
124             ),
125         };
126
127         Some(Self {
128             crate_name: crate_name.to_owned(),
129             file,
130             line: span.line_start,
131             column: span.column_start,
132             lint_type,
133             message: diag.message,
134             is_ice: diag.level == DiagnosticLevel::Ice,
135         })
136     }
137
138     fn to_output(&self, markdown: bool) -> String {
139         let file_with_pos = format!("{}:{}:{}", &self.file, &self.line, &self.column);
140         if markdown {
141             let mut file = self.file.clone();
142             if !file.starts_with('$') {
143                 file.insert_str(0, "../");
144             }
145
146             let mut output = String::from("| ");
147             let _ = write!(output, "[`{}`]({}#L{})", file_with_pos, file, self.line);
148             let _ = write!(output, r#" | `{:<50}` | "{}" |"#, self.lint_type, self.message);
149             output.push('\n');
150             output
151         } else {
152             format!("{} {} \"{}\"\n", file_with_pos, self.lint_type, self.message)
153         }
154     }
155 }
156
157 fn get(path: &str) -> Result<ureq::Response, ureq::Error> {
158     const MAX_RETRIES: u8 = 4;
159     let mut retries = 0;
160     loop {
161         match ureq::get(path).call() {
162             Ok(res) => return Ok(res),
163             Err(e) if retries >= MAX_RETRIES => return Err(e),
164             Err(ureq::Error::Transport(e)) => eprintln!("Error: {}", e),
165             Err(e) => return Err(e),
166         }
167         eprintln!("retrying in {} seconds...", retries);
168         thread::sleep(Duration::from_secs(retries as u64));
169         retries += 1;
170     }
171 }
172
173 impl CrateSource {
174     /// Makes the sources available on the disk for clippy to check.
175     /// Clones a git repo and checks out the specified commit or downloads a crate from crates.io or
176     /// copies a local folder
177     fn download_and_extract(&self) -> Crate {
178         match self {
179             CrateSource::CratesIo { name, version, options } => {
180                 let extract_dir = PathBuf::from(LINTCHECK_SOURCES);
181                 let krate_download_dir = PathBuf::from(LINTCHECK_DOWNLOADS);
182
183                 // url to download the crate from crates.io
184                 let url = format!("https://crates.io/api/v1/crates/{}/{}/download", name, version);
185                 println!("Downloading and extracting {} {} from {}", name, version, url);
186                 create_dirs(&krate_download_dir, &extract_dir);
187
188                 let krate_file_path = krate_download_dir.join(format!("{}-{}.crate.tar.gz", name, version));
189                 // don't download/extract if we already have done so
190                 if !krate_file_path.is_file() {
191                     // create a file path to download and write the crate data into
192                     let mut krate_dest = std::fs::File::create(&krate_file_path).unwrap();
193                     let mut krate_req = get(&url).unwrap().into_reader();
194                     // copy the crate into the file
195                     std::io::copy(&mut krate_req, &mut krate_dest).unwrap();
196
197                     // unzip the tarball
198                     let ungz_tar = flate2::read::GzDecoder::new(std::fs::File::open(&krate_file_path).unwrap());
199                     // extract the tar archive
200                     let mut archive = tar::Archive::new(ungz_tar);
201                     archive.unpack(&extract_dir).expect("Failed to extract!");
202                 }
203                 // crate is extracted, return a new Krate object which contains the path to the extracted
204                 // sources that clippy can check
205                 Crate {
206                     version: version.clone(),
207                     name: name.clone(),
208                     path: extract_dir.join(format!("{}-{}/", name, version)),
209                     options: options.clone(),
210                 }
211             },
212             CrateSource::Git {
213                 name,
214                 url,
215                 commit,
216                 options,
217             } => {
218                 let repo_path = {
219                     let mut repo_path = PathBuf::from(LINTCHECK_SOURCES);
220                     // add a -git suffix in case we have the same crate from crates.io and a git repo
221                     repo_path.push(format!("{}-git", name));
222                     repo_path
223                 };
224                 // clone the repo if we have not done so
225                 if !repo_path.is_dir() {
226                     println!("Cloning {} and checking out {}", url, commit);
227                     if !Command::new("git")
228                         .arg("clone")
229                         .arg(url)
230                         .arg(&repo_path)
231                         .status()
232                         .expect("Failed to clone git repo!")
233                         .success()
234                     {
235                         eprintln!("Failed to clone {} into {}", url, repo_path.display())
236                     }
237                 }
238                 // check out the commit/branch/whatever
239                 if !Command::new("git")
240                     .args(["-c", "advice.detachedHead=false"])
241                     .arg("checkout")
242                     .arg(commit)
243                     .current_dir(&repo_path)
244                     .status()
245                     .expect("Failed to check out commit")
246                     .success()
247                 {
248                     eprintln!("Failed to checkout {} of repo at {}", commit, repo_path.display())
249                 }
250
251                 Crate {
252                     version: commit.clone(),
253                     name: name.clone(),
254                     path: repo_path,
255                     options: options.clone(),
256                 }
257             },
258             CrateSource::Path { name, path, options } => {
259                 // copy path into the dest_crate_root but skip directories that contain a CACHEDIR.TAG file.
260                 // The target/ directory contains a CACHEDIR.TAG file so it is the most commonly skipped directory
261                 // as a result of this filter.
262                 let dest_crate_root = PathBuf::from(LINTCHECK_SOURCES).join(name);
263                 if dest_crate_root.exists() {
264                     println!("Deleting existing directory at {:?}", dest_crate_root);
265                     std::fs::remove_dir_all(&dest_crate_root).unwrap();
266                 }
267
268                 println!("Copying {:?} to {:?}", path, dest_crate_root);
269
270                 fn is_cache_dir(entry: &DirEntry) -> bool {
271                     std::fs::read(entry.path().join("CACHEDIR.TAG"))
272                         .map(|x| x.starts_with(b"Signature: 8a477f597d28d172789f06886806bc55"))
273                         .unwrap_or(false)
274                 }
275
276                 for entry in WalkDir::new(path).into_iter().filter_entry(|e| !is_cache_dir(e)) {
277                     let entry = entry.unwrap();
278                     let entry_path = entry.path();
279                     let relative_entry_path = entry_path.strip_prefix(path).unwrap();
280                     let dest_path = dest_crate_root.join(relative_entry_path);
281                     let metadata = entry_path.symlink_metadata().unwrap();
282
283                     if metadata.is_dir() {
284                         std::fs::create_dir(dest_path).unwrap();
285                     } else if metadata.is_file() {
286                         std::fs::copy(entry_path, dest_path).unwrap();
287                     }
288                 }
289
290                 Crate {
291                     version: String::from("local"),
292                     name: name.clone(),
293                     path: dest_crate_root,
294                     options: options.clone(),
295                 }
296             },
297         }
298     }
299 }
300
301 impl Crate {
302     /// Run `cargo clippy` on the `Crate` and collect and return all the lint warnings that clippy
303     /// issued
304     fn run_clippy_lints(
305         &self,
306         cargo_clippy_path: &Path,
307         clippy_driver_path: &Path,
308         target_dir_index: &AtomicUsize,
309         total_crates_to_lint: usize,
310         config: &LintcheckConfig,
311         lint_filter: &Vec<String>,
312         server: &Option<LintcheckServer>,
313     ) -> Vec<ClippyWarning> {
314         // advance the atomic index by one
315         let index = target_dir_index.fetch_add(1, Ordering::SeqCst);
316         // "loop" the index within 0..thread_limit
317         let thread_index = index % config.max_jobs;
318         let perc = (index * 100) / total_crates_to_lint;
319
320         if config.max_jobs == 1 {
321             println!(
322                 "{}/{} {}% Linting {} {}",
323                 index, total_crates_to_lint, perc, &self.name, &self.version
324             );
325         } else {
326             println!(
327                 "{}/{} {}% Linting {} {} in target dir {:?}",
328                 index, total_crates_to_lint, perc, &self.name, &self.version, thread_index
329             );
330         }
331
332         let cargo_clippy_path = std::fs::canonicalize(cargo_clippy_path).unwrap();
333
334         let shared_target_dir = clippy_project_root().join("target/lintcheck/shared_target_dir");
335
336         let mut cargo_clippy_args = if config.fix {
337             vec!["--fix", "--"]
338         } else {
339             vec!["--", "--message-format=json", "--"]
340         };
341
342         let mut clippy_args = Vec::<&str>::new();
343         if let Some(options) = &self.options {
344             for opt in options {
345                 clippy_args.push(opt);
346             }
347         } else {
348             clippy_args.extend(&["-Wclippy::pedantic", "-Wclippy::cargo"])
349         }
350
351         if lint_filter.is_empty() {
352             clippy_args.push("--cap-lints=warn");
353         } else {
354             clippy_args.push("--cap-lints=allow");
355             clippy_args.extend(lint_filter.iter().map(|filter| filter.as_str()))
356         }
357
358         if let Some(server) = server {
359             let target = shared_target_dir.join("recursive");
360
361             // `cargo clippy` is a wrapper around `cargo check` that mainly sets `RUSTC_WORKSPACE_WRAPPER` to
362             // `clippy-driver`. We do the same thing here with a couple changes:
363             //
364             // `RUSTC_WRAPPER` is used instead of `RUSTC_WORKSPACE_WRAPPER` so that we can lint all crate
365             // dependencies rather than only workspace members
366             //
367             // The wrapper is set to the `lintcheck` so we can force enable linting and ignore certain crates
368             // (see `crate::driver`)
369             let status = Command::new("cargo")
370                 .arg("check")
371                 .arg("--quiet")
372                 .current_dir(&self.path)
373                 .env("CLIPPY_ARGS", clippy_args.join("__CLIPPY_HACKERY__"))
374                 .env("CARGO_TARGET_DIR", target)
375                 .env("RUSTC_WRAPPER", env::current_exe().unwrap())
376                 // Pass the absolute path so `crate::driver` can find `clippy-driver`, as it's executed in various
377                 // different working directories
378                 .env("CLIPPY_DRIVER", clippy_driver_path)
379                 .env("LINTCHECK_SERVER", server.local_addr.to_string())
380                 .status()
381                 .expect("failed to run cargo");
382
383             assert_eq!(status.code(), Some(0));
384
385             return Vec::new();
386         }
387
388         cargo_clippy_args.extend(clippy_args);
389
390         let all_output = Command::new(&cargo_clippy_path)
391             // use the looping index to create individual target dirs
392             .env(
393                 "CARGO_TARGET_DIR",
394                 shared_target_dir.join(format!("_{:?}", thread_index)),
395             )
396             .args(&cargo_clippy_args)
397             .current_dir(&self.path)
398             .output()
399             .unwrap_or_else(|error| {
400                 panic!(
401                     "Encountered error:\n{:?}\ncargo_clippy_path: {}\ncrate path:{}\n",
402                     error,
403                     &cargo_clippy_path.display(),
404                     &self.path.display()
405                 );
406             });
407         let stdout = String::from_utf8_lossy(&all_output.stdout);
408         let stderr = String::from_utf8_lossy(&all_output.stderr);
409         let status = &all_output.status;
410
411         if !status.success() {
412             eprintln!(
413                 "\nWARNING: bad exit status after checking {} {} \n",
414                 self.name, self.version
415             );
416         }
417
418         if config.fix {
419             if let Some(stderr) = stderr
420                 .lines()
421                 .find(|line| line.contains("failed to automatically apply fixes suggested by rustc to crate"))
422             {
423                 let subcrate = &stderr[63..];
424                 println!(
425                     "ERROR: failed to apply some suggetion to {} / to (sub)crate {}",
426                     self.name, subcrate
427                 );
428             }
429             // fast path, we don't need the warnings anyway
430             return Vec::new();
431         }
432
433         // get all clippy warnings and ICEs
434         let warnings: Vec<ClippyWarning> = Message::parse_stream(stdout.as_bytes())
435             .filter_map(|msg| match msg {
436                 Ok(Message::CompilerMessage(message)) => ClippyWarning::new(message.message, &self.name, &self.version),
437                 _ => None,
438             })
439             .collect();
440
441         warnings
442     }
443 }
444
445 /// Builds clippy inside the repo to make sure we have a clippy executable we can use.
446 fn build_clippy() {
447     let status = Command::new("cargo")
448         .arg("build")
449         .status()
450         .expect("Failed to build clippy!");
451     if !status.success() {
452         eprintln!("Error: Failed to compile Clippy!");
453         std::process::exit(1);
454     }
455 }
456
457 /// Read a `lintcheck_crates.toml` file
458 fn read_crates(toml_path: &Path) -> (Vec<CrateSource>, RecursiveOptions) {
459     let toml_content: String =
460         std::fs::read_to_string(&toml_path).unwrap_or_else(|_| panic!("Failed to read {}", toml_path.display()));
461     let crate_list: SourceList =
462         toml::from_str(&toml_content).unwrap_or_else(|e| panic!("Failed to parse {}: \n{}", toml_path.display(), e));
463     // parse the hashmap of the toml file into a list of crates
464     let tomlcrates: Vec<TomlCrate> = crate_list
465         .crates
466         .into_iter()
467         .map(|(_cratename, tomlcrate)| tomlcrate)
468         .collect();
469
470     // flatten TomlCrates into CrateSources (one TomlCrates may represent several versions of a crate =>
471     // multiple Cratesources)
472     let mut crate_sources = Vec::new();
473     tomlcrates.into_iter().for_each(|tk| {
474         if let Some(ref path) = tk.path {
475             crate_sources.push(CrateSource::Path {
476                 name: tk.name.clone(),
477                 path: PathBuf::from(path),
478                 options: tk.options.clone(),
479             });
480         } else if let Some(ref versions) = tk.versions {
481             // if we have multiple versions, save each one
482             versions.iter().for_each(|ver| {
483                 crate_sources.push(CrateSource::CratesIo {
484                     name: tk.name.clone(),
485                     version: ver.to_string(),
486                     options: tk.options.clone(),
487                 });
488             })
489         } else if tk.git_url.is_some() && tk.git_hash.is_some() {
490             // otherwise, we should have a git source
491             crate_sources.push(CrateSource::Git {
492                 name: tk.name.clone(),
493                 url: tk.git_url.clone().unwrap(),
494                 commit: tk.git_hash.clone().unwrap(),
495                 options: tk.options.clone(),
496             });
497         } else {
498             panic!("Invalid crate source: {tk:?}");
499         }
500
501         // if we have a version as well as a git data OR only one git data, something is funky
502         if tk.versions.is_some() && (tk.git_url.is_some() || tk.git_hash.is_some())
503             || tk.git_hash.is_some() != tk.git_url.is_some()
504         {
505             eprintln!("tomlkrate: {:?}", tk);
506             if tk.git_hash.is_some() != tk.git_url.is_some() {
507                 panic!("Error: Encountered TomlCrate with only one of git_hash and git_url!");
508             }
509             if tk.path.is_some() && (tk.git_hash.is_some() || tk.versions.is_some()) {
510                 panic!("Error: TomlCrate can only have one of 'git_.*', 'version' or 'path' fields");
511             }
512             unreachable!("Failed to translate TomlCrate into CrateSource!");
513         }
514     });
515     // sort the crates
516     crate_sources.sort();
517
518     (crate_sources, crate_list.recursive)
519 }
520
521 /// Generate a short list of occurring lints-types and their count
522 fn gather_stats(clippy_warnings: &[ClippyWarning]) -> (String, HashMap<&String, usize>) {
523     // count lint type occurrences
524     let mut counter: HashMap<&String, usize> = HashMap::new();
525     clippy_warnings
526         .iter()
527         .for_each(|wrn| *counter.entry(&wrn.lint_type).or_insert(0) += 1);
528
529     // collect into a tupled list for sorting
530     let mut stats: Vec<(&&String, &usize)> = counter.iter().map(|(lint, count)| (lint, count)).collect();
531     // sort by "000{count} {clippy::lintname}"
532     // to not have a lint with 200 and 2 warnings take the same spot
533     stats.sort_by_key(|(lint, count)| format!("{:0>4}, {}", count, lint));
534
535     let mut header = String::from("| lint                                               | count |\n");
536     header.push_str("| -------------------------------------------------- | ----- |\n");
537     let stats_string = stats
538         .iter()
539         .map(|(lint, count)| format!("| {:<50} |  {:>4} |\n", lint, count))
540         .fold(header, |mut table, line| {
541             table.push_str(&line);
542             table
543         });
544
545     (stats_string, counter)
546 }
547
548 /// check if the latest modification of the logfile is older than the modification date of the
549 /// clippy binary, if this is true, we should clean the lintchec shared target directory and recheck
550 fn lintcheck_needs_rerun(lintcheck_logs_path: &Path, paths: [&Path; 2]) -> bool {
551     if !lintcheck_logs_path.exists() {
552         return true;
553     }
554
555     let clippy_modified: std::time::SystemTime = {
556         let [cargo, driver] = paths.map(|p| {
557             std::fs::metadata(p)
558                 .expect("failed to get metadata of file")
559                 .modified()
560                 .expect("failed to get modification date")
561         });
562         // the oldest modification of either of the binaries
563         std::cmp::max(cargo, driver)
564     };
565
566     let logs_modified: std::time::SystemTime = std::fs::metadata(lintcheck_logs_path)
567         .expect("failed to get metadata of file")
568         .modified()
569         .expect("failed to get modification date");
570
571     // time is represented in seconds since X
572     // logs_modified 2 and clippy_modified 5 means clippy binary is older and we need to recheck
573     logs_modified < clippy_modified
574 }
575
576 fn main() {
577     // We're being executed as a `RUSTC_WRAPPER` as part of `--recursive`
578     if let Ok(addr) = env::var("LINTCHECK_SERVER") {
579         driver::drive(&addr);
580     }
581
582     // assert that we launch lintcheck from the repo root (via cargo lintcheck)
583     if std::fs::metadata("lintcheck/Cargo.toml").is_err() {
584         eprintln!("lintcheck needs to be run from clippy's repo root!\nUse `cargo lintcheck` alternatively.");
585         std::process::exit(3);
586     }
587
588     let config = LintcheckConfig::new();
589
590     println!("Compiling clippy...");
591     build_clippy();
592     println!("Done compiling");
593
594     let cargo_clippy_path = fs::canonicalize(format!("target/debug/cargo-clippy{EXE_SUFFIX}")).unwrap();
595     let clippy_driver_path = fs::canonicalize(format!("target/debug/clippy-driver{EXE_SUFFIX}")).unwrap();
596
597     // if the clippy bin is newer than our logs, throw away target dirs to force clippy to
598     // refresh the logs
599     if lintcheck_needs_rerun(
600         &config.lintcheck_results_path,
601         [&cargo_clippy_path, &clippy_driver_path],
602     ) {
603         let shared_target_dir = "target/lintcheck/shared_target_dir";
604         // if we get an Err here, the shared target dir probably does simply not exist
605         if let Ok(metadata) = std::fs::metadata(&shared_target_dir) {
606             if metadata.is_dir() {
607                 println!("Clippy is newer than lint check logs, clearing lintcheck shared target dir...");
608                 std::fs::remove_dir_all(&shared_target_dir)
609                     .expect("failed to remove target/lintcheck/shared_target_dir");
610             }
611         }
612     }
613
614     // assert that clippy is found
615     assert!(
616         cargo_clippy_path.is_file(),
617         "target/debug/cargo-clippy binary not found! {}",
618         cargo_clippy_path.display()
619     );
620
621     let clippy_ver = std::process::Command::new(&cargo_clippy_path)
622         .arg("--version")
623         .output()
624         .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
625         .expect("could not get clippy version!");
626
627     // download and extract the crates, then run clippy on them and collect clippy's warnings
628     // flatten into one big list of warnings
629
630     let (crates, recursive_options) = read_crates(&config.sources_toml_path);
631     let old_stats = read_stats_from_file(&config.lintcheck_results_path);
632
633     let counter = AtomicUsize::new(1);
634     let lint_filter: Vec<String> = config
635         .lint_filter
636         .iter()
637         .map(|filter| {
638             let mut filter = filter.clone();
639             filter.insert_str(0, "--force-warn=");
640             filter
641         })
642         .collect();
643
644     let crates: Vec<Crate> = crates
645         .into_iter()
646         .filter(|krate| {
647             if let Some(only_one_crate) = &config.only {
648                 let name = match krate {
649                     CrateSource::CratesIo { name, .. }
650                     | CrateSource::Git { name, .. }
651                     | CrateSource::Path { name, .. } => name,
652                 };
653
654                 name == only_one_crate
655             } else {
656                 true
657             }
658         })
659         .map(|krate| krate.download_and_extract())
660         .collect();
661
662     if crates.is_empty() {
663         eprintln!(
664             "ERROR: could not find crate '{}' in lintcheck/lintcheck_crates.toml",
665             config.only.unwrap(),
666         );
667         std::process::exit(1);
668     }
669
670     // run parallel with rayon
671
672     // This helps when we check many small crates with dep-trees that don't have a lot of branches in
673     // order to achieve some kind of parallelism
674
675     rayon::ThreadPoolBuilder::new()
676         .num_threads(config.max_jobs)
677         .build_global()
678         .unwrap();
679
680     let server = config.recursive.then(|| {
681         let _ = fs::remove_dir_all("target/lintcheck/shared_target_dir/recursive");
682
683         LintcheckServer::spawn(recursive_options)
684     });
685
686     let mut clippy_warnings: Vec<ClippyWarning> = crates
687         .par_iter()
688         .flat_map(|krate| {
689             krate.run_clippy_lints(
690                 &cargo_clippy_path,
691                 &clippy_driver_path,
692                 &counter,
693                 crates.len(),
694                 &config,
695                 &lint_filter,
696                 &server,
697             )
698         })
699         .collect();
700
701     if let Some(server) = server {
702         clippy_warnings.extend(server.warnings());
703     }
704
705     // if we are in --fix mode, don't change the log files, terminate here
706     if config.fix {
707         return;
708     }
709
710     // generate some stats
711     let (stats_formatted, new_stats) = gather_stats(&clippy_warnings);
712
713     // grab crashes/ICEs, save the crate name and the ice message
714     let ices: Vec<(&String, &String)> = clippy_warnings
715         .iter()
716         .filter(|warning| warning.is_ice)
717         .map(|w| (&w.crate_name, &w.message))
718         .collect();
719
720     let mut all_msgs: Vec<String> = clippy_warnings
721         .iter()
722         .map(|warn| warn.to_output(config.markdown))
723         .collect();
724     all_msgs.sort();
725     all_msgs.push("\n\n### Stats:\n\n".into());
726     all_msgs.push(stats_formatted);
727
728     // save the text into lintcheck-logs/logs.txt
729     let mut text = clippy_ver; // clippy version number on top
730     text.push_str("\n### Reports\n\n");
731     if config.markdown {
732         text.push_str("| file | lint | message |\n");
733         text.push_str("| --- | --- | --- |\n");
734     }
735     write!(text, "{}", all_msgs.join("")).unwrap();
736     text.push_str("\n\n### ICEs:\n");
737     for (cratename, msg) in ices.iter() {
738         let _ = write!(text, "{}: '{}'", cratename, msg);
739     }
740
741     println!("Writing logs to {}", config.lintcheck_results_path.display());
742     fs::create_dir_all(config.lintcheck_results_path.parent().unwrap()).unwrap();
743     fs::write(&config.lintcheck_results_path, text).unwrap();
744
745     print_stats(old_stats, new_stats, &config.lint_filter);
746 }
747
748 /// read the previous stats from the lintcheck-log file
749 fn read_stats_from_file(file_path: &Path) -> HashMap<String, usize> {
750     let file_content: String = match std::fs::read_to_string(file_path).ok() {
751         Some(content) => content,
752         None => {
753             return HashMap::new();
754         },
755     };
756
757     let lines: Vec<String> = file_content.lines().map(ToString::to_string).collect();
758
759     lines
760         .iter()
761         .skip_while(|line| line.as_str() != "### Stats:")
762         // Skipping the table header and the `Stats:` label
763         .skip(4)
764         .take_while(|line| line.starts_with("| "))
765         .filter_map(|line| {
766             let mut spl = line.split('|');
767             // Skip the first `|` symbol
768             spl.next();
769             if let (Some(lint), Some(count)) = (spl.next(), spl.next()) {
770                 Some((lint.trim().to_string(), count.trim().parse::<usize>().unwrap()))
771             } else {
772                 None
773             }
774         })
775         .collect::<HashMap<String, usize>>()
776 }
777
778 /// print how lint counts changed between runs
779 fn print_stats(old_stats: HashMap<String, usize>, new_stats: HashMap<&String, usize>, lint_filter: &Vec<String>) {
780     let same_in_both_hashmaps = old_stats
781         .iter()
782         .filter(|(old_key, old_val)| new_stats.get::<&String>(&old_key) == Some(old_val))
783         .map(|(k, v)| (k.to_string(), *v))
784         .collect::<Vec<(String, usize)>>();
785
786     let mut old_stats_deduped = old_stats;
787     let mut new_stats_deduped = new_stats;
788
789     // remove duplicates from both hashmaps
790     same_in_both_hashmaps.iter().for_each(|(k, v)| {
791         assert!(old_stats_deduped.remove(k) == Some(*v));
792         assert!(new_stats_deduped.remove(k) == Some(*v));
793     });
794
795     println!("\nStats:");
796
797     // list all new counts  (key is in new stats but not in old stats)
798     new_stats_deduped
799         .iter()
800         .filter(|(new_key, _)| old_stats_deduped.get::<str>(&new_key).is_none())
801         .for_each(|(new_key, new_value)| {
802             println!("{} 0 => {}", new_key, new_value);
803         });
804
805     // list all changed counts (key is in both maps but value differs)
806     new_stats_deduped
807         .iter()
808         .filter(|(new_key, _new_val)| old_stats_deduped.get::<str>(&new_key).is_some())
809         .for_each(|(new_key, new_val)| {
810             let old_val = old_stats_deduped.get::<str>(&new_key).unwrap();
811             println!("{} {} => {}", new_key, old_val, new_val);
812         });
813
814     // list all gone counts (key is in old status but not in new stats)
815     old_stats_deduped
816         .iter()
817         .filter(|(old_key, _)| new_stats_deduped.get::<&String>(&old_key).is_none())
818         .filter(|(old_key, _)| lint_filter.is_empty() || lint_filter.contains(old_key))
819         .for_each(|(old_key, old_value)| {
820             println!("{} {} => 0", old_key, old_value);
821         });
822 }
823
824 /// Create necessary directories to run the lintcheck tool.
825 ///
826 /// # Panics
827 ///
828 /// This function panics if creating one of the dirs fails.
829 fn create_dirs(krate_download_dir: &Path, extract_dir: &Path) {
830     std::fs::create_dir("target/lintcheck/").unwrap_or_else(|err| {
831         if err.kind() != ErrorKind::AlreadyExists {
832             panic!("cannot create lintcheck target dir");
833         }
834     });
835     std::fs::create_dir(&krate_download_dir).unwrap_or_else(|err| {
836         if err.kind() != ErrorKind::AlreadyExists {
837             panic!("cannot create crate download dir");
838         }
839     });
840     std::fs::create_dir(&extract_dir).unwrap_or_else(|err| {
841         if err.kind() != ErrorKind::AlreadyExists {
842             panic!("cannot create crate extraction dir");
843         }
844     });
845 }
846
847 /// Returns the path to the Clippy project directory
848 #[must_use]
849 fn clippy_project_root() -> &'static Path {
850     Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap()
851 }
852
853 #[test]
854 fn lintcheck_test() {
855     let args = [
856         "run",
857         "--target-dir",
858         "lintcheck/target",
859         "--manifest-path",
860         "./lintcheck/Cargo.toml",
861         "--",
862         "--crates-toml",
863         "lintcheck/test_sources.toml",
864     ];
865     let status = std::process::Command::new("cargo")
866         .args(&args)
867         .current_dir("..") // repo root
868         .status();
869     //.output();
870
871     assert!(status.unwrap().success());
872 }