Skip to main content

vvv_engine/vfs/
mod.rs

1//! Virtual file system: the only way the engine touches files.
2//!
3//! Tests run against [`MemoryVfs`]; the CLI runs against [`DiskVfs`]; a plan
4//! that has to be planned *against* (the next step of a batch) is applied to
5//! an [`Overlay`] first. Because every read and write goes through the trait,
6//! the planners never know which.
7
8mod disk;
9mod memory;
10mod overlay;
11
12use std::path::{Path, PathBuf};
13
14pub use disk::DiskVfs;
15pub use memory::MemoryVfs;
16pub use overlay::Overlay;
17
18#[derive(Debug, thiserror::Error)]
19pub enum VfsError {
20    #[error("file not found: {0}")]
21    NotFound(PathBuf),
22    #[error("destination already exists: {0}")]
23    Exists(PathBuf),
24    #[error("{path}: not valid UTF-8")]
25    InvalidUtf8 { path: PathBuf },
26    #[error("{path}: {source}")]
27    Io {
28        path: PathBuf,
29        #[source]
30        source: std::io::Error,
31    },
32}
33
34/// The file effects of a failed move. Unknown outcomes require observation.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum MoveState {
37    Unchanged,
38    DestinationLinked,
39    Moved,
40    Unknown,
41}
42
43#[derive(Debug, thiserror::Error)]
44#[error("{source}")]
45pub struct MoveError {
46    #[source]
47    pub source: VfsError,
48    pub state: MoveState,
49}
50
51impl MoveError {
52    pub fn new(source: VfsError, state: MoveState) -> Self {
53        Self { source, state }
54    }
55
56    pub fn into_source(self) -> VfsError {
57        self.source
58    }
59}
60
61/// Parent directories created before a file mutation, including partial failure.
62#[derive(Debug)]
63pub struct ParentCreation {
64    pub created: Vec<PathBuf>,
65    pub result: Result<(), VfsError>,
66}
67
68impl ParentCreation {
69    pub fn new(created: Vec<PathBuf>, result: Result<(), VfsError>) -> Self {
70        Self { created, result }
71    }
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum EntryKind {
76    File,
77    Directory,
78    Other,
79}
80
81/// A cheap witness of a file's state: modification time and size on disk, a
82/// version counter in memory. Two equal stamps mean the contents could not
83/// have changed, which is what lets a warm corpus skip the read. Like `make`
84/// and `git`, it trusts the clock: an edit that keeps the length and lands
85/// within the same timestamp tick is invisible until the next one. Writes are
86/// never trusted to a stamp — `Plan::apply` checks content fingerprints.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
88pub struct Stamp {
89    modified: u128,
90    len: u64,
91}
92
93impl Stamp {
94    pub fn new(modified: u128, len: u64) -> Self {
95        Self { modified, len }
96    }
97}
98
99pub trait Vfs: Send + Sync {
100    fn read(&self, path: &Path) -> Result<String, VfsError>;
101    /// Raw inputs for validation, including non-UTF-8 resources.
102    fn read_bytes(&self, path: &Path) -> Result<Vec<u8>, VfsError> {
103        self.read(path).map(String::into_bytes)
104    }
105    /// The file's current [`Stamp`], without reading it.
106    fn stamp(&self, path: &Path) -> Result<Stamp, VfsError>;
107    /// Write a whole file, creating parent directories as needed.
108    fn write(&self, path: &Path, contents: &str) -> Result<(), VfsError>;
109    fn exists(&self, path: &Path) -> bool;
110    /// Inspect a directory entry without following its final symlink.
111    fn entry_kind(&self, path: &Path) -> Result<Option<EntryKind>, VfsError>;
112    /// Stored directory-entry spelling, rather than a requested case alias.
113    /// Case-sensitive implementations can use this default.
114    fn entry_path(&self, path: &Path) -> Result<Option<PathBuf>, VfsError> {
115        Ok(self.entry_kind(path)?.map(|_| path.to_path_buf()))
116    }
117
118    /// Whether two names would address one entry, even when the names are
119    /// currently absent. Overlay uses this to preserve the base's name policy.
120    /// Case-sensitive filesystems use lexical equality.
121    fn names_alias(&self, from: &Path, to: &Path) -> Result<bool, VfsError> {
122        Ok(from == to)
123    }
124
125    /// Whether two paths resolve to the same directory entry. Distinct hard
126    /// links to the same inode are different entries and return false.
127    fn same_entry(&self, from: &Path, to: &Path) -> Result<bool, VfsError> {
128        let Some(from) = self.entry_path(from)? else {
129            return Ok(false);
130        };
131        Ok(self.entry_path(to)?.is_some_and(|to| from == to))
132    }
133
134    /// Create missing parents and retain every directory created, even on error.
135    fn prepare_parent(&self, path: &Path) -> ParentCreation;
136    /// Recreate one removed directory during recovery, without creating parents
137    /// or replacing an occupied entry. File-only backends do not model directories.
138    fn create_dir(&self, path: &Path) -> Result<(), VfsError> {
139        Err(VfsError::Io {
140            path: path.to_path_buf(),
141            source: std::io::Error::new(
142                std::io::ErrorKind::Unsupported,
143                "directory creation is not modeled by this file system",
144            ),
145        })
146    }
147    fn remove_file(&self, path: &Path) -> Result<(), VfsError>;
148    /// Remove only an empty directory.
149    fn remove_empty_dir(&self, path: &Path) -> Result<(), VfsError>;
150    /// Move a regular file without replacing an occupied destination.
151    /// Prepare destination parents first with `prepare_parent`. Success removes
152    /// the source; failure retains its observed effect state for recovery.
153    fn move_if_absent(&self, from: &Path, to: &Path) -> Result<(), MoveError>;
154    /// Every regular file under `root`, in a deterministic order.
155    fn walk(&self, root: &Path) -> Result<Vec<PathBuf>, VfsError>;
156}