]> git.lizzy.rs Git - rust.git/blob - build_system/utils.rs
Pass around Compiler instead of target triples
[rust.git] / build_system / utils.rs
1 use std::env;
2 use std::fs;
3 use std::io::Write;
4 use std::path::{Path, PathBuf};
5 use std::process::{self, Command, Stdio};
6
7 use super::path::{Dirs, RelPath};
8 use super::rustc_info::{get_cargo_path, get_rustc_path, get_rustdoc_path, get_wrapper_file_name};
9
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>,
19 }
20
21 impl Compiler {
22     pub(crate) fn llvm_with_triple(triple: String) -> Compiler {
23         Compiler {
24             cargo: get_cargo_path(),
25             rustc: get_rustc_path(),
26             rustdoc: get_rustdoc_path(),
27             rustflags: String::new(),
28             rustdocflags: String::new(),
29             triple,
30             runner: vec![],
31         }
32     }
33
34     pub(crate) fn clif_with_triple(dirs: &Dirs, triple: String) -> Compiler {
35         let rustc_clif =
36             RelPath::DIST.to_path(&dirs).join(get_wrapper_file_name("rustc-clif", "bin"));
37         let rustdoc_clif =
38             RelPath::DIST.to_path(&dirs).join(get_wrapper_file_name("rustdoc-clif", "bin"));
39
40         Compiler {
41             cargo: get_cargo_path(),
42             rustc: rustc_clif.clone(),
43             rustdoc: rustdoc_clif.clone(),
44             rustflags: String::new(),
45             rustdocflags: String::new(),
46             triple,
47             runner: vec![],
48         }
49     }
50 }
51
52 pub(crate) struct CargoProject {
53     source: &'static RelPath,
54     target: &'static str,
55 }
56
57 impl CargoProject {
58     pub(crate) const fn new(path: &'static RelPath, target: &'static str) -> CargoProject {
59         CargoProject { source: path, target }
60     }
61
62     pub(crate) fn source_dir(&self, dirs: &Dirs) -> PathBuf {
63         self.source.to_path(dirs)
64     }
65
66     pub(crate) fn manifest_path(&self, dirs: &Dirs) -> PathBuf {
67         self.source_dir(dirs).join("Cargo.toml")
68     }
69
70     pub(crate) fn target_dir(&self, dirs: &Dirs) -> PathBuf {
71         RelPath::BUILD.join(self.target).to_path(dirs)
72     }
73
74     fn base_cmd(&self, command: &str, cargo: &Path, dirs: &Dirs) -> Command {
75         let mut cmd = Command::new(cargo);
76
77         cmd.arg(command)
78             .arg("--manifest-path")
79             .arg(self.manifest_path(dirs))
80             .arg("--target-dir")
81             .arg(self.target_dir(dirs));
82
83         cmd
84     }
85
86     fn build_cmd(&self, command: &str, compiler: &Compiler, dirs: &Dirs) -> Command {
87         let mut cmd = self.base_cmd(command, &compiler.cargo, dirs);
88
89         cmd.arg("--target").arg(&compiler.triple);
90
91         cmd.env("RUSTC", &compiler.rustc);
92         cmd.env("RUSTDOC", &compiler.rustdoc);
93         cmd.env("RUSTFLAGS", &compiler.rustflags);
94         cmd.env("RUSTDOCFLAGS", &compiler.rustdocflags);
95         if !compiler.runner.is_empty() {
96             cmd.env(
97                 format!("CARGO_TARGET_{}_RUNNER", compiler.triple.to_uppercase().replace('-', "_")),
98                 compiler.runner.join(" "),
99             );
100         }
101
102         cmd
103     }
104
105     #[must_use]
106     pub(crate) fn fetch(&self, cargo: impl AsRef<Path>, dirs: &Dirs) -> Command {
107         let mut cmd = Command::new(cargo.as_ref());
108
109         cmd.arg("fetch").arg("--manifest-path").arg(self.manifest_path(dirs));
110
111         cmd
112     }
113
114     #[must_use]
115     pub(crate) fn clean(&self, cargo: &Path, dirs: &Dirs) -> Command {
116         self.base_cmd("clean", cargo, dirs)
117     }
118
119     #[must_use]
120     pub(crate) fn build(&self, compiler: &Compiler, dirs: &Dirs) -> Command {
121         self.build_cmd("build", compiler, dirs)
122     }
123
124     #[must_use]
125     pub(crate) fn test(&self, compiler: &Compiler, dirs: &Dirs) -> Command {
126         self.build_cmd("test", compiler, dirs)
127     }
128
129     #[must_use]
130     pub(crate) fn run(&self, compiler: &Compiler, dirs: &Dirs) -> Command {
131         self.build_cmd("run", compiler, dirs)
132     }
133 }
134
135 #[must_use]
136 pub(crate) fn hyperfine_command(
137     warmup: u64,
138     runs: u64,
139     prepare: Option<&str>,
140     a: &str,
141     b: &str,
142 ) -> Command {
143     let mut bench = Command::new("hyperfine");
144
145     if warmup != 0 {
146         bench.arg("--warmup").arg(warmup.to_string());
147     }
148
149     if runs != 0 {
150         bench.arg("--runs").arg(runs.to_string());
151     }
152
153     if let Some(prepare) = prepare {
154         bench.arg("--prepare").arg(prepare);
155     }
156
157     bench.arg(a).arg(b);
158
159     bench
160 }
161
162 #[track_caller]
163 pub(crate) fn try_hard_link(src: impl AsRef<Path>, dst: impl AsRef<Path>) {
164     let src = src.as_ref();
165     let dst = dst.as_ref();
166     if let Err(_) = fs::hard_link(src, dst) {
167         fs::copy(src, dst).unwrap(); // Fallback to copying if hardlinking failed
168     }
169 }
170
171 #[track_caller]
172 pub(crate) fn spawn_and_wait(mut cmd: Command) {
173     if !cmd.spawn().unwrap().wait().unwrap().success() {
174         process::exit(1);
175     }
176 }
177
178 // Based on the retry function in rust's src/ci/shared.sh
179 #[track_caller]
180 pub(crate) fn retry_spawn_and_wait(tries: u64, mut cmd: Command) {
181     for i in 1..tries + 1 {
182         if i != 1 {
183             println!("Command failed. Attempt {i}/{tries}:");
184         }
185         if cmd.spawn().unwrap().wait().unwrap().success() {
186             return;
187         }
188         std::thread::sleep(std::time::Duration::from_secs(i * 5));
189     }
190     println!("The command has failed after {tries} attempts.");
191     process::exit(1);
192 }
193
194 #[track_caller]
195 pub(crate) fn spawn_and_wait_with_input(mut cmd: Command, input: String) -> String {
196     let mut child = cmd
197         .stdin(Stdio::piped())
198         .stdout(Stdio::piped())
199         .spawn()
200         .expect("Failed to spawn child process");
201
202     let mut stdin = child.stdin.take().expect("Failed to open stdin");
203     std::thread::spawn(move || {
204         stdin.write_all(input.as_bytes()).expect("Failed to write to stdin");
205     });
206
207     let output = child.wait_with_output().expect("Failed to read stdout");
208     if !output.status.success() {
209         process::exit(1);
210     }
211
212     String::from_utf8(output.stdout).unwrap()
213 }
214
215 pub(crate) fn copy_dir_recursively(from: &Path, to: &Path) {
216     for entry in fs::read_dir(from).unwrap() {
217         let entry = entry.unwrap();
218         let filename = entry.file_name();
219         if filename == "." || filename == ".." {
220             continue;
221         }
222         if entry.metadata().unwrap().is_dir() {
223             fs::create_dir(to.join(&filename)).unwrap();
224             copy_dir_recursively(&from.join(&filename), &to.join(&filename));
225         } else {
226             fs::copy(from.join(&filename), to.join(&filename)).unwrap();
227         }
228     }
229 }
230
231 pub(crate) fn is_ci() -> bool {
232     env::var("CI").as_deref() == Ok("true")
233 }