1 use std::ffi::{OsStr, OsString};
3 use std::path::{Path, PathBuf};
4 use std::process::{Command, Stdio};
5 use std::time::{SystemTime, UNIX_EPOCH};
8 /// A helper macro to `unwrap` a result except also print out details like:
10 /// * The file/line of the panic
11 /// * The expression that failed
12 /// * The error itself
14 /// This is currently used judiciously throughout the build system rather than
15 /// using a `Result` with `try!`, but this may change one day...
21 Err(e) => panic!("{} failed with {}", stringify!($e), e),
24 // it can show extra info in the second parameter
25 ($e:expr, $extra:expr) => {
28 Err(e) => panic!("{} failed with {} ({:?})", stringify!($e), e, $extra),
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);
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
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);
54 env::remove_var(&key);
58 /// Run the command, printing what we are running.
59 pub fn run_verbose(cmd: &mut Command) {
60 println!("running: {:?}", cmd);
64 pub fn run(cmd: &mut Command) {
66 std::process::exit(1);
70 pub fn try_run(cmd: &mut Command) -> bool {
71 let status = match cmd.status() {
73 Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
75 if !status.success() {
77 "\n\ncommand did not execute successfully: {:?}\n\
78 expected success, got: {}\n\n",
85 pub fn run_suppressed(cmd: &mut Command) {
86 if !try_run_suppressed(cmd) {
87 std::process::exit(1);
91 pub fn try_run_suppressed(cmd: &mut Command) -> bool {
92 let output = match cmd.output() {
94 Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
96 if !output.status.success() {
98 "\n\ncommand did not execute successfully: {:?}\n\
99 expected success, got: {}\n\n\
101 stderr ----\n{}\n\n",
104 String::from_utf8_lossy(&output.stdout),
105 String::from_utf8_lossy(&output.stderr)
108 output.status.success()
111 pub fn gnu_target(target: &str) -> &str {
113 "i686-pc-windows-msvc" => "i686-pc-win32",
114 "x86_64-pc-windows-msvc" => "x86_64-pc-win32",
115 "i686-pc-windows-gnu" => "i686-w64-mingw32",
116 "x86_64-pc-windows-gnu" => "x86_64-w64-mingw32",
121 pub fn make(host: &str) -> PathBuf {
122 if host.contains("dragonfly")
123 || host.contains("freebsd")
124 || host.contains("netbsd")
125 || host.contains("openbsd")
127 PathBuf::from("gmake")
129 PathBuf::from("make")
133 pub fn output(cmd: &mut Command) -> String {
134 let output = match cmd.stderr(Stdio::inherit()).output() {
135 Ok(status) => status,
136 Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
138 if !output.status.success() {
140 "command did not execute successfully: {:?}\n\
141 expected success, got: {}",
145 String::from_utf8(output.stdout).unwrap()
148 pub fn rerun_if_changed_anything_in_dir(dir: &Path) {
153 .filter(|e| &*e.file_name() != ".git")
154 .collect::<Vec<_>>();
155 while let Some(entry) = stack.pop() {
156 let path = entry.path();
157 if entry.file_type().unwrap().is_dir() {
158 stack.extend(path.read_dir().unwrap().map(|e| e.unwrap()));
160 println!("cargo:rerun-if-changed={}", path.display());
165 /// Returns the last-modified time for `path`, or zero if it doesn't exist.
166 pub fn mtime(path: &Path) -> SystemTime {
167 fs::metadata(path).and_then(|f| f.modified()).unwrap_or(UNIX_EPOCH)
170 /// Returns `true` if `dst` is up to date given that the file or files in `src`
171 /// are used to generate it.
173 /// Uses last-modified time checks to verify this.
174 pub fn up_to_date(src: &Path, dst: &Path) -> bool {
178 let threshold = mtime(dst);
179 let meta = match fs::metadata(src) {
181 Err(e) => panic!("source {:?} failed to get metadata: {}", src, e),
184 dir_up_to_date(src, threshold)
186 meta.modified().unwrap_or(UNIX_EPOCH) <= threshold
190 fn dir_up_to_date(src: &Path, threshold: SystemTime) -> bool {
191 t!(fs::read_dir(src)).map(|e| t!(e)).all(|e| {
192 let meta = t!(e.metadata());
194 dir_up_to_date(&e.path(), threshold)
196 meta.modified().unwrap_or(UNIX_EPOCH) < threshold
201 fn fail(s: &str) -> ! {
202 println!("\n\n{}\n\n", s);
203 std::process::exit(1);