rustc_fs_util/
lib.rs

1use std::ffi::CString;
2use std::path::{Path, PathBuf, absolute};
3use std::{fs, io};
4
5// Unfortunately, on windows, it looks like msvcrt.dll is silently translating
6// verbatim paths under the hood to non-verbatim paths! This manifests itself as
7// gcc looking like it cannot accept paths of the form `\\?\C:\...`, but the
8// real bug seems to lie in msvcrt.dll.
9//
10// Verbatim paths are generally pretty rare, but the implementation of
11// `fs::canonicalize` currently generates paths of this form, meaning that we're
12// going to be passing quite a few of these down to gcc, so we need to deal with
13// this case.
14//
15// For now we just strip the "verbatim prefix" of `\\?\` from the path. This
16// will probably lose information in some cases, but there's not a whole lot
17// more we can do with a buggy msvcrt...
18//
19// For some more information, see this comment:
20//   https://github.com/rust-lang/rust/issues/25505#issuecomment-102876737
21#[cfg(windows)]
22pub fn fix_windows_verbatim_for_gcc(p: &Path) -> PathBuf {
23    use std::ffi::OsString;
24    use std::path;
25    let mut components = p.components();
26    let prefix = match components.next() {
27        Some(path::Component::Prefix(p)) => p,
28        _ => return p.to_path_buf(),
29    };
30    match prefix.kind() {
31        path::Prefix::VerbatimDisk(disk) => {
32            let mut base = OsString::from(format!("{}:", disk as char));
33            base.push(components.as_path());
34            PathBuf::from(base)
35        }
36        path::Prefix::VerbatimUNC(server, share) => {
37            let mut base = OsString::from(r"\\");
38            base.push(server);
39            base.push(r"\");
40            base.push(share);
41            base.push(components.as_path());
42            PathBuf::from(base)
43        }
44        _ => p.to_path_buf(),
45    }
46}
47
48#[cfg(not(windows))]
49pub fn fix_windows_verbatim_for_gcc(p: &Path) -> PathBuf {
50    p.to_path_buf()
51}
52
53pub enum LinkOrCopy {
54    Link,
55    Copy,
56}
57
58/// Copies `p` into `q`, preferring to use hard-linking if possible. If
59/// `q` already exists, it is removed first.
60/// The result indicates which of the two operations has been performed.
61pub fn link_or_copy<P: AsRef<Path>, Q: AsRef<Path>>(p: P, q: Q) -> io::Result<LinkOrCopy> {
62    let p = p.as_ref();
63    let q = q.as_ref();
64    match fs::remove_file(q) {
65        Ok(()) => (),
66        Err(err) if err.kind() == io::ErrorKind::NotFound => (),
67        Err(err) => return Err(err),
68    }
69
70    match fs::hard_link(p, q) {
71        Ok(()) => Ok(LinkOrCopy::Link),
72        Err(_) => match fs::copy(p, q) {
73            Ok(_) => Ok(LinkOrCopy::Copy),
74            Err(e) => Err(e),
75        },
76    }
77}
78
79#[cfg(any(unix, all(target_os = "wasi", target_env = "p1")))]
80pub fn path_to_c_string(p: &Path) -> CString {
81    use std::ffi::OsStr;
82    #[cfg(unix)]
83    use std::os::unix::ffi::OsStrExt;
84    #[cfg(all(target_os = "wasi", target_env = "p1"))]
85    use std::os::wasi::ffi::OsStrExt;
86
87    let p: &OsStr = p.as_ref();
88    CString::new(p.as_bytes()).unwrap()
89}
90#[cfg(windows)]
91pub fn path_to_c_string(p: &Path) -> CString {
92    CString::new(p.to_str().unwrap()).unwrap()
93}
94
95#[inline]
96pub fn try_canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
97    fs::canonicalize(&path).or_else(|_| absolute(&path))
98}