]> git.lizzy.rs Git - rust.git/blob - clippy_dev/src/lintcheck.rs
lintcheck: refactor: introduce a basic LintcheckConfig struct which holds the job...
[rust.git] / clippy_dev / src / lintcheck.rs
1 // Run clippy on a fixed set of crates and collect the warnings.
2 // This helps observing the impact clippy changs have on a set of real-world code.
3 //
4 // When a new lint is introduced, we can search the results for new warnings and check for false
5 // positives.
6
7 #![cfg(feature = "lintcheck")]
8 #![allow(clippy::filter_map)]
9
10 use crate::clippy_project_root;
11
12 use std::collections::HashMap;
13 use std::process::Command;
14 use std::sync::atomic::{AtomicUsize, Ordering};
15 use std::{env, fmt, fs::write, path::PathBuf};
16
17 use clap::ArgMatches;
18 use rayon::prelude::*;
19 use serde::{Deserialize, Serialize};
20 use serde_json::Value;
21
22 /// List of sources to check, loaded from a .toml file
23 #[derive(Debug, Serialize, Deserialize)]
24 struct SourceList {
25     crates: HashMap<String, TomlCrate>,
26 }
27
28 /// A crate source stored inside the .toml
29 /// will be translated into on one of the `CrateSource` variants
30 #[derive(Debug, Serialize, Deserialize)]
31 struct TomlCrate {
32     name: String,
33     versions: Option<Vec<String>>,
34     git_url: Option<String>,
35     git_hash: Option<String>,
36     path: Option<String>,
37     options: Option<Vec<String>>,
38 }
39
40 /// Represents an archive we download from crates.io, or a git repo, or a local repo/folder
41 /// Once processed (downloaded/extracted/cloned/copied...), this will be translated into a `Crate`
42 #[derive(Debug, Serialize, Deserialize, Eq, Hash, PartialEq, Ord, PartialOrd)]
43 enum CrateSource {
44     CratesIo {
45         name: String,
46         version: String,
47         options: Option<Vec<String>>,
48     },
49     Git {
50         name: String,
51         url: String,
52         commit: String,
53         options: Option<Vec<String>>,
54     },
55     Path {
56         name: String,
57         path: PathBuf,
58         options: Option<Vec<String>>,
59     },
60 }
61
62 /// Represents the actual source code of a crate that we ran "cargo clippy" on
63 #[derive(Debug)]
64 struct Crate {
65     version: String,
66     name: String,
67     // path to the extracted sources that clippy can check
68     path: PathBuf,
69     options: Option<Vec<String>>,
70 }
71
72 /// A single warning that clippy issued while checking a `Crate`
73 #[derive(Debug)]
74 struct ClippyWarning {
75     crate_name: String,
76     crate_version: String,
77     file: String,
78     line: String,
79     column: String,
80     linttype: String,
81     message: String,
82     is_ice: bool,
83 }
84
85 impl std::fmt::Display for ClippyWarning {
86     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87         writeln!(
88             f,
89             r#"{}-{}/{}:{}:{} {} "{}""#,
90             &self.crate_name, &self.crate_version, &self.file, &self.line, &self.column, &self.linttype, &self.message
91         )
92     }
93 }
94
95 impl CrateSource {
96     /// Makes the sources available on the disk for clippy to check.
97     /// Clones a git repo and checks out the specified commit or downloads a crate from crates.io or
98     /// copies a local folder
99     fn download_and_extract(&self) -> Crate {
100         match self {
101             CrateSource::CratesIo { name, version, options } => {
102                 let extract_dir = PathBuf::from("target/lintcheck/crates");
103                 let krate_download_dir = PathBuf::from("target/lintcheck/downloads");
104
105                 // url to download the crate from crates.io
106                 let url = format!("https://crates.io/api/v1/crates/{}/{}/download", name, version);
107                 println!("Downloading and extracting {} {} from {}", name, version, url);
108                 let _ = std::fs::create_dir("target/lintcheck/");
109                 let _ = std::fs::create_dir(&krate_download_dir);
110                 let _ = std::fs::create_dir(&extract_dir);
111
112                 let krate_file_path = krate_download_dir.join(format!("{}-{}.crate.tar.gz", name, version));
113                 // don't download/extract if we already have done so
114                 if !krate_file_path.is_file() {
115                     // create a file path to download and write the crate data into
116                     let mut krate_dest = std::fs::File::create(&krate_file_path).unwrap();
117                     let mut krate_req = ureq::get(&url).call().unwrap().into_reader();
118                     // copy the crate into the file
119                     std::io::copy(&mut krate_req, &mut krate_dest).unwrap();
120
121                     // unzip the tarball
122                     let ungz_tar = flate2::read::GzDecoder::new(std::fs::File::open(&krate_file_path).unwrap());
123                     // extract the tar archive
124                     let mut archive = tar::Archive::new(ungz_tar);
125                     archive.unpack(&extract_dir).expect("Failed to extract!");
126                 }
127                 // crate is extracted, return a new Krate object which contains the path to the extracted
128                 // sources that clippy can check
129                 Crate {
130                     version: version.clone(),
131                     name: name.clone(),
132                     path: extract_dir.join(format!("{}-{}/", name, version)),
133                     options: options.clone(),
134                 }
135             },
136             CrateSource::Git {
137                 name,
138                 url,
139                 commit,
140                 options,
141             } => {
142                 let repo_path = {
143                     let mut repo_path = PathBuf::from("target/lintcheck/crates");
144                     // add a -git suffix in case we have the same crate from crates.io and a git repo
145                     repo_path.push(format!("{}-git", name));
146                     repo_path
147                 };
148                 // clone the repo if we have not done so
149                 if !repo_path.is_dir() {
150                     println!("Cloning {} and checking out {}", url, commit);
151                     if !Command::new("git")
152                         .arg("clone")
153                         .arg(url)
154                         .arg(&repo_path)
155                         .status()
156                         .expect("Failed to clone git repo!")
157                         .success()
158                     {
159                         eprintln!("Failed to clone {} into {}", url, repo_path.display())
160                     }
161                 }
162                 // check out the commit/branch/whatever
163                 if !Command::new("git")
164                     .arg("checkout")
165                     .arg(commit)
166                     .current_dir(&repo_path)
167                     .status()
168                     .expect("Failed to check out commit")
169                     .success()
170                 {
171                     eprintln!("Failed to checkout {} of repo at {}", commit, repo_path.display())
172                 }
173
174                 Crate {
175                     version: commit.clone(),
176                     name: name.clone(),
177                     path: repo_path,
178                     options: options.clone(),
179                 }
180             },
181             CrateSource::Path { name, path, options } => {
182                 use fs_extra::dir;
183
184                 // simply copy the entire directory into our target dir
185                 let copy_dest = PathBuf::from("target/lintcheck/crates/");
186
187                 // the source path of the crate we copied,  ${copy_dest}/crate_name
188                 let crate_root = copy_dest.join(name); // .../crates/local_crate
189
190                 if !crate_root.exists() {
191                     println!("Copying {} to {}", path.display(), copy_dest.display());
192
193                     dir::copy(path, &copy_dest, &dir::CopyOptions::new()).expect(&format!(
194                         "Failed to copy from {}, to  {}",
195                         path.display(),
196                         crate_root.display()
197                     ));
198                 } else {
199                     println!(
200                         "Not copying {} to {}, destination already exists",
201                         path.display(),
202                         crate_root.display()
203                     );
204                 }
205
206                 Crate {
207                     version: String::from("local"),
208                     name: name.clone(),
209                     path: crate_root,
210                     options: options.clone(),
211                 }
212             },
213         }
214     }
215 }
216
217 impl Crate {
218     /// Run `cargo clippy` on the `Crate` and collect and return all the lint warnings that clippy
219     /// issued
220     fn run_clippy_lints(
221         &self,
222         cargo_clippy_path: &PathBuf,
223         target_dir_index: &AtomicUsize,
224         thread_limit: usize,
225         total_crates_to_lint: usize,
226     ) -> Vec<ClippyWarning> {
227         // advance the atomic index by one
228         let index = target_dir_index.fetch_add(1, Ordering::SeqCst);
229         // "loop" the index within 0..thread_limit
230         let target_dir_index = index % thread_limit;
231         let perc = ((index * 100) as f32 / total_crates_to_lint as f32) as u8;
232
233         if thread_limit == 1 {
234             println!(
235                 "{}/{} {}% Linting {} {}",
236                 index, total_crates_to_lint, perc, &self.name, &self.version
237             );
238         } else {
239             println!(
240                 "{}/{} {}% Linting {} {} in target dir {:?}",
241                 index, total_crates_to_lint, perc, &self.name, &self.version, target_dir_index
242             );
243         }
244
245         let cargo_clippy_path = std::fs::canonicalize(cargo_clippy_path).unwrap();
246
247         let shared_target_dir = clippy_project_root().join("target/lintcheck/shared_target_dir");
248
249         let mut args = vec!["--", "--message-format=json", "--", "--cap-lints=warn"];
250
251         if let Some(options) = &self.options {
252             for opt in options {
253                 args.push(opt);
254             }
255         } else {
256             args.extend(&["-Wclippy::pedantic", "-Wclippy::cargo"])
257         }
258
259         let all_output = std::process::Command::new(&cargo_clippy_path)
260             // use the looping index to create individual target dirs
261             .env(
262                 "CARGO_TARGET_DIR",
263                 shared_target_dir.join(format!("_{:?}", target_dir_index)),
264             )
265             // lint warnings will look like this:
266             // src/cargo/ops/cargo_compile.rs:127:35: warning: usage of `FromIterator::from_iter`
267             .args(&args)
268             .current_dir(&self.path)
269             .output()
270             .unwrap_or_else(|error| {
271                 panic!(
272                     "Encountered error:\n{:?}\ncargo_clippy_path: {}\ncrate path:{}\n",
273                     error,
274                     &cargo_clippy_path.display(),
275                     &self.path.display()
276                 );
277             });
278         let stdout = String::from_utf8_lossy(&all_output.stdout);
279         let output_lines = stdout.lines();
280         let warnings: Vec<ClippyWarning> = output_lines
281             .into_iter()
282             // get all clippy warnings and ICEs
283             .filter(|line| filter_clippy_warnings(&line))
284             .map(|json_msg| parse_json_message(json_msg, &self))
285             .collect();
286         warnings
287     }
288 }
289
290 #[derive(Debug)]
291 struct LintcheckConfig {
292     // max number of jobs to spawn (default 1)
293     max_jobs: usize,
294     // we read the sources to check from here
295     sources_toml_path: PathBuf,
296     // we save the clippy lint results here
297     lintcheck_results_path: PathBuf,
298 }
299
300 impl LintcheckConfig {
301     fn from_clap(clap_config: &ArgMatches) -> Self {
302         // first, check if we got anything passed via the LINTCHECK_TOML env var,
303         // if not, ask clap if we got any value for --crates-toml  <foo>
304         // if not, use the default "clippy_dev/lintcheck_crates.toml"
305         let sources_toml = env::var("LINTCHECK_TOML").unwrap_or(
306             clap_config
307                 .value_of("crates-toml")
308                 .clone()
309                 .unwrap_or("clippy_dev/lintcheck_crates.toml")
310                 .to_string(),
311         );
312
313         let sources_toml_path = PathBuf::from(sources_toml);
314
315         // for the path where we save the lint results, get the filename without extenstion ( so for
316         // wasd.toml, use "wasd"....)
317         let filename: PathBuf = sources_toml_path.file_stem().unwrap().into();
318         let lintcheck_results_path = PathBuf::from(format!("lintcheck-logs/{}_logs.txt", filename.display()));
319
320         let max_jobs = match clap_config.value_of("threads") {
321             Some(threads) => {
322                 let threads: usize = threads
323                     .parse()
324                     .expect(&format!("Failed to parse '{}' to a digit", threads));
325                 if threads == 0 {
326                     // automatic choice
327                     // Rayon seems to return thread count so half that for core count
328                     (rayon::current_num_threads() / 2) as usize
329                 } else {
330                     threads
331                 }
332             },
333             // no -j passed, use a single thread
334             None => 1,
335         };
336
337         LintcheckConfig {
338             max_jobs,
339             sources_toml_path,
340             lintcheck_results_path,
341         }
342     }
343 }
344
345 /// takes a single json-formatted clippy warnings and returns true (we are interested in that line)
346 /// or false (we aren't)
347 fn filter_clippy_warnings(line: &str) -> bool {
348     // we want to collect ICEs because clippy might have crashed.
349     // these are summarized later
350     if line.contains("internal compiler error: ") {
351         return true;
352     }
353     // in general, we want all clippy warnings
354     // however due to some kind of bug, sometimes there are absolute paths
355     // to libcore files inside the message
356     // or we end up with cargo-metadata output (https://github.com/rust-lang/rust-clippy/issues/6508)
357
358     // filter out these message to avoid unnecessary noise in the logs
359     if line.contains("clippy::")
360         && !(line.contains("could not read cargo metadata")
361             || (line.contains(".rustup") && line.contains("toolchains")))
362     {
363         return true;
364     }
365     false
366 }
367
368 /// Builds clippy inside the repo to make sure we have a clippy executable we can use.
369 fn build_clippy() {
370     let status = Command::new("cargo")
371         .arg("build")
372         .status()
373         .expect("Failed to build clippy!");
374     if !status.success() {
375         eprintln!("Error: Failed to compile Clippy!");
376         std::process::exit(1);
377     }
378 }
379
380 /// Read a `toml` file and return a list of `CrateSources` that we want to check with clippy
381 fn read_crates(toml_path: &PathBuf) -> Vec<CrateSource> {
382     let toml_content: String =
383         std::fs::read_to_string(&toml_path).unwrap_or_else(|_| panic!("Failed to read {}", toml_path.display()));
384     let crate_list: SourceList =
385         toml::from_str(&toml_content).unwrap_or_else(|e| panic!("Failed to parse {}: \n{}", toml_path.display(), e));
386     // parse the hashmap of the toml file into a list of crates
387     let tomlcrates: Vec<TomlCrate> = crate_list
388         .crates
389         .into_iter()
390         .map(|(_cratename, tomlcrate)| tomlcrate)
391         .collect();
392
393     // flatten TomlCrates into CrateSources (one TomlCrates may represent several versions of a crate =>
394     // multiple Cratesources)
395     let mut crate_sources = Vec::new();
396     tomlcrates.into_iter().for_each(|tk| {
397         if let Some(ref path) = tk.path {
398             crate_sources.push(CrateSource::Path {
399                 name: tk.name.clone(),
400                 path: PathBuf::from(path),
401                 options: tk.options.clone(),
402             });
403         }
404
405         // if we have multiple versions, save each one
406         if let Some(ref versions) = tk.versions {
407             versions.iter().for_each(|ver| {
408                 crate_sources.push(CrateSource::CratesIo {
409                     name: tk.name.clone(),
410                     version: ver.to_string(),
411                     options: tk.options.clone(),
412                 });
413             })
414         }
415         // otherwise, we should have a git source
416         if tk.git_url.is_some() && tk.git_hash.is_some() {
417             crate_sources.push(CrateSource::Git {
418                 name: tk.name.clone(),
419                 url: tk.git_url.clone().unwrap(),
420                 commit: tk.git_hash.clone().unwrap(),
421                 options: tk.options.clone(),
422             });
423         }
424         // if we have a version as well as a git data OR only one git data, something is funky
425         if tk.versions.is_some() && (tk.git_url.is_some() || tk.git_hash.is_some())
426             || tk.git_hash.is_some() != tk.git_url.is_some()
427         {
428             eprintln!("tomlkrate: {:?}", tk);
429             if tk.git_hash.is_some() != tk.git_url.is_some() {
430                 panic!("Error: Encountered TomlCrate with only one of git_hash and git_url!");
431             }
432             if tk.path.is_some() && (tk.git_hash.is_some() || tk.versions.is_some()) {
433                 panic!("Error: TomlCrate can only have one of 'git_.*', 'version' or 'path' fields");
434             }
435             unreachable!("Failed to translate TomlCrate into CrateSource!");
436         }
437     });
438     // sort the crates
439     crate_sources.sort();
440
441     crate_sources
442 }
443
444 /// Parse the json output of clippy and return a `ClippyWarning`
445 fn parse_json_message(json_message: &str, krate: &Crate) -> ClippyWarning {
446     let jmsg: Value = serde_json::from_str(&json_message).unwrap_or_else(|e| panic!("Failed to parse json:\n{:?}", e));
447
448     ClippyWarning {
449         crate_name: krate.name.to_string(),
450         crate_version: krate.version.to_string(),
451         file: jmsg["message"]["spans"][0]["file_name"]
452             .to_string()
453             .trim_matches('"')
454             .into(),
455         line: jmsg["message"]["spans"][0]["line_start"]
456             .to_string()
457             .trim_matches('"')
458             .into(),
459         column: jmsg["message"]["spans"][0]["text"][0]["highlight_start"]
460             .to_string()
461             .trim_matches('"')
462             .into(),
463         linttype: jmsg["message"]["code"]["code"].to_string().trim_matches('"').into(),
464         message: jmsg["message"]["message"].to_string().trim_matches('"').into(),
465         is_ice: json_message.contains("internal compiler error: "),
466     }
467 }
468
469 /// Generate a short list of occuring lints-types and their count
470 fn gather_stats(clippy_warnings: &[ClippyWarning]) -> (String, HashMap<&String, usize>) {
471     // count lint type occurrences
472     let mut counter: HashMap<&String, usize> = HashMap::new();
473     clippy_warnings
474         .iter()
475         .for_each(|wrn| *counter.entry(&wrn.linttype).or_insert(0) += 1);
476
477     // collect into a tupled list for sorting
478     let mut stats: Vec<(&&String, &usize)> = counter.iter().map(|(lint, count)| (lint, count)).collect();
479     // sort by "000{count} {clippy::lintname}"
480     // to not have a lint with 200 and 2 warnings take the same spot
481     stats.sort_by_key(|(lint, count)| format!("{:0>4}, {}", count, lint));
482
483     let stats_string = stats
484         .iter()
485         .map(|(lint, count)| format!("{} {}\n", lint, count))
486         .collect::<String>();
487
488     (stats_string, counter)
489 }
490
491 /// check if the latest modification of the logfile is older than the modification date of the
492 /// clippy binary, if this is true, we should clean the lintchec shared target directory and recheck
493 fn lintcheck_needs_rerun(toml_path: &PathBuf) -> bool {
494     let clippy_modified: std::time::SystemTime = {
495         let mut times = ["target/debug/clippy-driver", "target/debug/cargo-clippy"]
496             .iter()
497             .map(|p| {
498                 std::fs::metadata(p)
499                     .expect("failed to get metadata of file")
500                     .modified()
501                     .expect("failed to get modification date")
502             });
503         // the oldest modification of either of the binaries
504         std::cmp::min(times.next().unwrap(), times.next().unwrap())
505     };
506
507     let logs_modified: std::time::SystemTime = std::fs::metadata(toml_path)
508         .expect("failed to get metadata of file")
509         .modified()
510         .expect("failed to get modification date");
511
512     // if clippys modification time is smaller (older) than the logs mod time, we need to rerun
513     // lintcheck
514     clippy_modified < logs_modified
515 }
516
517 /// lintchecks `main()` function
518 pub fn run(clap_config: &ArgMatches) {
519     let config = LintcheckConfig::from_clap(clap_config);
520
521     println!("Compiling clippy...");
522     build_clippy();
523     println!("Done compiling");
524
525     // if the clippy bin is newer than our logs, throw away target dirs to force clippy to
526     // refresh the logs
527     if lintcheck_needs_rerun(&config.sources_toml_path) {
528         let shared_target_dir = "target/lintcheck/shared_target_dir";
529         match std::fs::metadata(&shared_target_dir) {
530             Ok(metadata) => {
531                 if metadata.is_dir() {
532                     println!("Clippy is newer than lint check logs, clearing lintcheck shared target dir...");
533                     std::fs::remove_dir_all(&shared_target_dir)
534                         .expect("failed to remove target/lintcheck/shared_target_dir");
535                 }
536             },
537             Err(_) => { // dir probably does not exist, don't remove anything
538             },
539         }
540     }
541
542     let cargo_clippy_path: PathBuf = PathBuf::from("target/debug/cargo-clippy")
543         .canonicalize()
544         .expect("failed to canonicalize path to clippy binary");
545
546     // assert that clippy is found
547     assert!(
548         cargo_clippy_path.is_file(),
549         "target/debug/cargo-clippy binary not found! {}",
550         cargo_clippy_path.display()
551     );
552
553     let clippy_ver = std::process::Command::new("target/debug/cargo-clippy")
554         .arg("--version")
555         .output()
556         .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
557         .expect("could not get clippy version!");
558
559     // download and extract the crates, then run clippy on them and collect clippys warnings
560     // flatten into one big list of warnings
561
562     let crates = read_crates(&config.sources_toml_path);
563     let old_stats = read_stats_from_file(&config.lintcheck_results_path);
564
565     let clippy_warnings: Vec<ClippyWarning> = if let Some(only_one_crate) = clap_config.value_of("only") {
566         // if we don't have the specified crate in the .toml, throw an error
567         if !crates.iter().any(|krate| {
568             let name = match krate {
569                 CrateSource::CratesIo { name, .. } => name,
570                 CrateSource::Git { name, .. } => name,
571                 CrateSource::Path { name, .. } => name,
572             };
573             name == only_one_crate
574         }) {
575             eprintln!(
576                 "ERROR: could not find crate '{}' in clippy_dev/lintcheck_crates.toml",
577                 only_one_crate
578             );
579             std::process::exit(1);
580         }
581
582         // only check a single crate that was passed via cmdline
583         crates
584             .into_iter()
585             .map(|krate| krate.download_and_extract())
586             .filter(|krate| krate.name == only_one_crate)
587             .map(|krate| krate.run_clippy_lints(&cargo_clippy_path, &AtomicUsize::new(0), 1, 1))
588             .flatten()
589             .collect()
590     } else {
591         let counter = std::sync::atomic::AtomicUsize::new(0);
592
593         // Ask rayon for thread count. Assume that half of that is the number of physical cores
594         // Use one target dir for each core so that we can run N clippys in parallel.
595         // We need to use different target dirs because cargo would lock them for a single build otherwise,
596         // killing the parallelism. However this also means that deps will only be reused half/a
597         // quarter of the time which might result in a longer wall clock runtime
598
599         // This helps when we check many small crates with dep-trees that don't have a lot of branches in
600         // order to achive some kind of parallelism
601
602         // by default, use a single thread
603         let num_cpus = config.max_jobs;
604         let num_crates = crates.len();
605
606         // check all crates (default)
607         crates
608             .into_par_iter()
609             .map(|krate| krate.download_and_extract())
610             .map(|krate| krate.run_clippy_lints(&cargo_clippy_path, &counter, num_cpus, num_crates))
611             .flatten()
612             .collect()
613     };
614
615     // generate some stats
616     let (stats_formatted, new_stats) = gather_stats(&clippy_warnings);
617
618     // grab crashes/ICEs, save the crate name and the ice message
619     let ices: Vec<(&String, &String)> = clippy_warnings
620         .iter()
621         .filter(|warning| warning.is_ice)
622         .map(|w| (&w.crate_name, &w.message))
623         .collect();
624
625     let mut all_msgs: Vec<String> = clippy_warnings.iter().map(|warning| warning.to_string()).collect();
626     all_msgs.sort();
627     all_msgs.push("\n\n\n\nStats:\n".into());
628     all_msgs.push(stats_formatted);
629
630     // save the text into lintcheck-logs/logs.txt
631     let mut text = clippy_ver; // clippy version number on top
632     text.push_str(&format!("\n{}", all_msgs.join("")));
633     text.push_str("ICEs:\n");
634     ices.iter()
635         .for_each(|(cratename, msg)| text.push_str(&format!("{}: '{}'", cratename, msg)));
636
637     println!("Writing logs to {}", config.lintcheck_results_path.display());
638     write(&config.lintcheck_results_path, text).unwrap();
639
640     print_stats(old_stats, new_stats);
641 }
642
643 /// read the previous stats from the lintcheck-log file
644 fn read_stats_from_file(file_path: &PathBuf) -> HashMap<String, usize> {
645     let file_content: String = match std::fs::read_to_string(file_path).ok() {
646         Some(content) => content,
647         None => {
648             eprintln!("RETURND");
649             return HashMap::new();
650         },
651     };
652
653     let lines: Vec<String> = file_content.lines().map(|l| l.to_string()).collect();
654
655     // search for the beginning "Stats:" and the end "ICEs:" of the section we want
656     let start = lines.iter().position(|line| line == "Stats:").unwrap();
657     let end = lines.iter().position(|line| line == "ICEs:").unwrap();
658
659     let stats_lines = &lines[start + 1..=end - 1];
660
661     stats_lines
662         .into_iter()
663         .map(|line| {
664             let mut spl = line.split(" ").into_iter();
665             (
666                 spl.next().unwrap().to_string(),
667                 spl.next().unwrap().parse::<usize>().unwrap(),
668             )
669         })
670         .collect::<HashMap<String, usize>>()
671 }
672
673 /// print how lint counts changed between runs
674 fn print_stats(old_stats: HashMap<String, usize>, new_stats: HashMap<&String, usize>) {
675     let same_in_both_hashmaps = old_stats
676         .iter()
677         .filter(|(old_key, old_val)| new_stats.get::<&String>(&old_key) == Some(old_val))
678         .map(|(k, v)| (k.to_string(), *v))
679         .collect::<Vec<(String, usize)>>();
680
681     let mut old_stats_deduped = old_stats;
682     let mut new_stats_deduped = new_stats;
683
684     // remove duplicates from both hashmaps
685     same_in_both_hashmaps.iter().for_each(|(k, v)| {
686         assert!(old_stats_deduped.remove(k) == Some(*v));
687         assert!(new_stats_deduped.remove(k) == Some(*v));
688     });
689
690     println!("\nStats:");
691
692     // list all new counts  (key is in new stats but not in old stats)
693     new_stats_deduped
694         .iter()
695         .filter(|(new_key, _)| old_stats_deduped.get::<str>(&new_key).is_none())
696         .for_each(|(new_key, new_value)| {
697             println!("{} 0 => {}", new_key, new_value);
698         });
699
700     // list all changed counts (key is in both maps but value differs)
701     new_stats_deduped
702         .iter()
703         .filter(|(new_key, _new_val)| old_stats_deduped.get::<str>(&new_key).is_some())
704         .for_each(|(new_key, new_val)| {
705             let old_val = old_stats_deduped.get::<str>(&new_key).unwrap();
706             println!("{} {} => {}", new_key, old_val, new_val);
707         });
708
709     // list all gone counts (key is in old status but not in new stats)
710     old_stats_deduped
711         .iter()
712         .filter(|(old_key, _)| new_stats_deduped.get::<&String>(&old_key).is_none())
713         .for_each(|(old_key, old_value)| {
714             println!("{} {} => 0", old_key, old_value);
715         });
716 }