Dir

Struct Dir 

Source
#[repr(transparent)]
pub struct Dir<P>(pub P) where P: AsRef<Path>;
Expand description

Acts as a Working Directory. Provides a variety of functions to manipulate and query directories and files in the context of that directory.

Tuple Fields§

§0: P

Implementations§

Source§

impl<P> Dir<P>
where P: AsRef<Path>,

Source

pub fn join<P2: AsRef<Path>>(&self, path: P2) -> PathBuf

Join this working dir with some path

Source

pub fn open<P2: AsRef<Path>>( &self, path: P2, opts: &OpenOptions, ) -> Result<File>

Opens a file with the given OpenOptions

Source

pub fn open_readonly<P2: AsRef<Path>>(&self, path: P2) -> Result<File>

Opens a file in read-only mode

See: std::fs::File::open

Source

pub fn create_parents<P2: AsRef<Path>>(&self, path: P2) -> Result<()>

Creates any parent directories for a given path. Does nothing if the path has no parents.

§Errors

This function returns an error if the creation of the parent directories fails

Examples found in repository?
examples/working_dir.rs (line 8)
4fn main() -> Result<()> {
5    let cwd = Dir::new("my/root");
6    let path = Path::new("path/to/file.txt");
7
8    cwd.create_parents(path)?;
9
10    cwd.write(path, "Hello, world!\n")?;
11
12    // This path *shouldn't* exist in the program's global working directory
13    assert!(!path.exists());
14
15    // But it *should* exist in the directory specified by cwd
16    assert!(cwd.exists(path));
17
18    // This should be the same as the previous assert
19    assert!(Path::new("my/root/path/to/file.txt").exists());
20
21    // Check that the content is what we expect
22    assert_eq!(cwd.read_to_string(path)?, "Hello, world!\n");
23
24    let other_cwd = Dir::new("some/other/root");
25
26    cwd.move_to(&other_cwd, path)?;
27
28    // Now we should exist in the other directory
29    assert!(!cwd.exists(path));
30    assert!(other_cwd.exists(path));
31
32    Ok(())
33}
Source

pub fn exists<P2: AsRef<Path>>(&self, path: P2) -> bool

Returns true if the path points at an existing entity.

Warning: this method may be error-prone, consider using try_exists() instead! It also has a risk of introducing time-of-check to time-of-use (TOCTOU) bugs.

This function will traverse symbolic links to query information about the destination file.

If you cannot access the metadata of the file, e.g. because of a permission error or broken symbolic links, this will return false.

See: std::path::Path::exists

Examples found in repository?
examples/working_dir.rs (line 16)
4fn main() -> Result<()> {
5    let cwd = Dir::new("my/root");
6    let path = Path::new("path/to/file.txt");
7
8    cwd.create_parents(path)?;
9
10    cwd.write(path, "Hello, world!\n")?;
11
12    // This path *shouldn't* exist in the program's global working directory
13    assert!(!path.exists());
14
15    // But it *should* exist in the directory specified by cwd
16    assert!(cwd.exists(path));
17
18    // This should be the same as the previous assert
19    assert!(Path::new("my/root/path/to/file.txt").exists());
20
21    // Check that the content is what we expect
22    assert_eq!(cwd.read_to_string(path)?, "Hello, world!\n");
23
24    let other_cwd = Dir::new("some/other/root");
25
26    cwd.move_to(&other_cwd, path)?;
27
28    // Now we should exist in the other directory
29    assert!(!cwd.exists(path));
30    assert!(other_cwd.exists(path));
31
32    Ok(())
33}
Source

pub fn contains<P2: AsRef<Path>>(&self, path: P2) -> bool

Checks if this directory contains a given path. Alias for Dir::exists

Examples found in repository?
examples/include_set.rs (line 9)
5fn find_include<P: AsRef<Path>, Q: AsRef<Path>>(include_set: &[Dir<P>], file: Q) -> Option<PathBuf> {
6    let file = file.as_ref();
7
8    for include_dir in include_set {
9        if include_dir.contains(file) {
10            return Some(include_dir / file)
11        }
12    }
13    return None
14}
Source

pub fn try_exists<P2: AsRef<Path>>(&self, path: P2) -> Result<bool>

Returns Ok(true) if the path points at an existing entity.

This function will traverse symbolic links to query information about the destination file. In case of broken symbolic links this will return Ok(false).

As opposed to the exists() method, this one doesn’t silently ignore errors unrelated to the path not existing. (E.g. it will return Err(_) in case of permission denied on some of the parent directories.)

Note that while this avoids some pitfalls of the exists() method, it still can not prevent time-of-check to time-of-use (TOCTOU) bugs. You should only use it in scenarios where those bugs are not an issue.

See: std::path::Path::try_exists

Source

pub fn try_contains<P2: AsRef<Path>>(&self, path: P2) -> Result<bool>

Checks if this directory contains a given path. Alias for Dir::try_exists

Source

pub fn move_to<P2: AsRef<Path>, P3: AsRef<Path>>( &self, new_root: P2, path: P3, ) -> Result<()>

Moves a path from this working directory, to another working directory.

Suppose we have some path path/to/thing, corresponding to <self>/path/to/thing in the current working directory.

This function will move it to <B>/path/to/thing, in working directory B, creating any parent dirs as necessary

§Errors

This function will return an error in the following cases:

  • <working dir>/<path> does not exist (in which case, there is nothing to rename)
  • The user lacks permission to view the contents of the path.
  • The destination is on a separate filesystem
Examples found in repository?
examples/working_dir.rs (line 26)
4fn main() -> Result<()> {
5    let cwd = Dir::new("my/root");
6    let path = Path::new("path/to/file.txt");
7
8    cwd.create_parents(path)?;
9
10    cwd.write(path, "Hello, world!\n")?;
11
12    // This path *shouldn't* exist in the program's global working directory
13    assert!(!path.exists());
14
15    // But it *should* exist in the directory specified by cwd
16    assert!(cwd.exists(path));
17
18    // This should be the same as the previous assert
19    assert!(Path::new("my/root/path/to/file.txt").exists());
20
21    // Check that the content is what we expect
22    assert_eq!(cwd.read_to_string(path)?, "Hello, world!\n");
23
24    let other_cwd = Dir::new("some/other/root");
25
26    cwd.move_to(&other_cwd, path)?;
27
28    // Now we should exist in the other directory
29    assert!(!cwd.exists(path));
30    assert!(other_cwd.exists(path));
31
32    Ok(())
33}
Source

pub fn canonicalize<P2: AsRef<Path>>(&self, path: P2) -> Result<PathBuf>

Returns the canonical, absolute form of a path relative to the current working directory, with all intermediate components normalized and symbolic links resolved.

See: std::fs::canonicalize

Source

pub fn copy<P2: AsRef<Path>, P3: AsRef<Path>>( &self, from: P2, to: P3, ) -> Result<u64>

Copies the contents of one file to another. This function will also copy the permission bits of the original file to the destination file.

This function will overwrite the contents of to.

Note that if from and to both point to the same file, then the file will likely get truncated by this operation.

On success, the total number of bytes copied is returned and it is equal to the length of the to file as reported by metadata.

If you’re wanting to copy the contents of one file to another and you’re working with Files, see the io::copy() function.

See: std::fs::create_dir

Source

pub fn create_dir<P2: AsRef<Path>>(&self, path: P2) -> Result<()>

Creates a new, empty directory at the provided path

See: std::fs::create_dir

Source

pub fn create_dir_all<P2: AsRef<Path>>(&self, path: P2) -> Result<()>

Recursively create a directory and all of its parent components if they are missing.

See: std::fs::create_dir_all

Creates a new hard link on the filesystem.

The link path will be a link pointing to the original path. Note that systems often require these two paths to both be located on the same filesystem.

If original names a symbolic link, it is platform-specific whether the symbolic link is followed. On platforms where it’s possible to not follow it, it is not followed, and the created hard link points to the symbolic link itself.

See: std::fs::hard_link

Source

pub fn metadata<P2: AsRef<Path>>(&self, path: P2) -> Result<Metadata>

Given a path, query the file system to get information about a file, directory, etc.

This function will traverse symbolic links to query information about the destination file.

See: std::fs::metadata

Source

pub fn read<P2: AsRef<Path>>(&self, path: P2) -> Result<Vec<u8>>

Read the entire contents of a file into a bytes vector.

This is a convenience function for using File::open and read_to_end with fewer imports and without an intermediate variable.

See: std::fs::read

Source

pub fn read_dir<P2: AsRef<Path>>(&self, path: P2) -> Result<ReadDir>

Returns an iterator over the entries within a directory.

The iterator will yield instances of io::Result<DirEntry>. New errors may be encountered after an iterator is initially constructed. Entries for the current and parent directories (typically . and ..) are skipped.

See: std::fs::read_dir

Reads a symbolic link, returning the file that the link points to.

See: std::fs::read_link

Source

pub fn read_to_string<P2: AsRef<Path>>(&self, path: P2) -> Result<String>

Read the entire contents of a file into a string.

This is a convenience function for using File::open and read_to_string with fewer imports and without an intermediate variable.

See: std::fs::read_to_string

Examples found in repository?
examples/working_dir.rs (line 22)
4fn main() -> Result<()> {
5    let cwd = Dir::new("my/root");
6    let path = Path::new("path/to/file.txt");
7
8    cwd.create_parents(path)?;
9
10    cwd.write(path, "Hello, world!\n")?;
11
12    // This path *shouldn't* exist in the program's global working directory
13    assert!(!path.exists());
14
15    // But it *should* exist in the directory specified by cwd
16    assert!(cwd.exists(path));
17
18    // This should be the same as the previous assert
19    assert!(Path::new("my/root/path/to/file.txt").exists());
20
21    // Check that the content is what we expect
22    assert_eq!(cwd.read_to_string(path)?, "Hello, world!\n");
23
24    let other_cwd = Dir::new("some/other/root");
25
26    cwd.move_to(&other_cwd, path)?;
27
28    // Now we should exist in the other directory
29    assert!(!cwd.exists(path));
30    assert!(other_cwd.exists(path));
31
32    Ok(())
33}
Source

pub fn remove_dir<P2: AsRef<Path>>(&self, path: P2) -> Result<()>

Removes an empty directory.

See: std::fs::remove_dir

Source

pub fn remove_dir_all<P2: AsRef<Path>>(&self, path: P2) -> Result<()>

Removes a directory at this path, after removing all its contents. Use carefully!

This function does not follow symbolic links and it will simply remove the symbolic link itself.

See: std::fs::remove_dir_all

Source

pub fn remove_file<P2: AsRef<Path>>(&self, path: P2) -> Result<()>

Removes a file from the filesystem.

Note that there is no guarantee that the file is immediately deleted (e.g., depending on platform, other open file descriptors may prevent immediate removal).

See: std::fs::remove_file

Source

pub fn rename<P2: AsRef<Path>, P3: AsRef<Path>>( &self, from: P2, to: P3, ) -> Result<()>

Rename a file or directory to a new name, replacing the original file if to already exists.

This will not work if the new name is on a different mount point.

See: std::fs::rename

Query the metadata about a file without following symlinks.

See: std::fs::symlink_metadata

Source

pub fn write<P2: AsRef<Path>, C: AsRef<[u8]>>( &self, path: P2, contents: C, ) -> Result<()>

Write a slice as the entire contents of a file.

This function will create a file if it does not exist, and will entirely replace its contents if it does.

Depending on the platform, this function may fail if the full directory path does not exist.

This is a convenience function for using File::create and write_all with fewer imports.

See: std::fs::write

Examples found in repository?
examples/working_dir.rs (line 10)
4fn main() -> Result<()> {
5    let cwd = Dir::new("my/root");
6    let path = Path::new("path/to/file.txt");
7
8    cwd.create_parents(path)?;
9
10    cwd.write(path, "Hello, world!\n")?;
11
12    // This path *shouldn't* exist in the program's global working directory
13    assert!(!path.exists());
14
15    // But it *should* exist in the directory specified by cwd
16    assert!(cwd.exists(path));
17
18    // This should be the same as the previous assert
19    assert!(Path::new("my/root/path/to/file.txt").exists());
20
21    // Check that the content is what we expect
22    assert_eq!(cwd.read_to_string(path)?, "Hello, world!\n");
23
24    let other_cwd = Dir::new("some/other/root");
25
26    cwd.move_to(&other_cwd, path)?;
27
28    // Now we should exist in the other directory
29    assert!(!cwd.exists(path));
30    assert!(other_cwd.exists(path));
31
32    Ok(())
33}
Source§

impl<P> Dir<P>
where P: AsRef<Path>,

Source

pub fn new(path: P) -> Dir<P>

Creates a Dir from the given path

Examples found in repository?
examples/working_dir.rs (line 5)
4fn main() -> Result<()> {
5    let cwd = Dir::new("my/root");
6    let path = Path::new("path/to/file.txt");
7
8    cwd.create_parents(path)?;
9
10    cwd.write(path, "Hello, world!\n")?;
11
12    // This path *shouldn't* exist in the program's global working directory
13    assert!(!path.exists());
14
15    // But it *should* exist in the directory specified by cwd
16    assert!(cwd.exists(path));
17
18    // This should be the same as the previous assert
19    assert!(Path::new("my/root/path/to/file.txt").exists());
20
21    // Check that the content is what we expect
22    assert_eq!(cwd.read_to_string(path)?, "Hello, world!\n");
23
24    let other_cwd = Dir::new("some/other/root");
25
26    cwd.move_to(&other_cwd, path)?;
27
28    // Now we should exist in the other directory
29    assert!(!cwd.exists(path));
30    assert!(other_cwd.exists(path));
31
32    Ok(())
33}

Trait Implementations§

Source§

impl<P> AsRef<Path> for Dir<P>
where P: AsRef<Path>,

Source§

fn as_ref(&self) -> &Path

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl<P> Debug for Dir<P>
where P: AsRef<Path>,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<P, Q> Div<Q> for &Dir<P>
where P: AsRef<Path>, Q: AsRef<Path>,

Source§

type Output = PathBuf

The resulting type after applying the / operator.
Source§

fn div(self, rhs: Q) -> Self::Output

Performs the / operation. Read more
Source§

impl<P, Q> Div<Q> for Dir<P>
where P: AsRef<Path>, Q: AsRef<Path>,

Source§

type Output = PathBuf

The resulting type after applying the / operator.
Source§

fn div(self, rhs: Q) -> Self::Output

Performs the / operation. Read more
Source§

impl<P> From<P> for Dir<P>
where P: AsRef<Path>,

Source§

fn from(value: P) -> Self

Converts to this type from the input type.
Source§

impl<P> Ord for Dir<P>
where P: AsRef<Path> + Ord,

Source§

fn cmp(&self, other: &Dir<P>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<P> PartialEq for Dir<P>
where P: AsRef<Path> + PartialEq,

Source§

fn eq(&self, other: &Dir<P>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<P> PartialOrd for Dir<P>
where P: AsRef<Path> + PartialOrd,

Source§

fn partial_cmp(&self, other: &Dir<P>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<P> Eq for Dir<P>
where P: AsRef<Path> + Eq,

Source§

impl<P> StructuralPartialEq for Dir<P>
where P: AsRef<Path>,

Auto Trait Implementations§

§

impl<P> Freeze for Dir<P>
where P: Freeze,

§

impl<P> RefUnwindSafe for Dir<P>
where P: RefUnwindSafe,

§

impl<P> Send for Dir<P>
where P: Send,

§

impl<P> Sync for Dir<P>
where P: Sync,

§

impl<P> Unpin for Dir<P>
where P: Unpin,

§

impl<P> UnwindSafe for Dir<P>
where P: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.