]> git.lizzy.rs Git - rust.git/blob - src/tools/tidy/src/deps.rs
Use the new Entry::or_default method where possible.
[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 ];
54
55 /// Which crates to check against the whitelist?
56 static WHITELIST_CRATES: &'static [CrateVersion] = &[
57     CrateVersion("rustc", "0.0.0"),
58     CrateVersion("rustc_codegen_llvm", "0.0.0"),
59 ];
60
61 /// Whitelist of crates rustc is allowed to depend on. Avoid adding to the list if possible.
62 static WHITELIST: &'static [Crate] = &[
63     Crate("aho-corasick"),
64     Crate("arrayvec"),
65     Crate("atty"),
66     Crate("backtrace"),
67     Crate("backtrace-sys"),
68     Crate("bitflags"),
69     Crate("byteorder"),
70     Crate("cc"),
71     Crate("chalk-engine"),
72     Crate("chalk-macros"),
73     Crate("cfg-if"),
74     Crate("cmake"),
75     Crate("crossbeam-deque"),
76     Crate("crossbeam-epoch"),
77     Crate("crossbeam-utils"),
78     Crate("datafrog"),
79     Crate("either"),
80     Crate("ena"),
81     Crate("env_logger"),
82     Crate("filetime"),
83     Crate("flate2"),
84     Crate("fuchsia-zircon"),
85     Crate("fuchsia-zircon-sys"),
86     Crate("getopts"),
87     Crate("humantime"),
88     Crate("jobserver"),
89     Crate("kernel32-sys"),
90     Crate("lazy_static"),
91     Crate("libc"),
92     Crate("log"),
93     Crate("log_settings"),
94     Crate("memchr"),
95     Crate("memoffset"),
96     Crate("miniz-sys"),
97     Crate("nodrop"),
98     Crate("num_cpus"),
99     Crate("owning_ref"),
100     Crate("parking_lot"),
101     Crate("parking_lot_core"),
102     Crate("polonius-engine"),
103     Crate("pkg-config"),
104     Crate("quick-error"),
105     Crate("rand"),
106     Crate("redox_syscall"),
107     Crate("redox_termios"),
108     Crate("regex"),
109     Crate("regex-syntax"),
110     Crate("remove_dir_all"),
111     Crate("rustc-demangle"),
112     Crate("rustc-hash"),
113     Crate("rustc-rayon"),
114     Crate("rustc-rayon-core"),
115     Crate("scoped-tls"),
116     Crate("scopeguard"),
117     Crate("smallvec"),
118     Crate("stable_deref_trait"),
119     Crate("tempfile"),
120     Crate("termcolor"),
121     Crate("terminon"),
122     Crate("termion"),
123     Crate("thread_local"),
124     Crate("ucd-util"),
125     Crate("unicode-width"),
126     Crate("unreachable"),
127     Crate("utf8-ranges"),
128     Crate("void"),
129     Crate("winapi"),
130     Crate("winapi-build"),
131     Crate("winapi-i686-pc-windows-gnu"),
132     Crate("winapi-x86_64-pc-windows-gnu"),
133     Crate("wincolor"),
134 ];
135
136 // Some types for Serde to deserialize the output of `cargo metadata` to...
137
138 #[derive(Deserialize)]
139 struct Output {
140     resolve: Resolve,
141 }
142
143 #[derive(Deserialize)]
144 struct Resolve {
145     nodes: Vec<ResolveNode>,
146 }
147
148 #[derive(Deserialize)]
149 struct ResolveNode {
150     id: String,
151     dependencies: Vec<String>,
152 }
153
154 /// A unique identifier for a crate
155 #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Debug, Hash)]
156 struct Crate<'a>(&'a str); // (name,)
157
158 #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Debug, Hash)]
159 struct CrateVersion<'a>(&'a str, &'a str); // (name, version)
160
161 impl<'a> Crate<'a> {
162     pub fn id_str(&self) -> String {
163         format!("{} ", self.0)
164     }
165 }
166
167 impl<'a> CrateVersion<'a> {
168     /// Returns the struct and whether or not the dep is in-tree
169     pub fn from_str(s: &'a str) -> (Self, bool) {
170         let mut parts = s.split(' ');
171         let name = parts.next().unwrap();
172         let version = parts.next().unwrap();
173         let path = parts.next().unwrap();
174
175         let is_path_dep = path.starts_with("(path+");
176
177         (CrateVersion(name, version), is_path_dep)
178     }
179
180     pub fn id_str(&self) -> String {
181         format!("{} {}", self.0, self.1)
182     }
183 }
184
185 impl<'a> From<CrateVersion<'a>> for Crate<'a> {
186     fn from(cv: CrateVersion<'a>) -> Crate<'a> {
187         Crate(cv.0)
188     }
189 }
190
191 /// Checks the dependency at the given path. Changes `bad` to `true` if a check failed.
192 ///
193 /// Specifically, this checks that the license is correct.
194 pub fn check(path: &Path, bad: &mut bool) {
195     // Check licences
196     let path = path.join("vendor");
197     assert!(path.exists(), "vendor directory missing");
198     let mut saw_dir = false;
199     for dir in t!(path.read_dir()) {
200         saw_dir = true;
201         let dir = t!(dir);
202
203         // skip our exceptions
204         if EXCEPTIONS.iter().any(|exception| {
205             dir.path()
206                 .to_str()
207                 .unwrap()
208                 .contains(&format!("src/vendor/{}", exception))
209         }) {
210             continue;
211         }
212
213         let toml = dir.path().join("Cargo.toml");
214         *bad = *bad || !check_license(&toml);
215     }
216     assert!(saw_dir, "no vendored source");
217 }
218
219 /// Checks the dependency of WHITELIST_CRATES at the given path. Changes `bad` to `true` if a check
220 /// failed.
221 ///
222 /// Specifically, this checks that the dependencies are on the WHITELIST.
223 pub fn check_whitelist(path: &Path, cargo: &Path, bad: &mut bool) {
224     // Get dependencies from cargo metadata
225     let resolve = get_deps(path, cargo);
226
227     // Get the whitelist into a convenient form
228     let whitelist: HashSet<_> = WHITELIST.iter().cloned().collect();
229
230     // Check dependencies
231     let mut visited = BTreeSet::new();
232     let mut unapproved = BTreeSet::new();
233     for &krate in WHITELIST_CRATES.iter() {
234         let mut bad = check_crate_whitelist(&whitelist, &resolve, &mut visited, krate, false);
235         unapproved.append(&mut bad);
236     }
237
238     if unapproved.len() > 0 {
239         println!("Dependencies not on the whitelist:");
240         for dep in unapproved {
241             println!("* {}", dep.id_str());
242         }
243         *bad = true;
244     }
245
246     check_crate_duplicate(&resolve, bad);
247 }
248
249 fn check_license(path: &Path) -> bool {
250     if !path.exists() {
251         panic!("{} does not exist", path.display());
252     }
253     let mut contents = String::new();
254     t!(t!(File::open(path)).read_to_string(&mut contents));
255
256     let mut found_license = false;
257     for line in contents.lines() {
258         if !line.starts_with("license") {
259             continue;
260         }
261         let license = extract_license(line);
262         if !LICENSES.contains(&&*license) {
263             println!("invalid license {} in {}", license, path.display());
264             return false;
265         }
266         found_license = true;
267         break;
268     }
269     if !found_license {
270         println!("no license in {}", path.display());
271         return false;
272     }
273
274     true
275 }
276
277 fn extract_license(line: &str) -> String {
278     let first_quote = line.find('"');
279     let last_quote = line.rfind('"');
280     if let (Some(f), Some(l)) = (first_quote, last_quote) {
281         let license = &line[f + 1..l];
282         license.into()
283     } else {
284         "bad-license-parse".into()
285     }
286 }
287
288 /// Get the dependencies of the crate at the given path using `cargo metadata`.
289 fn get_deps(path: &Path, cargo: &Path) -> Resolve {
290     // Run `cargo metadata` to get the set of dependencies
291     let output = Command::new(cargo)
292         .arg("metadata")
293         .arg("--format-version")
294         .arg("1")
295         .arg("--manifest-path")
296         .arg(path.join("Cargo.toml"))
297         .output()
298         .expect("Unable to run `cargo metadata`")
299         .stdout;
300     let output = String::from_utf8_lossy(&output);
301     let output: Output = serde_json::from_str(&output).unwrap();
302
303     output.resolve
304 }
305
306 /// Checks the dependencies of the given crate from the given cargo metadata to see if they are on
307 /// the whitelist. Returns a list of illegal dependencies.
308 fn check_crate_whitelist<'a, 'b>(
309     whitelist: &'a HashSet<Crate>,
310     resolve: &'a Resolve,
311     visited: &'b mut BTreeSet<CrateVersion<'a>>,
312     krate: CrateVersion<'a>,
313     must_be_on_whitelist: bool,
314 ) -> BTreeSet<Crate<'a>> {
315     // Will contain bad deps
316     let mut unapproved = BTreeSet::new();
317
318     // Check if we have already visited this crate
319     if visited.contains(&krate) {
320         return unapproved;
321     }
322
323     visited.insert(krate);
324
325     // If this path is in-tree, we don't require it to be on the whitelist
326     if must_be_on_whitelist {
327         // If this dependency is not on the WHITELIST, add to bad set
328         if !whitelist.contains(&krate.into()) {
329             unapproved.insert(krate.into());
330         }
331     }
332
333     // Do a DFS in the crate graph (it's a DAG, so we know we have no cycles!)
334     let to_check = resolve
335         .nodes
336         .iter()
337         .find(|n| n.id.starts_with(&krate.id_str()))
338         .expect("crate does not exist");
339
340     for dep in to_check.dependencies.iter() {
341         let (krate, is_path_dep) = CrateVersion::from_str(dep);
342
343         let mut bad = check_crate_whitelist(whitelist, resolve, visited, krate, !is_path_dep);
344         unapproved.append(&mut bad);
345     }
346
347     unapproved
348 }
349
350 fn check_crate_duplicate(resolve: &Resolve, bad: &mut bool) {
351     const FORBIDDEN_TO_HAVE_DUPLICATES: &[&str] = &[
352         // These two crates take quite a long time to build, let's not let two
353         // versions of them accidentally sneak into our dependency graph to
354         // ensure we keep our CI times under control
355         // "cargo", // FIXME(#53005)
356         "rustc-ap-syntax",
357     ];
358     let mut name_to_id: HashMap<_, Vec<_>> = HashMap::new();
359     for node in resolve.nodes.iter() {
360         name_to_id.entry(node.id.split_whitespace().next().unwrap())
361             .or_default()
362             .push(&node.id);
363     }
364
365     for name in FORBIDDEN_TO_HAVE_DUPLICATES {
366         if name_to_id[name].len() <= 1 {
367             continue
368         }
369         println!("crate `{}` is duplicated in `Cargo.lock`", name);
370         for id in name_to_id[name].iter() {
371             println!("  * {}", id);
372         }
373         *bad = true;
374     }
375 }