]> git.lizzy.rs Git - rust.git/blob - src/build_helper/lib.rs
Rollup merge of #92134 - nico-abram:patch-1, r=michaelwoerister
[rust.git] / src / build_helper / lib.rs
1 use std::ffi::{OsStr, OsString};
2 use std::fmt::Display;
3 use std::path::{Path, PathBuf};
4 use std::process::{Command, Stdio};
5 use std::time::{SystemTime, UNIX_EPOCH};
6 use std::{env, fs};
7
8 /// A helper macro to `unwrap` a result except also print out details like:
9 ///
10 /// * The file/line of the panic
11 /// * The expression that failed
12 /// * The error itself
13 ///
14 /// This is currently used judiciously throughout the build system rather than
15 /// using a `Result` with `try!`, but this may change one day...
16 #[macro_export]
17 macro_rules! t {
18     ($e:expr) => {
19         match $e {
20             Ok(e) => e,
21             Err(e) => panic!("{} failed with {}", stringify!($e), e),
22         }
23     };
24     // it can show extra info in the second parameter
25     ($e:expr, $extra:expr) => {
26         match $e {
27             Ok(e) => e,
28             Err(e) => panic!("{} failed with {} ({:?})", stringify!($e), e, $extra),
29         }
30     };
31 }
32
33 /// Reads an environment variable and adds it to dependencies.
34 /// Supposed to be used for all variables except those set for build scripts by cargo
35 /// <https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts>
36 pub fn tracked_env_var_os<K: AsRef<OsStr> + Display>(key: K) -> Option<OsString> {
37     println!("cargo:rerun-if-env-changed={}", key);
38     env::var_os(key)
39 }
40
41 // Because Cargo adds the compiler's dylib path to our library search path, llvm-config may
42 // break: the dylib path for the compiler, as of this writing, contains a copy of the LLVM
43 // shared library, which means that when our freshly built llvm-config goes to load it's
44 // associated LLVM, it actually loads the compiler's LLVM. In particular when building the first
45 // compiler (i.e., in stage 0) that's a problem, as the compiler's LLVM is likely different from
46 // the one we want to use. As such, we restore the environment to what bootstrap saw. This isn't
47 // perfect -- we might actually want to see something from Cargo's added library paths -- but
48 // for now it works.
49 pub fn restore_library_path() {
50     let key = tracked_env_var_os("REAL_LIBRARY_PATH_VAR").expect("REAL_LIBRARY_PATH_VAR");
51     if let Some(env) = tracked_env_var_os("REAL_LIBRARY_PATH") {
52         env::set_var(&key, &env);
53     } else {
54         env::remove_var(&key);
55     }
56 }
57
58 pub fn run(cmd: &mut Command) {
59     if !try_run(cmd) {
60         std::process::exit(1);
61     }
62 }
63
64 pub fn try_run(cmd: &mut Command) -> bool {
65     let status = match cmd.status() {
66         Ok(status) => status,
67         Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
68     };
69     if !status.success() {
70         println!(
71             "\n\ncommand did not execute successfully: {:?}\n\
72              expected success, got: {}\n\n",
73             cmd, status
74         );
75     }
76     status.success()
77 }
78
79 pub fn run_suppressed(cmd: &mut Command) {
80     if !try_run_suppressed(cmd) {
81         std::process::exit(1);
82     }
83 }
84
85 pub fn try_run_suppressed(cmd: &mut Command) -> bool {
86     let output = match cmd.output() {
87         Ok(status) => status,
88         Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
89     };
90     if !output.status.success() {
91         println!(
92             "\n\ncommand did not execute successfully: {:?}\n\
93              expected success, got: {}\n\n\
94              stdout ----\n{}\n\
95              stderr ----\n{}\n\n",
96             cmd,
97             output.status,
98             String::from_utf8_lossy(&output.stdout),
99             String::from_utf8_lossy(&output.stderr)
100         );
101     }
102     output.status.success()
103 }
104
105 pub fn make(host: &str) -> PathBuf {
106     if host.contains("dragonfly")
107         || host.contains("freebsd")
108         || host.contains("netbsd")
109         || host.contains("openbsd")
110     {
111         PathBuf::from("gmake")
112     } else {
113         PathBuf::from("make")
114     }
115 }
116
117 #[track_caller]
118 pub fn output(cmd: &mut Command) -> String {
119     let output = match cmd.stderr(Stdio::inherit()).output() {
120         Ok(status) => status,
121         Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
122     };
123     if !output.status.success() {
124         panic!(
125             "command did not execute successfully: {:?}\n\
126              expected success, got: {}",
127             cmd, output.status
128         );
129     }
130     String::from_utf8(output.stdout).unwrap()
131 }
132
133 pub fn rerun_if_changed_anything_in_dir(dir: &Path) {
134     let mut stack = dir
135         .read_dir()
136         .unwrap()
137         .map(|e| e.unwrap())
138         .filter(|e| &*e.file_name() != ".git")
139         .collect::<Vec<_>>();
140     while let Some(entry) = stack.pop() {
141         let path = entry.path();
142         if entry.file_type().unwrap().is_dir() {
143             stack.extend(path.read_dir().unwrap().map(|e| e.unwrap()));
144         } else {
145             println!("cargo:rerun-if-changed={}", path.display());
146         }
147     }
148 }
149
150 /// Returns the last-modified time for `path`, or zero if it doesn't exist.
151 pub fn mtime(path: &Path) -> SystemTime {
152     fs::metadata(path).and_then(|f| f.modified()).unwrap_or(UNIX_EPOCH)
153 }
154
155 /// Returns `true` if `dst` is up to date given that the file or files in `src`
156 /// are used to generate it.
157 ///
158 /// Uses last-modified time checks to verify this.
159 pub fn up_to_date(src: &Path, dst: &Path) -> bool {
160     if !dst.exists() {
161         return false;
162     }
163     let threshold = mtime(dst);
164     let meta = match fs::metadata(src) {
165         Ok(meta) => meta,
166         Err(e) => panic!("source {:?} failed to get metadata: {}", src, e),
167     };
168     if meta.is_dir() {
169         dir_up_to_date(src, threshold)
170     } else {
171         meta.modified().unwrap_or(UNIX_EPOCH) <= threshold
172     }
173 }
174
175 fn dir_up_to_date(src: &Path, threshold: SystemTime) -> bool {
176     t!(fs::read_dir(src)).map(|e| t!(e)).all(|e| {
177         let meta = t!(e.metadata());
178         if meta.is_dir() {
179             dir_up_to_date(&e.path(), threshold)
180         } else {
181             meta.modified().unwrap_or(UNIX_EPOCH) < threshold
182         }
183     })
184 }
185
186 fn fail(s: &str) -> ! {
187     println!("\n\n{}\n\n", s);
188     std::process::exit(1);
189 }