Skip to main content

vvv_engine/vfs/
disk.rs

1use std::path::{Path, PathBuf};
2
3use super::{Stamp, Vfs, VfsError};
4
5/// Real file system. Walks respect `.gitignore` and skip hidden entries.
6#[derive(Debug, Default, Clone)]
7pub struct DiskVfs;
8
9impl DiskVfs {
10    pub fn new() -> Self {
11        Self
12    }
13
14    fn io(path: &Path, source: std::io::Error) -> VfsError {
15        match source.kind() {
16            std::io::ErrorKind::NotFound => VfsError::NotFound(path.to_path_buf()),
17            _ => VfsError::Io {
18                path: path.to_path_buf(),
19                source,
20            },
21        }
22    }
23}
24
25impl Vfs for DiskVfs {
26    fn read(&self, path: &Path) -> Result<String, VfsError> {
27        let bytes = std::fs::read(path).map_err(|e| Self::io(path, e))?;
28        String::from_utf8(bytes).map_err(|_| VfsError::InvalidUtf8 {
29            path: path.to_path_buf(),
30        })
31    }
32
33    fn stamp(&self, path: &Path) -> Result<Stamp, VfsError> {
34        let meta = std::fs::metadata(path).map_err(|e| Self::io(path, e))?;
35        let modified = meta
36            .modified()
37            .ok()
38            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
39            .map_or(0, |d| d.as_nanos());
40        Ok(Stamp::new(modified, meta.len()))
41    }
42
43    fn write(&self, path: &Path, contents: &str) -> Result<(), VfsError> {
44        if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
45            std::fs::create_dir_all(parent).map_err(|e| Self::io(parent, e))?;
46        }
47        std::fs::write(path, contents).map_err(|e| Self::io(path, e))
48    }
49
50    fn exists(&self, path: &Path) -> bool {
51        path.exists()
52    }
53
54    fn rename(&self, from: &Path, to: &Path) -> Result<(), VfsError> {
55        if let Some(parent) = to.parent() {
56            std::fs::create_dir_all(parent).map_err(|e| Self::io(parent, e))?;
57        }
58        std::fs::rename(from, to).map_err(|e| Self::io(from, e))
59    }
60
61    fn walk(&self, root: &Path) -> Result<Vec<PathBuf>, VfsError> {
62        // The parallel walker is what makes ripgrep's traversal fast; on a
63        // large tree the serial one costs more than reading every file.
64        // Each thread collects into its own buffer and hands it over once.
65        let all = std::sync::Mutex::new(Vec::new());
66        ignore::WalkBuilder::new(root).build_parallel().run(|| {
67            let mut mine = Buffer {
68                paths: Vec::new(),
69                all: &all,
70            };
71            Box::new(move |entry| {
72                if let Ok(entry) = entry
73                    && entry.file_type().is_some_and(|t| t.is_file())
74                {
75                    mine.paths.push(entry.into_path());
76                }
77                ignore::WalkState::Continue
78            })
79        });
80        let mut files = all.into_inner().expect("walk lock");
81        files.sort();
82        Ok(files)
83    }
84}
85
86/// One walker thread's paths, merged into the shared list when the thread
87/// is done with them.
88struct Buffer<'a> {
89    paths: Vec<PathBuf>,
90    all: &'a std::sync::Mutex<Vec<PathBuf>>,
91}
92
93impl Drop for Buffer<'_> {
94    fn drop(&mut self) {
95        self.all.lock().expect("walk lock").append(&mut self.paths);
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102
103    #[test]
104    fn write_and_rename_create_parent_directories() {
105        let root = std::env::temp_dir().join(format!("vvv-disk-vfs-{}", std::process::id()));
106        let vfs = DiskVfs::new();
107        let deep = root.join("a/b/c.txt");
108        vfs.write(&deep, "hi").unwrap();
109        assert_eq!(vfs.read(&deep).unwrap(), "hi");
110        let moved = root.join("x/y/z.txt");
111        vfs.rename(&deep, &moved).unwrap();
112        assert!(!vfs.exists(&deep));
113        assert_eq!(vfs.read(&moved).unwrap(), "hi");
114        std::fs::remove_dir_all(&root).unwrap();
115    }
116}