1 //! Various utility functions used throughout rustbuild.
3 //! Simple things like testing the various filesystem operations here and there,
4 //! not a lot of interesting happenings here unfortunately.
9 use std::io::{self, Write};
10 use std::path::{Path, PathBuf};
11 use std::process::Command;
12 use std::time::{SystemTime, Instant};
14 use crate::config::Config;
15 use crate::builder::Builder;
17 /// Returns the `name` as the filename of a static library for `target`.
18 pub fn staticlib(name: &str, target: &str) -> String {
19 if target.contains("windows") {
20 format!("{}.lib", name)
22 format!("lib{}.a", name)
26 /// Given an executable called `name`, return the filename for the
27 /// executable for a particular target.
28 pub fn exe(name: &str, target: &str) -> String {
29 if target.contains("windows") {
30 format!("{}.exe", name)
36 /// Returns `true` if the file name given looks like a dynamic library.
37 pub fn is_dylib(name: &str) -> bool {
38 name.ends_with(".dylib") || name.ends_with(".so") || name.ends_with(".dll")
41 /// Returns the corresponding relative library directory that the compiler's
42 /// dylibs will be found in.
43 pub fn libdir(target: &str) -> &'static str {
44 if target.contains("windows") {"bin"} else {"lib"}
47 /// Adds a list of lookup paths to `cmd`'s dynamic library lookup path.
48 pub fn add_lib_path(path: Vec<PathBuf>, cmd: &mut Command) {
49 let mut list = dylib_path();
53 cmd.env(dylib_path_var(), t!(env::join_paths(list)));
56 /// Returns the environment variable which the dynamic library lookup path
57 /// resides in for this platform.
58 pub fn dylib_path_var() -> &'static str {
59 if cfg!(target_os = "windows") {
61 } else if cfg!(target_os = "macos") {
63 } else if cfg!(target_os = "haiku") {
70 /// Parses the `dylib_path_var()` environment variable, returning a list of
71 /// paths that are members of this lookup path.
72 pub fn dylib_path() -> Vec<PathBuf> {
73 let var = match env::var_os(dylib_path_var()) {
75 None => return vec![],
77 env::split_paths(&var).collect()
80 /// `push` all components to `buf`. On windows, append `.exe` to the last component.
81 pub fn push_exe_path(mut buf: PathBuf, components: &[&str]) -> PathBuf {
82 let (&file, components) = components.split_last().expect("at least one component required");
83 let mut file = file.to_owned();
86 file.push_str(".exe");
89 buf.extend(components);
95 pub struct TimeIt(bool, Instant);
97 /// Returns an RAII structure that prints out how long it took to drop.
98 pub fn timeit(builder: &Builder) -> TimeIt {
99 TimeIt(builder.config.dry_run, Instant::now())
102 impl Drop for TimeIt {
104 let time = self.1.elapsed();
106 println!("\tfinished in {}.{:03}",
108 time.subsec_nanos() / 1_000_000);
113 /// Symlinks two directories, using junctions on Windows and normal symlinks on
115 pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> {
116 if config.dry_run { return Ok(()); }
117 let _ = fs::remove_dir(dest);
118 return symlink_dir_inner(src, dest);
121 fn symlink_dir_inner(src: &Path, dest: &Path) -> io::Result<()> {
122 use std::os::unix::fs;
123 fs::symlink(src, dest)
126 // Creating a directory junction on windows involves dealing with reparse
127 // points and the DeviceIoControl function, and this code is a skeleton of
128 // what can be found here:
130 // http://www.flexhex.com/docs/articles/hard-links.phtml
134 #[allow(nonstandard_style)]
135 fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
138 use std::os::windows::ffi::OsStrExt;
140 const MAXIMUM_REPARSE_DATA_BUFFER_SIZE: usize = 16 * 1024;
141 const GENERIC_WRITE: DWORD = 0x40000000;
142 const OPEN_EXISTING: DWORD = 3;
143 const FILE_FLAG_OPEN_REPARSE_POINT: DWORD = 0x00200000;
144 const FILE_FLAG_BACKUP_SEMANTICS: DWORD = 0x02000000;
145 const FSCTL_SET_REPARSE_POINT: DWORD = 0x900a4;
146 const IO_REPARSE_TAG_MOUNT_POINT: DWORD = 0xa0000003;
147 const FILE_SHARE_DELETE: DWORD = 0x4;
148 const FILE_SHARE_READ: DWORD = 0x1;
149 const FILE_SHARE_WRITE: DWORD = 0x2;
153 type HANDLE = *mut u8;
154 type LPCWSTR = *const u16;
155 type LPDWORD = *mut DWORD;
156 type LPOVERLAPPED = *mut u8;
157 type LPSECURITY_ATTRIBUTES = *mut u8;
158 type LPVOID = *mut u8;
163 struct REPARSE_MOUNTPOINT_DATA_BUFFER {
165 ReparseDataLength: DWORD,
167 ReparseTargetLength: WORD,
168 ReparseTargetMaximumLength: WORD,
170 ReparseTarget: WCHAR,
174 fn CreateFileW(lpFileName: LPCWSTR,
175 dwDesiredAccess: DWORD,
177 lpSecurityAttributes: LPSECURITY_ATTRIBUTES,
178 dwCreationDisposition: DWORD,
179 dwFlagsAndAttributes: DWORD,
180 hTemplateFile: HANDLE)
182 fn DeviceIoControl(hDevice: HANDLE,
183 dwIoControlCode: DWORD,
185 nInBufferSize: DWORD,
187 nOutBufferSize: DWORD,
188 lpBytesReturned: LPDWORD,
189 lpOverlapped: LPOVERLAPPED) -> BOOL;
190 fn CloseHandle(hObject: HANDLE) -> BOOL;
193 fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
194 Ok(s.as_ref().encode_wide().chain(Some(0)).collect())
197 // We're using low-level APIs to create the junction, and these are more
198 // picky about paths. For example, forward slashes cannot be used as a
199 // path separator, so we should try to canonicalize the path first.
200 let target = fs::canonicalize(target)?;
202 fs::create_dir(junction)?;
204 let path = to_u16s(junction)?;
207 let h = CreateFileW(path.as_ptr(),
209 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
212 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
215 let mut data = [0u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
216 let db = data.as_mut_ptr()
217 as *mut REPARSE_MOUNTPOINT_DATA_BUFFER;
218 let buf = &mut (*db).ReparseTarget as *mut u16;
220 // FIXME: this conversion is very hacky
222 let v = v.iter().map(|x| *x as u16);
223 for c in v.chain(target.as_os_str().encode_wide().skip(4)) {
229 (*db).ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
230 (*db).ReparseTargetMaximumLength = (i * 2) as WORD;
231 (*db).ReparseTargetLength = ((i - 1) * 2) as WORD;
232 (*db).ReparseDataLength =
233 (*db).ReparseTargetLength as DWORD + 12;
236 let res = DeviceIoControl(h as *mut _,
237 FSCTL_SET_REPARSE_POINT,
238 data.as_ptr() as *mut _,
239 (*db).ReparseDataLength + 8,
244 let out = if res == 0 {
245 Err(io::Error::last_os_error())
255 /// An RAII structure that indicates all output until this instance is dropped
256 /// is part of the same group.
258 /// On Travis CI, these output will be folded by default, together with the
259 /// elapsed time in this block. This reduces noise from unnecessary logs,
260 /// allowing developers to quickly identify the error.
262 /// Travis CI supports folding by printing `travis_fold:start:<name>` and
263 /// `travis_fold:end:<name>` around the block. Time elapsed is recognized
264 /// similarly with `travis_time:[start|end]:<name>`. These are undocumented, but
265 /// can easily be deduced from source code of the [Travis build commands].
267 /// [Travis build commands]:
268 /// https://github.com/travis-ci/travis-build/blob/f603c0089/lib/travis/build/templates/header.sh
269 pub struct OutputFolder {
271 start_time: SystemTime, // we need SystemTime to get the UNIX timestamp.
275 /// Creates a new output folder with the given group name.
276 pub fn new(name: String) -> OutputFolder {
277 // "\r" moves the cursor to the beginning of the line, and "\x1b[0K" is
278 // the ANSI escape code to clear from the cursor to end of line.
279 // Travis seems to have trouble when _not_ using "\r\x1b[0K", that will
280 // randomly put lines to the top of the webpage.
281 print!("travis_fold:start:{0}\r\x1b[0Ktravis_time:start:{0}\r\x1b[0K", name);
284 start_time: SystemTime::now(),
289 impl Drop for OutputFolder {
294 fn to_nanos(duration: Result<Duration, SystemTimeError>) -> u64 {
296 Ok(d) => d.as_secs() * 1_000_000_000 + d.subsec_nanos() as u64,
301 let end_time = SystemTime::now();
302 let duration = end_time.duration_since(self.start_time);
303 let start = self.start_time.duration_since(UNIX_EPOCH);
304 let finish = end_time.duration_since(UNIX_EPOCH);
306 "travis_fold:end:{0}\r\x1b[0K\n\
307 travis_time:end:{0}:start={1},finish={2},duration={3}\r\x1b[0K",
313 io::stdout().flush().unwrap();
317 /// The CI environment rustbuild is running in. This mainly affects how the logs
319 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
321 /// Not a CI environment.
323 /// The Travis CI environment, for Linux (including Docker) and macOS builds.
325 /// The AppVeyor environment, for Windows builds.
330 /// Obtains the current CI environment.
331 pub fn current() -> CiEnv {
332 if env::var("TRAVIS").ok().map_or(false, |e| &*e == "true") {
334 } else if env::var("APPVEYOR").ok().map_or(false, |e| &*e == "True") {
341 /// If in a CI environment, forces the command to run with colors.
342 pub fn force_coloring_in_ci(self, cmd: &mut Command) {
343 if self != CiEnv::None {
344 // Due to use of stamp/docker, the output stream of rustbuild is not
345 // a TTY in CI, so coloring is by-default turned off.
346 // The explicit `TERM=xterm` environment is needed for
347 // `--color always` to actually work. This env var was lost when
348 // compiling through the Makefile. Very strange.
349 cmd.env("TERM", "xterm").args(&["--color", "always"]);