Skip to main content

vfs_kit/
core.rs

1use std::path::Path;
2use crate::DirEntry;
3
4/// FsBackend defines a common API for all virtual file systems (vfs) in the crate.
5/// Some functions here use `path` as a parameter or return value.
6/// In all cases, `path` will refer to the virtual file system. The exception
7/// is the `root()` function, which returns the path in the host file system.
8pub trait FsBackend {
9    /// Returns root path refer to the host file system.
10    fn root(&self) -> &Path;
11
12    /// Returns current working directory related to the vfs root.
13    fn cwd(&self) -> &Path;
14
15    /// Changes the current working directory.
16    /// `path` can be in relative or absolute form, but in both cases it must exist in vfs.
17    /// Error returns in case the `path` is not exist.
18    fn cd<P: AsRef<Path>>(&mut self, path: P) -> Result<()>;
19
20    /// Returns true, if `path` exists.
21    fn exists<P: AsRef<Path>>(&self, path: P) -> bool;
22    
23    /// Returns an iterator over directory entries.
24    /// `path` is a directory, or CWD if None.
25    fn ls<P: AsRef<Path>>(&self, path: P) -> Result<impl Iterator<Item = DirEntry>>;
26
27    /// Returns a recursive iterator over the directory tree starting from a given path.
28    fn tree<P: AsRef<Path>>(&self, path: P) -> Result<impl Iterator<Item = DirEntry>>;
29
30    /// Creates directory and all it parents, if necessary.
31    fn mkdir<P: AsRef<Path>>(&mut self, path: P) -> Result<()>;
32
33    /// Creates new file in vfs.
34    fn mkfile<P: AsRef<Path>>(&mut self, name: P, content: Option<&[u8]>) -> Result<()>;
35    
36    /// Reads the entire contents of a file into a byte vector.
37    fn read<P: AsRef<Path>>(&self, path: P) -> Result<Vec<u8>>;
38
39    /// Writes bytes to an existing file, replacing its entire contents.
40    fn write<P: AsRef<Path>>(&self, path: P, content: &[u8]) -> Result<()>;
41
42    /// Appends bytes to the end of an existing file, preserving its old contents.
43    fn append<P: AsRef<Path>>(&self, path: P, content: &[u8]) -> Result<()>;
44
45    /// Removes a file or directory at the specified path.
46    fn rm<P: AsRef<Path>>(&mut self, path: P) -> Result<()>;
47
48    /// Removes all artifacts (dirs and files) in vfs, but preserve its root.
49    fn cleanup(&mut self) -> bool;
50}
51
52pub type Result<T> = std::result::Result<T, anyhow::Error>;