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