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