microclaw_engine/tools/
file_state.rs1use std::collections::HashMap;
15use std::path::{Path, PathBuf};
16use std::sync::Mutex;
17
18use sha2::{Digest, Sha256};
19
20const MAX_TRACKED_FILES: usize = 4096;
22
23type Fingerprint = [u8; 32];
24
25#[derive(Debug, Default)]
27pub struct FileStateTable {
28 entries: Mutex<HashMap<PathBuf, Fingerprint>>,
29}
30
31fn key(path: &Path) -> PathBuf {
32 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
33}
34
35fn fingerprint(content: &[u8]) -> Fingerprint {
36 Sha256::digest(content).into()
37}
38
39impl FileStateTable {
40 pub fn record(&self, path: &Path, content: &[u8]) {
42 let key = key(path);
43 let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
44 if entries.len() >= MAX_TRACKED_FILES && !entries.contains_key(&key) {
45 entries.clear();
46 }
47 entries.insert(key, fingerprint(content));
48 }
49
50 pub fn check_fresh(&self, path: &Path, current: &[u8]) -> Result<(), String> {
53 let entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
54 match entries.get(&key(path)) {
55 Some(known) if *known != fingerprint(current) => Err(format!(
56 "{} was modified on disk after you last read it (by the user, an editor, or another process). Read the file again before editing so those changes are not overwritten.",
57 path.display()
58 )),
59 _ => Ok(()),
60 }
61 }
62}
63
64#[cfg(test)]
65mod tests {
66 use super::*;
67
68 #[test]
69 fn untracked_files_are_always_fresh() {
70 let table = FileStateTable::default();
71 let dir = tempfile::tempdir().unwrap();
72 let file = dir.path().join("a.txt");
73 std::fs::write(&file, "one").unwrap();
74 assert!(table.check_fresh(&file, b"anything").is_ok());
75 }
76
77 #[test]
78 fn external_change_after_read_is_detected() {
79 let table = FileStateTable::default();
80 let dir = tempfile::tempdir().unwrap();
81 let file = dir.path().join("a.txt");
82 std::fs::write(&file, "one").unwrap();
83 table.record(&file, b"one");
84 assert!(table.check_fresh(&file, b"one").is_ok());
85 let err = table.check_fresh(&file, b"two").unwrap_err();
86 assert!(err.contains("modified on disk"));
87 }
88
89 #[test]
90 fn tables_are_independent() {
91 let a = FileStateTable::default();
92 let b = FileStateTable::default();
93 let dir = tempfile::tempdir().unwrap();
94 let file = dir.path().join("a.txt");
95 a.record(&file, b"one");
96 assert!(b.check_fresh(&file, b"two").is_ok());
97 }
98}