use notify::{Event as NotifyEvent, RecommendedWatcher, RecursiveMode, Watcher};
use std::error::Error;
use std::path::Path;
use std::sync::mpsc;
pub struct FileWatcher {
watcher: RecommendedWatcher,
rx: mpsc::Receiver<NotifyEvent>,
}
impl FileWatcher {
pub fn new(_todotxt_dir: &str) -> Result<Self, Box<dyn Error>> {
let (tx, rx) = mpsc::channel();
let watcher = RecommendedWatcher::new(
move |res: Result<NotifyEvent, notify::Error>| {
if let Ok(event) = res {
let _ = tx.send(event);
}
},
notify::Config::default(),
)?;
Ok(Self {
watcher,
rx,
})
}
pub fn start_watching(&mut self, todotxt_dir: &str) -> Result<(), Box<dyn Error>> {
self.watcher
.watch(Path::new(todotxt_dir), RecursiveMode::NonRecursive)?;
Ok(())
}
pub const fn receiver(&self) -> &mpsc::Receiver<NotifyEvent> {
&self.rx
}
}