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