use std::path::{Path, PathBuf};
use notify::Watcher;
use tokio::sync::mpsc;
pub(crate) struct FileWatcher {
_watcher: notify::RecommendedWatcher,
events: mpsc::Receiver<()>,
}
impl FileWatcher {
pub(crate) fn new(paths: &[PathBuf]) -> notify::Result<Self> {
let (tx, rx) = mpsc::channel(1);
let mut watcher = notify::recommended_watcher(move |_event| {
let _ = tx.try_send(());
})?;
let mut dirs: Vec<&Path> = paths.iter().filter_map(|p| p.parent()).collect();
dirs.sort_unstable();
dirs.dedup();
for dir in dirs {
watcher.watch(dir, notify::RecursiveMode::NonRecursive)?;
}
Ok(Self {
_watcher: watcher,
events: rx,
})
}
pub(crate) async fn changed(&mut self) {
self.events
.recv()
.await
.expect("file watcher channel closed unexpectedly");
}
}