4 use std::path::{Path, PathBuf};
6 // Unfortunately, on windows, it looks like msvcrt.dll is silently translating
7 // verbatim paths under the hood to non-verbatim paths! This manifests itself as
8 // gcc looking like it cannot accept paths of the form `\\?\C:\...`, but the
9 // real bug seems to lie in msvcrt.dll.
11 // Verbatim paths are generally pretty rare, but the implementation of
12 // `fs::canonicalize` currently generates paths of this form, meaning that we're
13 // going to be passing quite a few of these down to gcc, so we need to deal with
16 // For now we just strip the "verbatim prefix" of `\\?\` from the path. This
17 // will probably lose information in some cases, but there's not a whole lot
18 // more we can do with a buggy msvcrt...
20 // For some more information, see this comment:
21 // https://github.com/rust-lang/rust/issues/25505#issuecomment-102876737
23 pub fn fix_windows_verbatim_for_gcc(p: &Path) -> PathBuf {
24 use std::ffi::OsString;
26 let mut components = p.components();
27 let prefix = match components.next() {
28 Some(path::Component::Prefix(p)) => p,
29 _ => return p.to_path_buf(),
32 path::Prefix::VerbatimDisk(disk) => {
33 let mut base = OsString::from(format!("{}:", disk as char));
34 base.push(components.as_path());
37 path::Prefix::VerbatimUNC(server, share) => {
38 let mut base = OsString::from(r"\\");
42 base.push(components.as_path());
50 pub fn fix_windows_verbatim_for_gcc(p: &Path) -> PathBuf {
59 /// Copies `p` into `q`, preferring to use hard-linking if possible. If
60 /// `q` already exists, it is removed first.
61 /// The result indicates which of the two operations has been performed.
62 pub fn link_or_copy<P: AsRef<Path>, Q: AsRef<Path>>(p: P, q: Q) -> io::Result<LinkOrCopy> {
69 match fs::hard_link(p, q) {
70 Ok(()) => Ok(LinkOrCopy::Link),
71 Err(_) => match fs::copy(p, q) {
72 Ok(_) => Ok(LinkOrCopy::Copy),
79 pub enum RenameOrCopyRemove {
84 /// Rename `p` into `q`, preferring to use `rename` if possible.
85 /// If `rename` fails (rename may fail for reasons such as crossing
86 /// filesystem), fallback to copy & remove
87 pub fn rename_or_copy_remove<P: AsRef<Path>, Q: AsRef<Path>>(
90 ) -> io::Result<RenameOrCopyRemove> {
93 match fs::rename(p, q) {
94 Ok(()) => Ok(RenameOrCopyRemove::Rename),
95 Err(_) => match fs::copy(p, q) {
98 Ok(RenameOrCopyRemove::CopyRemove)
106 pub fn path_to_c_string(p: &Path) -> CString {
108 use std::os::unix::ffi::OsStrExt;
109 let p: &OsStr = p.as_ref();
110 CString::new(p.as_bytes()).unwrap()
113 pub fn path_to_c_string(p: &Path) -> CString {
114 CString::new(p.to_str().unwrap()).unwrap()