use notify::event::{Event, EventKind, ModifyKind};
use notify::{RecommendedWatcher, Watcher};
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::task::Waker;
pub(crate) fn file_removal_watcher<P>(
path: P,
waker: Arc<Mutex<Option<Waker>>>,
) -> RecommendedWatcher
where
P: AsRef<Path>,
{
let mut watcher =
notify::recommended_watcher(move |maybe_event: notify::Result<notify::Event>| {
match maybe_event.expect("received error from watcher") {
Event {
kind: EventKind::Remove(_),
..
} => {
waker
.lock()
.expect("waker poisoned")
.take()
.map(|waker: Waker| waker.wake());
}
_ => {}
}
})
.expect("could not create watcher");
watcher
.watch(
path.as_ref().parent().expect("file must have parent"),
notify::RecursiveMode::NonRecursive,
)
.expect("could not start watching file");
watcher
}
pub(crate) fn removal_watcher(path: &Path, waker: Arc<Mutex<Option<Waker>>>) -> RecommendedWatcher {
let mut watcher =
notify::recommended_watcher(move |maybe_event: notify::Result<notify::Event>| {
match maybe_event.expect("received error from watcher") {
Event {
kind: EventKind::Remove(_),
..
} => {
waker
.lock()
.expect("waker poisoned")
.take()
.map(|waker: Waker| waker.wake());
}
_ => {}
}
})
.expect("could not create watcher");
watcher
.watch(path, notify::RecursiveMode::NonRecursive)
.expect("could not start watching file");
watcher
}
pub(crate) fn file_watcher(path: &Path, waker: Arc<Mutex<Option<Waker>>>) -> RecommendedWatcher {
let mut watcher =
notify::recommended_watcher(move |maybe_event: notify::Result<notify::Event>| {
match maybe_event.expect("received error from watcher") {
Event {
kind: EventKind::Modify(ModifyKind::Data(_)),
..
} => {
waker
.lock()
.expect("waker poisoned")
.take()
.map(|waker: Waker| waker.wake());
}
Event {
kind: EventKind::Remove(_),
..
} => {
log::debug!("file being watched was removed");
}
_ => {}
}
})
.expect("could not create watcher");
watcher
.watch(path, notify::RecursiveMode::NonRecursive)
.expect("could not start watching file");
watcher
}