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)]
11 use std
::process
::Command
;
12 use std
::sync
::atomic
::{AtomicUsize, Ordering}
;
13 use std
::{collections::HashMap, io::ErrorKind}
;
17 path
::{Path, PathBuf}
,
22 use clap
::{App, Arg, ArgMatches}
;
23 use rayon
::prelude
::*;
24 use serde
::{Deserialize, Serialize}
;
25 use serde_json
::Value
;
26 use walkdir
::{DirEntry, WalkDir}
;
29 const CLIPPY_DRIVER_PATH
: &str = "target/debug/clippy-driver";
31 const CARGO_CLIPPY_PATH
: &str = "target/debug/cargo-clippy";
34 const CLIPPY_DRIVER_PATH
: &str = "target/debug/clippy-driver.exe";
36 const CARGO_CLIPPY_PATH
: &str = "target/debug/cargo-clippy.exe";
38 const LINTCHECK_DOWNLOADS
: &str = "target/lintcheck/downloads";
39 const LINTCHECK_SOURCES
: &str = "target/lintcheck/sources";
41 /// List of sources to check, loaded from a .toml file
42 #[derive(Debug, Serialize, Deserialize)]
44 crates
: HashMap
<String
, TomlCrate
>,
47 /// A crate source stored inside the .toml
48 /// will be translated into on one of the `CrateSource` variants
49 #[derive(Debug, Serialize, Deserialize)]
52 versions
: Option
<Vec
<String
>>,
53 git_url
: Option
<String
>,
54 git_hash
: Option
<String
>,
56 options
: Option
<Vec
<String
>>,
59 /// Represents an archive we download from crates.io, or a git repo, or a local repo/folder
60 /// Once processed (downloaded/extracted/cloned/copied...), this will be translated into a `Crate`
61 #[derive(Debug, Serialize, Deserialize, Eq, Hash, PartialEq, Ord, PartialOrd)]
66 options
: Option
<Vec
<String
>>,
72 options
: Option
<Vec
<String
>>,
77 options
: Option
<Vec
<String
>>,
81 /// Represents the actual source code of a crate that we ran "cargo clippy" on
86 // path to the extracted sources that clippy can check
88 options
: Option
<Vec
<String
>>,
91 /// A single warning that clippy issued while checking a `Crate`
93 struct ClippyWarning
{
95 crate_version
: String
,
104 impl std
::fmt
::Display
for ClippyWarning
{
105 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
108 r
#"target/lintcheck/sources/{}-{}/{}:{}:{} {} "{}""#,
109 &self.crate_name
, &self.crate_version
, &self.file
, &self.line
, &self.column
, &self.linttype
, &self.message
114 fn get(path
: &str) -> Result
<ureq
::Response
, ureq
::Error
> {
115 const MAX_RETRIES
: u8 = 4;
118 match ureq
::get(path
).call() {
119 Ok(res
) => return Ok(res
),
120 Err(e
) if retries
>= MAX_RETRIES
=> return Err(e
),
121 Err(ureq
::Error
::Transport(e
)) => eprintln
!("Error: {}", e
),
122 Err(e
) => return Err(e
),
124 eprintln
!("retrying in {} seconds...", retries
);
125 thread
::sleep(Duration
::from_secs(retries
as u64));
131 /// Makes the sources available on the disk for clippy to check.
132 /// Clones a git repo and checks out the specified commit or downloads a crate from crates.io or
133 /// copies a local folder
134 fn download_and_extract(&self) -> Crate
{
136 CrateSource
::CratesIo { name, version, options }
=> {
137 let extract_dir
= PathBuf
::from(LINTCHECK_SOURCES
);
138 let krate_download_dir
= PathBuf
::from(LINTCHECK_DOWNLOADS
);
140 // url to download the crate from crates.io
141 let url
= format
!("https://crates.io/api/v1/crates/{}/{}/download", name
, version
);
142 println
!("Downloading and extracting {} {} from {}", name
, version
, url
);
143 create_dirs(&krate_download_dir
, &extract_dir
);
145 let krate_file_path
= krate_download_dir
.join(format
!("{}-{}.crate.tar.gz", name
, version
));
146 // don't download/extract if we already have done so
147 if !krate_file_path
.is_file() {
148 // create a file path to download and write the crate data into
149 let mut krate_dest
= std
::fs
::File
::create(&krate_file_path
).unwrap();
150 let mut krate_req
= get(&url
).unwrap().into_reader();
151 // copy the crate into the file
152 std
::io
::copy(&mut krate_req
, &mut krate_dest
).unwrap();
155 let ungz_tar
= flate2
::read
::GzDecoder
::new(std
::fs
::File
::open(&krate_file_path
).unwrap());
156 // extract the tar archive
157 let mut archive
= tar
::Archive
::new(ungz_tar
);
158 archive
.unpack(&extract_dir
).expect("Failed to extract!");
160 // crate is extracted, return a new Krate object which contains the path to the extracted
161 // sources that clippy can check
163 version
: version
.clone(),
165 path
: extract_dir
.join(format
!("{}-{}/", name
, version
)),
166 options
: options
.clone(),
176 let mut repo_path
= PathBuf
::from(LINTCHECK_SOURCES
);
177 // add a -git suffix in case we have the same crate from crates.io and a git repo
178 repo_path
.push(format
!("{}-git", name
));
181 // clone the repo if we have not done so
182 if !repo_path
.is_dir() {
183 println
!("Cloning {} and checking out {}", url
, commit
);
184 if !Command
::new("git")
189 .expect("Failed to clone git repo!")
192 eprintln
!("Failed to clone {} into {}", url
, repo_path
.display())
195 // check out the commit/branch/whatever
196 if !Command
::new("git")
199 .current_dir(&repo_path
)
201 .expect("Failed to check out commit")
204 eprintln
!("Failed to checkout {} of repo at {}", commit
, repo_path
.display())
208 version
: commit
.clone(),
211 options
: options
.clone(),
214 CrateSource
::Path { name, path, options }
=> {
215 // copy path into the dest_crate_root but skip directories that contain a CACHEDIR.TAG file.
216 // The target/ directory contains a CACHEDIR.TAG file so it is the most commonly skipped directory
217 // as a result of this filter.
218 let dest_crate_root
= PathBuf
::from(LINTCHECK_SOURCES
).join(name
);
219 if dest_crate_root
.exists() {
220 println
!("Deleting existing directory at {:?}", dest_crate_root
);
221 std
::fs
::remove_dir_all(&dest_crate_root
).unwrap();
224 println
!("Copying {:?} to {:?}", path
, dest_crate_root
);
226 fn is_cache_dir(entry
: &DirEntry
) -> bool
{
227 std
::fs
::read(entry
.path().join("CACHEDIR.TAG"))
228 .map(|x
| x
.starts_with(b
"Signature: 8a477f597d28d172789f06886806bc55"))
232 for entry
in WalkDir
::new(path
).into_iter().filter_entry(|e
| !is_cache_dir(e
)) {
233 let entry
= entry
.unwrap();
234 let entry_path
= entry
.path();
235 let relative_entry_path
= entry_path
.strip_prefix(path
).unwrap();
236 let dest_path
= dest_crate_root
.join(relative_entry_path
);
237 let metadata
= entry_path
.symlink_metadata().unwrap();
239 if metadata
.is_dir() {
240 std
::fs
::create_dir(dest_path
).unwrap();
241 } else if metadata
.is_file() {
242 std
::fs
::copy(entry_path
, dest_path
).unwrap();
247 version
: String
::from("local"),
249 path
: dest_crate_root
,
250 options
: options
.clone(),
258 /// Run `cargo clippy` on the `Crate` and collect and return all the lint warnings that clippy
262 cargo_clippy_path
: &Path
,
263 target_dir_index
: &AtomicUsize
,
265 total_crates_to_lint
: usize,
267 ) -> Vec
<ClippyWarning
> {
268 // advance the atomic index by one
269 let index
= target_dir_index
.fetch_add(1, Ordering
::SeqCst
);
270 // "loop" the index within 0..thread_limit
271 let thread_index
= index
% thread_limit
;
272 let perc
= (index
* 100) / total_crates_to_lint
;
274 if thread_limit
== 1 {
276 "{}/{} {}% Linting {} {}",
277 index
, total_crates_to_lint
, perc
, &self.name
, &self.version
281 "{}/{} {}% Linting {} {} in target dir {:?}",
282 index
, total_crates_to_lint
, perc
, &self.name
, &self.version
, thread_index
286 let cargo_clippy_path
= std
::fs
::canonicalize(cargo_clippy_path
).unwrap();
288 let shared_target_dir
= clippy_project_root().join("target/lintcheck/shared_target_dir");
290 let mut args
= if fix
{
291 vec
!["--fix", "--allow-no-vcs", "--", "--cap-lints=warn"]
293 vec
!["--", "--message-format=json", "--", "--cap-lints=warn"]
296 if let Some(options
) = &self.options
{
301 args
.extend(&["-Wclippy::pedantic", "-Wclippy::cargo"])
304 let all_output
= std
::process
::Command
::new(&cargo_clippy_path
)
305 // use the looping index to create individual target dirs
308 shared_target_dir
.join(format
!("_{:?}", thread_index
)),
310 // lint warnings will look like this:
311 // src/cargo/ops/cargo_compile.rs:127:35: warning: usage of `FromIterator::from_iter`
313 .current_dir(&self.path
)
315 .unwrap_or_else(|error
| {
317 "Encountered error:\n{:?}\ncargo_clippy_path: {}\ncrate path:{}\n",
319 &cargo_clippy_path
.display(),
323 let stdout
= String
::from_utf8_lossy(&all_output
.stdout
);
324 let stderr
= String
::from_utf8_lossy(&all_output
.stderr
);
325 let status
= &all_output
.status
;
327 if !status
.success() {
329 "\nWARNING: bad exit status after checking {} {} \n",
330 self.name
, self.version
335 if let Some(stderr
) = stderr
337 .find(|line
| line
.contains("failed to automatically apply fixes suggested by rustc to crate"))
339 let subcrate
= &stderr
[63..];
341 "ERROR: failed to apply some suggetion to {} / to (sub)crate {}",
345 // fast path, we don't need the warnings anyway
349 let output_lines
= stdout
.lines();
350 let warnings
: Vec
<ClippyWarning
> = output_lines
352 // get all clippy warnings and ICEs
353 .filter(|line
| filter_clippy_warnings(&line
))
354 .map(|json_msg
| parse_json_message(json_msg
, &self))
362 struct LintcheckConfig
{
363 // max number of jobs to spawn (default 1)
365 // we read the sources to check from here
366 sources_toml_path
: PathBuf
,
367 // we save the clippy lint results here
368 lintcheck_results_path
: PathBuf
,
369 // whether to just run --fix and not collect all the warnings
373 impl LintcheckConfig
{
374 fn from_clap(clap_config
: &ArgMatches
) -> Self {
375 // first, check if we got anything passed via the LINTCHECK_TOML env var,
376 // if not, ask clap if we got any value for --crates-toml <foo>
377 // if not, use the default "lintcheck/lintcheck_crates.toml"
378 let sources_toml
= env
::var("LINTCHECK_TOML").unwrap_or_else(|_
| {
380 .value_of("crates-toml")
382 .unwrap_or("lintcheck/lintcheck_crates.toml")
386 let sources_toml_path
= PathBuf
::from(sources_toml
);
388 // for the path where we save the lint results, get the filename without extension (so for
389 // wasd.toml, use "wasd"...)
390 let filename
: PathBuf
= sources_toml_path
.file_stem().unwrap().into();
391 let lintcheck_results_path
= PathBuf
::from(format
!("lintcheck-logs/{}_logs.txt", filename
.display()));
393 // look at the --threads arg, if 0 is passed, ask rayon rayon how many threads it would spawn and
394 // use half of that for the physical core count
395 // by default use a single thread
396 let max_jobs
= match clap_config
.value_of("threads") {
398 let threads
: usize = threads
400 .unwrap_or_else(|_
| panic
!("Failed to parse '{}' to a digit", threads
));
403 // Rayon seems to return thread count so half that for core count
404 (rayon
::current_num_threads() / 2) as usize
409 // no -j passed, use a single thread
412 let fix
: bool
= clap_config
.is_present("fix");
417 lintcheck_results_path
,
423 /// takes a single json-formatted clippy warnings and returns true (we are interested in that line)
424 /// or false (we aren't)
425 fn filter_clippy_warnings(line
: &str) -> bool
{
426 // we want to collect ICEs because clippy might have crashed.
427 // these are summarized later
428 if line
.contains("internal compiler error: ") {
431 // in general, we want all clippy warnings
432 // however due to some kind of bug, sometimes there are absolute paths
433 // to libcore files inside the message
434 // or we end up with cargo-metadata output (https://github.com/rust-lang/rust-clippy/issues/6508)
436 // filter out these message to avoid unnecessary noise in the logs
437 if line
.contains("clippy::")
438 && !(line
.contains("could not read cargo metadata")
439 || (line
.contains(".rustup") && line
.contains("toolchains")))
446 /// Builds clippy inside the repo to make sure we have a clippy executable we can use.
448 let status
= Command
::new("cargo")
451 .expect("Failed to build clippy!");
452 if !status
.success() {
453 eprintln
!("Error: Failed to compile Clippy!");
454 std
::process
::exit(1);
458 /// Read a `toml` file and return a list of `CrateSources` that we want to check with clippy
459 fn read_crates(toml_path
: &Path
) -> Vec
<CrateSource
> {
460 let toml_content
: String
=
461 std
::fs
::read_to_string(&toml_path
).unwrap_or_else(|_
| panic
!("Failed to read {}", toml_path
.display()));
462 let crate_list
: SourceList
=
463 toml
::from_str(&toml_content
).unwrap_or_else(|e
| panic
!("Failed to parse {}: \n{}", toml_path
.display(), e
));
464 // parse the hashmap of the toml file into a list of crates
465 let tomlcrates
: Vec
<TomlCrate
> = crate_list
468 .map(|(_cratename
, tomlcrate
)| tomlcrate
)
471 // flatten TomlCrates into CrateSources (one TomlCrates may represent several versions of a crate =>
472 // multiple Cratesources)
473 let mut crate_sources
= Vec
::new();
474 tomlcrates
.into_iter().for_each(|tk
| {
475 if let Some(ref path
) = tk
.path
{
476 crate_sources
.push(CrateSource
::Path
{
477 name
: tk
.name
.clone(),
478 path
: PathBuf
::from(path
),
479 options
: tk
.options
.clone(),
483 // if we have multiple versions, save each one
484 if let Some(ref versions
) = tk
.versions
{
485 versions
.iter().for_each(|ver
| {
486 crate_sources
.push(CrateSource
::CratesIo
{
487 name
: tk
.name
.clone(),
488 version
: ver
.to_string(),
489 options
: tk
.options
.clone(),
493 // otherwise, we should have a git source
494 if tk
.git_url
.is_some() && tk
.git_hash
.is_some() {
495 crate_sources
.push(CrateSource
::Git
{
496 name
: tk
.name
.clone(),
497 url
: tk
.git_url
.clone().unwrap(),
498 commit
: tk
.git_hash
.clone().unwrap(),
499 options
: tk
.options
.clone(),
502 // if we have a version as well as a git data OR only one git data, something is funky
503 if tk
.versions
.is_some() && (tk
.git_url
.is_some() || tk
.git_hash
.is_some())
504 || tk
.git_hash
.is_some() != tk
.git_url
.is_some()
506 eprintln
!("tomlkrate: {:?}", tk
);
507 if tk
.git_hash
.is_some() != tk
.git_url
.is_some() {
508 panic
!("Error: Encountered TomlCrate with only one of git_hash and git_url!");
510 if tk
.path
.is_some() && (tk
.git_hash
.is_some() || tk
.versions
.is_some()) {
511 panic
!("Error: TomlCrate can only have one of 'git_.*', 'version' or 'path' fields");
513 unreachable
!("Failed to translate TomlCrate into CrateSource!");
517 crate_sources
.sort();
522 /// Parse the json output of clippy and return a `ClippyWarning`
523 fn parse_json_message(json_message
: &str, krate
: &Crate
) -> ClippyWarning
{
524 let jmsg
: Value
= serde_json
::from_str(&json_message
).unwrap_or_else(|e
| panic
!("Failed to parse json:\n{:?}", e
));
526 let file
: String
= jmsg
["message"]["spans"][0]["file_name"]
531 let file = if file.contains(".cargo
") {
532 // if we deal with macros, a filename may show the origin of a macro which can be inside a dep from
534 // don't show the full path in that case.
536 // /home/matthias/.cargo/registry/src/github.com-1ecc6299db9ec823/syn-1.0.63/src/custom_keyword.rs
537 let path = PathBuf::from(file);
538 let mut piter = path.iter();
539 // consume all elements until we find ".cargo
", so that "/home
/matthias
" is skipped
540 let _: Option<&OsStr> = piter.find(|x| x == &std::ffi::OsString::from(".cargo
"));
541 // collect the remaining segments
542 let file = piter.collect::<PathBuf>();
543 format!("{}
", file.display())
549 crate_name: krate.name.to_string(),
550 crate_version: krate.version.to_string(),
552 line: jmsg["message
"]["spans
"][0]["line_start
"]
556 column
: jmsg
["message"]["spans"][0]["text"][0]["highlight_start"]
560 linttype: jmsg["message
"]["code
"]["code
"].to_string().trim_matches('"'
).into(),
561 message
: jmsg
["message"]["message"].to_string().trim_matches('
"').into(),
562 is_ice: json_message.contains("internal compiler error
: "),
566 /// Generate a short list of occuring lints-types and their count
567 fn gather_stats(clippy_warnings: &[ClippyWarning]) -> (String, HashMap<&String, usize>) {
568 // count lint type occurrences
569 let mut counter: HashMap<&String, usize> = HashMap::new();
572 .for_each(|wrn| *counter.entry(&wrn.linttype).or_insert(0) += 1);
574 // collect into a tupled list for sorting
575 let mut stats: Vec<(&&String, &usize)> = counter.iter().map(|(lint, count)| (lint, count)).collect();
576 // sort by "000{count} {clippy::lintname}
"
577 // to not have a lint with 200 and 2 warnings take the same spot
578 stats.sort_by_key(|(lint, count)| format!("{:0>4}
, {}
", count, lint));
580 let stats_string = stats
582 .map(|(lint, count)| format!("{} {}
\n", lint, count))
583 .collect::<String>();
585 (stats_string, counter)
588 /// check if the latest modification of the logfile is older than the modification date of the
589 /// clippy binary, if this is true, we should clean the lintchec shared target directory and recheck
590 fn lintcheck_needs_rerun(lintcheck_logs_path: &Path) -> bool {
591 if !lintcheck_logs_path.exists() {
595 let clippy_modified: std::time::SystemTime = {
596 let mut times = [CLIPPY_DRIVER_PATH, CARGO_CLIPPY_PATH].iter().map(|p| {
598 .expect("failed to get metadata of file
")
600 .expect("failed to get modification date
")
602 // the oldest modification of either of the binaries
603 std::cmp::max(times.next().unwrap(), times.next().unwrap())
606 let logs_modified: std::time::SystemTime = std::fs::metadata(lintcheck_logs_path)
607 .expect("failed to get metadata of file
")
609 .expect("failed to get modification date
");
611 // time is represented in seconds since X
612 // logs_modified 2 and clippy_modified 5 means clippy binary is older and we need to recheck
613 logs_modified < clippy_modified
616 fn is_in_clippy_root() -> bool {
617 if let Ok(pb) = std::env::current_dir() {
618 if let Some(file) = pb.file_name() {
619 return file == PathBuf::from("rust
-clippy
");
626 /// lintchecks `main()` function
630 /// This function panics if the clippy binaries don't exist
631 /// or if lintcheck is executed from the wrong directory (aka none-repo-root)
633 // assert that we launch lintcheck from the repo root (via cargo lintcheck)
634 if !is_in_clippy_root() {
635 eprintln!("lintcheck needs to be run from clippys repo root
!\nUse `cargo lintcheck` alternatively
.");
636 std::process::exit(3);
639 let clap_config = &get_clap_config();
641 let config = LintcheckConfig::from_clap(clap_config);
643 println!("Compiling clippy
...");
645 println!("Done compiling
");
647 // if the clippy bin is newer than our logs, throw away target dirs to force clippy to
649 if lintcheck_needs_rerun(&config.lintcheck_results_path) {
650 let shared_target_dir = "target
/lintcheck
/shared_target_dir
";
651 // if we get an Err here, the shared target dir probably does simply not exist
652 if let Ok(metadata) = std::fs::metadata(&shared_target_dir) {
653 if metadata.is_dir() {
654 println!("Clippy is newer than lint check logs
, clearing lintcheck shared target dir
...");
655 std::fs::remove_dir_all(&shared_target_dir)
656 .expect("failed to remove target
/lintcheck
/shared_target_dir
");
661 let cargo_clippy_path: PathBuf = PathBuf::from(CARGO_CLIPPY_PATH)
663 .expect("failed to canonicalize path to clippy binary
");
665 // assert that clippy is found
667 cargo_clippy_path.is_file(),
668 "target
/debug
/cargo
-clippy binary not found
! {}
",
669 cargo_clippy_path.display()
672 let clippy_ver = std::process::Command::new(CARGO_CLIPPY_PATH)
675 .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
676 .expect("could not get clippy version
!");
678 // download and extract the crates, then run clippy on them and collect clippys warnings
679 // flatten into one big list of warnings
681 let crates = read_crates(&config.sources_toml_path);
682 let old_stats = read_stats_from_file(&config.lintcheck_results_path);
684 let counter = AtomicUsize::new(1);
686 let clippy_warnings: Vec<ClippyWarning> = if let Some(only_one_crate) = clap_config.value_of("only
") {
687 // if we don't have the specified crate in the .toml, throw an error
688 if !crates.iter().any(|krate| {
689 let name = match krate {
690 CrateSource::CratesIo { name, .. } | CrateSource::Git { name, .. } | CrateSource::Path { name, .. } => {
694 name == only_one_crate
697 "ERROR
: could not find
crate '{}'
in lintcheck
/lintcheck_crates
.toml
",
700 std::process::exit(1);
703 // only check a single crate that was passed via cmdline
706 .map(|krate| krate.download_and_extract())
707 .filter(|krate| krate.name == only_one_crate)
708 .flat_map(|krate| krate.run_clippy_lints(&cargo_clippy_path, &AtomicUsize::new(0), 1, 1, config.fix))
711 if config.max_jobs > 1 {
712 // run parallel with rayon
714 // Ask rayon for thread count. Assume that half of that is the number of physical cores
715 // Use one target dir for each core so that we can run N clippys in parallel.
716 // We need to use different target dirs because cargo would lock them for a single build otherwise,
717 // killing the parallelism. However this also means that deps will only be reused half/a
718 // quarter of the time which might result in a longer wall clock runtime
720 // This helps when we check many small crates with dep-trees that don't have a lot of branches in
721 // order to achive some kind of parallelism
723 // by default, use a single thread
724 let num_cpus = config.max_jobs;
725 let num_crates = crates.len();
727 // check all crates (default)
730 .map(|krate| krate.download_and_extract())
732 krate.run_clippy_lints(&cargo_clippy_path, &counter, num_cpus, num_crates, config.fix)
737 let num_crates = crates.len();
740 .map(|krate| krate.download_and_extract())
741 .flat_map(|krate| krate.run_clippy_lints(&cargo_clippy_path, &counter, 1, num_crates, config.fix))
746 // if we are in --fix mode, don't change the log files, terminate here
751 // generate some stats
752 let (stats_formatted, new_stats) = gather_stats(&clippy_warnings);
754 // grab crashes/ICEs, save the crate name and the ice message
755 let ices: Vec<(&String, &String)> = clippy_warnings
757 .filter(|warning| warning.is_ice)
758 .map(|w| (&w.crate_name, &w.message))
761 let mut all_msgs: Vec<String> = clippy_warnings.iter().map(ToString::to_string).collect();
763 all_msgs.push("\n\n\n\nStats
:\n".into());
764 all_msgs.push(stats_formatted);
766 // save the text into lintcheck-logs/logs.txt
767 let mut text = clippy_ver; // clippy version number on top
768 text.push_str(&format!("\n{}
", all_msgs.join("")));
769 text.push_str("ICEs
:\n");
771 .for_each(|(cratename, msg)| text.push_str(&format!("{}
: '{}'
", cratename, msg)));
773 println!("Writing logs to {}
", config.lintcheck_results_path.display());
774 write(&config.lintcheck_results_path, text).unwrap();
776 print_stats(old_stats, new_stats);
779 /// read the previous stats from the lintcheck-log file
780 fn read_stats_from_file(file_path: &Path) -> HashMap<String, usize> {
781 let file_content: String = match std::fs::read_to_string(file_path).ok() {
782 Some(content) => content,
784 return HashMap::new();
788 let lines: Vec<String> = file_content.lines().map(ToString::to_string).collect();
790 // search for the beginning "Stats
:" and the end "ICEs
:" of the section we want
791 let start = lines.iter().position(|line| line == "Stats
:").unwrap();
792 let end = lines.iter().position(|line| line == "ICEs
:").unwrap();
794 let stats_lines = &lines[start + 1..end];
799 let mut spl = line.split(' ');
801 spl.next().unwrap().to_string(),
802 spl.next().unwrap().parse::<usize>().unwrap(),
805 .collect::<HashMap<String, usize>>()
808 /// print how lint counts changed between runs
809 fn print_stats(old_stats: HashMap<String, usize>, new_stats: HashMap<&String, usize>) {
810 let same_in_both_hashmaps = old_stats
812 .filter(|(old_key, old_val)| new_stats.get::<&String>(&old_key) == Some(old_val))
813 .map(|(k, v)| (k.to_string(), *v))
814 .collect::<Vec<(String, usize)>>();
816 let mut old_stats_deduped = old_stats;
817 let mut new_stats_deduped = new_stats;
819 // remove duplicates from both hashmaps
820 same_in_both_hashmaps.iter().for_each(|(k, v)| {
821 assert!(old_stats_deduped.remove(k) == Some(*v));
822 assert!(new_stats_deduped.remove(k) == Some(*v));
825 println!("\nStats
:");
827 // list all new counts (key is in new stats but not in old stats)
830 .filter(|(new_key, _)| old_stats_deduped.get::<str>(&new_key).is_none())
831 .for_each(|(new_key, new_value)| {
832 println!("{}
0 => {}
", new_key, new_value);
835 // list all changed counts (key is in both maps but value differs)
838 .filter(|(new_key, _new_val)| old_stats_deduped.get::<str>(&new_key).is_some())
839 .for_each(|(new_key, new_val)| {
840 let old_val = old_stats_deduped.get::<str>(&new_key).unwrap();
841 println!("{} {}
=> {}
", new_key, old_val, new_val);
844 // list all gone counts (key is in old status but not in new stats)
847 .filter(|(old_key, _)| new_stats_deduped.get::<&String>(&old_key).is_none())
848 .for_each(|(old_key, old_value)| {
849 println!("{} {}
=> 0", old_key, old_value);
853 /// Create necessary directories to run the lintcheck tool.
857 /// This function panics if creating one of the dirs fails.
858 fn create_dirs(krate_download_dir: &Path, extract_dir: &Path) {
859 std::fs::create_dir("target
/lintcheck
/").unwrap_or_else(|err| {
860 if err.kind() != ErrorKind::AlreadyExists {
861 panic!("cannot create lintcheck target dir
");
864 std::fs::create_dir(&krate_download_dir).unwrap_or_else(|err| {
865 if err.kind() != ErrorKind::AlreadyExists {
866 panic!("cannot create
crate download dir
");
869 std::fs::create_dir(&extract_dir).unwrap_or_else(|err| {
870 if err.kind() != ErrorKind::AlreadyExists {
871 panic!("cannot create
crate extraction dir
");
876 fn get_clap_config<'a>() -> ArgMatches<'a> {
877 App::new("lintcheck
")
878 .about("run clippy on a set of crates and check output
")
880 Arg::with_name("only
")
884 .help("only process a single
crate of the list
"),
887 Arg::with_name("crates
-toml
")
889 .value_name("CRATES
-SOURCES
-TOML
-PATH
")
891 .help("set the path
for a crates
.toml
where lintcheck should read the sources from
"),
894 Arg::with_name("threads
")
899 .help("number of threads to
use, 0 automatic choice
"),
902 Arg::with_name("fix
")
904 .help("runs cargo clippy
--fix and checks
if all suggestions apply
"),
909 /// Returns the path to the Clippy project directory
913 /// Panics if the current directory could not be retrieved, there was an error reading any of the
914 /// Cargo.toml files or ancestor directory is the clippy root directory
916 pub fn clippy_project_root() -> PathBuf {
917 let current_dir = std::env::current_dir().unwrap();
918 for path in current_dir.ancestors() {
919 let result = std::fs::read_to_string(path.join("Cargo
.toml
"));
920 if let Err(err) = &result {
921 if err.kind() == std::io::ErrorKind::NotFound {
926 let content = result.unwrap();
927 if content.contains("[package
]\nname
= \"clippy
\"") {
928 return path.to_path_buf();
931 panic!("error
: Can't determine root of project
. Please run inside a Clippy working dir
.");
935 fn lintcheck_test() {
941 "./lintcheck
/Cargo
.toml
",
944 "lintcheck
/test_sources
.toml
",
946 let status = std::process::Command::new("cargo
")
948 .current_dir("..") // repo root
952 assert!(status.unwrap().success());