Skip to main content

cp_desktop/
watcher.rs

1//! File system watcher for detecting changes
2
3use cp_core::{CPError, Result};
4use notify::{Config, Event, RecommendedWatcher, RecursiveMode, Watcher};
5use std::path::Path;
6use std::sync::mpsc;
7
8/// File system watcher for real-time change detection
9pub struct FileWatcher {
10    watcher: RecommendedWatcher,
11    // receiver: mpsc::Receiver<notify::Result<Event>>, // No longer needed if we push to external tx
12}
13
14impl FileWatcher {
15    /// Create a new file watcher
16    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    /// Start watching a directory
29    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    /// Stop watching a directory
37    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}