1use cp_core::{CPError, Result};
4use notify::{Config, Event, RecommendedWatcher, RecursiveMode, Watcher};
5use std::path::Path;
6use std::sync::mpsc;
7
8pub struct FileWatcher {
10 watcher: RecommendedWatcher,
11 }
13
14impl FileWatcher {
15 pub fn new(tx: mpsc::Sender<notify::Result<Event>>) -> Result<Self> {
17 let watcher = RecommendedWatcher::new(
18 move |res| {
19 let _ = tx.send(res);
20 },
21 Config::default(),
22 )
23 .map_err(|e| CPError::Io(std::io::Error::other(e)))?;
24
25 Ok(Self { watcher })
26 }
27
28 pub fn watch(&mut self, path: &Path) -> Result<()> {
30 self.watcher
31 .watch(path, RecursiveMode::Recursive)
32 .map_err(|e| CPError::Io(std::io::Error::other(e)))?;
33 Ok(())
34 }
35
36 pub fn unwatch(&mut self, path: &Path) -> Result<()> {
38 self.watcher
39 .unwatch(path)
40 .map_err(|e| CPError::Io(std::io::Error::other(e)))?;
41 Ok(())
42 }
43}