]> git.lizzy.rs Git - rust.git/blob - src/tools/tidy/src/deps.rs
Rollup merge of #59432 - phansch:compiletest_docs, r=alexcrichton
[rust.git] / src / tools / tidy / src / deps.rs
1 //! Checks the licenses of third-party dependencies by inspecting vendors.
2
3 use std::collections::{BTreeSet, HashSet, HashMap};
4 use std::fs;
5 use std::path::Path;
6 use std::process::Command;
7
8 use serde_json;
9
10 const LICENSES: &[&str] = &[
11     "MIT/Apache-2.0",
12     "MIT / Apache-2.0",
13     "Apache-2.0/MIT",
14     "Apache-2.0 / MIT",
15     "MIT OR Apache-2.0",
16     "MIT",
17     "Unlicense/MIT",
18     "Unlicense OR MIT",
19 ];
20
21 /// These are exceptions to Rust's permissive licensing policy, and
22 /// should be considered bugs. Exceptions are only allowed in Rust
23 /// tooling. It is _crucial_ that no exception crates be dependencies
24 /// of the Rust runtime (std/test).
25 const EXCEPTIONS: &[&str] = &[
26     "mdbook",             // MPL2, mdbook
27     "openssl",            // BSD+advertising clause, cargo, mdbook
28     "pest",               // MPL2, mdbook via handlebars
29     "arrayref",           // BSD-2-Clause, mdbook via handlebars via pest
30     "thread-id",          // Apache-2.0, mdbook
31     "toml-query",         // MPL-2.0, mdbook
32     "is-match",           // MPL-2.0, mdbook
33     "cssparser",          // MPL-2.0, rustdoc
34     "smallvec",           // MPL-2.0, rustdoc
35     "fuchsia-zircon-sys", // BSD-3-Clause, rustdoc, rustc, cargo
36     "fuchsia-zircon",     // BSD-3-Clause, rustdoc, rustc, cargo (jobserver & tempdir)
37     "cssparser-macros",   // MPL-2.0, rustdoc
38     "selectors",          // MPL-2.0, rustdoc
39     "clippy_lints",       // MPL-2.0, rls
40     "colored",            // MPL-2.0, rustfmt
41     "ordslice",           // Apache-2.0, rls
42     "cloudabi",           // BSD-2-Clause, (rls -> crossbeam-channel 0.2 -> rand 0.5)
43     "ryu",                // Apache-2.0, rls/cargo/... (because of serde)
44     "bytesize",           // Apache-2.0, cargo
45     "im-rc",              // MPL-2.0+, cargo
46     "adler32",            // BSD-3-Clause AND Zlib, cargo dep that isn't used
47     "fortanix-sgx-abi",   // MPL-2.0+, libstd but only for `sgx` target
48     "constant_time_eq",   // CC0-1.0, rustfmt
49 ];
50
51 /// Which crates to check against the whitelist?
52 const WHITELIST_CRATES: &[CrateVersion<'_>] = &[
53     CrateVersion("rustc", "0.0.0"),
54     CrateVersion("rustc_codegen_llvm", "0.0.0"),
55 ];
56
57 /// Whitelist of crates rustc is allowed to depend on. Avoid adding to the list if possible.
58 const WHITELIST: &[Crate<'_>] = &[
59     Crate("adler32"),
60     Crate("aho-corasick"),
61     Crate("arrayvec"),
62     Crate("atty"),
63     Crate("backtrace"),
64     Crate("backtrace-sys"),
65     Crate("bitflags"),
66     Crate("build_const"),
67     Crate("byteorder"),
68     Crate("cc"),
69     Crate("cfg-if"),
70     Crate("chalk-engine"),
71     Crate("chalk-macros"),
72     Crate("cloudabi"),
73     Crate("cmake"),
74     Crate("compiler_builtins"),
75     Crate("crc"),
76     Crate("crc32fast"),
77     Crate("crossbeam-deque"),
78     Crate("crossbeam-epoch"),
79     Crate("crossbeam-utils"),
80     Crate("datafrog"),
81     Crate("either"),
82     Crate("ena"),
83     Crate("env_logger"),
84     Crate("filetime"),
85     Crate("flate2"),
86     Crate("fuchsia-zircon"),
87     Crate("fuchsia-zircon-sys"),
88     Crate("getopts"),
89     Crate("humantime"),
90     Crate("itertools"),
91     Crate("jobserver"),
92     Crate("kernel32-sys"),
93     Crate("lazy_static"),
94     Crate("libc"),
95     Crate("libz-sys"),
96     Crate("lock_api"),
97     Crate("log"),
98     Crate("log_settings"),
99     Crate("memchr"),
100     Crate("memmap"),
101     Crate("memoffset"),
102     Crate("miniz-sys"),
103     Crate("miniz_oxide"),
104     Crate("miniz_oxide_c_api"),
105     Crate("nodrop"),
106     Crate("num_cpus"),
107     Crate("owning_ref"),
108     Crate("parking_lot"),
109     Crate("parking_lot_core"),
110     Crate("pkg-config"),
111     Crate("polonius-engine"),
112     Crate("proc-macro2"),
113     Crate("quick-error"),
114     Crate("quote"),
115     Crate("rand"),
116     Crate("rand_chacha"),
117     Crate("rand_core"),
118     Crate("rand_hc"),
119     Crate("rand_isaac"),
120     Crate("rand_pcg"),
121     Crate("rand_xorshift"),
122     Crate("redox_syscall"),
123     Crate("redox_termios"),
124     Crate("regex"),
125     Crate("regex-syntax"),
126     Crate("remove_dir_all"),
127     Crate("rustc-demangle"),
128     Crate("rustc-hash"),
129     Crate("rustc-rayon"),
130     Crate("rustc-rayon-core"),
131     Crate("rustc_version"),
132     Crate("scoped-tls"),
133     Crate("scopeguard"),
134     Crate("semver"),
135     Crate("semver-parser"),
136     Crate("serde"),
137     Crate("serde_derive"),
138     Crate("smallvec"),
139     Crate("stable_deref_trait"),
140     Crate("syn"),
141     Crate("synstructure"),
142     Crate("tempfile"),
143     Crate("termcolor"),
144     Crate("terminon"),
145     Crate("termion"),
146     Crate("thread_local"),
147     Crate("ucd-util"),
148     Crate("unicode-width"),
149     Crate("unicode-xid"),
150     Crate("unreachable"),
151     Crate("utf8-ranges"),
152     Crate("vcpkg"),
153     Crate("version_check"),
154     Crate("void"),
155     Crate("winapi"),
156     Crate("winapi-build"),
157     Crate("winapi-i686-pc-windows-gnu"),
158     Crate("winapi-util"),
159     Crate("winapi-x86_64-pc-windows-gnu"),
160     Crate("wincolor"),
161 ];
162
163 // Some types for Serde to deserialize the output of `cargo metadata` to.
164
165 #[derive(Deserialize)]
166 struct Output {
167     resolve: Resolve,
168 }
169
170 #[derive(Deserialize)]
171 struct Resolve {
172     nodes: Vec<ResolveNode>,
173 }
174
175 #[derive(Deserialize)]
176 struct ResolveNode {
177     id: String,
178     dependencies: Vec<String>,
179 }
180
181 /// A unique identifier for a crate.
182 #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Debug, Hash)]
183 struct Crate<'a>(&'a str); // (name)
184
185 #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Debug, Hash)]
186 struct CrateVersion<'a>(&'a str, &'a str); // (name, version)
187
188 impl Crate<'_> {
189     pub fn id_str(&self) -> String {
190         format!("{} ", self.0)
191     }
192 }
193
194 impl<'a> CrateVersion<'a> {
195     /// Returns the struct and whether or not the dependency is in-tree.
196     pub fn from_str(s: &'a str) -> (Self, bool) {
197         let mut parts = s.split(' ');
198         let name = parts.next().unwrap();
199         let version = parts.next().unwrap();
200         let path = parts.next().unwrap();
201
202         let is_path_dep = path.starts_with("(path+");
203
204         (CrateVersion(name, version), is_path_dep)
205     }
206
207     pub fn id_str(&self) -> String {
208         format!("{} {}", self.0, self.1)
209     }
210 }
211
212 impl<'a> From<CrateVersion<'a>> for Crate<'a> {
213     fn from(cv: CrateVersion<'a>) -> Crate<'a> {
214         Crate(cv.0)
215     }
216 }
217
218 /// Checks the dependency at the given path. Changes `bad` to `true` if a check failed.
219 ///
220 /// Specifically, this checks that the license is correct.
221 pub fn check(path: &Path, bad: &mut bool) {
222     // Check licences.
223     let path = path.join("../vendor");
224     assert!(path.exists(), "vendor directory missing");
225     let mut saw_dir = false;
226     for dir in t!(path.read_dir()) {
227         saw_dir = true;
228         let dir = t!(dir);
229
230         // Skip our exceptions.
231         let is_exception = EXCEPTIONS.iter().any(|exception| {
232             dir.path()
233                 .to_str()
234                 .unwrap()
235                 .contains(&format!("vendor/{}", exception))
236         });
237         if is_exception {
238             continue;
239         }
240
241         let toml = dir.path().join("Cargo.toml");
242         *bad = *bad || !check_license(&toml);
243     }
244     assert!(saw_dir, "no vendored source");
245 }
246
247 /// Checks the dependency of `WHITELIST_CRATES` at the given path. Changes `bad` to `true` if a
248 /// check failed.
249 ///
250 /// Specifically, this checks that the dependencies are on the `WHITELIST`.
251 pub fn check_whitelist(path: &Path, cargo: &Path, bad: &mut bool) {
252     // Get dependencies from Cargo metadata.
253     let resolve = get_deps(path, cargo);
254
255     // Get the whitelist in a convenient form.
256     let whitelist: HashSet<_> = WHITELIST.iter().cloned().collect();
257
258     // Check dependencies.
259     let mut visited = BTreeSet::new();
260     let mut unapproved = BTreeSet::new();
261     for &krate in WHITELIST_CRATES.iter() {
262         let mut bad = check_crate_whitelist(&whitelist, &resolve, &mut visited, krate, false);
263         unapproved.append(&mut bad);
264     }
265
266     if !unapproved.is_empty() {
267         println!("Dependencies not on the whitelist:");
268         for dep in unapproved {
269             println!("* {}", dep.id_str());
270         }
271         *bad = true;
272     }
273
274     check_crate_duplicate(&resolve, bad);
275 }
276
277 fn check_license(path: &Path) -> bool {
278     if !path.exists() {
279         panic!("{} does not exist", path.display());
280     }
281     let contents = t!(fs::read_to_string(&path));
282
283     let mut found_license = false;
284     for line in contents.lines() {
285         if !line.starts_with("license") {
286             continue;
287         }
288         let license = extract_license(line);
289         if !LICENSES.contains(&&*license) {
290             println!("invalid license {} in {}", license, path.display());
291             return false;
292         }
293         found_license = true;
294         break;
295     }
296     if !found_license {
297         println!("no license in {}", path.display());
298         return false;
299     }
300
301     true
302 }
303
304 fn extract_license(line: &str) -> String {
305     let first_quote = line.find('"');
306     let last_quote = line.rfind('"');
307     if let (Some(f), Some(l)) = (first_quote, last_quote) {
308         let license = &line[f + 1..l];
309         license.into()
310     } else {
311         "bad-license-parse".into()
312     }
313 }
314
315 /// Gets the dependencies of the crate at the given path using `cargo metadata`.
316 fn get_deps(path: &Path, cargo: &Path) -> Resolve {
317     // Run `cargo metadata` to get the set of dependencies.
318     let output = Command::new(cargo)
319         .arg("metadata")
320         .arg("--format-version")
321         .arg("1")
322         .arg("--manifest-path")
323         .arg(path.join("../Cargo.toml"))
324         .output()
325         .expect("Unable to run `cargo metadata`")
326         .stdout;
327     let output = String::from_utf8_lossy(&output);
328     let output: Output = serde_json::from_str(&output).unwrap();
329
330     output.resolve
331 }
332
333 /// Checks the dependencies of the given crate from the given cargo metadata to see if they are on
334 /// the whitelist. Returns a list of illegal dependencies.
335 fn check_crate_whitelist<'a>(
336     whitelist: &'a HashSet<Crate<'_>>,
337     resolve: &'a Resolve,
338     visited: &mut BTreeSet<CrateVersion<'a>>,
339     krate: CrateVersion<'a>,
340     must_be_on_whitelist: bool,
341 ) -> BTreeSet<Crate<'a>> {
342     // This will contain bad deps.
343     let mut unapproved = BTreeSet::new();
344
345     // Check if we have already visited this crate.
346     if visited.contains(&krate) {
347         return unapproved;
348     }
349
350     visited.insert(krate);
351
352     // If this path is in-tree, we don't require it to be on the whitelist.
353     if must_be_on_whitelist {
354         // If this dependency is not on `WHITELIST`, add to bad set.
355         if !whitelist.contains(&krate.into()) {
356             unapproved.insert(krate.into());
357         }
358     }
359
360     // Do a DFS in the crate graph (it's a DAG, so we know we have no cycles!).
361     let to_check = resolve
362         .nodes
363         .iter()
364         .find(|n| n.id.starts_with(&krate.id_str()))
365         .expect("crate does not exist");
366
367     for dep in to_check.dependencies.iter() {
368         let (krate, is_path_dep) = CrateVersion::from_str(dep);
369
370         let mut bad = check_crate_whitelist(whitelist, resolve, visited, krate, !is_path_dep);
371         unapproved.append(&mut bad);
372     }
373
374     unapproved
375 }
376
377 fn check_crate_duplicate(resolve: &Resolve, bad: &mut bool) {
378     const FORBIDDEN_TO_HAVE_DUPLICATES: &[&str] = &[
379         // These two crates take quite a long time to build, so don't allow two versions of them
380         // to accidentally sneak into our dependency graph, in order to ensure we keep our CI times
381         // under control.
382
383         "cargo",
384         "rustc-ap-syntax",
385     ];
386     let mut name_to_id: HashMap<_, Vec<_>> = HashMap::new();
387     for node in resolve.nodes.iter() {
388         name_to_id.entry(node.id.split_whitespace().next().unwrap())
389             .or_default()
390             .push(&node.id);
391     }
392
393     for name in FORBIDDEN_TO_HAVE_DUPLICATES {
394         if name_to_id[name].len() <= 1 {
395             continue
396         }
397         println!("crate `{}` is duplicated in `Cargo.lock`", name);
398         for id in name_to_id[name].iter() {
399             println!("  * {}", id);
400         }
401         *bad = true;
402     }
403 }