Files
hx/crates/hx-lens/src/seq.rs
T

95 lines
2.4 KiB
Rust

//! Project change log: monotonic `project_seq` + per-file seq, with the source of each change.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Source {
AgentWrite,
AgentEdit,
Format,
Autofix,
/// Changed during an agent run by something other than a file tool (bash, subagent, aborted tool).
Agent,
External,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Change {
pub seq: u64,
pub path: PathBuf,
pub source: Source,
}
#[derive(Default)]
pub struct SeqLog {
inner: Mutex<Inner>,
}
#[derive(Default)]
struct Inner {
seq: u64,
files: HashMap<PathBuf, u64>,
log: Vec<Change>,
}
impl SeqLog {
pub fn bump(&self, path: &Path, source: Source) -> u64 {
let mut i = self.inner.lock().unwrap_or_else(|e| e.into_inner());
i.seq += 1;
let seq = i.seq;
i.files.insert(path.to_path_buf(), seq);
i.log.push(Change {
seq,
path: path.to_path_buf(),
source,
});
seq
}
pub fn project(&self) -> u64 {
self.inner.lock().unwrap_or_else(|e| e.into_inner()).seq
}
/// Seq of the last change to `path` (0 = never changed).
pub fn file(&self, path: &Path) -> u64 {
self.inner
.lock()
.unwrap_or_else(|e| e.into_inner())
.files
.get(path)
.copied()
.unwrap_or(0)
}
/// Distinct paths changed after `seq`, in first-change order.
pub fn since(&self, seq: u64) -> Vec<PathBuf> {
let i = self.inner.lock().unwrap_or_else(|e| e.into_inner());
let mut out: Vec<PathBuf> = vec![];
for c in i.log.iter().filter(|c| c.seq > seq) {
if !out.contains(&c.path) {
out.push(c.path.clone());
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ordering() {
let l = SeqLog::default();
let (a, b) = (Path::new("/a"), Path::new("/b"));
assert_eq!(l.bump(a, Source::AgentWrite), 1);
assert_eq!(l.bump(b, Source::AgentEdit), 2);
assert_eq!(l.bump(a, Source::Format), 3);
assert_eq!(
(l.file(a), l.file(b), l.file(Path::new("/c")), l.project()),
(3, 2, 0, 3)
);
assert_eq!(l.since(1), [b, a]);
assert!(l.since(3).is_empty());
}
}