Debian Codegraph @

test-crates/cargo-mock/src/main.rs

raw
1 //! Caches cargo invocations to make maturin's tests faster
2 //!
3 //! For each invocation, a directory inside `target/test-cache` is created with the
4 //! name `<PYTHON_SYS_EXECUTABLE> <cargo arg1> <cargo arg2> ... <cargo argx>` with some args
5 //! stripped for path length constrains. It contains a `cargo.stdout`, a `cargo.stderr` and all
6 //! non-rlib artifacts.
7
8 use anyhow::{bail, format_err, Context, Result};
9 use cargo_metadata::Message;
10 use std::env;
11 use std::fs;
12 use std::fs::File;
13 use std::io;
14 use std::io::{BufRead, BufReader, BufWriter, Write};
15 use std::path::Path;
16 use std::process::Command;
17
18 fn run() -> Result<()> {
19 let base_cache_path = Path::new("target").join("test-cache");
20
21 fs::create_dir_all(&base_cache_path).context("Couldn't create cache dir")?;
22 let env_args_os_str = env::var_os("PYTHON_SYS_EXECUTABLE").unwrap_or_default();
23 let env_args = env_args_os_str
24 .into_string()
25 .map_err(|e| format_err!("PYTHON_SYS_EXECUTABLE is not valid unicode: {:?}", e))?;
26 let cargo_args = env::args().skip(1).collect::<Vec<String>>().join(" ");
27 // Assumption: Slash is the only character in the cli args that we must not use for directory names
28 let cwd = env::current_dir().unwrap().to_string_lossy().to_string();
29 let env_key = env_args.replace(" ", "-").replace("/", "-");
30 let cargo_key = cargo_args
31 .replace("--message-format json", "")
32 .replace("--target-dir test-crates/targets/", "")
33 .replace("--quiet", "")
34 .replace(&cwd, "")
35 .replace(" ", "-")
36 .replace("/", "-")
37 .replace("-----C-link-arg=-s", "");
38
39 let cache_path = base_cache_path.join(&env_key).join(&cargo_key);
40 let stdout_path = cache_path.join("cargo.stdout");
41 let stderr_path = cache_path.join("cargo.stderr");
42
43 let is_cached = stderr_path.is_file();
44 if is_cached {
45 let context_message: &'static str = "Failed to read from capture file";
46
47 // Write the capture stdout and stderr back out
48 let mut stdout_file = File::open(&stdout_path).context(context_message)?;
49 let mut stdout = io::stdout();
50 io::copy(&mut stdout_file, &mut stdout).context(context_message)?;
51
52 let mut stderr_file = File::open(stderr_path).context(context_message)?;
53 let mut stderr = io::stderr();
54 io::copy(&mut stderr_file, &mut stderr).context(context_message)?;
55 } else {
56 fs::create_dir_all(&cache_path).context(format!(
57 "Failed to create cache path {}",
58 cache_path.display()
59 ))?;
60 // Unmock to run the real cargo
61 let old_path = env::var_os("PATH").expect("PATH must be set");
62 let mut path_split = env::split_paths(&old_path);
63 let first_path = path_split.next().expect("PATH must have a first entry");
64 if !first_path.join("cargo").is_file() && !first_path.join("cargo.exe").is_file() {
65 bail!("The first part of PATH hasn't overwritten cargo");
66 }
67 let remainder = env::join_paths(path_split).expect("Expected to be able to re-join PATH");
68
69 let output = Command::new("cargo")
70 .args(env::args().skip(1))
71 .env("PATH", remainder)
72 .output()
73 .context("Starting cargo failed")?;
74
75 if !output.status.success() {
76 std::process::exit(output.status.code().unwrap());
77 }
78
79 let mut stdout_writer =
80 BufWriter::new(File::create(&stdout_path).context("Failed to create stdout path")?);
81
82 for line in output.stdout.lines() {
83 let line = line.context("Failed to read line from stdout")?;
84 println!("{}", line);
85 stdout_writer
86 .write_all(line.as_bytes())
87 .context("Failed to write to stdout file")?;
88 stdout_writer
89 .write_all(b"\n")
90 .context("Failed to write to stdout file")?;
91 }
92
93 File::create(stderr_path)
94 .and_then(|mut file| file.write_all(&output.stderr))
95 .context("Failed to write to stderr file")?;
96 }
97
98 copy_artifacts(&cache_path, &stdout_path, is_cached).context("Copying the artifacts failed")?;
99
100 Ok(())
101 }
102
103 /// Copy over the compiler artifacts (binaries and .so)
104 /// If this is a new run, copy it to the cache, otherwise copy it back to its original location
105 fn copy_artifacts(cache_path: &Path, stdout_path: &Path, is_cached: bool) -> Result<()> {
106 // Re-reading the file makes the code a lot easier
107 let reader = BufReader::new(File::open(&stdout_path).context("Failed to create stdout path")?);
108 for message in Message::parse_stream(reader) {
109 match message.context("Failed to parse message coming from cargo")? {
110 cargo_metadata::Message::CompilerArtifact(artifact) => {
111 let artifacts = artifact
112 .target
113 .crate_types
114 .clone()
115 .into_iter()
116 .zip(artifact.filenames.clone());
117 for (artifact_type, original_path) in artifacts {
118 if artifact_type == "lib" {
119 continue;
120 }
121 let cached_path = cache_path.join(
122 original_path
123 .file_name()
124 .expect("Path from cargo should have a filename"),
125 );
126 if is_cached {
127 if !original_path.is_file() {
128 fs::copy(cached_path, original_path)
129 .context("Failed to copy the artifact from the cache")?;
130 }
131 } else {
132 fs::copy(original_path, cached_path)
133 .context("Failed to copy the artifact to the cache")?;
134 };
135 }
136 }
137 _ => {}
138 }
139 }
140 Ok(())
141 }
142
143 fn main() {
144 if let Err(e) = run() {
145 eprintln!("💥 Cargo mock failed");
146 for cause in e.chain() {
147 eprintln!(" Caused by: {}", cause);
148 }
149 std::process::exit(1);
150 }
151 }