Skip to main content

reflex/
watcher.rs

1//! File system watcher for automatic reindexing
2//!
3//! The watcher monitors the workspace for file changes and automatically
4//! triggers incremental reindexing with configurable debouncing.
5
6use 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/// Configuration for file watching
17#[derive(Debug, Clone)]
18pub struct WatchConfig {
19    /// Debounce duration in milliseconds
20    /// Waits this long after the last change before triggering reindex
21    pub debounce_ms: u64,
22    /// Suppress output (only log errors)
23    pub quiet: bool,
24}
25
26impl Default for WatchConfig {
27    fn default() -> Self {
28        Self {
29            debounce_ms: 15000, // 15 seconds
30            quiet: false,
31        }
32    }
33}
34
35/// Watch a directory for file changes and auto-reindex
36///
37/// This function blocks until interrupted (Ctrl+C).
38///
39/// # Algorithm
40///
41/// 1. Set up file system watcher using notify crate
42/// 2. Collect file change events into a HashSet (deduplicate)
43/// 3. Wait for debounce period after last change
44/// 4. Trigger incremental reindex (only changed files)
45/// 5. Repeat
46///
47/// # Debouncing
48///
49/// The debounce timer resets on every file change event. This batches
50/// rapid changes (e.g., multi-file refactors, format-on-save) into a
51/// single reindex operation.
52///
53/// Example timeline:
54/// ```text
55/// t=0s:  File A changed  [timer starts]
56/// t=2s:  File B changed  [timer resets]
57/// t=5s:  File C changed  [timer resets]
58/// t=20s: Timer expires    [reindex A, B, C]
59/// ```
60pub 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    // Setup channel for receiving file system events
69    let (tx, rx) = channel();
70
71    // Create watcher with default config
72    let mut watcher =
73        RecommendedWatcher::new(tx, Config::default()).context("Failed to create file watcher")?;
74
75    // Start watching the directory recursively
76    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    // Track pending file changes
88    let mut pending_files: HashSet<PathBuf> = HashSet::new();
89    // Deleted file paths that need to be removed from the index.
90    // Tracked separately because the file no longer exists on disk and
91    // should_watch_file() cannot reliably inspect it.
92    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    // Event loop
97    loop {
98        // Try to receive events with 100ms timeout (allows checking debounce timer)
99        match rx.recv_timeout(Duration::from_millis(100)) {
100            Ok(Ok(event)) => {
101                // Process the file system event
102                if let Some((changed_path, is_removal)) = process_event_typed(&event) {
103                    if is_removal {
104                        // File is gone — we can no longer call should_watch_file() on it,
105                        // but we must still reindex so the deleted entry is removed.
106                        // Accept any path whose extension suggests a code file OR has no
107                        // extension at all (e.g. a deleted directory triggers a broad Remove).
108                        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                // Check if debounce period has elapsed
127                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                    // Trigger reindex
133                    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                    // Clear pending changes
169                    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
188/// Process a file system event and extract the changed path together with a
189/// flag indicating whether this is a deletion (Remove) event.
190///
191/// Returns `Some((path, is_removal))`, or `None` for events that should be
192/// ignored (metadata-only changes, etc.).
193fn 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/// Process a file system event and extract the changed path
204///
205/// Returns None if the event should be ignored (e.g., metadata changes, directory events)
206#[allow(dead_code)]
207fn process_event(event: &Event) -> Option<PathBuf> {
208    process_event_typed(event).map(|(p, _)| p)
209}
210
211/// Check if a file should trigger a reindex
212///
213/// Returns true if the file has a supported language extension
214#[cfg(test)]
215fn should_watch_file(path: &Path) -> bool {
216    should_watch_file_with(path, None)
217}
218
219/// [`should_watch_file`] under the workspace's `[index] include/exclude` policy.
220fn 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    // Skip hidden files and directories, unless `[index] hidden` walks them.
230    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    // Skip directories
238    if path.is_dir() {
239        return false;
240    }
241
242    // The same classifier as the walker: the text tier is watched too, so editing
243    // a README, a config file or a Makefile triggers a reindex like any other
244    // indexed file, and a lock file is watched exactly when the mode indexes it.
245    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        // Since 2.0.0 (tracked mode) every non-binary file is indexed, so every
267        // file is watched; only allowlist mode leaves an unclaimed extension out.
268        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        // A lock file matches a text extension but must not trigger a reindex.
281        // Tracked mode (the default) indexes lock files, so it watches them too;
282        // allowlist mode does neither.
283        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        // Editing a README must trigger a reindex like any other indexed file.
300        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}