]> git.lizzy.rs Git - rust.git/blob - clippy_dev/src/crater.rs
cargo dev crater: cleanup, don't re-download and reextract crates on every run
[rust.git] / clippy_dev / src / crater.rs
1 use std::path::PathBuf;
2 use std::process::Command;
3
4 // represents an archive we download from crates.io
5 #[derive(Debug)]
6 struct KrateSource {
7     version: String,
8     name: String,
9 }
10
11 // represents the extracted sourcecode of a crate
12 #[derive(Debug)]
13 struct Krate {
14     version: String,
15     name: String,
16     // path to the extracted sources that clippy can check
17     path: PathBuf,
18 }
19
20 impl KrateSource {
21     fn new(name: &str, version: &str) -> Self {
22         KrateSource {
23             version: version.into(),
24             name: name.into(),
25         }
26     }
27
28     fn download_and_extract(&self) -> Krate {
29         let extract_dir = PathBuf::from("target/crater/crates");
30         let krate_download_dir = PathBuf::from("target/crater/downloads");
31
32         // url to download the crate from crates.io
33         let url = format!(
34             "https://crates.io/api/v1/crates/{}/{}/download",
35             self.name, self.version
36         );
37         println!("Downloading and extracting {} {} from {}", self.name, self.version, url);
38         let _ = std::fs::create_dir("target/crater/");
39         let _ = std::fs::create_dir(&krate_download_dir);
40         let _ = std::fs::create_dir(&extract_dir);
41
42         let krate_file_path = krate_download_dir.join(format!("{}-{}.crate.tar.gz", &self.name, &self.version));
43         // don't download/extract if we already have done so
44         if !krate_file_path.is_file() {
45             // create a file path to download and write the crate data into
46             let mut krate_dest = std::fs::File::create(&krate_file_path).unwrap();
47             let mut krate_req = ureq::get(&url).call().unwrap().into_reader();
48             // copy the crate into the file
49             std::io::copy(&mut krate_req, &mut krate_dest).unwrap();
50
51             // unzip the tarball
52             let ungz_tar = flate2::read::GzDecoder::new(std::fs::File::open(&krate_file_path).unwrap());
53             // extract the tar archive
54             let mut archiv = tar::Archive::new(ungz_tar);
55             archiv.unpack(&extract_dir).expect("Failed to extract!");
56
57             // unzip the tarball
58             let ungz_tar = flate2::read::GzDecoder::new(std::fs::File::open(&krate_file_path).unwrap());
59             // extract the tar archive
60             let mut archiv = tar::Archive::new(ungz_tar);
61             archiv.unpack(&extract_dir).expect("Failed to extract!");
62         }
63         // crate is extracted, return a new Krate object which contains the path to the extracted
64         // sources that clippy can check
65         Krate {
66             version: self.version.clone(),
67             name: self.name.clone(),
68             path: extract_dir.join(format!("{}-{}/", self.name, self.version)),
69         }
70     }
71 }
72
73 impl Krate {
74     fn run_clippy_lints(&self, cargo_clippy_path: &PathBuf) -> Vec<String> {
75         println!("Linting {} {}...", &self.name, &self.version);
76         let cargo_clippy_path = std::fs::canonicalize(cargo_clippy_path).unwrap();
77
78         let all_output = std::process::Command::new(cargo_clippy_path)
79             // lint warnings will look like this:
80             // src/cargo/ops/cargo_compile.rs:127:35: warning: usage of `FromIterator::from_iter`
81             .args(&["--", "--message-format=short", "--", "--cap-lints=warn"])
82             .current_dir(&self.path)
83             .output()
84             .unwrap();
85         let stderr = String::from_utf8_lossy(&all_output.stderr);
86         let output_lines = stderr.lines();
87         let mut output: Vec<String> = output_lines
88             .into_iter()
89             .filter(|line| line.contains(": warning: "))
90             // prefix with the crate name and version
91             // cargo-0.49.0/src/cargo/ops/cargo_compile.rs:127:35: warning: usage of `FromIterator::from_iter`
92             .map(|line| format!("{}-{}/{}", self.name, self.version, line))
93             // remove the "warning: "
94             .map(|line| {
95                 let remove_pat = "warning: ";
96                 let pos = line
97                     .find(&remove_pat)
98                     .expect("clippy output did not contain \"warning: \"");
99                 let mut new = line[0..pos].to_string();
100                 new.push_str(&line[pos + remove_pat.len()..]);
101                 new
102             })
103             .collect();
104
105         // sort messages alphabtically to avoid noise in the logs
106         output.sort();
107         output
108     }
109 }
110
111 fn build_clippy() {
112     Command::new("cargo")
113         .arg("build")
114         .output()
115         .expect("Failed to build clippy!");
116 }
117
118 // the main fn
119 pub fn run() {
120     let cargo_clippy_path: PathBuf = PathBuf::from("target/debug/cargo-clippy");
121
122     // crates we want to check:
123     let krates: Vec<KrateSource> = vec![KrateSource::new("regex", "1.4.2"), KrateSource::new("cargo", "0.49.0")];
124
125     println!("Compiling clippy...");
126     build_clippy();
127     println!("Done compiling");
128
129     // assert that clippy is found
130     assert!(
131         cargo_clippy_path.is_file(),
132         "target/debug/cargo-clippy binary not found! {}",
133         cargo_clippy_path.display()
134     );
135
136     // download and extract the crates, then run clippy on them and collect clippys warnings
137     let clippy_lint_results: Vec<Vec<String>> = krates
138         .into_iter()
139         .map(|krate| krate.download_and_extract())
140         .map(|krate| krate.run_clippy_lints(&cargo_clippy_path))
141         .collect();
142
143     let all_warnings: Vec<String> = clippy_lint_results.into_iter().flatten().collect();
144
145     // TODO: save these into a file
146     all_warnings.iter().for_each(|l| println!("{}", l));
147 }