use std::path::PathBuf;
use std::sync::mpsc;
use std::time::{Duration, Instant};
use notify::{EventKind, RecursiveMode, Watcher as _};
const QUIET: Duration = Duration::from_millis(400);
const MAX_WAIT: Duration = Duration::from_secs(2);
pub struct Watch {
dirs: Vec<PathBuf>,
_watcher: Option<notify::RecommendedWatcher>,
}
impl Watch {
pub fn start(dirs: Vec<PathBuf>) -> (Watch, async_channel::Receiver<()>) {
let (tx, rx) = async_channel::bounded(1);
let (ev_tx, ev_rx) = mpsc::channel::<()>();
let watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
if res.is_ok_and(|e| relevant(&e)) {
let _ = ev_tx.send(());
}
})
.map(|mut w| {
for d in &dirs {
if let Err(e) = w.watch(d, RecursiveMode::Recursive) {
eprintln!("not watching {}: {e}", d.display());
}
}
w
});
let watcher = match watcher {
Ok(w) => Some(w),
Err(e) => {
eprintln!("folder watching is unavailable: {e}");
None
}
};
std::thread::Builder::new()
.name("rosier-watch".into())
.spawn(move || gather(&ev_rx, &tx, QUIET, MAX_WAIT))
.ok();
(Watch { dirs, _watcher: watcher }, rx)
}
pub fn dirs(&self) -> &[PathBuf] {
&self.dirs
}
}
fn relevant(e: ¬ify::Event) -> bool {
match e.kind {
EventKind::Access(_) | EventKind::Other => false,
EventKind::Remove(_) | EventKind::Modify(notify::event::ModifyKind::Name(_)) => true,
_ => e.paths.iter().any(|p| crate::media::kind_of(p).is_some()),
}
}
fn gather(events: &mpsc::Receiver<()>, out: &async_channel::Sender<()>, quiet: Duration, max_wait: Duration) {
while events.recv().is_ok() {
let start = Instant::now();
loop {
let left = max_wait.saturating_sub(start.elapsed());
match events.recv_timeout(quiet.min(left)) {
Ok(()) if !left.is_zero() => continue,
Err(mpsc::RecvTimeoutError::Disconnected) => return,
_ => break,
}
}
if out.try_send(()).is_err() && out.is_closed() {
return;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_burst_of_events_asks_for_one_rescan() {
let (ev_tx, ev_rx) = mpsc::channel();
let (tx, rx) = async_channel::bounded(1);
let t = std::thread::spawn(move || gather(&ev_rx, &tx, Duration::from_millis(50), Duration::from_secs(5)));
for _ in 0..20 {
ev_tx.send(()).unwrap();
}
std::thread::sleep(Duration::from_millis(200));
assert!(rx.try_recv().is_ok());
assert!(rx.try_recv().is_err(), "one message for the whole burst");
drop(ev_tx);
t.join().unwrap();
}
#[test]
fn only_media_and_folder_changes_count() {
use notify::event::{AccessKind, CreateKind, RemoveKind};
let ev = |kind, p: &str| notify::Event::new(kind).add_path(PathBuf::from(p));
assert!(relevant(&ev(EventKind::Create(CreateKind::File), "/a/b.png")));
assert!(!relevant(&ev(EventKind::Create(CreateKind::File), "/a/b.txt")));
assert!(!relevant(&ev(EventKind::Access(AccessKind::Any), "/a/b.png")));
assert!(relevant(&ev(EventKind::Remove(RemoveKind::Folder), "/a/old")));
}
#[test]
fn new_files_are_reported() {
let dir = std::env::temp_dir().join(format!("rosier-watch-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let (_w, rx) = Watch::start(vec![dir.clone()]);
std::thread::sleep(Duration::from_millis(100));
std::fs::write(dir.join("new.jpg"), b"x").unwrap();
let deadline = Instant::now() + Duration::from_secs(5);
while rx.try_recv().is_err() {
assert!(Instant::now() < deadline, "no change reported");
std::thread::sleep(Duration::from_millis(20));
}
let _ = std::fs::remove_dir_all(&dir);
}
}