use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime};
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WatchEvent {
Changed(Vec<PathBuf>),
Removed(Vec<PathBuf>),
Stopped(String),
}
#[derive(Debug)]
pub struct WatchHandle {
cancelled: Arc<AtomicBool>,
_watcher: Option<RecommendedWatcher>,
}
impl WatchHandle {
pub fn cancel(&self) {
self.cancelled.store(true, Ordering::Relaxed);
}
}
impl Drop for WatchHandle {
fn drop(&mut self) {
self.cancel();
}
}
pub fn spawn(
root: PathBuf,
debounce: Duration,
sink: impl Fn(WatchEvent) + Send + Sync + 'static,
) -> WatchHandle {
let cancelled = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&cancelled);
let (tx, rx) = crossbeam_channel::unbounded();
let watcher = notify::recommended_watcher(move |event| {
let _ = tx.send(event);
});
let mut watcher = match watcher {
Ok(watcher) => watcher,
Err(e) => {
sink(WatchEvent::Stopped(stopped_message(&e)));
return WatchHandle {
cancelled,
_watcher: None,
};
}
};
if let Err(e) = watcher.watch(&root, RecursiveMode::Recursive) {
sink(WatchEvent::Stopped(stopped_message(&e)));
return WatchHandle {
cancelled,
_watcher: None,
};
}
let spawned = std::thread::Builder::new()
.name("perga-watch".to_string())
.spawn(move || debounce_loop(&root, debounce, &rx, &flag, &sink));
if spawned.is_err() {
return WatchHandle {
cancelled,
_watcher: None,
};
}
WatchHandle {
cancelled,
_watcher: Some(watcher),
}
}
fn debounce_loop(
root: &Path,
debounce: Duration,
rx: &crossbeam_channel::Receiver<notify::Result<notify::Event>>,
cancelled: &AtomicBool,
sink: &impl Fn(WatchEvent),
) {
let mut pending = Batch::default();
loop {
if cancelled.load(Ordering::Relaxed) {
return;
}
let first = match rx.recv() {
Ok(event) => event,
Err(_) => return,
};
pending.add(root, first);
let deadline = Instant::now() + debounce;
while let Some(remaining) = deadline.checked_duration_since(Instant::now()) {
match rx.recv_timeout(remaining) {
Ok(event) => pending.add(root, event),
Err(crossbeam_channel::RecvTimeoutError::Timeout) => break,
Err(crossbeam_channel::RecvTimeoutError::Disconnected) => return,
}
}
if cancelled.load(Ordering::Relaxed) {
return;
}
for event in pending.drain() {
sink(event);
}
}
}
#[derive(Debug, Default)]
struct Batch {
changed: Vec<PathBuf>,
removed: Vec<PathBuf>,
stopped: Option<String>,
}
impl Batch {
fn add(&mut self, root: &Path, event: notify::Result<notify::Event>) {
let event = match event {
Ok(event) => event,
Err(e) => {
self.stopped = Some(stopped_message(&e));
return;
}
};
let removed = matches!(event.kind, notify::EventKind::Remove(_));
for path in event.paths {
let Ok(relative) = path.strip_prefix(root) else {
continue;
};
if relative.as_os_str().is_empty() {
continue;
}
let list = if removed {
&mut self.removed
} else {
&mut self.changed
};
if !list.contains(&relative.to_path_buf()) {
list.push(relative.to_path_buf());
}
}
}
fn drain(&mut self) -> Vec<WatchEvent> {
let mut out = Vec::new();
if !self.changed.is_empty() {
out.push(WatchEvent::Changed(std::mem::take(&mut self.changed)));
}
if !self.removed.is_empty() {
out.push(WatchEvent::Removed(std::mem::take(&mut self.removed)));
}
if let Some(reason) = self.stopped.take() {
out.push(WatchEvent::Stopped(reason));
}
out
}
}
fn stopped_message(error: ¬ify::Error) -> String {
let text = error.to_string();
if text.contains("limit") || text.contains("No space left") {
return "Too many files to watch; reload manually with `r`".to_string();
}
format!("Not watching for changes: {text}")
}
#[derive(Debug, Default)]
pub struct OwnWrites {
seen: HashMap<PathBuf, SystemTime>,
}
impl OwnWrites {
pub fn record(&mut self, path: PathBuf, mtime: SystemTime) {
self.seen.insert(path, mtime);
}
pub fn claim(&mut self, path: &Path, mtime: Option<SystemTime>) -> bool {
let Some(recorded) = self.seen.get(path).copied() else {
return false;
};
match mtime {
Some(mtime) if mtime == recorded => {
self.seen.remove(path);
true
}
Some(_) => {
self.seen.remove(path);
false
}
None => false,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("perga-watch-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("a scratch directory");
dir
}
#[test]
fn a_burst_of_writes_arrives_as_one_batch() {
let root = scratch("burst");
let seen: Arc<Mutex<Vec<WatchEvent>>> = Arc::new(Mutex::new(Vec::new()));
let sink = Arc::clone(&seen);
let _handle = spawn(root.clone(), Duration::from_millis(80), move |event| {
sink.lock().unwrap().push(event);
});
std::thread::sleep(Duration::from_millis(100));
for i in 0..5 {
std::fs::write(root.join("note.md"), format!("version {i}\n")).unwrap();
}
std::thread::sleep(Duration::from_millis(400));
let events = seen.lock().unwrap();
let changed: Vec<&WatchEvent> = events
.iter()
.filter(|e| matches!(e, WatchEvent::Changed(_)))
.collect();
assert!(!changed.is_empty(), "the watcher saw nothing");
assert!(
changed.len() <= 2,
"five writes produced {} batches",
changed.len()
);
let WatchEvent::Changed(paths) = changed[0] else {
unreachable!()
};
assert_eq!(paths, &[PathBuf::from("note.md")]);
}
#[test]
fn a_write_perga_made_is_claimed_once() {
let mut own = OwnWrites::default();
let path = PathBuf::from("note.md");
let mtime = SystemTime::UNIX_EPOCH + Duration::from_secs(10);
own.record(path.clone(), mtime);
assert!(own.claim(&path, Some(mtime)));
assert!(
!own.claim(&path, Some(mtime)),
"the record is consumed by the event it explains"
);
}
#[test]
fn a_later_change_to_the_same_path_is_not_claimed() {
let mut own = OwnWrites::default();
let path = PathBuf::from("note.md");
let ours = SystemTime::UNIX_EPOCH + Duration::from_secs(10);
let theirs = SystemTime::UNIX_EPOCH + Duration::from_secs(20);
own.record(path.clone(), ours);
assert!(!own.claim(&path, Some(theirs)));
assert!(!own.claim(&path, Some(ours)), "the stale record is gone");
}
#[test]
fn a_path_perga_never_wrote_is_never_claimed() {
let mut own = OwnWrites::default();
assert!(!own.claim(Path::new("other.md"), Some(SystemTime::UNIX_EPOCH)));
}
#[test]
fn an_inotify_limit_is_named_rather_than_shown_raw() {
let error = notify::Error::new(notify::ErrorKind::MaxFilesWatch);
assert_eq!(
stopped_message(&error),
"Too many files to watch; reload manually with `r`"
);
let other = notify::Error::generic("the disk fell over");
assert!(stopped_message(&other).contains("the disk fell over"));
}
}