]> git.lizzy.rs Git - rust.git/blob - crates/paths/src/lib.rs
Merge #10902
[rust.git] / crates / paths / src / lib.rs
1 //! Thin wrappers around `std::path`, distinguishing between absolute and
2 //! relative paths.
3 use std::{
4     borrow::Borrow,
5     ffi::OsStr,
6     ops,
7     path::{Component, Path, PathBuf},
8 };
9
10 /// Wrapper around an absolute [`PathBuf`].
11 #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
12 pub struct AbsPathBuf(PathBuf);
13
14 impl From<AbsPathBuf> for PathBuf {
15     fn from(AbsPathBuf(path_buf): AbsPathBuf) -> PathBuf {
16         path_buf
17     }
18 }
19
20 impl ops::Deref for AbsPathBuf {
21     type Target = AbsPath;
22     fn deref(&self) -> &AbsPath {
23         self.as_path()
24     }
25 }
26
27 impl AsRef<Path> for AbsPathBuf {
28     fn as_ref(&self) -> &Path {
29         self.0.as_path()
30     }
31 }
32
33 impl AsRef<AbsPath> for AbsPathBuf {
34     fn as_ref(&self) -> &AbsPath {
35         self.as_path()
36     }
37 }
38
39 impl Borrow<AbsPath> for AbsPathBuf {
40     fn borrow(&self) -> &AbsPath {
41         self.as_path()
42     }
43 }
44
45 impl TryFrom<PathBuf> for AbsPathBuf {
46     type Error = PathBuf;
47     fn try_from(path_buf: PathBuf) -> Result<AbsPathBuf, PathBuf> {
48         if !path_buf.is_absolute() {
49             return Err(path_buf);
50         }
51         Ok(AbsPathBuf(path_buf))
52     }
53 }
54
55 impl TryFrom<&str> for AbsPathBuf {
56     type Error = PathBuf;
57     fn try_from(path: &str) -> Result<AbsPathBuf, PathBuf> {
58         AbsPathBuf::try_from(PathBuf::from(path))
59     }
60 }
61
62 impl PartialEq<AbsPath> for AbsPathBuf {
63     fn eq(&self, other: &AbsPath) -> bool {
64         self.as_path() == other
65     }
66 }
67
68 impl AbsPathBuf {
69     /// Wrap the given absolute path in `AbsPathBuf`
70     ///
71     /// # Panics
72     ///
73     /// Panics if `path` is not absolute.
74     pub fn assert(path: PathBuf) -> AbsPathBuf {
75         AbsPathBuf::try_from(path)
76             .unwrap_or_else(|path| panic!("expected absolute path, got {}", path.display()))
77     }
78
79     /// Coerces to an `AbsPath` slice.
80     ///
81     /// Equivalent of [`PathBuf::as_path`] for `AbsPathBuf`.
82     pub fn as_path(&self) -> &AbsPath {
83         AbsPath::assert(self.0.as_path())
84     }
85
86     /// Equivalent of [`PathBuf::pop`] for `AbsPathBuf`.
87     ///
88     /// Note that this won't remove the root component, so `self` will still be
89     /// absolute.
90     pub fn pop(&mut self) -> bool {
91         self.0.pop()
92     }
93 }
94
95 /// Wrapper around an absolute [`Path`].
96 #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
97 #[repr(transparent)]
98 pub struct AbsPath(Path);
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     pub fn starts_with(&self, base: &AbsPath) -> bool {
165         self.0.starts_with(&base.0)
166     }
167     pub fn ends_with(&self, suffix: &RelPath) -> bool {
168         self.0.ends_with(&suffix.0)
169     }
170
171     // region:delegate-methods
172
173     // Note that we deliberately don't implement `Deref<Target = Path>` here.
174     //
175     // The problem with `Path` is that it directly exposes convenience IO-ing
176     // methods. For example, `Path::exists` delegates to `fs::metadata`.
177     //
178     // For `AbsPath`, we want to make sure that this is a POD type, and that all
179     // IO goes via `fs`. That way, it becomes easier to mock IO when we need it.
180
181     pub fn file_name(&self) -> Option<&OsStr> {
182         self.0.file_name()
183     }
184     pub fn extension(&self) -> Option<&OsStr> {
185         self.0.extension()
186     }
187     pub fn file_stem(&self) -> Option<&OsStr> {
188         self.0.file_stem()
189     }
190     pub fn as_os_str(&self) -> &OsStr {
191         self.0.as_os_str()
192     }
193     pub fn display(&self) -> std::path::Display<'_> {
194         self.0.display()
195     }
196     #[deprecated(note = "use std::fs::metadata().is_ok() instead")]
197     pub fn exists(&self) -> bool {
198         self.0.exists()
199     }
200     // endregion:delegate-methods
201 }
202
203 /// Wrapper around a relative [`PathBuf`].
204 #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
205 pub struct RelPathBuf(PathBuf);
206
207 impl From<RelPathBuf> for PathBuf {
208     fn from(RelPathBuf(path_buf): RelPathBuf) -> PathBuf {
209         path_buf
210     }
211 }
212
213 impl ops::Deref for RelPathBuf {
214     type Target = RelPath;
215     fn deref(&self) -> &RelPath {
216         self.as_path()
217     }
218 }
219
220 impl AsRef<Path> for RelPathBuf {
221     fn as_ref(&self) -> &Path {
222         self.0.as_path()
223     }
224 }
225
226 impl TryFrom<PathBuf> for RelPathBuf {
227     type Error = PathBuf;
228     fn try_from(path_buf: PathBuf) -> Result<RelPathBuf, PathBuf> {
229         if !path_buf.is_relative() {
230             return Err(path_buf);
231         }
232         Ok(RelPathBuf(path_buf))
233     }
234 }
235
236 impl TryFrom<&str> for RelPathBuf {
237     type Error = PathBuf;
238     fn try_from(path: &str) -> Result<RelPathBuf, PathBuf> {
239         RelPathBuf::try_from(PathBuf::from(path))
240     }
241 }
242
243 impl RelPathBuf {
244     /// Coerces to a `RelPath` slice.
245     ///
246     /// Equivalent of [`PathBuf::as_path`] for `RelPathBuf`.
247     pub fn as_path(&self) -> &RelPath {
248         RelPath::new_unchecked(self.0.as_path())
249     }
250 }
251
252 /// Wrapper around a relative [`Path`].
253 #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
254 #[repr(transparent)]
255 pub struct RelPath(Path);
256
257 impl AsRef<Path> for RelPath {
258     fn as_ref(&self) -> &Path {
259         &self.0
260     }
261 }
262
263 impl RelPath {
264     /// Creates a new `RelPath` from `path`, without checking if it is relative.
265     pub fn new_unchecked(path: &Path) -> &RelPath {
266         unsafe { &*(path as *const Path as *const RelPath) }
267     }
268 }
269
270 /// Taken from <https://github.com/rust-lang/cargo/blob/79c769c3d7b4c2cf6a93781575b7f592ef974255/src/cargo/util/paths.rs#L60-L85>
271 fn normalize_path(path: &Path) -> PathBuf {
272     let mut components = path.components().peekable();
273     let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().copied() {
274         components.next();
275         PathBuf::from(c.as_os_str())
276     } else {
277         PathBuf::new()
278     };
279
280     for component in components {
281         match component {
282             Component::Prefix(..) => unreachable!(),
283             Component::RootDir => {
284                 ret.push(component.as_os_str());
285             }
286             Component::CurDir => {}
287             Component::ParentDir => {
288                 ret.pop();
289             }
290             Component::Normal(c) => {
291                 ret.push(c);
292             }
293         }
294     }
295     ret
296 }