]> git.lizzy.rs Git - rust.git/blob - clippy_dev/src/crater.rs
cargo dev crater: save all warnings into a file
[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.push('\n');
102                 new
103             })
104             .collect();
105
106         // sort messages alphabtically to avoid noise in the logs
107         output.sort();
108         output
109     }
110 }
111
112 fn build_clippy() {
113     Command::new("cargo")
114         .arg("build")
115         .output()
116         .expect("Failed to build clippy!");
117 }
118
119 // the main fn
120 pub fn run() {
121     let cargo_clippy_path: PathBuf = PathBuf::from("target/debug/cargo-clippy");
122
123     // crates we want to check:
124     let krates: Vec<KrateSource> = vec![KrateSource::new("regex", "1.4.2"), KrateSource::new("cargo", "0.49.0")];
125
126     println!("Compiling clippy...");
127     build_clippy();
128     println!("Done compiling");
129
130     // assert that clippy is found
131     assert!(
132         cargo_clippy_path.is_file(),
133         "target/debug/cargo-clippy binary not found! {}",
134         cargo_clippy_path.display()
135     );
136
137     // download and extract the crates, then run clippy on them and collect clippys warnings
138     let clippy_lint_results: Vec<Vec<String>> = krates
139         .into_iter()
140         .map(|krate| krate.download_and_extract())
141         .map(|krate| krate.run_clippy_lints(&cargo_clippy_path))
142         .collect();
143
144     let all_warnings: Vec<String> = clippy_lint_results.into_iter().flatten().collect();
145
146     // save the text into mini-crater/logs.txt
147     let text = all_warnings.join("");
148     std::fs::write("mini-crater/logs.txt", text).unwrap();
149 }