]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/build_system/utils.rs
Auto merge of #103431 - Dylan-DPC:rollup-oozfo89, r=Dylan-DPC
[rust.git] / compiler / rustc_codegen_cranelift / build_system / utils.rs
1 use std::env;
2 use std::fs;
3 use std::io::Write;
4 use std::path::Path;
5 use std::process::{self, Command, Stdio};
6
7 #[track_caller]
8 pub(crate) fn try_hard_link(src: impl AsRef<Path>, dst: impl AsRef<Path>) {
9     let src = src.as_ref();
10     let dst = dst.as_ref();
11     if let Err(_) = fs::hard_link(src, dst) {
12         fs::copy(src, dst).unwrap(); // Fallback to copying if hardlinking failed
13     }
14 }
15
16 #[track_caller]
17 pub(crate) fn spawn_and_wait(mut cmd: Command) {
18     if !cmd.spawn().unwrap().wait().unwrap().success() {
19         process::exit(1);
20     }
21 }
22
23 #[track_caller]
24 pub(crate) fn spawn_and_wait_with_input(mut cmd: Command, input: String) -> String {
25     let mut child = cmd
26         .stdin(Stdio::piped())
27         .stdout(Stdio::piped())
28         .spawn()
29         .expect("Failed to spawn child process");
30
31     let mut stdin = child.stdin.take().expect("Failed to open stdin");
32     std::thread::spawn(move || {
33         stdin.write_all(input.as_bytes()).expect("Failed to write to stdin");
34     });
35
36     let output = child.wait_with_output().expect("Failed to read stdout");
37     if !output.status.success() {
38         process::exit(1);
39     }
40
41     String::from_utf8(output.stdout).unwrap()
42 }
43
44 pub(crate) fn copy_dir_recursively(from: &Path, to: &Path) {
45     for entry in fs::read_dir(from).unwrap() {
46         let entry = entry.unwrap();
47         let filename = entry.file_name();
48         if filename == "." || filename == ".." {
49             continue;
50         }
51         if entry.metadata().unwrap().is_dir() {
52             fs::create_dir(to.join(&filename)).unwrap();
53             copy_dir_recursively(&from.join(&filename), &to.join(&filename));
54         } else {
55             fs::copy(from.join(&filename), to.join(&filename)).unwrap();
56         }
57     }
58 }
59
60 pub(crate) fn is_ci() -> bool {
61     env::var("CI").as_ref().map(|val| &**val) == Ok("true")
62 }