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