Skip to main content

fs_err/
path.rs

1#[allow(unused_imports)]
2use crate::errors::{Error, ErrorKind};
3use std::fs;
4use std::io;
5use std::path::{Path, PathBuf};
6
7use crate as fs_err; // for docs
8
9/// Defines aliases on [`std::path::Path`] for fs-err functions.
10///
11/// This trait is sealed and can not be implemented by other crates.
12//
13// Because no one else can implement it, we can add methods backwards-compatibly.
14pub trait PathExt: crate::Sealed {
15    /// Returns Ok(true) if the path points at an existing entity.
16    ///
17    /// Wrapper for [`std::path::Path::try_exists`].
18    #[cfg(rustc_1_63)]
19    fn fs_err_try_exists(&self) -> io::Result<bool>;
20    /// Given a path, query the file system to get information about a file, directory, etc.
21    ///
22    /// Wrapper for [`fs_err::metadata`].
23    fn fs_err_metadata(&self) -> io::Result<fs::Metadata>;
24    /// Query the metadata about a file without following symlinks.
25    ///
26    /// Wrapper for [`fs_err::symlink_metadata`].
27    fn fs_err_symlink_metadata(&self) -> io::Result<fs::Metadata>;
28    /// Returns the canonical, absolute form of a path with all intermediate components
29    /// normalized and symbolic links resolved.
30    ///
31    /// Wrapper for [`fs_err::canonicalize`].
32    fn fs_err_canonicalize(&self) -> io::Result<PathBuf>;
33    /// Reads a symbolic link, returning the file that the link points to.
34    ///
35    /// Wrapper for [`fs_err::read_link`].
36    fn fs_err_read_link(&self) -> io::Result<PathBuf>;
37    /// Returns an iterator over the entries within a directory.
38    ///
39    /// Wrapper for [`fs_err::read_dir`].
40    fn fs_err_read_dir(&self) -> io::Result<fs_err::ReadDir>;
41}
42
43impl PathExt for Path {
44    #[cfg(rustc_1_63)]
45    fn fs_err_try_exists(&self) -> io::Result<bool> {
46        self.try_exists()
47            .map_err(|source| Error::build(source, ErrorKind::FileExists, self))
48    }
49
50    fn fs_err_metadata(&self) -> io::Result<fs::Metadata> {
51        crate::metadata(self)
52    }
53
54    fn fs_err_symlink_metadata(&self) -> io::Result<fs::Metadata> {
55        crate::symlink_metadata(self)
56    }
57
58    fn fs_err_canonicalize(&self) -> io::Result<PathBuf> {
59        crate::canonicalize(self)
60    }
61
62    fn fs_err_read_link(&self) -> io::Result<PathBuf> {
63        crate::read_link(self)
64    }
65
66    fn fs_err_read_dir(&self) -> io::Result<fs_err::ReadDir> {
67        crate::read_dir(self)
68    }
69}