1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
use std::ffi::CString;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
#[cfg(windows)]
pub fn fix_windows_verbatim_for_gcc(p: &Path) -> PathBuf {
use std::ffi::OsString;
use std::path;
let mut components = p.components();
let prefix = match components.next() {
Some(path::Component::Prefix(p)) => p,
_ => return p.to_path_buf(),
};
match prefix.kind() {
path::Prefix::VerbatimDisk(disk) => {
let mut base = OsString::from(format!("{}:", disk as char));
base.push(components.as_path());
PathBuf::from(base)
}
path::Prefix::VerbatimUNC(server, share) => {
let mut base = OsString::from(r"\\");
base.push(server);
base.push(r"\");
base.push(share);
base.push(components.as_path());
PathBuf::from(base)
}
_ => p.to_path_buf(),
}
}
#[cfg(not(windows))]
pub fn fix_windows_verbatim_for_gcc(p: &Path) -> PathBuf {
p.to_path_buf()
}
pub enum LinkOrCopy {
Link,
Copy,
}
pub fn link_or_copy<P: AsRef<Path>, Q: AsRef<Path>>(p: P, q: Q) -> io::Result<LinkOrCopy> {
let p = p.as_ref();
let q = q.as_ref();
if q.exists() {
fs::remove_file(&q)?;
}
match fs::hard_link(p, q) {
Ok(()) => Ok(LinkOrCopy::Link),
Err(_) => match fs::copy(p, q) {
Ok(_) => Ok(LinkOrCopy::Copy),
Err(e) => Err(e),
},
}
}
#[derive(Debug)]
pub enum RenameOrCopyRemove {
Rename,
CopyRemove,
}
pub fn rename_or_copy_remove<P: AsRef<Path>, Q: AsRef<Path>>(
p: P,
q: Q,
) -> io::Result<RenameOrCopyRemove> {
let p = p.as_ref();
let q = q.as_ref();
match fs::rename(p, q) {
Ok(()) => Ok(RenameOrCopyRemove::Rename),
Err(_) => match fs::copy(p, q) {
Ok(_) => {
fs::remove_file(p)?;
Ok(RenameOrCopyRemove::CopyRemove)
}
Err(e) => Err(e),
},
}
}
#[cfg(unix)]
pub fn path_to_c_string(p: &Path) -> CString {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let p: &OsStr = p.as_ref();
CString::new(p.as_bytes()).unwrap()
}
#[cfg(windows)]
pub fn path_to_c_string(p: &Path) -> CString {
CString::new(p.to_str().unwrap()).unwrap()
}