]> git.lizzy.rs Git - rust.git/blob - crates/paths/src/lib.rs
Merge #7335 #7691
[rust.git] / crates / paths / src / lib.rs
1 //! Thin wrappers around `std::path`, distinguishing between absolute and
2 //! relative paths.
3 use std::{
4     convert::{TryFrom, TryInto},
5     ops,
6     path::{Component, Path, PathBuf},
7 };
8
9 /// Wrapper around an absolute [`PathBuf`].
10 #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
11 pub struct AbsPathBuf(PathBuf);
12
13 impl From<AbsPathBuf> for PathBuf {
14     fn from(AbsPathBuf(path_buf): AbsPathBuf) -> PathBuf {
15         path_buf
16     }
17 }
18
19 impl ops::Deref for AbsPathBuf {
20     type Target = AbsPath;
21     fn deref(&self) -> &AbsPath {
22         self.as_path()
23     }
24 }
25
26 impl AsRef<Path> for AbsPathBuf {
27     fn as_ref(&self) -> &Path {
28         self.0.as_path()
29     }
30 }
31
32 impl AsRef<AbsPath> for AbsPathBuf {
33     fn as_ref(&self) -> &AbsPath {
34         self.as_path()
35     }
36 }
37
38 impl TryFrom<PathBuf> for AbsPathBuf {
39     type Error = PathBuf;
40     fn try_from(path_buf: PathBuf) -> Result<AbsPathBuf, PathBuf> {
41         if !path_buf.is_absolute() {
42             return Err(path_buf);
43         }
44         Ok(AbsPathBuf(path_buf))
45     }
46 }
47
48 impl TryFrom<&str> for AbsPathBuf {
49     type Error = PathBuf;
50     fn try_from(path: &str) -> Result<AbsPathBuf, PathBuf> {
51         AbsPathBuf::try_from(PathBuf::from(path))
52     }
53 }
54
55 impl PartialEq<AbsPath> for AbsPathBuf {
56     fn eq(&self, other: &AbsPath) -> bool {
57         self.as_path() == other
58     }
59 }
60
61 impl AbsPathBuf {
62     /// Wrap the given absolute path in `AbsPathBuf`
63     ///
64     /// # Panics
65     ///
66     /// Panics if `path` is not absolute.
67     pub fn assert(path: PathBuf) -> AbsPathBuf {
68         AbsPathBuf::try_from(path)
69             .unwrap_or_else(|path| panic!("expected absolute path, got {}", path.display()))
70     }
71
72     /// Coerces to a `AbsPath` slice.
73     ///
74     /// Equivalent of [`PathBuf::as_path`] for `AbsPathBuf`.
75     pub fn as_path(&self) -> &AbsPath {
76         AbsPath::assert(self.0.as_path())
77     }
78
79     /// Equivalent of [`PathBuf::pop`] for `AbsPathBuf`.
80     ///
81     /// Note that this won't remove the root component, so `self` will still be
82     /// absolute.
83     pub fn pop(&mut self) -> bool {
84         self.0.pop()
85     }
86 }
87
88 /// Wrapper around an absolute [`Path`].
89 #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
90 #[repr(transparent)]
91 pub struct AbsPath(Path);
92
93 impl ops::Deref for AbsPath {
94     type Target = Path;
95     fn deref(&self) -> &Path {
96         &self.0
97     }
98 }
99
100 impl AsRef<Path> for AbsPath {
101     fn as_ref(&self) -> &Path {
102         &self.0
103     }
104 }
105
106 impl<'a> TryFrom<&'a Path> for &'a AbsPath {
107     type Error = &'a Path;
108     fn try_from(path: &'a Path) -> Result<&'a AbsPath, &'a Path> {
109         if !path.is_absolute() {
110             return Err(path);
111         }
112         Ok(AbsPath::assert(path))
113     }
114 }
115
116 impl AbsPath {
117     /// Wrap the given absolute path in `AbsPath`
118     ///
119     /// # Panics
120     ///
121     /// Panics if `path` is not absolute.
122     pub fn assert(path: &Path) -> &AbsPath {
123         assert!(path.is_absolute());
124         unsafe { &*(path as *const Path as *const AbsPath) }
125     }
126
127     /// Equivalent of [`Path::parent`] for `AbsPath`.
128     pub fn parent(&self) -> Option<&AbsPath> {
129         self.0.parent().map(AbsPath::assert)
130     }
131
132     /// Equivalent of [`Path::join`] for `AbsPath`.
133     pub fn join(&self, path: impl AsRef<Path>) -> AbsPathBuf {
134         self.as_ref().join(path).try_into().unwrap()
135     }
136
137     /// Normalize the given path:
138     /// - Removes repeated separators: `/a//b` becomes `/a/b`
139     /// - Removes occurrences of `.` and resolves `..`.
140     /// - Removes trailing slashes: `/a/b/` becomes `/a/b`.
141     ///
142     /// # Example
143     /// ```
144     /// # use paths::AbsPathBuf;
145     /// let abs_path_buf = AbsPathBuf::assert("/a/../../b/.//c//".into());
146     /// let normalized = abs_path_buf.normalize();
147     /// assert_eq!(normalized, AbsPathBuf::assert("/b/c".into()));
148     /// ```
149     pub fn normalize(&self) -> AbsPathBuf {
150         AbsPathBuf(normalize_path(&self.0))
151     }
152
153     /// Equivalent of [`Path::to_path_buf`] for `AbsPath`.
154     pub fn to_path_buf(&self) -> AbsPathBuf {
155         AbsPathBuf::try_from(self.0.to_path_buf()).unwrap()
156     }
157
158     /// Equivalent of [`Path::strip_prefix`] for `AbsPath`.
159     ///
160     /// Returns a relative path.
161     pub fn strip_prefix(&self, base: &AbsPath) -> Option<&RelPath> {
162         self.0.strip_prefix(base).ok().map(RelPath::new_unchecked)
163     }
164 }
165
166 /// Wrapper around a relative [`PathBuf`].
167 #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
168 pub struct RelPathBuf(PathBuf);
169
170 impl From<RelPathBuf> for PathBuf {
171     fn from(RelPathBuf(path_buf): RelPathBuf) -> PathBuf {
172         path_buf
173     }
174 }
175
176 impl ops::Deref for RelPathBuf {
177     type Target = RelPath;
178     fn deref(&self) -> &RelPath {
179         self.as_path()
180     }
181 }
182
183 impl AsRef<Path> for RelPathBuf {
184     fn as_ref(&self) -> &Path {
185         self.0.as_path()
186     }
187 }
188
189 impl TryFrom<PathBuf> for RelPathBuf {
190     type Error = PathBuf;
191     fn try_from(path_buf: PathBuf) -> Result<RelPathBuf, PathBuf> {
192         if !path_buf.is_relative() {
193             return Err(path_buf);
194         }
195         Ok(RelPathBuf(path_buf))
196     }
197 }
198
199 impl TryFrom<&str> for RelPathBuf {
200     type Error = PathBuf;
201     fn try_from(path: &str) -> Result<RelPathBuf, PathBuf> {
202         RelPathBuf::try_from(PathBuf::from(path))
203     }
204 }
205
206 impl RelPathBuf {
207     /// Coerces to a `RelPath` slice.
208     ///
209     /// Equivalent of [`PathBuf::as_path`] for `RelPathBuf`.
210     pub fn as_path(&self) -> &RelPath {
211         RelPath::new_unchecked(self.0.as_path())
212     }
213 }
214
215 /// Wrapper around a relative [`Path`].
216 #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
217 #[repr(transparent)]
218 pub struct RelPath(Path);
219
220 impl ops::Deref for RelPath {
221     type Target = Path;
222     fn deref(&self) -> &Path {
223         &self.0
224     }
225 }
226
227 impl AsRef<Path> for RelPath {
228     fn as_ref(&self) -> &Path {
229         &self.0
230     }
231 }
232
233 impl RelPath {
234     /// Creates a new `RelPath` from `path`, without checking if it is relative.
235     pub fn new_unchecked(path: &Path) -> &RelPath {
236         unsafe { &*(path as *const Path as *const RelPath) }
237     }
238 }
239
240 /// Taken from https://github.com/rust-lang/cargo/blob/79c769c3d7b4c2cf6a93781575b7f592ef974255/src/cargo/util/paths.rs#L60-L85
241 fn normalize_path(path: &Path) -> PathBuf {
242     let mut components = path.components().peekable();
243     let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
244         components.next();
245         PathBuf::from(c.as_os_str())
246     } else {
247         PathBuf::new()
248     };
249
250     for component in components {
251         match component {
252             Component::Prefix(..) => unreachable!(),
253             Component::RootDir => {
254                 ret.push(component.as_os_str());
255             }
256             Component::CurDir => {}
257             Component::ParentDir => {
258                 ret.pop();
259             }
260             Component::Normal(c) => {
261                 ret.push(c);
262             }
263         }
264     }
265     ret
266 }