1use notify_debouncer_full::notify::{RecommendedWatcher, RecursiveMode};
4use notify_debouncer_full::{DebounceEventResult, Debouncer, RecommendedCache, new_debouncer};
5use ragfs_core::FileEvent;
6use std::path::Path;
7use std::sync::Arc;
8use std::sync::atomic::{AtomicUsize, Ordering};
9use std::sync::mpsc;
10use std::time::Duration;
11use tokio::sync::mpsc as tokio_mpsc;
12use tracing::{debug, error, warn};
13
14use crate::exclude::ExclusionMatcher;
15
16pub struct FileWatcher {
18 debouncer: Debouncer<RecommendedWatcher, RecommendedCache>,
19}
20
21impl FileWatcher {
22 pub fn new(
24 event_tx: tokio_mpsc::Sender<FileEvent>,
25 debounce_duration: Duration,
26 ) -> Result<Self, notify::Error> {
27 Self::with_pending(event_tx, debounce_duration, None)
28 }
29
30 pub fn with_pending(
32 event_tx: tokio_mpsc::Sender<FileEvent>,
33 debounce_duration: Duration,
34 pending: Option<Arc<AtomicUsize>>,
35 ) -> Result<Self, notify::Error> {
36 Self::with_filter(event_tx, debounce_duration, pending, None)
37 }
38
39 pub fn with_filter(
41 event_tx: tokio_mpsc::Sender<FileEvent>,
42 debounce_duration: Duration,
43 pending: Option<Arc<AtomicUsize>>,
44 matcher: Option<Arc<ExclusionMatcher>>,
45 ) -> Result<Self, notify::Error> {
46 let (tx, rx) = mpsc::channel();
47
48 let event_tx_clone = event_tx.clone();
49 std::thread::spawn(move || {
50 while let Ok(result) = rx.recv() {
51 if let Err(e) = handle_debounced_events(
52 result,
53 &event_tx_clone,
54 pending.as_deref(),
55 matcher.as_deref(),
56 ) {
57 error!("Error handling file events: {e}");
58 }
59 }
60 });
61
62 let debouncer = new_debouncer(debounce_duration, None, move |result| {
63 let _ = tx.send(result);
64 })?;
65
66 Ok(Self { debouncer })
67 }
68
69 pub fn watch(&mut self, path: &Path) -> Result<(), notify_debouncer_full::notify::Error> {
71 debug!("Starting to watch: {:?}", path);
72 self.debouncer.watch(path, RecursiveMode::Recursive)?;
73 Ok(())
74 }
75
76 pub fn unwatch(&mut self, path: &Path) -> Result<(), notify_debouncer_full::notify::Error> {
78 debug!("Stopping watch: {:?}", path);
79 self.debouncer.unwatch(path)?;
80 Ok(())
81 }
82}
83
84fn handle_debounced_events(
85 result: DebounceEventResult,
86 event_tx: &tokio_mpsc::Sender<FileEvent>,
87 pending: Option<&AtomicUsize>,
88 matcher: Option<&ExclusionMatcher>,
89) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
90 match result {
91 Ok(events) => {
92 for event in events {
93 if let Some(file_event) = convert_event(&event, matcher) {
94 if let Some(pending) = pending {
95 pending.fetch_add(1, Ordering::SeqCst);
96 }
97 if event_tx.blocking_send(file_event).is_err() {
99 if let Some(pending) = pending {
100 pending.fetch_sub(1, Ordering::SeqCst);
101 }
102 warn!("Event channel closed");
103 break;
104 }
105 }
106 }
107 }
108 Err(errors) => {
109 for error in errors {
110 error!("Watch error: {error}");
111 }
112 }
113 }
114 Ok(())
115}
116
117fn convert_event(
118 event: ¬ify_debouncer_full::DebouncedEvent,
119 matcher: Option<&ExclusionMatcher>,
120) -> Option<FileEvent> {
121 use notify_debouncer_full::notify::EventKind;
122
123 let path = event.paths.first()?.clone();
124
125 if let Some(matcher) = matcher {
126 if matcher.is_excluded(&path) {
127 return None;
128 }
129 } else if path.components().any(|component| {
130 let name = component.as_os_str().to_string_lossy();
131 name.starts_with('.') && name != "." && name != ".."
132 }) {
133 return None;
135 }
136
137 match &event.kind {
138 EventKind::Create(_) => Some(FileEvent::Created(path)),
139 EventKind::Modify(_) => Some(FileEvent::Modified(path)),
140 EventKind::Remove(_) => Some(FileEvent::Deleted(path)),
141 EventKind::Other => {
142 if event.paths.len() >= 2 {
144 Some(FileEvent::Renamed {
145 from: event.paths[0].clone(),
146 to: event.paths[1].clone(),
147 })
148 } else {
149 None
150 }
151 }
152 _ => None,
153 }
154}
155
156#[cfg(test)]
157mod tests {
158 use super::*;
159 use crate::exclude::ExclusionOptions;
160 use notify_debouncer_full::DebouncedEvent;
161 use notify_debouncer_full::notify::EventKind;
162 use notify_debouncer_full::notify::event::{CreateKind, ModifyKind, RemoveKind};
163 use std::path::PathBuf;
164 use std::time::Instant;
165
166 fn make_event(kind: EventKind, paths: Vec<PathBuf>) -> DebouncedEvent {
167 DebouncedEvent {
168 event: notify_debouncer_full::notify::Event {
169 kind,
170 paths,
171 attrs: Default::default(),
172 },
173 time: Instant::now(),
174 }
175 }
176
177 #[test]
178 fn test_convert_event_create() {
179 let path = PathBuf::from("/tmp/test.txt");
180 let event = make_event(EventKind::Create(CreateKind::File), vec![path.clone()]);
181
182 let result = convert_event(&event, None);
183 assert!(matches!(result, Some(FileEvent::Created(p)) if p == path));
184 }
185
186 #[test]
187 fn test_convert_event_modify() {
188 use notify_debouncer_full::notify::event::DataChange;
189 let path = PathBuf::from("/tmp/test.txt");
190 let event = make_event(
191 EventKind::Modify(ModifyKind::Data(DataChange::Any)),
192 vec![path.clone()],
193 );
194
195 let result = convert_event(&event, None);
196 assert!(matches!(result, Some(FileEvent::Modified(p)) if p == path));
197 }
198
199 #[test]
200 fn test_convert_event_delete() {
201 let path = PathBuf::from("/tmp/test.txt");
202 let event = make_event(EventKind::Remove(RemoveKind::File), vec![path.clone()]);
203
204 let result = convert_event(&event, None);
205 assert!(matches!(result, Some(FileEvent::Deleted(p)) if p == path));
206 }
207
208 #[test]
209 fn test_hidden_files_skipped() {
210 let path = PathBuf::from("/tmp/.hidden");
211 let event = make_event(EventKind::Create(CreateKind::File), vec![path]);
212
213 let result = convert_event(&event, None);
214 assert!(result.is_none());
215 }
216
217 #[test]
218 fn test_matcher_skips_secret_and_hidden_dir() {
219 let matcher = ExclusionMatcher::new("/proj", ExclusionOptions::default());
220 let secret = make_event(
221 EventKind::Create(CreateKind::File),
222 vec![PathBuf::from("/proj/server.pem")],
223 );
224 let hidden_dir = make_event(
225 EventKind::Create(CreateKind::File),
226 vec![PathBuf::from("/proj/.obsidian/x.md")],
227 );
228 let visible = make_event(
229 EventKind::Create(CreateKind::File),
230 vec![PathBuf::from("/proj/notes/keyboard.md")],
231 );
232 assert!(convert_event(&secret, Some(&matcher)).is_none());
233 assert!(convert_event(&hidden_dir, Some(&matcher)).is_none());
234 assert!(matches!(
235 convert_event(&visible, Some(&matcher)),
236 Some(FileEvent::Created(p)) if p.ends_with("keyboard.md")
237 ));
238 }
239}