3 use std::io::{self, Write};
4 use std::path::{Path, PathBuf};
5 use std::process::{self, Command, Stdio};
7 use super::path::{Dirs, RelPath};
8 use super::rustc_info::{get_cargo_path, get_rustc_path, get_rustdoc_path};
10 #[derive(Clone, Debug)]
11 pub(crate) struct Compiler {
12 pub(crate) cargo: PathBuf,
13 pub(crate) rustc: PathBuf,
14 pub(crate) rustdoc: PathBuf,
15 pub(crate) rustflags: String,
16 pub(crate) rustdocflags: String,
17 pub(crate) triple: String,
18 pub(crate) runner: Vec<String>,
22 pub(crate) fn bootstrap_with_triple(triple: String) -> Compiler {
24 cargo: get_cargo_path(),
25 rustc: get_rustc_path(),
26 rustdoc: get_rustdoc_path(),
27 rustflags: String::new(),
28 rustdocflags: String::new(),
34 pub(crate) fn set_cross_linker_and_runner(&mut self) {
35 match self.triple.as_str() {
36 "aarch64-unknown-linux-gnu" => {
37 // We are cross-compiling for aarch64. Use the correct linker and run tests in qemu.
38 self.rustflags += " -Clinker=aarch64-linux-gnu-gcc";
39 self.rustdocflags += " -Clinker=aarch64-linux-gnu-gcc";
41 "qemu-aarch64".to_owned(),
43 "/usr/aarch64-linux-gnu".to_owned(),
46 "s390x-unknown-linux-gnu" => {
47 // We are cross-compiling for s390x. Use the correct linker and run tests in qemu.
48 self.rustflags += " -Clinker=s390x-linux-gnu-gcc";
49 self.rustdocflags += " -Clinker=s390x-linux-gnu-gcc";
51 "qemu-s390x".to_owned(),
53 "/usr/s390x-linux-gnu".to_owned(),
56 "x86_64-pc-windows-gnu" => {
57 // We are cross-compiling for Windows. Run tests in wine.
58 self.runner = vec!["wine".to_owned()];
61 println!("Unknown non-native platform");
67 pub(crate) struct CargoProject {
68 source: &'static RelPath,
73 pub(crate) const fn new(path: &'static RelPath, target: &'static str) -> CargoProject {
74 CargoProject { source: path, target }
77 pub(crate) fn source_dir(&self, dirs: &Dirs) -> PathBuf {
78 self.source.to_path(dirs)
81 pub(crate) fn manifest_path(&self, dirs: &Dirs) -> PathBuf {
82 self.source_dir(dirs).join("Cargo.toml")
85 pub(crate) fn target_dir(&self, dirs: &Dirs) -> PathBuf {
86 RelPath::BUILD.join(self.target).to_path(dirs)
90 fn base_cmd(&self, command: &str, cargo: &Path, dirs: &Dirs) -> Command {
91 let mut cmd = Command::new(cargo);
94 .arg("--manifest-path")
95 .arg(self.manifest_path(dirs))
97 .arg(self.target_dir(dirs))
104 fn build_cmd(&self, command: &str, compiler: &Compiler, dirs: &Dirs) -> Command {
105 let mut cmd = self.base_cmd(command, &compiler.cargo, dirs);
107 cmd.arg("--target").arg(&compiler.triple);
109 cmd.env("RUSTC", &compiler.rustc);
110 cmd.env("RUSTDOC", &compiler.rustdoc);
111 cmd.env("RUSTFLAGS", &compiler.rustflags);
112 cmd.env("RUSTDOCFLAGS", &compiler.rustdocflags);
113 if !compiler.runner.is_empty() {
115 format!("CARGO_TARGET_{}_RUNNER", compiler.triple.to_uppercase().replace('-', "_")),
116 compiler.runner.join(" "),
126 cargo: impl AsRef<Path>,
127 rustc: impl AsRef<Path>,
130 let mut cmd = Command::new(cargo.as_ref());
132 cmd.env("RUSTC", rustc.as_ref())
134 .arg("--manifest-path")
135 .arg(self.manifest_path(dirs));
140 pub(crate) fn clean(&self, dirs: &Dirs) {
141 let _ = fs::remove_dir_all(self.target_dir(dirs));
145 pub(crate) fn build(&self, compiler: &Compiler, dirs: &Dirs) -> Command {
146 self.build_cmd("build", compiler, dirs)
150 pub(crate) fn test(&self, compiler: &Compiler, dirs: &Dirs) -> Command {
151 self.build_cmd("test", compiler, dirs)
155 pub(crate) fn run(&self, compiler: &Compiler, dirs: &Dirs) -> Command {
156 self.build_cmd("run", compiler, dirs)
161 pub(crate) fn hyperfine_command(
164 prepare: Option<&str>,
168 let mut bench = Command::new("hyperfine");
171 bench.arg("--warmup").arg(warmup.to_string());
175 bench.arg("--runs").arg(runs.to_string());
178 if let Some(prepare) = prepare {
179 bench.arg("--prepare").arg(prepare);
188 pub(crate) fn git_command<'a>(repo_dir: impl Into<Option<&'a Path>>, cmd: &str) -> Command {
189 let mut git_cmd = Command::new("git");
192 .arg("user.name=Dummy")
194 .arg("user.email=dummy@example.com")
196 .arg("core.autocrlf=false")
198 if let Some(repo_dir) = repo_dir.into() {
199 git_cmd.current_dir(repo_dir);
205 pub(crate) fn try_hard_link(src: impl AsRef<Path>, dst: impl AsRef<Path>) {
206 let src = src.as_ref();
207 let dst = dst.as_ref();
208 if let Err(_) = fs::hard_link(src, dst) {
209 fs::copy(src, dst).unwrap(); // Fallback to copying if hardlinking failed
214 pub(crate) fn spawn_and_wait(mut cmd: Command) {
215 if !cmd.spawn().unwrap().wait().unwrap().success() {
220 // Based on the retry function in rust's src/ci/shared.sh
222 pub(crate) fn retry_spawn_and_wait(tries: u64, mut cmd: Command) {
223 for i in 1..tries + 1 {
225 println!("Command failed. Attempt {i}/{tries}:");
227 if cmd.spawn().unwrap().wait().unwrap().success() {
230 std::thread::sleep(std::time::Duration::from_secs(i * 5));
232 println!("The command has failed after {tries} attempts.");
237 pub(crate) fn spawn_and_wait_with_input(mut cmd: Command, input: String) -> String {
239 .stdin(Stdio::piped())
240 .stdout(Stdio::piped())
242 .expect("Failed to spawn child process");
244 let mut stdin = child.stdin.take().expect("Failed to open stdin");
245 std::thread::spawn(move || {
246 stdin.write_all(input.as_bytes()).expect("Failed to write to stdin");
249 let output = child.wait_with_output().expect("Failed to read stdout");
250 if !output.status.success() {
254 String::from_utf8(output.stdout).unwrap()
257 pub(crate) fn remove_dir_if_exists(path: &Path) {
258 match fs::remove_dir_all(&path) {
260 Err(err) if err.kind() == io::ErrorKind::NotFound => {}
261 Err(err) => panic!("Failed to remove {path}: {err}", path = path.display()),
265 pub(crate) fn copy_dir_recursively(from: &Path, to: &Path) {
266 for entry in fs::read_dir(from).unwrap() {
267 let entry = entry.unwrap();
268 let filename = entry.file_name();
269 if filename == "." || filename == ".." {
272 if entry.metadata().unwrap().is_dir() {
273 fs::create_dir(to.join(&filename)).unwrap();
274 copy_dir_recursively(&from.join(&filename), &to.join(&filename));
276 fs::copy(from.join(&filename), to.join(&filename)).unwrap();
281 pub(crate) fn is_ci() -> bool {
282 env::var("CI").is_ok()
285 pub(crate) fn is_ci_opt() -> bool {
286 env::var("CI_OPT").is_ok()