use crate::fs::error::LogFSError;
use crate::fs::Unblocker;
use notify::event::{CreateKind, RemoveKind};
use notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher};
use std::path::Path;
use std::sync::Arc;
pub struct DirWatcher {
_watcher: RecommendedWatcher,
}
impl DirWatcher {
pub fn new<P: AsRef<Path>>(
path: P,
unblocker: impl Into<Arc<dyn Unblocker>>,
) -> Result<DirWatcher, LogFSError> {
let unblocker = unblocker.into();
let mut watcher =
notify::recommended_watcher(move |event: notify::Result<notify::Event>| {
let event: notify::Event = match event {
Ok(event) => event,
Err(error) => {
let _ = unblocker.unblock(Err(LogFSError::NotifyError(error)));
return;
}
};
#[cfg(target_family = "unix")]
match event.kind {
EventKind::Create(CreateKind::File) | EventKind::Remove(RemoveKind::Any) => {
true
}
_ => return,
};
#[cfg(target_family = "windows")]
match event.kind {
EventKind::Create(CreateKind::Any) | EventKind::Remove(RemoveKind::Any) => true,
_ => return,
};
let _ = unblocker.unblock(Ok(()));
})?;
watcher.watch(path.as_ref(), RecursiveMode::NonRecursive)?;
Ok(DirWatcher { _watcher: watcher })
}
}