]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/util.rs
Update Cargo to 0.23.0 and our lockfile
[rust.git] / src / bootstrap / util.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 //! Various utility functions used throughout rustbuild.
12 //!
13 //! Simple things like testing the various filesystem operations here and there,
14 //! not a lot of interesting happenings here unfortunately.
15
16 use std::env;
17 use std::fs;
18 use std::io::{self, Write};
19 use std::path::{Path, PathBuf};
20 use std::process::Command;
21 use std::time::{SystemTime, Instant};
22
23 use filetime::{self, FileTime};
24
25 /// Returns the `name` as the filename of a static library for `target`.
26 pub fn staticlib(name: &str, target: &str) -> String {
27     if target.contains("windows") {
28         format!("{}.lib", name)
29     } else {
30         format!("lib{}.a", name)
31     }
32 }
33
34 /// Copies a file from `src` to `dst`
35 pub fn copy(src: &Path, dst: &Path) {
36     let _ = fs::remove_file(&dst);
37     let res = fs::copy(src, dst);
38     if let Err(e) = res {
39         panic!("failed to copy `{}` to `{}`: {}", src.display(),
40                dst.display(), e)
41     }
42     let metadata = t!(src.metadata());
43     t!(fs::set_permissions(dst, metadata.permissions()));
44     let atime = FileTime::from_last_access_time(&metadata);
45     let mtime = FileTime::from_last_modification_time(&metadata);
46     t!(filetime::set_file_times(dst, atime, mtime));
47
48 }
49
50 /// Copies the `src` directory recursively to `dst`. Both are assumed to exist
51 /// when this function is called.
52 pub fn cp_r(src: &Path, dst: &Path) {
53     for f in t!(fs::read_dir(src)) {
54         let f = t!(f);
55         let path = f.path();
56         let name = path.file_name().unwrap();
57         let dst = dst.join(name);
58         if t!(f.file_type()).is_dir() {
59             t!(fs::create_dir_all(&dst));
60             cp_r(&path, &dst);
61         } else {
62             let _ = fs::remove_file(&dst);
63             copy(&path, &dst);
64         }
65     }
66 }
67
68 /// Copies the `src` directory recursively to `dst`. Both are assumed to exist
69 /// when this function is called. Unwanted files or directories can be skipped
70 /// by returning `false` from the filter function.
71 pub fn cp_filtered(src: &Path, dst: &Path, filter: &Fn(&Path) -> bool) {
72     // Inner function does the actual work
73     fn recurse(src: &Path, dst: &Path, relative: &Path, filter: &Fn(&Path) -> bool) {
74         for f in t!(fs::read_dir(src)) {
75             let f = t!(f);
76             let path = f.path();
77             let name = path.file_name().unwrap();
78             let dst = dst.join(name);
79             let relative = relative.join(name);
80             // Only copy file or directory if the filter function returns true
81             if filter(&relative) {
82                 if t!(f.file_type()).is_dir() {
83                     let _ = fs::remove_dir_all(&dst);
84                     t!(fs::create_dir(&dst));
85                     recurse(&path, &dst, &relative, filter);
86                 } else {
87                     let _ = fs::remove_file(&dst);
88                     copy(&path, &dst);
89                 }
90             }
91         }
92     }
93     // Immediately recurse with an empty relative path
94     recurse(src, dst, Path::new(""), filter)
95 }
96
97 /// Given an executable called `name`, return the filename for the
98 /// executable for a particular target.
99 pub fn exe(name: &str, target: &str) -> String {
100     if target.contains("windows") {
101         format!("{}.exe", name)
102     } else {
103         name.to_string()
104     }
105 }
106
107 /// Returns whether the file name given looks like a dynamic library.
108 pub fn is_dylib(name: &str) -> bool {
109     name.ends_with(".dylib") || name.ends_with(".so") || name.ends_with(".dll")
110 }
111
112 /// Returns the corresponding relative library directory that the compiler's
113 /// dylibs will be found in.
114 pub fn libdir(target: &str) -> &'static str {
115     if target.contains("windows") {"bin"} else {"lib"}
116 }
117
118 /// Adds a list of lookup paths to `cmd`'s dynamic library lookup path.
119 pub fn add_lib_path(path: Vec<PathBuf>, cmd: &mut Command) {
120     let mut list = dylib_path();
121     for path in path {
122         list.insert(0, path);
123     }
124     cmd.env(dylib_path_var(), t!(env::join_paths(list)));
125 }
126
127 /// Returns the environment variable which the dynamic library lookup path
128 /// resides in for this platform.
129 pub fn dylib_path_var() -> &'static str {
130     if cfg!(target_os = "windows") {
131         "PATH"
132     } else if cfg!(target_os = "macos") {
133         "DYLD_LIBRARY_PATH"
134     } else if cfg!(target_os = "haiku") {
135         "LIBRARY_PATH"
136     } else {
137         "LD_LIBRARY_PATH"
138     }
139 }
140
141 /// Parses the `dylib_path_var()` environment variable, returning a list of
142 /// paths that are members of this lookup path.
143 pub fn dylib_path() -> Vec<PathBuf> {
144     env::split_paths(&env::var_os(dylib_path_var()).unwrap_or_default()).collect()
145 }
146
147 /// `push` all components to `buf`. On windows, append `.exe` to the last component.
148 pub fn push_exe_path(mut buf: PathBuf, components: &[&str]) -> PathBuf {
149     let (&file, components) = components.split_last().expect("at least one component required");
150     let mut file = file.to_owned();
151
152     if cfg!(windows) {
153         file.push_str(".exe");
154     }
155
156     for c in components {
157         buf.push(c);
158     }
159
160     buf.push(file);
161
162     buf
163 }
164
165 pub struct TimeIt(Instant);
166
167 /// Returns an RAII structure that prints out how long it took to drop.
168 pub fn timeit() -> TimeIt {
169     TimeIt(Instant::now())
170 }
171
172 impl Drop for TimeIt {
173     fn drop(&mut self) {
174         let time = self.0.elapsed();
175         println!("\tfinished in {}.{:03}",
176                  time.as_secs(),
177                  time.subsec_nanos() / 1_000_000);
178     }
179 }
180
181 /// Symlinks two directories, using junctions on Windows and normal symlinks on
182 /// Unix.
183 pub fn symlink_dir(src: &Path, dest: &Path) -> io::Result<()> {
184     let _ = fs::remove_dir(dest);
185     return symlink_dir_inner(src, dest);
186
187     #[cfg(not(windows))]
188     fn symlink_dir_inner(src: &Path, dest: &Path) -> io::Result<()> {
189         use std::os::unix::fs;
190         fs::symlink(src, dest)
191     }
192
193     // Creating a directory junction on windows involves dealing with reparse
194     // points and the DeviceIoControl function, and this code is a skeleton of
195     // what can be found here:
196     //
197     // http://www.flexhex.com/docs/articles/hard-links.phtml
198     //
199     // Copied from std
200     #[cfg(windows)]
201     #[allow(bad_style)]
202     fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
203         use std::ptr;
204         use std::ffi::OsStr;
205         use std::os::windows::ffi::OsStrExt;
206
207         const MAXIMUM_REPARSE_DATA_BUFFER_SIZE: usize = 16 * 1024;
208         const GENERIC_WRITE: DWORD = 0x40000000;
209         const OPEN_EXISTING: DWORD = 3;
210         const FILE_FLAG_OPEN_REPARSE_POINT: DWORD = 0x00200000;
211         const FILE_FLAG_BACKUP_SEMANTICS: DWORD = 0x02000000;
212         const FSCTL_SET_REPARSE_POINT: DWORD = 0x900a4;
213         const IO_REPARSE_TAG_MOUNT_POINT: DWORD = 0xa0000003;
214         const FILE_SHARE_DELETE: DWORD = 0x4;
215         const FILE_SHARE_READ: DWORD = 0x1;
216         const FILE_SHARE_WRITE: DWORD = 0x2;
217
218         type BOOL = i32;
219         type DWORD = u32;
220         type HANDLE = *mut u8;
221         type LPCWSTR = *const u16;
222         type LPDWORD = *mut DWORD;
223         type LPOVERLAPPED = *mut u8;
224         type LPSECURITY_ATTRIBUTES = *mut u8;
225         type LPVOID = *mut u8;
226         type WCHAR = u16;
227         type WORD = u16;
228
229         #[repr(C)]
230         struct REPARSE_MOUNTPOINT_DATA_BUFFER {
231             ReparseTag: DWORD,
232             ReparseDataLength: DWORD,
233             Reserved: WORD,
234             ReparseTargetLength: WORD,
235             ReparseTargetMaximumLength: WORD,
236             Reserved1: WORD,
237             ReparseTarget: WCHAR,
238         }
239
240         extern "system" {
241             fn CreateFileW(lpFileName: LPCWSTR,
242                            dwDesiredAccess: DWORD,
243                            dwShareMode: DWORD,
244                            lpSecurityAttributes: LPSECURITY_ATTRIBUTES,
245                            dwCreationDisposition: DWORD,
246                            dwFlagsAndAttributes: DWORD,
247                            hTemplateFile: HANDLE)
248                            -> HANDLE;
249             fn DeviceIoControl(hDevice: HANDLE,
250                                dwIoControlCode: DWORD,
251                                lpInBuffer: LPVOID,
252                                nInBufferSize: DWORD,
253                                lpOutBuffer: LPVOID,
254                                nOutBufferSize: DWORD,
255                                lpBytesReturned: LPDWORD,
256                                lpOverlapped: LPOVERLAPPED) -> BOOL;
257         }
258
259         fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
260             Ok(s.as_ref().encode_wide().chain(Some(0)).collect())
261         }
262
263         // We're using low-level APIs to create the junction, and these are more
264         // picky about paths. For example, forward slashes cannot be used as a
265         // path separator, so we should try to canonicalize the path first.
266         let target = try!(fs::canonicalize(target));
267
268         try!(fs::create_dir(junction));
269
270         let path = try!(to_u16s(junction));
271
272         unsafe {
273             let h = CreateFileW(path.as_ptr(),
274                                 GENERIC_WRITE,
275                                 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
276                                 0 as *mut _,
277                                 OPEN_EXISTING,
278                                 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
279                                 ptr::null_mut());
280
281             let mut data = [0u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
282             let db = data.as_mut_ptr()
283                             as *mut REPARSE_MOUNTPOINT_DATA_BUFFER;
284             let buf = &mut (*db).ReparseTarget as *mut _;
285             let mut i = 0;
286             // FIXME: this conversion is very hacky
287             let v = br"\??\";
288             let v = v.iter().map(|x| *x as u16);
289             for c in v.chain(target.as_os_str().encode_wide().skip(4)) {
290                 *buf.offset(i) = c;
291                 i += 1;
292             }
293             *buf.offset(i) = 0;
294             i += 1;
295             (*db).ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
296             (*db).ReparseTargetMaximumLength = (i * 2) as WORD;
297             (*db).ReparseTargetLength = ((i - 1) * 2) as WORD;
298             (*db).ReparseDataLength =
299                     (*db).ReparseTargetLength as DWORD + 12;
300
301             let mut ret = 0;
302             let res = DeviceIoControl(h as *mut _,
303                                       FSCTL_SET_REPARSE_POINT,
304                                       data.as_ptr() as *mut _,
305                                       (*db).ReparseDataLength + 8,
306                                       ptr::null_mut(), 0,
307                                       &mut ret,
308                                       ptr::null_mut());
309
310             if res == 0 {
311                 Err(io::Error::last_os_error())
312             } else {
313                 Ok(())
314             }
315         }
316     }
317 }
318
319 /// An RAII structure that indicates all output until this instance is dropped
320 /// is part of the same group.
321 ///
322 /// On Travis CI, these output will be folded by default, together with the
323 /// elapsed time in this block. This reduces noise from unnecessary logs,
324 /// allowing developers to quickly identify the error.
325 ///
326 /// Travis CI supports folding by printing `travis_fold:start:<name>` and
327 /// `travis_fold:end:<name>` around the block. Time elapsed is recognized
328 /// similarly with `travis_time:[start|end]:<name>`. These are undocumented, but
329 /// can easily be deduced from source code of the [Travis build commands].
330 ///
331 /// [Travis build commands]:
332 /// https://github.com/travis-ci/travis-build/blob/f603c0089/lib/travis/build/templates/header.sh
333 pub struct OutputFolder {
334     name: String,
335     start_time: SystemTime, // we need SystemTime to get the UNIX timestamp.
336 }
337
338 impl OutputFolder {
339     /// Creates a new output folder with the given group name.
340     pub fn new(name: String) -> OutputFolder {
341         // "\r" moves the cursor to the beginning of the line, and "\x1b[0K" is
342         // the ANSI escape code to clear from the cursor to end of line.
343         // Travis seems to have trouble when _not_ using "\r\x1b[0K", that will
344         // randomly put lines to the top of the webpage.
345         print!("travis_fold:start:{0}\r\x1b[0Ktravis_time:start:{0}\r\x1b[0K", name);
346         OutputFolder {
347             name,
348             start_time: SystemTime::now(),
349         }
350     }
351 }
352
353 impl Drop for OutputFolder {
354     fn drop(&mut self) {
355         use std::time::*;
356         use std::u64;
357
358         fn to_nanos(duration: Result<Duration, SystemTimeError>) -> u64 {
359             match duration {
360                 Ok(d) => d.as_secs() * 1_000_000_000 + d.subsec_nanos() as u64,
361                 Err(_) => u64::MAX,
362             }
363         }
364
365         let end_time = SystemTime::now();
366         let duration = end_time.duration_since(self.start_time);
367         let start = self.start_time.duration_since(UNIX_EPOCH);
368         let finish = end_time.duration_since(UNIX_EPOCH);
369         println!(
370             "travis_fold:end:{0}\r\x1b[0K\n\
371                 travis_time:end:{0}:start={1},finish={2},duration={3}\r\x1b[0K",
372             self.name,
373             to_nanos(start),
374             to_nanos(finish),
375             to_nanos(duration)
376         );
377         io::stdout().flush().unwrap();
378     }
379 }
380
381 /// The CI environment rustbuild is running in. This mainly affects how the logs
382 /// are printed.
383 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
384 pub enum CiEnv {
385     /// Not a CI environment.
386     None,
387     /// The Travis CI environment, for Linux (including Docker) and macOS builds.
388     Travis,
389     /// The AppVeyor environment, for Windows builds.
390     AppVeyor,
391 }
392
393 impl CiEnv {
394     /// Obtains the current CI environment.
395     pub fn current() -> CiEnv {
396         if env::var("TRAVIS").ok().map_or(false, |e| &*e == "true") {
397             CiEnv::Travis
398         } else if env::var("APPVEYOR").ok().map_or(false, |e| &*e == "True") {
399             CiEnv::AppVeyor
400         } else {
401             CiEnv::None
402         }
403     }
404
405     /// If in a CI environment, forces the command to run with colors.
406     pub fn force_coloring_in_ci(self, cmd: &mut Command) {
407         if self != CiEnv::None {
408             // Due to use of stamp/docker, the output stream of rustbuild is not
409             // a TTY in CI, so coloring is by-default turned off.
410             // The explicit `TERM=xterm` environment is needed for
411             // `--color always` to actually work. This env var was lost when
412             // compiling through the Makefile. Very strange.
413             cmd.env("TERM", "xterm").args(&["--color", "always"]);
414         }
415     }
416 }