Skip to main content

DirFS

Struct DirFS 

Source
pub struct DirFS { /* private fields */ }

Implementations§

Source§

impl DirFS

A virtual filesystem (VFS) implementation that maps to a real directory on the host system.

DirFS provides an isolated, path‑normalized view of a portion of the filesystem, rooted at a designated absolute path (root). It maintains an internal state of valid paths and supports standard operations:

  • Navigate via cd() (change working directory).
  • Create directories (mkdir()) and files (mkfile()).
  • Remove entries (rm()).
  • Check existence (exists()).
  • Read and write content (read() / write() / append()).

Key features:

  • Path normalization: Automatically resolves ., .., and trailing slashes.
  • State consistency: Tracks all valid VFS paths to ensure operations reflect the actual VFS structure.
  • Isolated root: All operations are confined to the root directory; no access to parent paths.
  • Auto‑cleanup: Optionally removes created parent directories on drop (when is_auto_clean = true).
  • Cross‑platform: Uses std::path::Path for portable path handling.

Usage notes:

  • DirFS does not follow symlinks; rm() removes the link, not the target.
  • Permissions are not automatically adjusted; ensure root is writable.
  • Not thread‑safe in current version (wrap in Mutex if needed).
  • Errors are returned via anyhow::Result with descriptive messages.

Example:

use vfs_kit::{DirFS, FsBackend};

let tmp = std::env::temp_dir();
let root = tmp.join("my_vfs");

let mut fs = DirFS::new(root).unwrap();
fs.mkdir("/docs").unwrap();
fs.mkfile("/docs/note.txt", Some(b"Hello")).unwrap();
assert!(fs.exists("/docs/note.txt"));

fs.rm("/docs/note.txt").unwrap();
Source

pub fn new<P: AsRef<Path>>(root: P) -> Result<Self>

Creates a new DirFs instance with the root directory at path. Checks permissions to create and write into path.

  • path is an absolute host path. If path is not absolute, error returns.
Source

pub fn set_auto_clean(&mut self, clean: bool)

Changes auto-clean flag. If auto-clean flag is true all created in vfs artifacts will be removed on drop.

Trait Implementations§

Source§

impl Drop for DirFS

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl FsBackend for DirFS

Source§

fn root(&self) -> &Path

Returns root path related to the host file system.

Source§

fn cwd(&self) -> &Path

Returns current working directory related to the vfs root.

Source§

fn cd<P: AsRef<Path>>(&mut self, path: P) -> Result<()>

Changes the current working directory.

  • path can be in relative or absolute form, but in both cases it must exist. An error is returned if the specified path does not exist.
Source§

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

Checks if a path exists in the vfs. The path can be:

  • absolute (starting with ‘/’),
  • relative (relative to the vfs cwd),
  • contain ‘..’ or ‘.’.
Source§

fn mkdir<P: AsRef<Path>>(&mut self, path: P) -> Result<()>

Creates directory and all it parents (if needed).

  • path - inner vfs path.
Source§

fn mkfile<P: AsRef<Path>>( &mut self, file_path: P, content: Option<&[u8]>, ) -> Result<()>

Creates new file in vfs.

  • file_path must be inner vfs path. It must contain the name of the file, optionally preceded by existing parent directory. If the parent directory does not exist, an error is returned.
Source§

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

Reads the entire contents of a file into a byte vector.

  • path is the inner VFS path.
§Returns
  • Ok(Vec<u8>) - File content as a byte vector if successful.
  • Err(anyhow::Error) - If any of the following occurs:
    • File does not exist in VFS (file does not exist: ...)
    • Path points to a directory (... is a directory)
    • Permission issues when accessing the host file
    • I/O errors during reading
§Notes
  • Does not follow symbolic links on the host filesystem (reads the link itself).
  • Returns an empty vector for empty files.
Source§

fn write<P: AsRef<Path>>(&self, path: P, content: &[u8]) -> Result<()>

Writes bytes to an existing file, replacing its entire contents.

  • path - Path to the file.
  • content - Byte slice (&[u8]) to write to the file.
§Returns
  • Ok(()) - If the write operation succeeded.
  • Err(anyhow::Error) - If any of the following occurs:
    • File does not exist in VFS (file does not exist: ...)
    • Path points to a directory (... is a directory)
    • Permission issues when accessing the host file
    • I/O errors during writing (e.g., disk full, invalid path)
§Behavior
  • Overwrites completely: The entire existing content is replaced.
  • No file creation: File must exist (use mkfile() first).
  • Atomic operation: Uses std::fs::write() which replaces the file in one step.
  • Permissions: The file retains its original permissions (no chmod is performed).
Source§

fn append<P: AsRef<Path>>(&self, path: P, content: &[u8]) -> Result<()>

Appends bytes to the end of an existing file, preserving its old contents.

§Arguments
  • path - Path to the existing file.
  • content - Byte slice (&[u8]) to append to the file.
§Returns
  • Ok(()) - If the append operation succeeded.
  • Err(anyhow::Error) - If any of the following occurs:
    • File does not exist in VFS (file does not exist: ...)
    • Path points to a directory (... is a directory)
    • Permission issues when accessing the host file
    • I/O errors during writing (e.g., disk full, invalid path)
§Behavior
  • Appends only: Existing content is preserved; new bytes are added at the end.
  • No parent creation: Parent directories must exist (use mkdir() first if needed).
  • File creation: Does NOT create the file if it doesn’t exist (returns error).
  • Permissions: The file retains its original permissions.
Source§

fn rm<P: AsRef<Path>>(&mut self, path: P) -> Result<()>

Removes a file or directory at the specified path.

  • path: can be absolute (starting with ‘/’) or relative to the current working directory (cwd).
  • If the path is a directory, all its contents are removed recursively.

Returns:

  • Ok(()) on successful removal.
  • Err(_) if:
    • the path does not exist in the VFS;
    • there are insufficient permissions;
    • a filesystem error occurs.
Source§

fn cleanup(&mut self) -> bool

Removes all artifacts (dirs and files) in vfs, but preserve its root.

Auto Trait Implementations§

§

impl Freeze for DirFS

§

impl RefUnwindSafe for DirFS

§

impl Send for DirFS

§

impl Sync for DirFS

§

impl Unpin for DirFS

§

impl UnwindSafe for DirFS

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.