-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathpath.rs
143 lines (130 loc) · 4.15 KB
/
path.rs
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
use anyhow::Result;
use std::{
convert::TryFrom,
fmt,
ops::Deref,
path::{Path, PathBuf},
};
/// Represents a canonicalized path to a file or directory.
#[derive(PartialOrd, Ord, Eq, PartialEq, Hash, Clone)]
pub struct AbsPath {
inner: PathBuf,
}
impl fmt::Debug for AbsPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.inner.display())
}
}
// Ideally we could could create a generic TryFrom implementation for anything
// that implements Into<PathBuf>, but apparently this is not possible?
// https://github.com/rust-lang/rust/issues/50133
impl TryFrom<PathBuf> for AbsPath {
type Error = anyhow::Error;
fn try_from(p: PathBuf) -> Result<Self> {
Ok(AbsPath {
inner: p.canonicalize()?,
})
}
}
impl TryFrom<&Path> for AbsPath {
type Error = anyhow::Error;
fn try_from(p: &Path) -> Result<Self> {
Ok(AbsPath {
inner: PathBuf::from(p).canonicalize()?,
})
}
}
impl TryFrom<&String> for AbsPath {
type Error = anyhow::Error;
fn try_from(p: &String) -> Result<Self> {
Ok(AbsPath {
inner: PathBuf::from(p).canonicalize()?,
})
}
}
impl TryFrom<String> for AbsPath {
type Error = anyhow::Error;
fn try_from(p: String) -> Result<Self> {
Ok(AbsPath {
inner: PathBuf::from(p).canonicalize()?,
})
}
}
impl TryFrom<&str> for AbsPath {
type Error = anyhow::Error;
fn try_from(p: &str) -> Result<Self> {
Ok(AbsPath {
inner: PathBuf::from(p).canonicalize()?,
})
}
}
impl Deref for AbsPath {
type Target = Path;
fn deref(&self) -> &Self::Target {
self.inner.as_path()
}
}
impl AsRef<Path> for AbsPath {
fn as_ref(&self) -> &Path {
self.inner.as_path()
}
}
// This routine is adapted from the *old* Path's `path_relative_from`
// function, which works differently from the new `relative_from` function.
// In particular, this handles the case on unix where both paths are
// absolute but with only the root as the common directory.
// From: https://stackoverflow.com/questions/39340924/given-two-absolute-paths-how-can-i-express-one-of-the-paths-relative-to-the-oth
//
// path_relative_from(/foo/bar, /foo) -> bar
pub fn path_relative_from(path: &Path, base: &Path) -> Option<PathBuf> {
use std::path::Component;
if path.is_absolute() != base.is_absolute() {
if path.is_absolute() {
Some(PathBuf::from(path))
} else {
None
}
} else {
let mut ita = path.components();
let mut itb = base.components();
let mut comps: Vec<Component> = vec![];
loop {
match (ita.next(), itb.next()) {
(None, None) => break,
(Some(a), None) => {
comps.push(a);
comps.extend(ita.by_ref());
break;
}
(None, _) => comps.push(Component::ParentDir),
(Some(a), Some(b)) if comps.is_empty() && a == b => (),
(Some(a), Some(b)) if b == Component::CurDir => comps.push(a),
(Some(_), Some(b)) if b == Component::ParentDir => return None,
(Some(a), Some(_)) => {
comps.push(Component::ParentDir);
for _ in itb {
comps.push(Component::ParentDir);
}
comps.push(a);
comps.extend(ita.by_ref());
break;
}
}
}
Some(comps.iter().map(|c| c.as_os_str()).collect())
}
}
//
pub fn get_display_path(path: &str, current_dir: &Path) -> String {
let abs_path = AbsPath::try_from(path);
match abs_path {
Ok(abs_path) => {
// unwrap will never panic because we know `abs_path` is absolute.
let relative_path = path_relative_from(&abs_path, current_dir).unwrap();
relative_path.display().to_string()
}
// If we can't relativize for some reason, just return the path as
// reported by the linter.
Err(_) => path.to_string(),
}
}