Skip to main content

teaql_tool_extra/
watcher.rs

1use teaql_tool_core::{Result, TeaQLToolError};
2use notify::{Watcher, RecursiveMode};
3use std::sync::mpsc::channel;
4
5#[derive(Debug, Clone)]
6pub struct WatcherTool;
7
8impl WatcherTool {
9    pub fn new() -> Self { Self }
10
11    pub fn watch<F>(&self, path: &str, callback: F) -> Result<()> 
12    where
13        F: Fn(&str) + Send + Sync + 'static,
14    {
15        let (tx, rx) = channel();
16        let mut watcher = notify::recommended_watcher(tx).map_err(|e| TeaQLToolError::ExecutionError(e.to_string()))?;
17        
18        watcher.watch(std::path::Path::new(path), RecursiveMode::Recursive)
19            .map_err(|e| TeaQLToolError::ExecutionError(e.to_string()))?;
20            
21        println!("Watching path: {}", path);
22        
23        for res in rx {
24            match res {
25                Ok(event) => {
26                    for p in event.paths {
27                        callback(&p.to_string_lossy());
28                    }
29                },
30                Err(e) => println!("Watch error: {:?}", e),
31            }
32        }
33        
34        Ok(())
35    }
36}
37
38impl Default for WatcherTool {
39    fn default() -> Self { Self::new() }
40}