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.
4 // When a new lint is introduced, we can search the results for new warnings and check for false
7 #![cfg(feature = "lintcheck")]
8 #![allow(clippy::filter_map)]
10 use crate::clippy_project_root;
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};
18 use rayon::prelude::*;
19 use serde::{Deserialize, Serialize};
20 use serde_json::Value;
22 /// List of sources to check, loaded from a .toml file
23 #[derive(Debug, Serialize, Deserialize)]
25 crates: HashMap<String, TomlCrate>,
28 /// A crate source stored inside the .toml
29 /// will be translated into on one of the `CrateSource` variants
30 #[derive(Debug, Serialize, Deserialize)]
33 versions: Option<Vec<String>>,
34 git_url: Option<String>,
35 git_hash: Option<String>,
37 options: Option<Vec<String>>,
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)]
47 options: Option<Vec<String>>,
53 options: Option<Vec<String>>,
58 options: Option<Vec<String>>,
62 /// Represents the actual source code of a crate that we ran "cargo clippy" on
67 // path to the extracted sources that clippy can check
69 options: Option<Vec<String>>,
72 /// A single warning that clippy issued while checking a `Crate`
74 struct ClippyWarning {
76 crate_version: String,
85 impl std::fmt::Display for ClippyWarning {
86 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89 r#"{}-{}/{}:{}:{} {} "{}""#,
90 &self.crate_name, &self.crate_version, &self.file, &self.line, &self.column, &self.linttype, &self.message
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 {
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");
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);
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();
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!");
127 // crate is extracted, return a new Krate object which contains the path to the extracted
128 // sources that clippy can check
130 version: version.clone(),
132 path: extract_dir.join(format!("{}-{}/", name, version)),
133 options: options.clone(),
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));
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")
156 .expect("Failed to clone git repo!")
159 eprintln!("Failed to clone {} into {}", url, repo_path.display())
162 // check out the commit/branch/whatever
163 if !Command::new("git")
166 .current_dir(&repo_path)
168 .expect("Failed to check out commit")
171 eprintln!("Failed to checkout {} of repo at {}", commit, repo_path.display())
175 version: commit.clone(),
178 options: options.clone(),
181 CrateSource::Path { name, path, options } => {
184 // simply copy the entire directory into our target dir
185 let copy_dest = PathBuf::from("target/lintcheck/crates/");
187 // the source path of the crate we copied, ${copy_dest}/crate_name
188 let crate_root = copy_dest.join(name); // .../crates/local_crate
190 if !crate_root.exists() {
191 println!("Copying {} to {}", path.display(), copy_dest.display());
193 dir::copy(path, ©_dest, &dir::CopyOptions::new()).expect(&format!(
194 "Failed to copy from {}, to {}",
200 "Not copying {} to {}, destination already exists",
207 version: String::from("local"),
210 options: options.clone(),
218 /// Run `cargo clippy` on the `Crate` and collect and return all the lint warnings that clippy
222 cargo_clippy_path: &PathBuf,
223 target_dir_index: &AtomicUsize,
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;
233 if thread_limit == 1 {
235 "{}/{} {}% Linting {} {}",
236 index, total_crates_to_lint, perc, &self.name, &self.version
240 "{}/{} {}% Linting {} {} in target dir {:?}",
241 index, total_crates_to_lint, perc, &self.name, &self.version, target_dir_index
245 let cargo_clippy_path = std::fs::canonicalize(cargo_clippy_path).unwrap();
247 let shared_target_dir = clippy_project_root().join("target/lintcheck/shared_target_dir");
249 let mut args = vec!["--", "--message-format=json", "--", "--cap-lints=warn"];
251 if let Some(options) = &self.options {
256 args.extend(&["-Wclippy::pedantic", "-Wclippy::cargo"])
259 let all_output = std::process::Command::new(&cargo_clippy_path)
260 // use the looping index to create individual target dirs
263 shared_target_dir.join(format!("_{:?}", target_dir_index)),
265 // lint warnings will look like this:
266 // src/cargo/ops/cargo_compile.rs:127:35: warning: usage of `FromIterator::from_iter`
268 .current_dir(&self.path)
270 .unwrap_or_else(|error| {
272 "Encountered error:\n{:?}\ncargo_clippy_path: {}\ncrate path:{}\n",
274 &cargo_clippy_path.display(),
278 let stdout = String::from_utf8_lossy(&all_output.stdout);
279 let output_lines = stdout.lines();
280 let warnings: Vec<ClippyWarning> = output_lines
282 // get all clippy warnings and ICEs
283 .filter(|line| filter_clippy_warnings(&line))
284 .map(|json_msg| parse_json_message(json_msg, &self))
291 struct LintcheckConfig {
292 // max number of jobs to spawn (default 1)
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,
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(
307 .value_of("crates-toml")
309 .unwrap_or("clippy_dev/lintcheck_crates.toml")
313 let sources_toml_path = PathBuf::from(sources_toml);
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()));
320 let max_jobs = match clap_config.value_of("threads") {
322 let threads: usize = threads
324 .expect(&format!("Failed to parse '{}' to a digit", threads));
327 // Rayon seems to return thread count so half that for core count
328 (rayon::current_num_threads() / 2) as usize
333 // no -j passed, use a single thread
340 lintcheck_results_path,
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: ") {
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)
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")))
368 /// Builds clippy inside the repo to make sure we have a clippy executable we can use.
370 let status = Command::new("cargo")
373 .expect("Failed to build clippy!");
374 if !status.success() {
375 eprintln!("Error: Failed to compile Clippy!");
376 std::process::exit(1);
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
390 .map(|(_cratename, tomlcrate)| tomlcrate)
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(),
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(),
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(),
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()
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!");
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");
435 unreachable!("Failed to translate TomlCrate into CrateSource!");
439 crate_sources.sort();
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));
449 crate_name: krate.name.to_string(),
450 crate_version: krate.version.to_string(),
451 file: jmsg["message"]["spans"][0]["file_name"]
455 line: jmsg["message"]["spans"][0]["line_start"]
459 column: jmsg["message"]["spans"][0]["text"][0]["highlight_start"]
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: "),
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();
475 .for_each(|wrn| *counter.entry(&wrn.linttype).or_insert(0) += 1);
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));
483 let stats_string = stats
485 .map(|(lint, count)| format!("{} {}\n", lint, count))
486 .collect::<String>();
488 (stats_string, counter)
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"]
499 .expect("failed to get metadata of file")
501 .expect("failed to get modification date")
503 // the oldest modification of either of the binaries
504 std::cmp::min(times.next().unwrap(), times.next().unwrap())
507 let logs_modified: std::time::SystemTime = std::fs::metadata(toml_path)
508 .expect("failed to get metadata of file")
510 .expect("failed to get modification date");
512 // if clippys modification time is smaller (older) than the logs mod time, we need to rerun
514 clippy_modified < logs_modified
517 /// lintchecks `main()` function
518 pub fn run(clap_config: &ArgMatches) {
519 let config = LintcheckConfig::from_clap(clap_config);
521 println!("Compiling clippy...");
523 println!("Done compiling");
525 // if the clippy bin is newer than our logs, throw away target dirs to force clippy to
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) {
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");
537 Err(_) => { // dir probably does not exist, don't remove anything
542 let cargo_clippy_path: PathBuf = PathBuf::from("target/debug/cargo-clippy")
544 .expect("failed to canonicalize path to clippy binary");
546 // assert that clippy is found
548 cargo_clippy_path.is_file(),
549 "target/debug/cargo-clippy binary not found! {}",
550 cargo_clippy_path.display()
553 let clippy_ver = std::process::Command::new("target/debug/cargo-clippy")
556 .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
557 .expect("could not get clippy version!");
559 // download and extract the crates, then run clippy on them and collect clippys warnings
560 // flatten into one big list of warnings
562 let crates = read_crates(&config.sources_toml_path);
563 let old_stats = read_stats_from_file(&config.lintcheck_results_path);
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,
573 name == only_one_crate
576 "ERROR: could not find crate '{}' in clippy_dev/lintcheck_crates.toml",
579 std::process::exit(1);
582 // only check a single crate that was passed via cmdline
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))
591 let counter = std::sync::atomic::AtomicUsize::new(0);
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
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
602 // by default, use a single thread
603 let num_cpus = config.max_jobs;
604 let num_crates = crates.len();
606 // check all crates (default)
609 .map(|krate| krate.download_and_extract())
610 .map(|krate| krate.run_clippy_lints(&cargo_clippy_path, &counter, num_cpus, num_crates))
615 // generate some stats
616 let (stats_formatted, new_stats) = gather_stats(&clippy_warnings);
618 // grab crashes/ICEs, save the crate name and the ice message
619 let ices: Vec<(&String, &String)> = clippy_warnings
621 .filter(|warning| warning.is_ice)
622 .map(|w| (&w.crate_name, &w.message))
625 let mut all_msgs: Vec<String> = clippy_warnings.iter().map(|warning| warning.to_string()).collect();
627 all_msgs.push("\n\n\n\nStats:\n".into());
628 all_msgs.push(stats_formatted);
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");
635 .for_each(|(cratename, msg)| text.push_str(&format!("{}: '{}'", cratename, msg)));
637 println!("Writing logs to {}", config.lintcheck_results_path.display());
638 write(&config.lintcheck_results_path, text).unwrap();
640 print_stats(old_stats, new_stats);
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,
648 eprintln!("RETURND");
649 return HashMap::new();
653 let lines: Vec<String> = file_content.lines().map(|l| l.to_string()).collect();
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();
659 let stats_lines = &lines[start + 1..=end - 1];
664 let mut spl = line.split(" ").into_iter();
666 spl.next().unwrap().to_string(),
667 spl.next().unwrap().parse::<usize>().unwrap(),
670 .collect::<HashMap<String, usize>>()
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
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)>>();
681 let mut old_stats_deduped = old_stats;
682 let mut new_stats_deduped = new_stats;
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));
690 println!("\nStats:");
692 // list all new counts (key is in new stats but not in old stats)
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);
700 // list all changed counts (key is in both maps but value differs)
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);
709 // list all gone counts (key is in old status but not in new stats)
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);