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
5 // When a new lint is introduced, we can search the results for new warnings and check for false
8 #![allow(clippy::collapsible_else_if)]
14 use crate::config::LintcheckConfig;
15 use crate::recursive::LintcheckServer;
17 use std::collections::{HashMap, HashSet};
19 use std::env::consts::EXE_SUFFIX;
20 use std::fmt::Write as _;
22 use std::io::ErrorKind;
23 use std::path::{Path, PathBuf};
24 use std::process::Command;
25 use std::sync::atomic::{AtomicUsize, Ordering};
27 use std::time::Duration;
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};
35 const LINTCHECK_DOWNLOADS: &str = "target/lintcheck/downloads";
36 const LINTCHECK_SOURCES: &str = "target/lintcheck/sources";
38 /// List of sources to check, loaded from a .toml file
39 #[derive(Debug, Serialize, Deserialize)]
41 crates: HashMap<String, TomlCrate>,
43 recursive: RecursiveOptions,
46 #[derive(Debug, Serialize, Deserialize, Default)]
47 struct RecursiveOptions {
48 ignore: HashSet<String>,
51 /// A crate source stored inside the .toml
52 /// will be translated into on one of the `CrateSource` variants
53 #[derive(Debug, Serialize, Deserialize)]
56 versions: Option<Vec<String>>,
57 git_url: Option<String>,
58 git_hash: Option<String>,
60 options: Option<Vec<String>>,
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)]
70 options: Option<Vec<String>>,
76 options: Option<Vec<String>>,
81 options: Option<Vec<String>>,
85 /// Represents the actual source code of a crate that we ran "cargo clippy" on
90 // path to the extracted sources that clippy can check
92 options: Option<Vec<String>>,
95 /// A single warning that clippy issued while checking a `Crate`
97 struct 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")
117 let span = diag.spans.into_iter().find(|span| span.is_primary)?;
119 let file = match Path::new(&span.file_name).strip_prefix(env!("CARGO_HOME")) {
120 Ok(stripped) => format!("$CARGO_HOME/{}", stripped.display()),
122 "target/lintcheck/sources/{}-{}/{}",
123 crate_name, crate_version, span.file_name
128 crate_name: crate_name.to_owned(),
130 line: span.line_start,
131 column: span.column_start,
133 message: diag.message,
134 is_ice: diag.level == DiagnosticLevel::Ice,
138 fn to_output(&self, markdown: bool) -> String {
139 let file_with_pos = format!("{}:{}:{}", &self.file, &self.line, &self.column);
141 let mut file = self.file.clone();
142 if !file.starts_with('$') {
143 file.insert_str(0, "../");
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);
152 format!("{} {} \"{}\"\n", file_with_pos, self.lint_type, self.message)
157 fn get(path: &str) -> Result<ureq::Response, ureq::Error> {
158 const MAX_RETRIES: u8 = 4;
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),
167 eprintln!("retrying in {} seconds...", retries);
168 thread::sleep(Duration::from_secs(retries as u64));
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 {
179 CrateSource::CratesIo { name, version, options } => {
180 let extract_dir = PathBuf::from(LINTCHECK_SOURCES);
181 let krate_download_dir = PathBuf::from(LINTCHECK_DOWNLOADS);
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);
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();
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!");
203 // crate is extracted, return a new Krate object which contains the path to the extracted
204 // sources that clippy can check
206 version: version.clone(),
208 path: extract_dir.join(format!("{}-{}/", name, version)),
209 options: options.clone(),
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));
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")
232 .expect("Failed to clone git repo!")
235 eprintln!("Failed to clone {} into {}", url, repo_path.display())
238 // check out the commit/branch/whatever
239 if !Command::new("git")
240 .args(["-c", "advice.detachedHead=false"])
243 .current_dir(&repo_path)
245 .expect("Failed to check out commit")
248 eprintln!("Failed to checkout {} of repo at {}", commit, repo_path.display())
252 version: commit.clone(),
255 options: options.clone(),
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();
268 println!("Copying {:?} to {:?}", path, dest_crate_root);
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"))
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();
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();
291 version: String::from("local"),
293 path: dest_crate_root,
294 options: options.clone(),
302 /// Run `cargo clippy` on the `Crate` and collect and return all the lint warnings that clippy
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;
320 if config.max_jobs == 1 {
322 "{}/{} {}% Linting {} {}",
323 index, total_crates_to_lint, perc, &self.name, &self.version
327 "{}/{} {}% Linting {} {} in target dir {:?}",
328 index, total_crates_to_lint, perc, &self.name, &self.version, thread_index
332 let cargo_clippy_path = std::fs::canonicalize(cargo_clippy_path).unwrap();
334 let shared_target_dir = clippy_project_root().join("target/lintcheck/shared_target_dir");
336 let mut cargo_clippy_args = if config.fix {
339 vec!["--", "--message-format=json", "--"]
342 let mut clippy_args = Vec::<&str>::new();
343 if let Some(options) = &self.options {
345 clippy_args.push(opt);
348 clippy_args.extend(&["-Wclippy::pedantic", "-Wclippy::cargo"])
351 if lint_filter.is_empty() {
352 clippy_args.push("--cap-lints=warn");
354 clippy_args.push("--cap-lints=allow");
355 clippy_args.extend(lint_filter.iter().map(|filter| filter.as_str()))
358 if let Some(server) = server {
359 let target = shared_target_dir.join("recursive");
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:
364 // `RUSTC_WRAPPER` is used instead of `RUSTC_WORKSPACE_WRAPPER` so that we can lint all crate
365 // dependencies rather than only workspace members
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")
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())
381 .expect("failed to run cargo");
383 assert_eq!(status.code(), Some(0));
388 cargo_clippy_args.extend(clippy_args);
390 let all_output = Command::new(&cargo_clippy_path)
391 // use the looping index to create individual target dirs
394 shared_target_dir.join(format!("_{:?}", thread_index)),
396 .args(&cargo_clippy_args)
397 .current_dir(&self.path)
399 .unwrap_or_else(|error| {
401 "Encountered error:\n{:?}\ncargo_clippy_path: {}\ncrate path:{}\n",
403 &cargo_clippy_path.display(),
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;
411 if !status.success() {
413 "\nWARNING: bad exit status after checking {} {} \n",
414 self.name, self.version
419 if let Some(stderr) = stderr
421 .find(|line| line.contains("failed to automatically apply fixes suggested by rustc to crate"))
423 let subcrate = &stderr[63..];
425 "ERROR: failed to apply some suggetion to {} / to (sub)crate {}",
429 // fast path, we don't need the warnings anyway
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),
445 /// Builds clippy inside the repo to make sure we have a clippy executable we can use.
447 let status = Command::new("cargo")
450 .expect("Failed to build clippy!");
451 if !status.success() {
452 eprintln!("Error: Failed to compile Clippy!");
453 std::process::exit(1);
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
467 .map(|(_cratename, tomlcrate)| tomlcrate)
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(),
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(),
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(),
498 panic!("Invalid crate source: {tk:?}");
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()
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!");
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");
512 unreachable!("Failed to translate TomlCrate into CrateSource!");
516 crate_sources.sort();
518 (crate_sources, crate_list.recursive)
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();
527 .for_each(|wrn| *counter.entry(&wrn.lint_type).or_insert(0) += 1);
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));
535 let mut header = String::from("| lint | count |\n");
536 header.push_str("| -------------------------------------------------- | ----- |\n");
537 let stats_string = stats
539 .map(|(lint, count)| format!("| {:<50} | {:>4} |\n", lint, count))
540 .fold(header, |mut table, line| {
541 table.push_str(&line);
545 (stats_string, counter)
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() {
555 let clippy_modified: std::time::SystemTime = {
556 let [cargo, driver] = paths.map(|p| {
558 .expect("failed to get metadata of file")
560 .expect("failed to get modification date")
562 // the oldest modification of either of the binaries
563 std::cmp::max(cargo, driver)
566 let logs_modified: std::time::SystemTime = std::fs::metadata(lintcheck_logs_path)
567 .expect("failed to get metadata of file")
569 .expect("failed to get modification date");
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
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);
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);
588 let config = LintcheckConfig::new();
590 println!("Compiling clippy...");
592 println!("Done compiling");
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();
597 // if the clippy bin is newer than our logs, throw away target dirs to force clippy to
599 if lintcheck_needs_rerun(
600 &config.lintcheck_results_path,
601 [&cargo_clippy_path, &clippy_driver_path],
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");
614 // assert that clippy is found
616 cargo_clippy_path.is_file(),
617 "target/debug/cargo-clippy binary not found! {}",
618 cargo_clippy_path.display()
621 let clippy_ver = std::process::Command::new(&cargo_clippy_path)
624 .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
625 .expect("could not get clippy version!");
627 // download and extract the crates, then run clippy on them and collect clippy's warnings
628 // flatten into one big list of warnings
630 let (crates, recursive_options) = read_crates(&config.sources_toml_path);
631 let old_stats = read_stats_from_file(&config.lintcheck_results_path);
633 let counter = AtomicUsize::new(1);
634 let lint_filter: Vec<String> = config
638 let mut filter = filter.clone();
639 filter.insert_str(0, "--force-warn=");
644 let crates: Vec<Crate> = crates
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,
654 name == only_one_crate
659 .map(|krate| krate.download_and_extract())
662 if crates.is_empty() {
664 "ERROR: could not find crate '{}' in lintcheck/lintcheck_crates.toml",
665 config.only.unwrap(),
667 std::process::exit(1);
670 // run parallel with rayon
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
675 rayon::ThreadPoolBuilder::new()
676 .num_threads(config.max_jobs)
680 let server = config.recursive.then(|| {
681 let _ = fs::remove_dir_all("target/lintcheck/shared_target_dir/recursive");
683 LintcheckServer::spawn(recursive_options)
686 let mut clippy_warnings: Vec<ClippyWarning> = crates
689 krate.run_clippy_lints(
701 if let Some(server) = server {
702 clippy_warnings.extend(server.warnings());
705 // if we are in --fix mode, don't change the log files, terminate here
710 // generate some stats
711 let (stats_formatted, new_stats) = gather_stats(&clippy_warnings);
713 // grab crashes/ICEs, save the crate name and the ice message
714 let ices: Vec<(&String, &String)> = clippy_warnings
716 .filter(|warning| warning.is_ice)
717 .map(|w| (&w.crate_name, &w.message))
720 let mut all_msgs: Vec<String> = clippy_warnings
722 .map(|warn| warn.to_output(config.markdown))
725 all_msgs.push("\n\n### Stats:\n\n".into());
726 all_msgs.push(stats_formatted);
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");
732 text.push_str("| file | lint | message |\n");
733 text.push_str("| --- | --- | --- |\n");
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);
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();
745 print_stats(old_stats, new_stats, &config.lint_filter);
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,
753 return HashMap::new();
757 let lines: Vec<String> = file_content.lines().map(ToString::to_string).collect();
761 .skip_while(|line| line.as_str() != "### Stats:")
762 // Skipping the table header and the `Stats:` label
764 .take_while(|line| line.starts_with("| "))
766 let mut spl = line.split('|');
767 // Skip the first `|` symbol
769 if let (Some(lint), Some(count)) = (spl.next(), spl.next()) {
770 Some((lint.trim().to_string(), count.trim().parse::<usize>().unwrap()))
775 .collect::<HashMap<String, usize>>()
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
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)>>();
786 let mut old_stats_deduped = old_stats;
787 let mut new_stats_deduped = new_stats;
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));
795 println!("\nStats:");
797 // list all new counts (key is in new stats but not in old stats)
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);
805 // list all changed counts (key is in both maps but value differs)
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);
814 // list all gone counts (key is in old status but not in new stats)
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);
824 /// Create necessary directories to run the lintcheck tool.
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");
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");
840 std::fs::create_dir(&extract_dir).unwrap_or_else(|err| {
841 if err.kind() != ErrorKind::AlreadyExists {
842 panic!("cannot create crate extraction dir");
847 /// Returns the path to the Clippy project directory
849 fn clippy_project_root() -> &'static Path {
850 Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap()
854 fn lintcheck_test() {
860 "./lintcheck/Cargo.toml",
863 "lintcheck/test_sources.toml",
865 let status = std::process::Command::new("cargo")
867 .current_dir("..") // repo root
871 assert!(status.unwrap().success());