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::filter_map, clippy::collapsible_else_if)]
11 use std::process::Command;
12 use std::sync::atomic::{AtomicUsize, Ordering};
13 use std::{collections::HashMap, io::ErrorKind};
17 path::{Path, PathBuf},
20 use clap::{App, Arg, ArgMatches};
21 use rayon::prelude::*;
22 use serde::{Deserialize, Serialize};
23 use serde_json::Value;
25 const CLIPPY_DRIVER_PATH: &str = "target/debug/clippy-driver";
26 const CARGO_CLIPPY_PATH: &str = "target/debug/cargo-clippy";
28 const LINTCHECK_DOWNLOADS: &str = "target/lintcheck/downloads";
29 const LINTCHECK_SOURCES: &str = "target/lintcheck/sources";
31 /// List of sources to check, loaded from a .toml file
32 #[derive(Debug, Serialize, Deserialize)]
34 crates: HashMap<String, TomlCrate>,
37 /// A crate source stored inside the .toml
38 /// will be translated into on one of the `CrateSource` variants
39 #[derive(Debug, Serialize, Deserialize)]
42 versions: Option<Vec<String>>,
43 git_url: Option<String>,
44 git_hash: Option<String>,
46 options: Option<Vec<String>>,
49 /// Represents an archive we download from crates.io, or a git repo, or a local repo/folder
50 /// Once processed (downloaded/extracted/cloned/copied...), this will be translated into a `Crate`
51 #[derive(Debug, Serialize, Deserialize, Eq, Hash, PartialEq, Ord, PartialOrd)]
56 options: Option<Vec<String>>,
62 options: Option<Vec<String>>,
67 options: Option<Vec<String>>,
71 /// Represents the actual source code of a crate that we ran "cargo clippy" on
76 // path to the extracted sources that clippy can check
78 options: Option<Vec<String>>,
81 /// A single warning that clippy issued while checking a `Crate`
83 struct ClippyWarning {
85 crate_version: String,
94 impl std::fmt::Display for ClippyWarning {
95 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98 r#"target/lintcheck/sources/{}-{}/{}:{}:{} {} "{}""#,
99 &self.crate_name, &self.crate_version, &self.file, &self.line, &self.column, &self.linttype, &self.message
105 /// Makes the sources available on the disk for clippy to check.
106 /// Clones a git repo and checks out the specified commit or downloads a crate from crates.io or
107 /// copies a local folder
108 fn download_and_extract(&self) -> Crate {
110 CrateSource::CratesIo { name, version, options } => {
111 let extract_dir = PathBuf::from(LINTCHECK_SOURCES);
112 let krate_download_dir = PathBuf::from(LINTCHECK_DOWNLOADS);
114 // url to download the crate from crates.io
115 let url = format!("https://crates.io/api/v1/crates/{}/{}/download", name, version);
116 println!("Downloading and extracting {} {} from {}", name, version, url);
117 create_dirs(&krate_download_dir, &extract_dir);
119 let krate_file_path = krate_download_dir.join(format!("{}-{}.crate.tar.gz", name, version));
120 // don't download/extract if we already have done so
121 if !krate_file_path.is_file() {
122 // create a file path to download and write the crate data into
123 let mut krate_dest = std::fs::File::create(&krate_file_path).unwrap();
124 let mut krate_req = ureq::get(&url).call().unwrap().into_reader();
125 // copy the crate into the file
126 std::io::copy(&mut krate_req, &mut krate_dest).unwrap();
129 let ungz_tar = flate2::read::GzDecoder::new(std::fs::File::open(&krate_file_path).unwrap());
130 // extract the tar archive
131 let mut archive = tar::Archive::new(ungz_tar);
132 archive.unpack(&extract_dir).expect("Failed to extract!");
134 // crate is extracted, return a new Krate object which contains the path to the extracted
135 // sources that clippy can check
137 version: version.clone(),
139 path: extract_dir.join(format!("{}-{}/", name, version)),
140 options: options.clone(),
150 let mut repo_path = PathBuf::from(LINTCHECK_SOURCES);
151 // add a -git suffix in case we have the same crate from crates.io and a git repo
152 repo_path.push(format!("{}-git", name));
155 // clone the repo if we have not done so
156 if !repo_path.is_dir() {
157 println!("Cloning {} and checking out {}", url, commit);
158 if !Command::new("git")
163 .expect("Failed to clone git repo!")
166 eprintln!("Failed to clone {} into {}", url, repo_path.display())
169 // check out the commit/branch/whatever
170 if !Command::new("git")
173 .current_dir(&repo_path)
175 .expect("Failed to check out commit")
178 eprintln!("Failed to checkout {} of repo at {}", commit, repo_path.display())
182 version: commit.clone(),
185 options: options.clone(),
188 CrateSource::Path { name, path, options } => {
191 // simply copy the entire directory into our target dir
192 let copy_dest = PathBuf::from(format!("{}/", LINTCHECK_SOURCES));
194 // the source path of the crate we copied, ${copy_dest}/crate_name
195 let crate_root = copy_dest.join(name); // .../crates/local_crate
197 if crate_root.exists() {
199 "Not copying {} to {}, destination already exists",
204 println!("Copying {} to {}", path.display(), copy_dest.display());
206 dir::copy(path, ©_dest, &dir::CopyOptions::new()).unwrap_or_else(|_| {
207 panic!("Failed to copy from {}, to {}", path.display(), crate_root.display())
212 version: String::from("local"),
215 options: options.clone(),
223 /// Run `cargo clippy` on the `Crate` and collect and return all the lint warnings that clippy
227 cargo_clippy_path: &Path,
228 target_dir_index: &AtomicUsize,
230 total_crates_to_lint: usize,
232 ) -> Vec<ClippyWarning> {
233 // advance the atomic index by one
234 let index = target_dir_index.fetch_add(1, Ordering::SeqCst);
235 // "loop" the index within 0..thread_limit
236 let thread_index = index % thread_limit;
237 let perc = (index * 100) / total_crates_to_lint;
239 if thread_limit == 1 {
241 "{}/{} {}% Linting {} {}",
242 index, total_crates_to_lint, perc, &self.name, &self.version
246 "{}/{} {}% Linting {} {} in target dir {:?}",
247 index, total_crates_to_lint, perc, &self.name, &self.version, thread_index
251 let cargo_clippy_path = std::fs::canonicalize(cargo_clippy_path).unwrap();
253 let shared_target_dir = clippy_project_root().join("target/lintcheck/shared_target_dir");
255 let mut args = if fix {
257 "-Zunstable-options",
259 "-Zunstable-options",
265 vec!["--", "--message-format=json", "--", "--cap-lints=warn"]
268 if let Some(options) = &self.options {
273 args.extend(&["-Wclippy::pedantic", "-Wclippy::cargo"])
276 let all_output = std::process::Command::new(&cargo_clippy_path)
277 // use the looping index to create individual target dirs
280 shared_target_dir.join(format!("_{:?}", thread_index)),
282 // lint warnings will look like this:
283 // src/cargo/ops/cargo_compile.rs:127:35: warning: usage of `FromIterator::from_iter`
285 .current_dir(&self.path)
287 .unwrap_or_else(|error| {
289 "Encountered error:\n{:?}\ncargo_clippy_path: {}\ncrate path:{}\n",
291 &cargo_clippy_path.display(),
295 let stdout = String::from_utf8_lossy(&all_output.stdout);
296 let stderr = String::from_utf8_lossy(&all_output.stderr);
297 let status = &all_output.status;
299 if !status.success() {
301 "\nWARNING: bad exit status after checking {} {} \n",
302 self.name, self.version
307 if let Some(stderr) = stderr
309 .find(|line| line.contains("failed to automatically apply fixes suggested by rustc to crate"))
311 let subcrate = &stderr[63..];
313 "ERROR: failed to apply some suggetion to {} / to (sub)crate {}",
317 // fast path, we don't need the warnings anyway
321 let output_lines = stdout.lines();
322 let warnings: Vec<ClippyWarning> = output_lines
324 // get all clippy warnings and ICEs
325 .filter(|line| filter_clippy_warnings(&line))
326 .map(|json_msg| parse_json_message(json_msg, &self))
334 struct LintcheckConfig {
335 // max number of jobs to spawn (default 1)
337 // we read the sources to check from here
338 sources_toml_path: PathBuf,
339 // we save the clippy lint results here
340 lintcheck_results_path: PathBuf,
341 // whether to just run --fix and not collect all the warnings
345 impl LintcheckConfig {
346 fn from_clap(clap_config: &ArgMatches) -> Self {
347 // first, check if we got anything passed via the LINTCHECK_TOML env var,
348 // if not, ask clap if we got any value for --crates-toml <foo>
349 // if not, use the default "lintcheck/lintcheck_crates.toml"
350 let sources_toml = env::var("LINTCHECK_TOML").unwrap_or_else(|_| {
352 .value_of("crates-toml")
354 .unwrap_or("lintcheck/lintcheck_crates.toml")
358 let sources_toml_path = PathBuf::from(sources_toml);
360 // for the path where we save the lint results, get the filename without extension (so for
361 // wasd.toml, use "wasd"...)
362 let filename: PathBuf = sources_toml_path.file_stem().unwrap().into();
363 let lintcheck_results_path = PathBuf::from(format!("lintcheck-logs/{}_logs.txt", filename.display()));
365 // look at the --threads arg, if 0 is passed, ask rayon rayon how many threads it would spawn and
366 // use half of that for the physical core count
367 // by default use a single thread
368 let max_jobs = match clap_config.value_of("threads") {
370 let threads: usize = threads
372 .unwrap_or_else(|_| panic!("Failed to parse '{}' to a digit", threads));
375 // Rayon seems to return thread count so half that for core count
376 (rayon::current_num_threads() / 2) as usize
381 // no -j passed, use a single thread
384 let fix: bool = clap_config.is_present("fix");
389 lintcheck_results_path,
395 /// takes a single json-formatted clippy warnings and returns true (we are interested in that line)
396 /// or false (we aren't)
397 fn filter_clippy_warnings(line: &str) -> bool {
398 // we want to collect ICEs because clippy might have crashed.
399 // these are summarized later
400 if line.contains("internal compiler error: ") {
403 // in general, we want all clippy warnings
404 // however due to some kind of bug, sometimes there are absolute paths
405 // to libcore files inside the message
406 // or we end up with cargo-metadata output (https://github.com/rust-lang/rust-clippy/issues/6508)
408 // filter out these message to avoid unnecessary noise in the logs
409 if line.contains("clippy::")
410 && !(line.contains("could not read cargo metadata")
411 || (line.contains(".rustup") && line.contains("toolchains")))
418 /// Builds clippy inside the repo to make sure we have a clippy executable we can use.
420 let status = Command::new("cargo")
423 .expect("Failed to build clippy!");
424 if !status.success() {
425 eprintln!("Error: Failed to compile Clippy!");
426 std::process::exit(1);
430 /// Read a `toml` file and return a list of `CrateSources` that we want to check with clippy
431 fn read_crates(toml_path: &Path) -> Vec<CrateSource> {
432 let toml_content: String =
433 std::fs::read_to_string(&toml_path).unwrap_or_else(|_| panic!("Failed to read {}", toml_path.display()));
434 let crate_list: SourceList =
435 toml::from_str(&toml_content).unwrap_or_else(|e| panic!("Failed to parse {}: \n{}", toml_path.display(), e));
436 // parse the hashmap of the toml file into a list of crates
437 let tomlcrates: Vec<TomlCrate> = crate_list
440 .map(|(_cratename, tomlcrate)| tomlcrate)
443 // flatten TomlCrates into CrateSources (one TomlCrates may represent several versions of a crate =>
444 // multiple Cratesources)
445 let mut crate_sources = Vec::new();
446 tomlcrates.into_iter().for_each(|tk| {
447 if let Some(ref path) = tk.path {
448 crate_sources.push(CrateSource::Path {
449 name: tk.name.clone(),
450 path: PathBuf::from(path),
451 options: tk.options.clone(),
455 // if we have multiple versions, save each one
456 if let Some(ref versions) = tk.versions {
457 versions.iter().for_each(|ver| {
458 crate_sources.push(CrateSource::CratesIo {
459 name: tk.name.clone(),
460 version: ver.to_string(),
461 options: tk.options.clone(),
465 // otherwise, we should have a git source
466 if tk.git_url.is_some() && tk.git_hash.is_some() {
467 crate_sources.push(CrateSource::Git {
468 name: tk.name.clone(),
469 url: tk.git_url.clone().unwrap(),
470 commit: tk.git_hash.clone().unwrap(),
471 options: tk.options.clone(),
474 // if we have a version as well as a git data OR only one git data, something is funky
475 if tk.versions.is_some() && (tk.git_url.is_some() || tk.git_hash.is_some())
476 || tk.git_hash.is_some() != tk.git_url.is_some()
478 eprintln!("tomlkrate: {:?}", tk);
479 if tk.git_hash.is_some() != tk.git_url.is_some() {
480 panic!("Error: Encountered TomlCrate with only one of git_hash and git_url!");
482 if tk.path.is_some() && (tk.git_hash.is_some() || tk.versions.is_some()) {
483 panic!("Error: TomlCrate can only have one of 'git_.*', 'version' or 'path' fields");
485 unreachable!("Failed to translate TomlCrate into CrateSource!");
489 crate_sources.sort();
494 /// Parse the json output of clippy and return a `ClippyWarning`
495 fn parse_json_message(json_message: &str, krate: &Crate) -> ClippyWarning {
496 let jmsg: Value = serde_json::from_str(&json_message).unwrap_or_else(|e| panic!("Failed to parse json:\n{:?}", e));
498 let file: String = jmsg["message"]["spans"][0]["file_name"]
503 let file = if file.contains(".cargo") {
504 // if we deal with macros, a filename may show the origin of a macro which can be inside a dep from
506 // don't show the full path in that case.
508 // /home/matthias/.cargo/registry/src/github.com-1ecc6299db9ec823/syn-1.0.63/src/custom_keyword.rs
509 let path = PathBuf::from(file);
510 let mut piter = path.iter();
511 // consume all elements until we find ".cargo", so that "/home/matthias" is skipped
512 let _: Option<&OsStr> = piter.find(|x| x == &std::ffi::OsString::from(".cargo"));
513 // collect the remaining segments
514 let file = piter.collect::<PathBuf>();
515 format!("{}", file.display())
521 crate_name: krate.name.to_string(),
522 crate_version: krate.version.to_string(),
524 line: jmsg["message"]["spans"][0]["line_start"]
528 column: jmsg["message"]["spans"][0]["text"][0]["highlight_start"]
532 linttype: jmsg["message"]["code"]["code"].to_string().trim_matches('"').into(),
533 message: jmsg["message"]["message"].to_string().trim_matches('"').into(),
534 is_ice: json_message.contains("internal compiler error: "),
538 /// Generate a short list of occuring lints-types and their count
539 fn gather_stats(clippy_warnings: &[ClippyWarning]) -> (String, HashMap<&String, usize>) {
540 // count lint type occurrences
541 let mut counter: HashMap<&String, usize> = HashMap::new();
544 .for_each(|wrn| *counter.entry(&wrn.linttype).or_insert(0) += 1);
546 // collect into a tupled list for sorting
547 let mut stats: Vec<(&&String, &usize)> = counter.iter().map(|(lint, count)| (lint, count)).collect();
548 // sort by "000{count} {clippy::lintname}"
549 // to not have a lint with 200 and 2 warnings take the same spot
550 stats.sort_by_key(|(lint, count)| format!("{:0>4}, {}", count, lint));
552 let stats_string = stats
554 .map(|(lint, count)| format!("{} {}\n", lint, count))
555 .collect::<String>();
557 (stats_string, counter)
560 /// check if the latest modification of the logfile is older than the modification date of the
561 /// clippy binary, if this is true, we should clean the lintchec shared target directory and recheck
562 fn lintcheck_needs_rerun(lintcheck_logs_path: &Path) -> bool {
563 if !lintcheck_logs_path.exists() {
567 let clippy_modified: std::time::SystemTime = {
568 let mut times = [CLIPPY_DRIVER_PATH, CARGO_CLIPPY_PATH].iter().map(|p| {
570 .expect("failed to get metadata of file")
572 .expect("failed to get modification date")
574 // the oldest modification of either of the binaries
575 std::cmp::max(times.next().unwrap(), times.next().unwrap())
578 let logs_modified: std::time::SystemTime = std::fs::metadata(lintcheck_logs_path)
579 .expect("failed to get metadata of file")
581 .expect("failed to get modification date");
583 // time is represented in seconds since X
584 // logs_modified 2 and clippy_modified 5 means clippy binary is older and we need to recheck
585 logs_modified < clippy_modified
588 fn is_in_clippy_root() -> bool {
589 if let Ok(pb) = std::env::current_dir() {
590 if let Some(file) = pb.file_name() {
591 return file == PathBuf::from("rust-clippy");
598 /// lintchecks `main()` function
602 /// This function panics if the clippy binaries don't exist
603 /// or if lintcheck is executed from the wrong directory (aka none-repo-root)
605 // assert that we launch lintcheck from the repo root (via cargo lintcheck)
606 if !is_in_clippy_root() {
607 eprintln!("lintcheck needs to be run from clippys repo root!\nUse `cargo lintcheck` alternatively.");
608 std::process::exit(3);
611 let clap_config = &get_clap_config();
613 let config = LintcheckConfig::from_clap(clap_config);
615 println!("Compiling clippy...");
617 println!("Done compiling");
619 // if the clippy bin is newer than our logs, throw away target dirs to force clippy to
621 if lintcheck_needs_rerun(&config.lintcheck_results_path) {
622 let shared_target_dir = "target/lintcheck/shared_target_dir";
623 // if we get an Err here, the shared target dir probably does simply not exist
624 if let Ok(metadata) = std::fs::metadata(&shared_target_dir) {
625 if metadata.is_dir() {
626 println!("Clippy is newer than lint check logs, clearing lintcheck shared target dir...");
627 std::fs::remove_dir_all(&shared_target_dir)
628 .expect("failed to remove target/lintcheck/shared_target_dir");
633 let cargo_clippy_path: PathBuf = PathBuf::from(CARGO_CLIPPY_PATH)
635 .expect("failed to canonicalize path to clippy binary");
637 // assert that clippy is found
639 cargo_clippy_path.is_file(),
640 "target/debug/cargo-clippy binary not found! {}",
641 cargo_clippy_path.display()
644 let clippy_ver = std::process::Command::new(CARGO_CLIPPY_PATH)
647 .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
648 .expect("could not get clippy version!");
650 // download and extract the crates, then run clippy on them and collect clippys warnings
651 // flatten into one big list of warnings
653 let crates = read_crates(&config.sources_toml_path);
654 let old_stats = read_stats_from_file(&config.lintcheck_results_path);
656 let counter = AtomicUsize::new(1);
658 let clippy_warnings: Vec<ClippyWarning> = if let Some(only_one_crate) = clap_config.value_of("only") {
659 // if we don't have the specified crate in the .toml, throw an error
660 if !crates.iter().any(|krate| {
661 let name = match krate {
662 CrateSource::CratesIo { name, .. } | CrateSource::Git { name, .. } | CrateSource::Path { name, .. } => {
666 name == only_one_crate
669 "ERROR: could not find crate '{}' in lintcheck/lintcheck_crates.toml",
672 std::process::exit(1);
675 // only check a single crate that was passed via cmdline
678 .map(|krate| krate.download_and_extract())
679 .filter(|krate| krate.name == only_one_crate)
680 .flat_map(|krate| krate.run_clippy_lints(&cargo_clippy_path, &AtomicUsize::new(0), 1, 1, config.fix))
683 if config.max_jobs > 1 {
684 // run parallel with rayon
686 // Ask rayon for thread count. Assume that half of that is the number of physical cores
687 // Use one target dir for each core so that we can run N clippys in parallel.
688 // We need to use different target dirs because cargo would lock them for a single build otherwise,
689 // killing the parallelism. However this also means that deps will only be reused half/a
690 // quarter of the time which might result in a longer wall clock runtime
692 // This helps when we check many small crates with dep-trees that don't have a lot of branches in
693 // order to achive some kind of parallelism
695 // by default, use a single thread
696 let num_cpus = config.max_jobs;
697 let num_crates = crates.len();
699 // check all crates (default)
702 .map(|krate| krate.download_and_extract())
704 krate.run_clippy_lints(&cargo_clippy_path, &counter, num_cpus, num_crates, config.fix)
709 let num_crates = crates.len();
712 .map(|krate| krate.download_and_extract())
713 .flat_map(|krate| krate.run_clippy_lints(&cargo_clippy_path, &counter, 1, num_crates, config.fix))
718 // if we are in --fix mode, don't change the log files, terminate here
723 // generate some stats
724 let (stats_formatted, new_stats) = gather_stats(&clippy_warnings);
726 // grab crashes/ICEs, save the crate name and the ice message
727 let ices: Vec<(&String, &String)> = clippy_warnings
729 .filter(|warning| warning.is_ice)
730 .map(|w| (&w.crate_name, &w.message))
733 let mut all_msgs: Vec<String> = clippy_warnings.iter().map(ToString::to_string).collect();
735 all_msgs.push("\n\n\n\nStats:\n".into());
736 all_msgs.push(stats_formatted);
738 // save the text into lintcheck-logs/logs.txt
739 let mut text = clippy_ver; // clippy version number on top
740 text.push_str(&format!("\n{}", all_msgs.join("")));
741 text.push_str("ICEs:\n");
743 .for_each(|(cratename, msg)| text.push_str(&format!("{}: '{}'", cratename, msg)));
745 println!("Writing logs to {}", config.lintcheck_results_path.display());
746 write(&config.lintcheck_results_path, text).unwrap();
748 print_stats(old_stats, new_stats);
751 /// read the previous stats from the lintcheck-log file
752 fn read_stats_from_file(file_path: &Path) -> HashMap<String, usize> {
753 let file_content: String = match std::fs::read_to_string(file_path).ok() {
754 Some(content) => content,
756 return HashMap::new();
760 let lines: Vec<String> = file_content.lines().map(ToString::to_string).collect();
762 // search for the beginning "Stats:" and the end "ICEs:" of the section we want
763 let start = lines.iter().position(|line| line == "Stats:").unwrap();
764 let end = lines.iter().position(|line| line == "ICEs:").unwrap();
766 let stats_lines = &lines[start + 1..end];
771 let mut spl = line.split(' ');
773 spl.next().unwrap().to_string(),
774 spl.next().unwrap().parse::<usize>().unwrap(),
777 .collect::<HashMap<String, usize>>()
780 /// print how lint counts changed between runs
781 fn print_stats(old_stats: HashMap<String, usize>, new_stats: HashMap<&String, usize>) {
782 let same_in_both_hashmaps = old_stats
784 .filter(|(old_key, old_val)| new_stats.get::<&String>(&old_key) == Some(old_val))
785 .map(|(k, v)| (k.to_string(), *v))
786 .collect::<Vec<(String, usize)>>();
788 let mut old_stats_deduped = old_stats;
789 let mut new_stats_deduped = new_stats;
791 // remove duplicates from both hashmaps
792 same_in_both_hashmaps.iter().for_each(|(k, v)| {
793 assert!(old_stats_deduped.remove(k) == Some(*v));
794 assert!(new_stats_deduped.remove(k) == Some(*v));
797 println!("\nStats:");
799 // list all new counts (key is in new stats but not in old stats)
802 .filter(|(new_key, _)| old_stats_deduped.get::<str>(&new_key).is_none())
803 .for_each(|(new_key, new_value)| {
804 println!("{} 0 => {}", new_key, new_value);
807 // list all changed counts (key is in both maps but value differs)
810 .filter(|(new_key, _new_val)| old_stats_deduped.get::<str>(&new_key).is_some())
811 .for_each(|(new_key, new_val)| {
812 let old_val = old_stats_deduped.get::<str>(&new_key).unwrap();
813 println!("{} {} => {}", new_key, old_val, new_val);
816 // list all gone counts (key is in old status but not in new stats)
819 .filter(|(old_key, _)| new_stats_deduped.get::<&String>(&old_key).is_none())
820 .for_each(|(old_key, old_value)| {
821 println!("{} {} => 0", old_key, old_value);
825 /// Create necessary directories to run the lintcheck tool.
829 /// This function panics if creating one of the dirs fails.
830 fn create_dirs(krate_download_dir: &Path, extract_dir: &Path) {
831 std::fs::create_dir("target/lintcheck/").unwrap_or_else(|err| {
832 if err.kind() != ErrorKind::AlreadyExists {
833 panic!("cannot create lintcheck target dir");
836 std::fs::create_dir(&krate_download_dir).unwrap_or_else(|err| {
837 if err.kind() != ErrorKind::AlreadyExists {
838 panic!("cannot create crate download dir");
841 std::fs::create_dir(&extract_dir).unwrap_or_else(|err| {
842 if err.kind() != ErrorKind::AlreadyExists {
843 panic!("cannot create crate extraction dir");
848 fn get_clap_config<'a>() -> ArgMatches<'a> {
849 App::new("lintcheck")
850 .about("run clippy on a set of crates and check output")
852 Arg::with_name("only")
856 .help("only process a single crate of the list"),
859 Arg::with_name("crates-toml")
861 .value_name("CRATES-SOURCES-TOML-PATH")
863 .help("set the path for a crates.toml where lintcheck should read the sources from"),
866 Arg::with_name("threads")
871 .help("number of threads to use, 0 automatic choice"),
874 Arg::with_name("fix")
876 .help("runs cargo clippy --fix and checks if all suggestions apply"),
881 /// Returns the path to the Clippy project directory
885 /// Panics if the current directory could not be retrieved, there was an error reading any of the
886 /// Cargo.toml files or ancestor directory is the clippy root directory
888 pub fn clippy_project_root() -> PathBuf {
889 let current_dir = std::env::current_dir().unwrap();
890 for path in current_dir.ancestors() {
891 let result = std::fs::read_to_string(path.join("Cargo.toml"));
892 if let Err(err) = &result {
893 if err.kind() == std::io::ErrorKind::NotFound {
898 let content = result.unwrap();
899 if content.contains("[package]\nname = \"clippy\"") {
900 return path.to_path_buf();
903 panic!("error: Can't determine root of project. Please run inside a Clippy working dir.");
907 fn lintcheck_test() {
913 "./lintcheck/Cargo.toml",
916 "lintcheck/test_sources.toml",
918 let status = std::process::Command::new("cargo")
920 .current_dir("..") // repo root
924 assert!(status.unwrap().success());