Struct Root

Source
pub struct Root { /* private fields */ }
Expand description

An open root directory from which relative paths can be opened.

In contrast to using APIs such as RelativePath::to_path, this does not require allocations to open a path.

This is achieved by keeping an open handle to the directory and using platform-specific APIs to open a relative path, such as openat on unix.

Implementations§

Source§

impl Root

Source

pub fn new<P>(path: P) -> Result<Self>
where P: AsRef<Path>,

Open the given directory that can be used as a root for opening and manipulating relative paths.

§Errors

Errors if the underlying I/O operation fails.

§Examples
use relative_path_utils::Root;

let root = Root::new(".")?;
Source

pub fn open_options(&self) -> OpenOptions<'_>

Construct an open options associated with this root.

§Examples
use relative_path_utils::Root;

let root = Root::new(".")?;

let file = root.open_options().read(true).open("foo.txt");
Source

pub fn create<P>(&self, path: P) -> Result<File>
where P: AsRef<RelativePath>,

Opens a file in write-only mode.

This function will create a file if it does not exist, and will truncate it if it does.

Depending on the platform, this function may fail if the full directory path does not exist. See the OpenOptions::open function for more details.

See also Root::write() for a simple function to create a file with a given data.

§Errors

Errors if the underlying I/O operation fails.

§Examples
use std::io::Write;

use relative_path_utils::Root;

let root = Root::new(".")?;

let mut f = root.create("foo.txt")?;
f.write_all(&1234_u32.to_be_bytes())?;
Source

pub fn open<P>(&self, path: P) -> Result<File>
where P: AsRef<RelativePath>,

Attempts to open a file in read-only mode.

See the OpenOptions::open method for more details.

If you only need to read the entire file contents, consider std::fs::read() or std::fs::read_to_string() instead.

§Errors

This function will return an error if path does not already exist. Other errors may also be returned according to OpenOptions::open.

§Examples
use std::io::Read;

use relative_path_utils::Root;

let root = Root::new(".")?;

let mut f = root.open("foo.txt")?;
let mut data = vec![];
f.read_to_end(&mut data)?;
Source

pub fn read<P>(&self, path: P) -> Result<Vec<u8>>
where P: AsRef<RelativePath>,

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.

§Errors

This function will return an error if path does not already exist. Other errors may also be returned according to OpenOptions::open.

While reading from the file, this function handles io::ErrorKind::Interrupted with automatic retries. See io::Read documentation for details.

§Examples
use std::net::SocketAddr;

use relative_path_utils::Root;

let root = Root::new(".")?;
let foo: SocketAddr = String::from_utf8_lossy(&root.read("address.txt")?).parse()?;
Source

pub fn read_to_string<P>(&self, path: P) -> Result<String>
where P: AsRef<RelativePath>,

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.

§Errors

This function will return an error if path does not already exist. Other errors may also be returned according to OpenOptions::open.

If the contents of the file are not valid UTF-8, then an error will also be returned.

§Examples
use std::net::SocketAddr;

use relative_path_utils::Root;

let root = Root::new(".")?;
let foo: SocketAddr = root.read_to_string("address.txt")?.parse()?;
Source

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

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.

§Errors

Fails if an underlying I/O operation fails.

§Examples
use relative_path_utils::Root;

let root = Root::new(".")?;

root.write("foo.txt", b"Lorem ipsum")?;
root.write("bar.txt", "dolor sit")?;
Source

pub fn metadata<P>(&self, path: P) -> Result<Metadata>
where P: AsRef<RelativePath>,

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.

§Platform-specific behavior

This function currently corresponds to the stat function on Unix and the GetFileInformationByHandle function on Windows. Note that, this may change in the future.

§Errors

This function will return an error in the following situations, but is not limited to just these cases:

  • The user lacks permissions to perform metadata call on path.
  • path does not exist.
§Examples
use relative_path_utils::Root;

let root = Root::new(".")?;
let attr = root.metadata("file/path.txt")?;
Source

pub fn is_dir<P>(&self, path: P) -> bool
where P: AsRef<RelativePath>,

Returns true if the path exists on disk and is pointing at a directory.

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.

§Examples
use relative_path_utils::Root;

let root = Root::new(".")?;

assert_eq!(root.is_dir("./is_a_directory/"), true);
assert_eq!(root.is_dir("a_file.txt"), false);
§See Also

This is a convenience function that coerces errors to false. If you want to check errors, call Root::metadata and handle its Result. Then call Metadata::is_dir if it was Ok.

Source

pub fn read_dir<P>(&self, path: P) -> Result<ReadDir>
where P: AsRef<RelativePath>,

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.

§Platform-specific behavior

This function currently corresponds to the opendir function on Unix and the FindFirstFile function on Windows. Advancing the iterator currently corresponds to readdir on Unix and FindNextFile on Windows. Note that, this may change in the future.

The order in which this iterator returns entries is platform and filesystem dependent.

§Errors

This function will return an error in the following situations, but is not limited to just these cases:

  • The provided path doesn’t exist.
  • The process lacks permissions to view the contents.
  • The path points at a non-directory file.
§Examples
use std::io;

use relative_path_utils::{Root, DirEntry};
use relative_path::RelativePath;

// one possible implementation of walking a directory only visiting files
fn visit_dirs(root: &Root, dir: &RelativePath, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
    if root.is_dir(dir) {
        for entry in root.read_dir(dir)? {
            let entry = entry?;
            let file_name = entry.file_name();
            let path = dir.join(file_name.to_string_lossy().as_ref());

            if root.is_dir(&path) {
                visit_dirs(root, &path, cb)?;
            } else {
                cb(&entry);
            }
        }
    }

    Ok(())
}
Source

pub fn glob<'a, P>(&'a self, path: &'a P) -> Glob<'a>
where P: ?Sized + AsRef<RelativePath>,

Parse a glob over the specified path.

To perform the globbing, use Glob::matcher.

§Examples
use relative_path_utils::Root;

let root = Root::new("src")?;

let glob = root.glob("**/*.rs");

let mut results = Vec::new();

for e in glob.matcher() {
    results.push(e?);
}

results.sort();
assert_eq!(results, vec!["lib.rs", "main.rs"]);

Auto Trait Implementations§

§

impl Freeze for Root

§

impl RefUnwindSafe for Root

§

impl Send for Root

§

impl Sync for Root

§

impl Unpin for Root

§

impl UnwindSafe for Root

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.