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

102 lines
3.3 KiB
Rust

//! External change watcher: polls mtimes of files the lens knows about and records changes made outside hx
//! (editor saves, git checkout) as `Source::External`, so the next report re-checks them.
//!
//! ponytail: mtime polling of tracked files only (no `notify` dependency, no new-file discovery).
//! Switch to `notify` if tracking whole trees becomes necessary.
use crate::seq::{SeqLog, Source};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime};
#[derive(Default)]
pub struct Watch {
mtimes: Mutex<HashMap<PathBuf, Option<SystemTime>>>,
}
fn mtime(p: &PathBuf) -> Option<SystemTime> {
std::fs::metadata(p).and_then(|m| m.modified()).ok()
}
impl Watch {
/// Start tracking (or re-baseline after our own write) without recording a change.
pub fn track(&self, p: PathBuf) {
let m = mtime(&p);
self.mtimes
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(p, m);
}
/// Record files whose mtime changed since last seen. Returns them.
pub fn scan(&self, seq: &SeqLog, src: Source) -> Vec<PathBuf> {
let mut map = self.mtimes.lock().unwrap_or_else(|e| e.into_inner());
let mut changed = vec![];
for (p, old) in map.iter_mut() {
let now = mtime(p);
if now != *old {
*old = now;
seq.bump(p, src);
changed.push(p.clone());
}
}
changed
}
pub fn spawn(
self: &Arc<Self>,
seq: Arc<SeqLog>,
every: Duration,
) -> tokio::task::JoinHandle<()> {
let w = self.clone();
tokio::spawn(async move {
let mut t = tokio::time::interval(every);
loop {
t.tick().await;
w.scan(&seq, Source::External);
}
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn external_bumps_once() {
let d = tempfile::tempdir().unwrap();
let f = d.path().join("a.rs");
std::fs::write(&f, "1").unwrap();
let (w, s) = (Watch::default(), SeqLog::default());
w.track(f.clone());
assert!(w.scan(&s, Source::External).is_empty());
std::thread::sleep(Duration::from_millis(20));
std::fs::write(&f, "2").unwrap();
assert_eq!(w.scan(&s, Source::External), std::slice::from_ref(&f));
assert!(w.scan(&s, Source::External).is_empty());
assert_eq!(s.project(), 1);
// our own write: re-baseline, no bump
std::thread::sleep(Duration::from_millis(20));
std::fs::write(&f, "3").unwrap();
w.track(f);
assert!(w.scan(&s, Source::External).is_empty());
}
#[test]
fn agent_scan_not_external() {
let d = tempfile::tempdir().unwrap();
let f = d.path().join("a.rs");
std::fs::write(&f, "1").unwrap();
let (w, s) = (Watch::default(), SeqLog::default());
w.track(f.clone());
std::thread::sleep(Duration::from_millis(20));
std::fs::write(&f, "2").unwrap(); // e.g. bash sed, or an aborted edit
assert_eq!(w.scan(&s, Source::Agent).len(), 1);
// later turn start: nothing left to call external
assert!(w.scan(&s, Source::External).is_empty());
assert!(s.since(0).len() == 1);
}
}