1use anyhow::{Context, Result};
8use notify::{Config, Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
9use std::collections::HashSet;
10use std::path::{Path, PathBuf};
11use std::sync::mpsc::{RecvTimeoutError, channel};
12use std::time::{Duration, Instant};
13
14use crate::indexer::Indexer;
15use crate::output;
16
17#[derive(Debug, Clone)]
19pub struct WatchConfig {
20 pub debounce_ms: u64,
23 pub quiet: bool,
25}
26
27impl Default for WatchConfig {
28 fn default() -> Self {
29 Self {
30 debounce_ms: 15000, quiet: false,
32 }
33 }
34}
35
36pub fn watch(path: &Path, indexer: Indexer, config: WatchConfig) -> Result<()> {
62 let policy = indexer.path_policy(path);
63 log::info!(
64 "Starting file watcher for {:?} with {}ms debounce",
65 path,
66 config.debounce_ms
67 );
68
69 let (tx, rx) = channel();
71
72 let mut watcher =
74 RecommendedWatcher::new(tx, Config::default()).context("Failed to create file watcher")?;
75
76 watcher
78 .watch(path, RecursiveMode::Recursive)
79 .context("Failed to start watching directory")?;
80
81 if !config.quiet {
82 println!(
83 "Watching for changes (debounce: {}s)...",
84 config.debounce_ms / 1000
85 );
86 }
87
88 let mut pending_files: HashSet<PathBuf> = HashSet::new();
90 let mut pending_deletions: HashSet<PathBuf> = HashSet::new();
94 let mut last_event_time: Option<Instant> = None;
95 let debounce_duration = Duration::from_millis(config.debounce_ms);
96
97 loop {
99 match rx.recv_timeout(Duration::from_millis(100)) {
101 Ok(Ok(event)) => {
102 if let Some((changed_path, is_removal)) = process_event_typed(&event) {
104 if is_removal {
105 let is_indexed = changed_path.extension().is_none()
110 || crate::models::Language::from_path(&changed_path).is_indexable();
111 if is_indexed {
112 log::debug!("Detected removal: {:?}", changed_path);
113 pending_deletions.insert(changed_path);
114 last_event_time = Some(Instant::now());
115 }
116 } else if should_watch_file_with(&changed_path, Some(&policy))
117 || is_rule_file_path(path, &changed_path)
118 {
119 log::debug!("Detected change: {:?}", changed_path);
120 pending_files.insert(changed_path);
121 last_event_time = Some(Instant::now());
122 }
123 }
124 }
125 Ok(Err(e)) => {
126 log::warn!("Watch error: {}", e);
127 }
128 Err(RecvTimeoutError::Timeout) => {
129 let has_pending = !pending_files.is_empty() || !pending_deletions.is_empty();
131 if let Some(last_time) = last_event_time
132 && has_pending
133 && last_time.elapsed() >= debounce_duration
134 {
135 let total_changes = pending_files.len() + pending_deletions.len();
137 if !config.quiet {
138 if pending_deletions.is_empty() {
139 println!(
140 "\nDetected {} changed file(s), reindexing...",
141 pending_files.len()
142 );
143 } else {
144 println!(
145 "\nDetected {} change(s) ({} deleted), reindexing...",
146 total_changes,
147 pending_deletions.len()
148 );
149 }
150 }
151
152 let changed: Vec<PathBuf> = pending_files
156 .iter()
157 .chain(&pending_deletions)
158 .cloned()
159 .collect();
160 let start = Instant::now();
161 match indexer.update_paths(path, &changed) {
162 Ok(stats) => {
163 let elapsed = start.elapsed();
164 if !config.quiet {
165 println!(
166 "✓ Reindexed {} files in {:.1}ms\n",
167 stats.total_files,
168 elapsed.as_secs_f64() * 1000.0
169 );
170 }
171 log::info!("Reindexed {} files in {:?}", stats.total_files, elapsed);
172 }
173 Err(e) => {
174 output::error(&format!("✗ Reindex failed: {}", e));
175 log::error!("Reindex failed: {}", e);
176 }
177 }
178
179 pending_files.clear();
181 pending_deletions.clear();
182 last_event_time = None;
183 }
184 }
185 Err(RecvTimeoutError::Disconnected) => {
186 log::info!("Watcher channel disconnected, stopping...");
187 break;
188 }
189 }
190 }
191
192 if !config.quiet {
193 println!("Watcher stopped.");
194 }
195
196 Ok(())
197}
198
199fn process_event_typed(event: &Event) -> Option<(PathBuf, bool)> {
205 match event.kind {
206 EventKind::Remove(_) => event.paths.first().cloned().map(|p| (p, true)),
207 EventKind::Create(_) | EventKind::Modify(_) => {
208 event.paths.first().cloned().map(|p| (p, false))
209 }
210 _ => None,
211 }
212}
213
214#[allow(dead_code)]
218fn process_event(event: &Event) -> Option<PathBuf> {
219 process_event_typed(event).map(|(p, _)| p)
220}
221
222#[cfg(test)]
226fn should_watch_file(path: &Path) -> bool {
227 should_watch_file_with(path, None)
228}
229
230fn is_rule_file_path(root: &Path, changed: &Path) -> bool {
234 let rel = changed
235 .strip_prefix(root)
236 .unwrap_or(changed)
237 .to_string_lossy()
238 .replace('\\', "/");
239 crate::indexer::is_rule_file(rel.trim_start_matches("./"))
240}
241
242fn should_watch_file_with(path: &Path, policy: Option<&crate::indexer::PathPolicy>) -> bool {
243 let default_policy;
244 let policy = match policy {
245 Some(p) => p,
246 None => {
247 default_policy = crate::indexer::PathPolicy::default();
248 &default_policy
249 }
250 };
251 if !policy.hidden()
253 && let Some(file_name) = path.file_name()
254 && file_name.to_string_lossy().starts_with('.')
255 {
256 return false;
257 }
258
259 if path.is_dir() {
261 return false;
262 }
263
264 policy.classify(path).is_some()
268}
269
270#[cfg(test)]
271mod tests {
272 use super::*;
273 use std::fs;
274 use tempfile::TempDir;
275
276 #[test]
277 fn test_should_watch_rust_file() {
278 let temp = TempDir::new().unwrap();
279 let rust_file = temp.path().join("test.rs");
280 fs::write(&rust_file, "fn main() {}").unwrap();
281
282 assert!(should_watch_file(&rust_file));
283 }
284
285 #[test]
286 fn test_should_not_watch_unsupported_file() {
287 let temp = TempDir::new().unwrap();
288 let unknown = temp.path().join("test.xyz");
291 fs::write(&unknown, "mystery format").unwrap();
292 assert!(should_watch_file(&unknown));
293 let allowlist_policy = crate::indexer::PathPolicy::from_config(
294 temp.path(),
295 &crate::models::IndexConfig {
296 mode: crate::models::IndexMode::Allowlist,
297 ..Default::default()
298 },
299 );
300 assert!(!should_watch_file_with(&unknown, Some(&allowlist_policy)));
301
302 let lock = temp.path().join("package-lock.json");
306 fs::write(&lock, "{}").unwrap();
307 assert!(should_watch_file(&lock));
308 let allowlist = crate::indexer::PathPolicy::from_config(
309 temp.path(),
310 &crate::models::IndexConfig {
311 mode: crate::models::IndexMode::Allowlist,
312 ..Default::default()
313 },
314 );
315 assert!(!should_watch_file_with(&lock, Some(&allowlist)));
316 }
317
318 #[test]
319 fn test_should_watch_text_tier_file() {
320 let temp = TempDir::new().unwrap();
321 for name in ["README.md", "config.yaml", "notes.txt"] {
323 let path = temp.path().join(name);
324 fs::write(&path, "content").unwrap();
325 assert!(should_watch_file(&path), "{name} should be watched");
326 }
327 }
328
329 #[test]
330 fn test_should_not_watch_hidden_file() {
331 let temp = TempDir::new().unwrap();
332 let hidden_file = temp.path().join(".hidden.rs");
333 fs::write(&hidden_file, "fn main() {}").unwrap();
334
335 assert!(!should_watch_file(&hidden_file));
336 }
337
338 #[test]
339 fn test_should_not_watch_directory() {
340 let temp = TempDir::new().unwrap();
341 let dir = temp.path().join("src");
342 fs::create_dir(&dir).unwrap();
343
344 assert!(!should_watch_file(&dir));
345 }
346
347 #[test]
348 fn test_watch_config_default() {
349 let config = WatchConfig::default();
350 assert_eq!(config.debounce_ms, 15000);
351 assert!(!config.quiet);
352 }
353
354 #[test]
355 fn test_process_event_create() {
356 let event = Event {
357 kind: EventKind::Create(notify::event::CreateKind::File),
358 paths: vec![PathBuf::from("/test/file.rs")],
359 attrs: Default::default(),
360 };
361
362 let path = process_event(&event);
363 assert!(path.is_some());
364 assert_eq!(path.unwrap(), PathBuf::from("/test/file.rs"));
365 }
366
367 #[test]
368 fn test_process_event_modify() {
369 let event = Event {
370 kind: EventKind::Modify(notify::event::ModifyKind::Data(
371 notify::event::DataChange::Any,
372 )),
373 paths: vec![PathBuf::from("/test/file.rs")],
374 attrs: Default::default(),
375 };
376
377 let path = process_event(&event);
378 assert!(path.is_some());
379 assert_eq!(path.unwrap(), PathBuf::from("/test/file.rs"));
380 }
381
382 #[test]
383 fn test_process_event_access_ignored() {
384 let event = Event {
385 kind: EventKind::Access(notify::event::AccessKind::Read),
386 paths: vec![PathBuf::from("/test/file.rs")],
387 attrs: Default::default(),
388 };
389
390 let path = process_event(&event);
391 assert!(path.is_none());
392 }
393}