use std::{
path::{Path, PathBuf},
sync::mpsc::{self, Receiver, Sender},
thread,
time::{Duration, Instant},
};
use anyhow::{Context, Result};
use notify::{Event, RecommendedWatcher, RecursiveMode, Watcher};
const DEBOUNCE: Duration = Duration::from_millis(500);
pub fn spawn(paths: &[PathBuf], index: &Path) -> Result<Receiver<Result<()>>> {
let cwd = std::env::current_dir()?;
let paths: Vec<PathBuf> = paths
.iter()
.map(|path| {
if path.is_absolute() {
path.clone()
} else {
cwd.join(path)
}
})
.collect();
let index = if index.is_absolute() {
index.to_owned()
} else {
cwd.join(index)
};
let (event_tx, event_rx) = mpsc::channel();
let mut watcher = notify::recommended_watcher(move |event| {
let _ = event_tx.send(event);
})
.context("creating file watcher")?;
for path in &paths {
watcher
.watch(path, RecursiveMode::Recursive)
.with_context(|| format!("watching {}", path.display()))?;
}
let (dirty_tx, dirty_rx) = mpsc::channel();
thread::spawn(move || watch_loop(watcher, event_rx, dirty_tx, index));
Ok(dirty_rx)
}
fn watch_loop(
_watcher: RecommendedWatcher,
events: Receiver<notify::Result<Event>>,
dirty: Sender<Result<()>>,
index: PathBuf,
) {
let mut deadline = None;
loop {
let timeout = deadline
.map(|until: Instant| until.saturating_duration_since(Instant::now()))
.unwrap_or(Duration::MAX);
match events.recv_timeout(timeout) {
Ok(Ok(event)) => {
if event.paths.iter().any(|path| relevant(path, &index)) {
deadline = Some(Instant::now() + DEBOUNCE);
}
}
Ok(Err(error)) => {
let _ = dirty.send(Err(error.into()));
deadline = None;
}
Err(mpsc::RecvTimeoutError::Timeout) => {
if deadline.take().is_some() {
let _ = dirty.send(Ok(()));
}
}
Err(mpsc::RecvTimeoutError::Disconnected) => break,
}
}
}
fn relevant(path: &Path, index: &Path) -> bool {
if path == index || sidecar(path, index, "-wal") || sidecar(path, index, "-shm") {
return false;
}
!path
.components()
.any(|component| matches!(component.as_os_str().to_str(), Some(".git" | ".geg")))
&& path.file_name().is_some()
}
fn sidecar(path: &Path, index: &Path, suffix: &str) -> bool {
let mut expected = index.as_os_str().to_owned();
expected.push(suffix);
path == Path::new(&expected)
}