]> git.lizzy.rs Git - rust.git/blob - crates/paths/src/lib.rs
Auto merge of #12841 - Veykril:query-fix, 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<'a> TryFrom<&'a Path> for &'a AbsPath {
110     type Error = &'a Path;
111     fn try_from(path: &'a Path) -> Result<&'a AbsPath, &'a Path> {
112         if !path.is_absolute() {
113             return Err(path);
114         }
115         Ok(AbsPath::assert(path))
116     }
117 }
118
119 impl AbsPath {
120     /// Wrap the given absolute path in `AbsPath`
121     ///
122     /// # Panics
123     ///
124     /// Panics if `path` is not absolute.
125     pub fn assert(path: &Path) -> &AbsPath {
126         assert!(path.is_absolute());
127         unsafe { &*(path as *const Path as *const AbsPath) }
128     }
129
130     /// Equivalent of [`Path::parent`] for `AbsPath`.
131     pub fn parent(&self) -> Option<&AbsPath> {
132         self.0.parent().map(AbsPath::assert)
133     }
134
135     /// Equivalent of [`Path::join`] for `AbsPath`.
136     pub fn join(&self, path: impl AsRef<Path>) -> AbsPathBuf {
137         self.as_ref().join(path).try_into().unwrap()
138     }
139
140     /// Normalize the given path:
141     /// - Removes repeated separators: `/a//b` becomes `/a/b`
142     /// - Removes occurrences of `.` and resolves `..`.
143     /// - Removes trailing slashes: `/a/b/` becomes `/a/b`.
144     ///
145     /// # Example
146     /// ```
147     /// # use paths::AbsPathBuf;
148     /// let abs_path_buf = AbsPathBuf::assert("/a/../../b/.//c//".into());
149     /// let normalized = abs_path_buf.normalize();
150     /// assert_eq!(normalized, AbsPathBuf::assert("/b/c".into()));
151     /// ```
152     pub fn normalize(&self) -> AbsPathBuf {
153         AbsPathBuf(normalize_path(&self.0))
154     }
155
156     /// Equivalent of [`Path::to_path_buf`] for `AbsPath`.
157     pub fn to_path_buf(&self) -> AbsPathBuf {
158         AbsPathBuf::try_from(self.0.to_path_buf()).unwrap()
159     }
160
161     /// Equivalent of [`Path::strip_prefix`] for `AbsPath`.
162     ///
163     /// Returns a relative path.
164     pub fn strip_prefix(&self, base: &AbsPath) -> Option<&RelPath> {
165         self.0.strip_prefix(base).ok().map(RelPath::new_unchecked)
166     }
167     pub fn starts_with(&self, base: &AbsPath) -> bool {
168         self.0.starts_with(&base.0)
169     }
170     pub fn ends_with(&self, suffix: &RelPath) -> bool {
171         self.0.ends_with(&suffix.0)
172     }
173
174     // region:delegate-methods
175
176     // Note that we deliberately don't implement `Deref<Target = Path>` here.
177     //
178     // The problem with `Path` is that it directly exposes convenience IO-ing
179     // methods. For example, `Path::exists` delegates to `fs::metadata`.
180     //
181     // For `AbsPath`, we want to make sure that this is a POD type, and that all
182     // IO goes via `fs`. That way, it becomes easier to mock IO when we need it.
183
184     pub fn file_name(&self) -> Option<&OsStr> {
185         self.0.file_name()
186     }
187     pub fn extension(&self) -> Option<&OsStr> {
188         self.0.extension()
189     }
190     pub fn file_stem(&self) -> Option<&OsStr> {
191         self.0.file_stem()
192     }
193     pub fn as_os_str(&self) -> &OsStr {
194         self.0.as_os_str()
195     }
196     pub fn display(&self) -> std::path::Display<'_> {
197         self.0.display()
198     }
199     #[deprecated(note = "use std::fs::metadata().is_ok() instead")]
200     pub fn exists(&self) -> bool {
201         self.0.exists()
202     }
203     // endregion:delegate-methods
204 }
205
206 /// Wrapper around a relative [`PathBuf`].
207 #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
208 pub struct RelPathBuf(PathBuf);
209
210 impl From<RelPathBuf> for PathBuf {
211     fn from(RelPathBuf(path_buf): RelPathBuf) -> PathBuf {
212         path_buf
213     }
214 }
215
216 impl ops::Deref for RelPathBuf {
217     type Target = RelPath;
218     fn deref(&self) -> &RelPath {
219         self.as_path()
220     }
221 }
222
223 impl AsRef<Path> for RelPathBuf {
224     fn as_ref(&self) -> &Path {
225         self.0.as_path()
226     }
227 }
228
229 impl TryFrom<PathBuf> for RelPathBuf {
230     type Error = PathBuf;
231     fn try_from(path_buf: PathBuf) -> Result<RelPathBuf, PathBuf> {
232         if !path_buf.is_relative() {
233             return Err(path_buf);
234         }
235         Ok(RelPathBuf(path_buf))
236     }
237 }
238
239 impl TryFrom<&str> for RelPathBuf {
240     type Error = PathBuf;
241     fn try_from(path: &str) -> Result<RelPathBuf, PathBuf> {
242         RelPathBuf::try_from(PathBuf::from(path))
243     }
244 }
245
246 impl RelPathBuf {
247     /// Coerces to a `RelPath` slice.
248     ///
249     /// Equivalent of [`PathBuf::as_path`] for `RelPathBuf`.
250     pub fn as_path(&self) -> &RelPath {
251         RelPath::new_unchecked(self.0.as_path())
252     }
253 }
254
255 /// Wrapper around a relative [`Path`].
256 #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
257 #[repr(transparent)]
258 pub struct RelPath(Path);
259
260 impl AsRef<Path> for RelPath {
261     fn as_ref(&self) -> &Path {
262         &self.0
263     }
264 }
265
266 impl RelPath {
267     /// Creates a new `RelPath` from `path`, without checking if it is relative.
268     pub fn new_unchecked(path: &Path) -> &RelPath {
269         unsafe { &*(path as *const Path as *const RelPath) }
270     }
271 }
272
273 /// Taken from <https://github.com/rust-lang/cargo/blob/79c769c3d7b4c2cf6a93781575b7f592ef974255/src/cargo/util/paths.rs#L60-L85>
274 fn normalize_path(path: &Path) -> PathBuf {
275     let mut components = path.components().peekable();
276     let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().copied() {
277         components.next();
278         PathBuf::from(c.as_os_str())
279     } else {
280         PathBuf::new()
281     };
282
283     for component in components {
284         match component {
285             Component::Prefix(..) => unreachable!(),
286             Component::RootDir => {
287                 ret.push(component.as_os_str());
288             }
289             Component::CurDir => {}
290             Component::ParentDir => {
291                 ret.pop();
292             }
293             Component::Normal(c) => {
294                 ret.push(c);
295             }
296         }
297     }
298     ret
299 }