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<'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() {
115 Ok(AbsPath::assert(path))
120 /// Wrap the given absolute path in `AbsPath`
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) }
130 /// Equivalent of [`Path::parent`] for `AbsPath`.
131 pub fn parent(&self) -> Option<&AbsPath> {
132 self.0.parent().map(AbsPath::assert)
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()
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`.
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()));
152 pub fn normalize(&self) -> AbsPathBuf {
153 AbsPathBuf(normalize_path(&self.0))
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()
161 /// Equivalent of [`Path::strip_prefix`] for `AbsPath`.
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)
167 pub fn starts_with(&self, base: &AbsPath) -> bool {
168 self.0.starts_with(&base.0)
170 pub fn ends_with(&self, suffix: &RelPath) -> bool {
171 self.0.ends_with(&suffix.0)
174 // region:delegate-methods
176 // Note that we deliberately don't implement `Deref<Target = Path>` here.
178 // The problem with `Path` is that it directly exposes convenience IO-ing
179 // methods. For example, `Path::exists` delegates to `fs::metadata`.
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.
184 pub fn file_name(&self) -> Option<&OsStr> {
187 pub fn extension(&self) -> Option<&OsStr> {
190 pub fn file_stem(&self) -> Option<&OsStr> {
193 pub fn as_os_str(&self) -> &OsStr {
196 pub fn display(&self) -> std::path::Display<'_> {
199 #[deprecated(note = "use std::fs::metadata().is_ok() instead")]
200 pub fn exists(&self) -> bool {
203 // endregion:delegate-methods
206 /// Wrapper around a relative [`PathBuf`].
207 #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
208 pub struct RelPathBuf(PathBuf);
210 impl From<RelPathBuf> for PathBuf {
211 fn from(RelPathBuf(path_buf): RelPathBuf) -> PathBuf {
216 impl ops::Deref for RelPathBuf {
217 type Target = RelPath;
218 fn deref(&self) -> &RelPath {
223 impl AsRef<Path> for RelPathBuf {
224 fn as_ref(&self) -> &Path {
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);
235 Ok(RelPathBuf(path_buf))
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))
247 /// Coerces to a `RelPath` slice.
249 /// Equivalent of [`PathBuf::as_path`] for `RelPathBuf`.
250 pub fn as_path(&self) -> &RelPath {
251 RelPath::new_unchecked(self.0.as_path())
255 /// Wrapper around a relative [`Path`].
256 #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
258 pub struct RelPath(Path);
260 impl AsRef<Path> for RelPath {
261 fn as_ref(&self) -> &Path {
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) }
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() {
278 PathBuf::from(c.as_os_str())
283 for component in components {
285 Component::Prefix(..) => unreachable!(),
286 Component::RootDir => {
287 ret.push(component.as_os_str());
289 Component::CurDir => {}
290 Component::ParentDir => {
293 Component::Normal(c) => {