]> git.lizzy.rs Git - rust.git/blob - src/build_helper/lib.rs
Auto merge of #39415 - alexcrichton:fix-upload-dirs, r=brson
[rust.git] / src / build_helper / lib.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![deny(warnings)]
12
13 extern crate filetime;
14
15 use std::fs;
16 use std::process::{Command, Stdio};
17 use std::path::{Path, PathBuf};
18
19 use filetime::FileTime;
20
21 /// A helper macro to `unwrap` a result except also print out details like:
22 ///
23 /// * The file/line of the panic
24 /// * The expression that failed
25 /// * The error itself
26 ///
27 /// This is currently used judiciously throughout the build system rather than
28 /// using a `Result` with `try!`, but this may change one day...
29 #[macro_export]
30 macro_rules! t {
31     ($e:expr) => (match $e {
32         Ok(e) => e,
33         Err(e) => panic!("{} failed with {}", stringify!($e), e),
34     })
35 }
36
37 pub fn run(cmd: &mut Command) {
38     println!("running: {:?}", cmd);
39     run_silent(cmd);
40 }
41
42 pub fn run_silent(cmd: &mut Command) {
43     let status = match cmd.status() {
44         Ok(status) => status,
45         Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}",
46                                 cmd, e)),
47     };
48     if !status.success() {
49         fail(&format!("command did not execute successfully: {:?}\n\
50                        expected success, got: {}",
51                       cmd,
52                       status));
53     }
54 }
55
56 pub fn gnu_target(target: &str) -> String {
57     match target {
58         "i686-pc-windows-msvc" => "i686-pc-win32".to_string(),
59         "x86_64-pc-windows-msvc" => "x86_64-pc-win32".to_string(),
60         "i686-pc-windows-gnu" => "i686-w64-mingw32".to_string(),
61         "x86_64-pc-windows-gnu" => "x86_64-w64-mingw32".to_string(),
62         s => s.to_string(),
63     }
64 }
65
66 pub fn cc2ar(cc: &Path, target: &str) -> Option<PathBuf> {
67     if target.contains("msvc") {
68         None
69     } else if target.contains("musl") {
70         Some(PathBuf::from("ar"))
71     } else if target.contains("openbsd") {
72         Some(PathBuf::from("ar"))
73     } else {
74         let parent = cc.parent().unwrap();
75         let file = cc.file_name().unwrap().to_str().unwrap();
76         for suffix in &["gcc", "cc", "clang"] {
77             if let Some(idx) = file.rfind(suffix) {
78                 let mut file = file[..idx].to_owned();
79                 file.push_str("ar");
80                 return Some(parent.join(&file));
81             }
82         }
83         Some(parent.join(file))
84     }
85 }
86
87 pub fn make(host: &str) -> PathBuf {
88     if host.contains("bitrig") || host.contains("dragonfly") ||
89         host.contains("freebsd") || host.contains("netbsd") ||
90         host.contains("openbsd") {
91         PathBuf::from("gmake")
92     } else {
93         PathBuf::from("make")
94     }
95 }
96
97 pub fn output(cmd: &mut Command) -> String {
98     let output = match cmd.stderr(Stdio::inherit()).output() {
99         Ok(status) => status,
100         Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}",
101                                 cmd, e)),
102     };
103     if !output.status.success() {
104         panic!("command did not execute successfully: {:?}\n\
105                 expected success, got: {}",
106                cmd,
107                output.status);
108     }
109     String::from_utf8(output.stdout).unwrap()
110 }
111
112 pub fn rerun_if_changed_anything_in_dir(dir: &Path) {
113     let mut stack = dir.read_dir().unwrap()
114                        .map(|e| e.unwrap())
115                        .filter(|e| &*e.file_name() != ".git")
116                        .collect::<Vec<_>>();
117     while let Some(entry) = stack.pop() {
118         let path = entry.path();
119         if entry.file_type().unwrap().is_dir() {
120             stack.extend(path.read_dir().unwrap().map(|e| e.unwrap()));
121         } else {
122             println!("cargo:rerun-if-changed={}", path.display());
123         }
124     }
125 }
126
127 /// Returns the last-modified time for `path`, or zero if it doesn't exist.
128 pub fn mtime(path: &Path) -> FileTime {
129     fs::metadata(path).map(|f| {
130         FileTime::from_last_modification_time(&f)
131     }).unwrap_or(FileTime::zero())
132 }
133
134 /// Returns whether `dst` is up to date given that the file or files in `src`
135 /// are used to generate it.
136 ///
137 /// Uses last-modified time checks to verify this.
138 pub fn up_to_date(src: &Path, dst: &Path) -> bool {
139     let threshold = mtime(dst);
140     let meta = match fs::metadata(src) {
141         Ok(meta) => meta,
142         Err(e) => panic!("source {:?} failed to get metadata: {}", src, e),
143     };
144     if meta.is_dir() {
145         dir_up_to_date(src, &threshold)
146     } else {
147         FileTime::from_last_modification_time(&meta) <= threshold
148     }
149 }
150
151 fn dir_up_to_date(src: &Path, threshold: &FileTime) -> bool {
152     t!(fs::read_dir(src)).map(|e| t!(e)).all(|e| {
153         let meta = t!(e.metadata());
154         if meta.is_dir() {
155             dir_up_to_date(&e.path(), threshold)
156         } else {
157             FileTime::from_last_modification_time(&meta) < *threshold
158         }
159     })
160 }
161
162 fn fail(s: &str) -> ! {
163     println!("\n\n{}\n\n", s);
164     std::process::exit(1);
165 }