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