1 //! Thin wrappers around `std::path`, distinguishing between absolute and
5 convert::{TryFrom, TryInto},
8 path::{Component, Path, PathBuf},
11 /// Wrapper around an absolute [`PathBuf`].
12 #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
13 pub struct AbsPathBuf(PathBuf);
15 impl From<AbsPathBuf> for PathBuf {
16 fn from(AbsPathBuf(path_buf): AbsPathBuf) -> PathBuf {
21 impl ops::Deref for AbsPathBuf {
22 type Target = AbsPath;
23 fn deref(&self) -> &AbsPath {
28 impl AsRef<Path> for AbsPathBuf {
29 fn as_ref(&self) -> &Path {
34 impl AsRef<AbsPath> for AbsPathBuf {
35 fn as_ref(&self) -> &AbsPath {
40 impl Borrow<AbsPath> for AbsPathBuf {
41 fn borrow(&self) -> &AbsPath {
46 impl TryFrom<PathBuf> for AbsPathBuf {
48 fn try_from(path_buf: PathBuf) -> Result<AbsPathBuf, PathBuf> {
49 if !path_buf.is_absolute() {
52 Ok(AbsPathBuf(path_buf))
56 impl TryFrom<&str> for AbsPathBuf {
58 fn try_from(path: &str) -> Result<AbsPathBuf, PathBuf> {
59 AbsPathBuf::try_from(PathBuf::from(path))
63 impl PartialEq<AbsPath> for AbsPathBuf {
64 fn eq(&self, other: &AbsPath) -> bool {
65 self.as_path() == other
70 /// Wrap the given absolute path in `AbsPathBuf`
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()))
80 /// Coerces to an `AbsPath` slice.
82 /// Equivalent of [`PathBuf::as_path`] for `AbsPathBuf`.
83 pub fn as_path(&self) -> &AbsPath {
84 AbsPath::assert(self.0.as_path())
87 /// Equivalent of [`PathBuf::pop`] for `AbsPathBuf`.
89 /// Note that this won't remove the root component, so `self` will still be
91 pub fn pop(&mut self) -> bool {
96 /// Wrapper around an absolute [`Path`].
97 #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
99 pub struct AbsPath(Path);
101 impl AsRef<Path> for AbsPath {
102 fn as_ref(&self) -> &Path {
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() {
113 Ok(AbsPath::assert(path))
118 /// Wrap the given absolute path in `AbsPath`
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) }
128 /// Equivalent of [`Path::parent`] for `AbsPath`.
129 pub fn parent(&self) -> Option<&AbsPath> {
130 self.0.parent().map(AbsPath::assert)
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()
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`.
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()));
150 pub fn normalize(&self) -> AbsPathBuf {
151 AbsPathBuf(normalize_path(&self.0))
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()
159 /// Equivalent of [`Path::strip_prefix`] for `AbsPath`.
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)
165 pub fn starts_with(&self, base: &AbsPath) -> bool {
166 self.0.starts_with(&base.0)
168 pub fn ends_with(&self, suffix: &RelPath) -> bool {
169 self.0.ends_with(&suffix.0)
172 // region:delegate-methods
174 // Note that we deliberately don't implement `Deref<Target = Path>` here.
176 // The problem with `Path` is that it directly exposes convenience IO-ing
177 // methods. For example, `Path::exists` delegates to `fs::metadata`.
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.
182 pub fn file_name(&self) -> Option<&OsStr> {
185 pub fn extension(&self) -> Option<&OsStr> {
188 pub fn file_stem(&self) -> Option<&OsStr> {
191 pub fn as_os_str(&self) -> &OsStr {
194 pub fn display(&self) -> std::path::Display<'_> {
197 #[deprecated(note = "use std::fs::metadata().is_ok() instead")]
198 pub fn exists(&self) -> bool {
201 // endregion:delegate-methods
204 /// Wrapper around a relative [`PathBuf`].
205 #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
206 pub struct RelPathBuf(PathBuf);
208 impl From<RelPathBuf> for PathBuf {
209 fn from(RelPathBuf(path_buf): RelPathBuf) -> PathBuf {
214 impl ops::Deref for RelPathBuf {
215 type Target = RelPath;
216 fn deref(&self) -> &RelPath {
221 impl AsRef<Path> for RelPathBuf {
222 fn as_ref(&self) -> &Path {
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);
233 Ok(RelPathBuf(path_buf))
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))
245 /// Coerces to a `RelPath` slice.
247 /// Equivalent of [`PathBuf::as_path`] for `RelPathBuf`.
248 pub fn as_path(&self) -> &RelPath {
249 RelPath::new_unchecked(self.0.as_path())
253 /// Wrapper around a relative [`Path`].
254 #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
256 pub struct RelPath(Path);
258 impl AsRef<Path> for RelPath {
259 fn as_ref(&self) -> &Path {
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) }
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() {
276 PathBuf::from(c.as_os_str())
281 for component in components {
283 Component::Prefix(..) => unreachable!(),
284 Component::RootDir => {
285 ret.push(component.as_os_str());
287 Component::CurDir => {}
288 Component::ParentDir => {
291 Component::Normal(c) => {