1 //! Thin wrappers around `std::path`, distinguishing between absolute and
7 path::{Component, Path, PathBuf},
10 /// Wrapper around an absolute [`PathBuf`].
11 #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
12 pub struct AbsPathBuf(PathBuf);
14 impl From<AbsPathBuf> for PathBuf {
15 fn from(AbsPathBuf(path_buf): AbsPathBuf) -> PathBuf {
20 impl ops::Deref for AbsPathBuf {
21 type Target = AbsPath;
22 fn deref(&self) -> &AbsPath {
27 impl AsRef<Path> for AbsPathBuf {
28 fn as_ref(&self) -> &Path {
33 impl AsRef<AbsPath> for AbsPathBuf {
34 fn as_ref(&self) -> &AbsPath {
39 impl Borrow<AbsPath> for AbsPathBuf {
40 fn borrow(&self) -> &AbsPath {
45 impl TryFrom<PathBuf> for AbsPathBuf {
47 fn try_from(path_buf: PathBuf) -> Result<AbsPathBuf, PathBuf> {
48 if !path_buf.is_absolute() {
51 Ok(AbsPathBuf(path_buf))
55 impl TryFrom<&str> for AbsPathBuf {
57 fn try_from(path: &str) -> Result<AbsPathBuf, PathBuf> {
58 AbsPathBuf::try_from(PathBuf::from(path))
62 impl PartialEq<AbsPath> for AbsPathBuf {
63 fn eq(&self, other: &AbsPath) -> bool {
64 self.as_path() == other
69 /// Wrap the given absolute path in `AbsPathBuf`
73 /// Panics if `path` is not absolute.
74 pub fn assert(path: PathBuf) -> AbsPathBuf {
75 AbsPathBuf::try_from(path)
76 .unwrap_or_else(|path| panic!("expected absolute path, got {}", path.display()))
79 /// Coerces to an `AbsPath` slice.
81 /// Equivalent of [`PathBuf::as_path`] for `AbsPathBuf`.
82 pub fn as_path(&self) -> &AbsPath {
83 AbsPath::assert(self.0.as_path())
86 /// Equivalent of [`PathBuf::pop`] for `AbsPathBuf`.
88 /// Note that this won't remove the root component, so `self` will still be
90 pub fn pop(&mut self) -> bool {
95 /// Wrapper around an absolute [`Path`].
96 #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
98 pub struct AbsPath(Path);
100 impl AsRef<Path> for AbsPath {
101 fn as_ref(&self) -> &Path {
106 impl<'a> TryFrom<&'a Path> for &'a AbsPath {
107 type Error = &'a Path;
108 fn try_from(path: &'a Path) -> Result<&'a AbsPath, &'a Path> {
109 if !path.is_absolute() {
112 Ok(AbsPath::assert(path))
117 /// Wrap the given absolute path in `AbsPath`
121 /// Panics if `path` is not absolute.
122 pub fn assert(path: &Path) -> &AbsPath {
123 assert!(path.is_absolute());
124 unsafe { &*(path as *const Path as *const AbsPath) }
127 /// Equivalent of [`Path::parent`] for `AbsPath`.
128 pub fn parent(&self) -> Option<&AbsPath> {
129 self.0.parent().map(AbsPath::assert)
132 /// Equivalent of [`Path::join`] for `AbsPath`.
133 pub fn join(&self, path: impl AsRef<Path>) -> AbsPathBuf {
134 self.as_ref().join(path).try_into().unwrap()
137 /// Normalize the given path:
138 /// - Removes repeated separators: `/a//b` becomes `/a/b`
139 /// - Removes occurrences of `.` and resolves `..`.
140 /// - Removes trailing slashes: `/a/b/` becomes `/a/b`.
144 /// # use paths::AbsPathBuf;
145 /// let abs_path_buf = AbsPathBuf::assert("/a/../../b/.//c//".into());
146 /// let normalized = abs_path_buf.normalize();
147 /// assert_eq!(normalized, AbsPathBuf::assert("/b/c".into()));
149 pub fn normalize(&self) -> AbsPathBuf {
150 AbsPathBuf(normalize_path(&self.0))
153 /// Equivalent of [`Path::to_path_buf`] for `AbsPath`.
154 pub fn to_path_buf(&self) -> AbsPathBuf {
155 AbsPathBuf::try_from(self.0.to_path_buf()).unwrap()
158 /// Equivalent of [`Path::strip_prefix`] for `AbsPath`.
160 /// Returns a relative path.
161 pub fn strip_prefix(&self, base: &AbsPath) -> Option<&RelPath> {
162 self.0.strip_prefix(base).ok().map(RelPath::new_unchecked)
164 pub fn starts_with(&self, base: &AbsPath) -> bool {
165 self.0.starts_with(&base.0)
167 pub fn ends_with(&self, suffix: &RelPath) -> bool {
168 self.0.ends_with(&suffix.0)
171 // region:delegate-methods
173 // Note that we deliberately don't implement `Deref<Target = Path>` here.
175 // The problem with `Path` is that it directly exposes convenience IO-ing
176 // methods. For example, `Path::exists` delegates to `fs::metadata`.
178 // For `AbsPath`, we want to make sure that this is a POD type, and that all
179 // IO goes via `fs`. That way, it becomes easier to mock IO when we need it.
181 pub fn file_name(&self) -> Option<&OsStr> {
184 pub fn extension(&self) -> Option<&OsStr> {
187 pub fn file_stem(&self) -> Option<&OsStr> {
190 pub fn as_os_str(&self) -> &OsStr {
193 pub fn display(&self) -> std::path::Display<'_> {
196 #[deprecated(note = "use std::fs::metadata().is_ok() instead")]
197 pub fn exists(&self) -> bool {
200 // endregion:delegate-methods
203 /// Wrapper around a relative [`PathBuf`].
204 #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
205 pub struct RelPathBuf(PathBuf);
207 impl From<RelPathBuf> for PathBuf {
208 fn from(RelPathBuf(path_buf): RelPathBuf) -> PathBuf {
213 impl ops::Deref for RelPathBuf {
214 type Target = RelPath;
215 fn deref(&self) -> &RelPath {
220 impl AsRef<Path> for RelPathBuf {
221 fn as_ref(&self) -> &Path {
226 impl TryFrom<PathBuf> for RelPathBuf {
227 type Error = PathBuf;
228 fn try_from(path_buf: PathBuf) -> Result<RelPathBuf, PathBuf> {
229 if !path_buf.is_relative() {
230 return Err(path_buf);
232 Ok(RelPathBuf(path_buf))
236 impl TryFrom<&str> for RelPathBuf {
237 type Error = PathBuf;
238 fn try_from(path: &str) -> Result<RelPathBuf, PathBuf> {
239 RelPathBuf::try_from(PathBuf::from(path))
244 /// Coerces to a `RelPath` slice.
246 /// Equivalent of [`PathBuf::as_path`] for `RelPathBuf`.
247 pub fn as_path(&self) -> &RelPath {
248 RelPath::new_unchecked(self.0.as_path())
252 /// Wrapper around a relative [`Path`].
253 #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
255 pub struct RelPath(Path);
257 impl AsRef<Path> for RelPath {
258 fn as_ref(&self) -> &Path {
264 /// Creates a new `RelPath` from `path`, without checking if it is relative.
265 pub fn new_unchecked(path: &Path) -> &RelPath {
266 unsafe { &*(path as *const Path as *const RelPath) }
270 /// Taken from <https://github.com/rust-lang/cargo/blob/79c769c3d7b4c2cf6a93781575b7f592ef974255/src/cargo/util/paths.rs#L60-L85>
271 fn normalize_path(path: &Path) -> PathBuf {
272 let mut components = path.components().peekable();
273 let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().copied() {
275 PathBuf::from(c.as_os_str())
280 for component in components {
282 Component::Prefix(..) => unreachable!(),
283 Component::RootDir => {
284 ret.push(component.as_os_str());
286 Component::CurDir => {}
287 Component::ParentDir => {
290 Component::Normal(c) => {