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
69 impl serde::Serialize for AbsPathBuf {
70 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
74 self.0.serialize(serializer)
78 impl<'de> serde::Deserialize<'de> for AbsPathBuf {
79 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
81 D: serde::Deserializer<'de>,
83 let path = PathBuf::deserialize(deserializer)?;
84 AbsPathBuf::try_from(path).map_err(|path| {
85 serde::de::Error::custom(format!("expected absolute path, got {}", path.display()))
91 /// Wrap the given absolute path in `AbsPathBuf`
95 /// Panics if `path` is not absolute.
96 pub fn assert(path: PathBuf) -> AbsPathBuf {
97 AbsPathBuf::try_from(path)
98 .unwrap_or_else(|path| panic!("expected absolute path, got {}", path.display()))
101 /// Coerces to an `AbsPath` slice.
103 /// Equivalent of [`PathBuf::as_path`] for `AbsPathBuf`.
104 pub fn as_path(&self) -> &AbsPath {
105 AbsPath::assert(self.0.as_path())
108 /// Equivalent of [`PathBuf::pop`] for `AbsPathBuf`.
110 /// Note that this won't remove the root component, so `self` will still be
112 pub fn pop(&mut self) -> bool {
117 /// Wrapper around an absolute [`Path`].
118 #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
120 pub struct AbsPath(Path);
122 impl AsRef<Path> for AbsPath {
123 fn as_ref(&self) -> &Path {
128 impl<'a> TryFrom<&'a Path> for &'a AbsPath {
129 type Error = &'a Path;
130 fn try_from(path: &'a Path) -> Result<&'a AbsPath, &'a Path> {
131 if !path.is_absolute() {
134 Ok(AbsPath::assert(path))
139 /// Wrap the given absolute path in `AbsPath`
143 /// Panics if `path` is not absolute.
144 pub fn assert(path: &Path) -> &AbsPath {
145 assert!(path.is_absolute());
146 unsafe { &*(path as *const Path as *const AbsPath) }
149 /// Equivalent of [`Path::parent`] for `AbsPath`.
150 pub fn parent(&self) -> Option<&AbsPath> {
151 self.0.parent().map(AbsPath::assert)
154 /// Equivalent of [`Path::join`] for `AbsPath`.
155 pub fn join(&self, path: impl AsRef<Path>) -> AbsPathBuf {
156 self.as_ref().join(path).try_into().unwrap()
159 /// Normalize the given path:
160 /// - Removes repeated separators: `/a//b` becomes `/a/b`
161 /// - Removes occurrences of `.` and resolves `..`.
162 /// - Removes trailing slashes: `/a/b/` becomes `/a/b`.
166 /// # use paths::AbsPathBuf;
167 /// let abs_path_buf = AbsPathBuf::assert("/a/../../b/.//c//".into());
168 /// let normalized = abs_path_buf.normalize();
169 /// assert_eq!(normalized, AbsPathBuf::assert("/b/c".into()));
171 pub fn normalize(&self) -> AbsPathBuf {
172 AbsPathBuf(normalize_path(&self.0))
175 /// Equivalent of [`Path::to_path_buf`] for `AbsPath`.
176 pub fn to_path_buf(&self) -> AbsPathBuf {
177 AbsPathBuf::try_from(self.0.to_path_buf()).unwrap()
180 /// Equivalent of [`Path::strip_prefix`] for `AbsPath`.
182 /// Returns a relative path.
183 pub fn strip_prefix(&self, base: &AbsPath) -> Option<&RelPath> {
184 self.0.strip_prefix(base).ok().map(RelPath::new_unchecked)
186 pub fn starts_with(&self, base: &AbsPath) -> bool {
187 self.0.starts_with(&base.0)
189 pub fn ends_with(&self, suffix: &RelPath) -> bool {
190 self.0.ends_with(&suffix.0)
193 // region:delegate-methods
195 // Note that we deliberately don't implement `Deref<Target = Path>` here.
197 // The problem with `Path` is that it directly exposes convenience IO-ing
198 // methods. For example, `Path::exists` delegates to `fs::metadata`.
200 // For `AbsPath`, we want to make sure that this is a POD type, and that all
201 // IO goes via `fs`. That way, it becomes easier to mock IO when we need it.
203 pub fn file_name(&self) -> Option<&OsStr> {
206 pub fn extension(&self) -> Option<&OsStr> {
209 pub fn file_stem(&self) -> Option<&OsStr> {
212 pub fn as_os_str(&self) -> &OsStr {
215 pub fn display(&self) -> std::path::Display<'_> {
218 #[deprecated(note = "use std::fs::metadata().is_ok() instead")]
219 pub fn exists(&self) -> bool {
222 // endregion:delegate-methods
225 /// Wrapper around a relative [`PathBuf`].
226 #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
227 pub struct RelPathBuf(PathBuf);
229 impl From<RelPathBuf> for PathBuf {
230 fn from(RelPathBuf(path_buf): RelPathBuf) -> PathBuf {
235 impl ops::Deref for RelPathBuf {
236 type Target = RelPath;
237 fn deref(&self) -> &RelPath {
242 impl AsRef<Path> for RelPathBuf {
243 fn as_ref(&self) -> &Path {
248 impl TryFrom<PathBuf> for RelPathBuf {
249 type Error = PathBuf;
250 fn try_from(path_buf: PathBuf) -> Result<RelPathBuf, PathBuf> {
251 if !path_buf.is_relative() {
252 return Err(path_buf);
254 Ok(RelPathBuf(path_buf))
258 impl TryFrom<&str> for RelPathBuf {
259 type Error = PathBuf;
260 fn try_from(path: &str) -> Result<RelPathBuf, PathBuf> {
261 RelPathBuf::try_from(PathBuf::from(path))
266 /// Coerces to a `RelPath` slice.
268 /// Equivalent of [`PathBuf::as_path`] for `RelPathBuf`.
269 pub fn as_path(&self) -> &RelPath {
270 RelPath::new_unchecked(self.0.as_path())
274 /// Wrapper around a relative [`Path`].
275 #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
277 pub struct RelPath(Path);
279 impl AsRef<Path> for RelPath {
280 fn as_ref(&self) -> &Path {
286 /// Creates a new `RelPath` from `path`, without checking if it is relative.
287 pub fn new_unchecked(path: &Path) -> &RelPath {
288 unsafe { &*(path as *const Path as *const RelPath) }
292 /// Taken from <https://github.com/rust-lang/cargo/blob/79c769c3d7b4c2cf6a93781575b7f592ef974255/src/cargo/util/paths.rs#L60-L85>
293 fn normalize_path(path: &Path) -> PathBuf {
294 let mut components = path.components().peekable();
295 let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
297 PathBuf::from(c.as_os_str())
302 for component in components {
304 Component::Prefix(..) => unreachable!(),
305 Component::RootDir => {
306 ret.push(component.as_os_str());
308 Component::CurDir => {}
309 Component::ParentDir => {
312 Component::Normal(c) => {