]> git.lizzy.rs Git - rust.git/blob - tests/cargo/mod.rs
Auto merge of #5139 - lzutao:linecount, r=llogiq
[rust.git] / tests / cargo / mod.rs
1 use cargo_metadata::{Message::CompilerArtifact, MetadataCommand};
2 use std::env;
3 use std::ffi::OsStr;
4 use std::mem;
5 use std::path::PathBuf;
6 use std::process::Command;
7
8 pub struct BuildInfo {
9     cargo_target_dir: PathBuf,
10 }
11
12 impl BuildInfo {
13     pub fn new() -> Self {
14         let data = MetadataCommand::new().exec().unwrap();
15         Self {
16             cargo_target_dir: data.target_directory,
17         }
18     }
19
20     pub fn host_lib(&self) -> PathBuf {
21         if let Some(path) = option_env!("HOST_LIBS") {
22             PathBuf::from(path)
23         } else {
24             self.cargo_target_dir.join(env!("PROFILE"))
25         }
26     }
27
28     pub fn target_lib(&self) -> PathBuf {
29         if let Some(path) = option_env!("TARGET_LIBS") {
30             path.into()
31         } else {
32             let mut dir = self.cargo_target_dir.clone();
33             if let Some(target) = env::var_os("CARGO_BUILD_TARGET") {
34                 dir.push(target);
35             }
36             dir.push(env!("PROFILE"));
37             dir
38         }
39     }
40
41     pub fn clippy_driver_path(&self) -> PathBuf {
42         if let Some(path) = option_env!("CLIPPY_DRIVER_PATH") {
43             PathBuf::from(path)
44         } else {
45             self.target_lib().join("clippy-driver")
46         }
47     }
48
49     // When we'll want to use `extern crate ..` for a dependency that is used
50     // both by the crate and the compiler itself, we can't simply pass -L flags
51     // as we'll get a duplicate matching versions. Instead, disambiguate with
52     // `--extern dep=path`.
53     // See https://github.com/rust-lang/rust-clippy/issues/4015.
54     pub fn third_party_crates() -> Vec<(&'static str, PathBuf)> {
55         const THIRD_PARTY_CRATES: [&str; 4] = ["serde", "serde_derive", "regex", "clippy_lints"];
56         let cargo = env::var_os("CARGO");
57         let cargo = cargo.as_deref().unwrap_or_else(|| OsStr::new("cargo"));
58         let output = Command::new(cargo)
59             .arg("build")
60             .arg("--test=compile-test")
61             .arg("--message-format=json")
62             .output()
63             .unwrap();
64
65         let mut crates = Vec::with_capacity(THIRD_PARTY_CRATES.len());
66         for message in cargo_metadata::parse_messages(output.stdout.as_slice()) {
67             if let CompilerArtifact(mut artifact) = message.unwrap() {
68                 if let Some(&krate) = THIRD_PARTY_CRATES.iter().find(|&&krate| krate == artifact.target.name) {
69                     crates.push((krate, mem::take(&mut artifact.filenames[0])));
70                 }
71             }
72         }
73         crates
74     }
75 }