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//! reindexes with configurable debouncing. A reindex rebuilds the whole index
5//! (there is no per-file update path yet; see `.context/TODO.md`).
6
7use 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/// Configuration for file watching
18#[derive(Debug, Clone)]
19pub struct WatchConfig {
20    /// Debounce duration in milliseconds
21    /// Waits this long after the last change before triggering reindex
22    pub debounce_ms: u64,
23    /// Suppress output (only log errors)
24    pub quiet: bool,
25}
26
27impl Default for WatchConfig {
28    fn default() -> Self {
29        Self {
30            debounce_ms: 15000, // 15 seconds
31            quiet: false,
32        }
33    }
34}
35
36/// Watch a directory for file changes and auto-reindex
37///
38/// This function blocks until interrupted (Ctrl+C).
39///
40/// # Algorithm
41///
42/// 1. Set up file system watcher using notify crate
43/// 2. Collect file change events into a HashSet (deduplicate)
44/// 3. Wait for debounce period after last change
45/// 4. Trigger a reindex (rebuilds the whole index and, today, the whole symbol cache)
46/// 5. Repeat
47///
48/// # Debouncing
49///
50/// The debounce timer resets on every file change event. This batches
51/// rapid changes (e.g., multi-file refactors, format-on-save) into a
52/// single reindex operation.
53///
54/// Example timeline:
55/// ```text
56/// t=0s:  File A changed  [timer starts]
57/// t=2s:  File B changed  [timer resets]
58/// t=5s:  File C changed  [timer resets]
59/// t=20s: Timer expires    [reindex A, B, C]
60/// ```
61pub 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    // Setup channel for receiving file system events
70    let (tx, rx) = channel();
71
72    // Create watcher with default config
73    let mut watcher =
74        RecommendedWatcher::new(tx, Config::default()).context("Failed to create file watcher")?;
75
76    // Start watching the directory recursively
77    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    // Track pending file changes
89    let mut pending_files: HashSet<PathBuf> = HashSet::new();
90    // Deleted file paths that need to be removed from the index.
91    // Tracked separately because the file no longer exists on disk and
92    // should_watch_file() cannot reliably inspect it.
93    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    // Event loop
98    loop {
99        // Try to receive events with 100ms timeout (allows checking debounce timer)
100        match rx.recv_timeout(Duration::from_millis(100)) {
101            Ok(Ok(event)) => {
102                // Process the file system event
103                if let Some((changed_path, is_removal)) = process_event_typed(&event) {
104                    if is_removal {
105                        // File is gone — we can no longer call should_watch_file() on it,
106                        // but we must still reindex so the deleted entry is removed.
107                        // Accept any path whose extension suggests a code file OR has no
108                        // extension at all (e.g. a deleted directory triggers a broad Remove).
109                        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                // Check if debounce period has elapsed
130                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                    // Trigger reindex
136                    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                    // Only the collected paths are read; `update_paths` runs a full
153                    // index itself when one of them needs it (an ignore file, the
154                    // config, a resolver config, a branch change).
155                    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                    // Clear pending changes
180                    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
199/// Process a file system event and extract the changed path together with a
200/// flag indicating whether this is a deletion (Remove) event.
201///
202/// Returns `Some((path, is_removal))`, or `None` for events that should be
203/// ignored (metadata-only changes, etc.).
204fn 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/// Process a file system event and extract the changed path
215///
216/// Returns None if the event should be ignored (e.g., metadata changes, directory events)
217#[allow(dead_code)]
218fn process_event(event: &Event) -> Option<PathBuf> {
219    process_event_typed(event).map(|(p, _)| p)
220}
221
222/// Check if a file should trigger a reindex
223///
224/// Returns true if the file has a supported language extension
225#[cfg(test)]
226fn should_watch_file(path: &Path) -> bool {
227    should_watch_file_with(path, None)
228}
229
230/// [`should_watch_file`] under the workspace's `[index] include/exclude` policy.
231/// Whether `changed` (absolute, under `root`) is a file that decides WHICH files
232/// are indexed: an ignore file or `.reflex/config.toml`.
233fn 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    // Skip hidden files and directories, unless `[index] hidden` walks them.
252    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    // Skip directories
260    if path.is_dir() {
261        return false;
262    }
263
264    // The same classifier as the walker: the text tier is watched too, so editing
265    // a README, a config file or a Makefile triggers a reindex like any other
266    // indexed file, and a lock file is watched exactly when the mode indexes it.
267    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        // Since 2.0.0 (tracked mode) every non-binary file is indexed, so every
289        // file is watched; only allowlist mode leaves an unclaimed extension out.
290        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        // A lock file matches a text extension but must not trigger a reindex.
303        // Tracked mode (the default) indexes lock files, so it watches them too;
304        // allowlist mode does neither.
305        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        // Editing a README must trigger a reindex like any other indexed file.
322        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}