1 //! Thin wrappers around `std::path`, distinguishing between absolute and
4 #![warn(rust_2018_idioms, unused_lifetimes, semicolon_in_expressions_from_macros)]
10 path::{Component, Path, PathBuf},
13 /// Wrapper around an absolute [`PathBuf`].
14 #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
15 pub struct AbsPathBuf(PathBuf);
17 impl From<AbsPathBuf> for PathBuf {
18 fn from(AbsPathBuf(path_buf): AbsPathBuf) -> PathBuf {
23 impl ops::Deref for AbsPathBuf {
24 type Target = AbsPath;
25 fn deref(&self) -> &AbsPath {
30 impl AsRef<Path> for AbsPathBuf {
31 fn as_ref(&self) -> &Path {
36 impl AsRef<AbsPath> for AbsPathBuf {
37 fn as_ref(&self) -> &AbsPath {
42 impl Borrow<AbsPath> for AbsPathBuf {
43 fn borrow(&self) -> &AbsPath {
48 impl TryFrom<PathBuf> for AbsPathBuf {
50 fn try_from(path_buf: PathBuf) -> Result<AbsPathBuf, PathBuf> {
51 if !path_buf.is_absolute() {
54 Ok(AbsPathBuf(path_buf))
58 impl TryFrom<&str> for AbsPathBuf {
60 fn try_from(path: &str) -> Result<AbsPathBuf, PathBuf> {
61 AbsPathBuf::try_from(PathBuf::from(path))
65 impl PartialEq<AbsPath> for AbsPathBuf {
66 fn eq(&self, other: &AbsPath) -> bool {
67 self.as_path() == other
72 /// Wrap the given absolute path in `AbsPathBuf`
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()))
82 /// Coerces to an `AbsPath` slice.
84 /// Equivalent of [`PathBuf::as_path`] for `AbsPathBuf`.
85 pub fn as_path(&self) -> &AbsPath {
86 AbsPath::assert(self.0.as_path())
89 /// Equivalent of [`PathBuf::pop`] for `AbsPathBuf`.
91 /// Note that this won't remove the root component, so `self` will still be
93 pub fn pop(&mut self) -> bool {
98 /// Wrapper around an absolute [`Path`].
99 #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
101 pub struct AbsPath(Path);
103 impl AsRef<Path> for AbsPath {
104 fn as_ref(&self) -> &Path {
109 impl ToOwned for AbsPath {
110 type Owned = AbsPathBuf;
112 fn to_owned(&self) -> Self::Owned {
113 AbsPathBuf(self.0.to_owned())
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() {
123 Ok(AbsPath::assert(path))
128 /// Wrap the given absolute path in `AbsPath`
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) }
138 /// Equivalent of [`Path::parent`] for `AbsPath`.
139 pub fn parent(&self) -> Option<&AbsPath> {
140 self.0.parent().map(AbsPath::assert)
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()
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`.
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()));
160 pub fn normalize(&self) -> AbsPathBuf {
161 AbsPathBuf(normalize_path(&self.0))
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()
169 /// Equivalent of [`Path::strip_prefix`] for `AbsPath`.
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)
175 pub fn starts_with(&self, base: &AbsPath) -> bool {
176 self.0.starts_with(&base.0)
178 pub fn ends_with(&self, suffix: &RelPath) -> bool {
179 self.0.ends_with(&suffix.0)
182 // region:delegate-methods
184 // Note that we deliberately don't implement `Deref<Target = Path>` here.
186 // The problem with `Path` is that it directly exposes convenience IO-ing
187 // methods. For example, `Path::exists` delegates to `fs::metadata`.
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.
192 pub fn file_name(&self) -> Option<&OsStr> {
195 pub fn extension(&self) -> Option<&OsStr> {
198 pub fn file_stem(&self) -> Option<&OsStr> {
201 pub fn as_os_str(&self) -> &OsStr {
204 pub fn display(&self) -> std::path::Display<'_> {
207 #[deprecated(note = "use std::fs::metadata().is_ok() instead")]
208 pub fn exists(&self) -> bool {
211 // endregion:delegate-methods
214 /// Wrapper around a relative [`PathBuf`].
215 #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
216 pub struct RelPathBuf(PathBuf);
218 impl From<RelPathBuf> for PathBuf {
219 fn from(RelPathBuf(path_buf): RelPathBuf) -> PathBuf {
224 impl ops::Deref for RelPathBuf {
225 type Target = RelPath;
226 fn deref(&self) -> &RelPath {
231 impl AsRef<Path> for RelPathBuf {
232 fn as_ref(&self) -> &Path {
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);
243 Ok(RelPathBuf(path_buf))
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))
255 /// Coerces to a `RelPath` slice.
257 /// Equivalent of [`PathBuf::as_path`] for `RelPathBuf`.
258 pub fn as_path(&self) -> &RelPath {
259 RelPath::new_unchecked(self.0.as_path())
263 /// Wrapper around a relative [`Path`].
264 #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
266 pub struct RelPath(Path);
268 impl AsRef<Path> for RelPath {
269 fn as_ref(&self) -> &Path {
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) }
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() {
286 PathBuf::from(c.as_os_str())
291 for component in components {
293 Component::Prefix(..) => unreachable!(),
294 Component::RootDir => {
295 ret.push(component.as_os_str());
297 Component::CurDir => {}
298 Component::ParentDir => {
301 Component::Normal(c) => {