1 #![deny(rust_2018_idioms)]
3 use std::path::{Path, PathBuf};
8 // Unfortunately, on windows, it looks like msvcrt.dll is silently translating
9 // verbatim paths under the hood to non-verbatim paths! This manifests itself as
10 // gcc looking like it cannot accept paths of the form `\\?\C:\...`, but the
11 // real bug seems to lie in msvcrt.dll.
13 // Verbatim paths are generally pretty rare, but the implementation of
14 // `fs::canonicalize` currently generates paths of this form, meaning that we're
15 // going to be passing quite a few of these down to gcc, so we need to deal with
18 // For now we just strip the "verbatim prefix" of `\\?\` from the path. This
19 // will probably lose information in some cases, but there's not a whole lot
20 // more we can do with a buggy msvcrt...
22 // For some more information, see this comment:
23 // https://github.com/rust-lang/rust/issues/25505#issuecomment-102876737
25 pub fn fix_windows_verbatim_for_gcc(p: &Path) -> PathBuf {
27 use std::ffi::OsString;
28 let mut components = p.components();
29 let prefix = match components.next() {
30 Some(path::Component::Prefix(p)) => p,
31 _ => return p.to_path_buf(),
34 path::Prefix::VerbatimDisk(disk) => {
35 let mut base = OsString::from(format!("{}:", disk as char));
36 base.push(components.as_path());
39 path::Prefix::VerbatimUNC(server, share) => {
40 let mut base = OsString::from(r"\\");
44 base.push(components.as_path());
52 pub fn fix_windows_verbatim_for_gcc(p: &Path) -> PathBuf {
61 /// Copies `p` into `q`, preferring to use hard-linking if possible. If
62 /// `q` already exists, it is removed first.
63 /// The result indicates which of the two operations has been performed.
64 pub fn link_or_copy<P: AsRef<Path>, Q: AsRef<Path>>(p: P, q: Q) -> io::Result<LinkOrCopy> {
71 match fs::hard_link(p, q) {
72 Ok(()) => Ok(LinkOrCopy::Link),
74 match fs::copy(p, q) {
75 Ok(_) => Ok(LinkOrCopy::Copy),
83 pub enum RenameOrCopyRemove {
88 /// Rename `p` into `q`, preferring to use `rename` if possible.
89 /// If `rename` fails (rename may fail for reasons such as crossing
90 /// filesystem), fallback to copy & remove
91 pub fn rename_or_copy_remove<P: AsRef<Path>, Q: AsRef<Path>>(p: P,
93 -> io::Result<RenameOrCopyRemove> {
96 match fs::rename(p, q) {
97 Ok(()) => Ok(RenameOrCopyRemove::Rename),
99 match fs::copy(p, q) {
102 Ok(RenameOrCopyRemove::CopyRemove)
111 pub fn path_to_c_string(p: &Path) -> CString {
112 use std::os::unix::ffi::OsStrExt;
114 let p: &OsStr = p.as_ref();
115 CString::new(p.as_bytes()).unwrap()
118 pub fn path_to_c_string(p: &Path) -> CString {
119 CString::new(p.to_str().unwrap()).unwrap()