ratatui_toolkit/services/file_watcher/methods/
check_for_changes.rs

1//! Check for file change events.
2
3use std::sync::mpsc::TryRecvError;
4
5use crate::services::file_watcher::helpers::is_relevant_event;
6use crate::services::file_watcher::FileWatcher;
7
8impl FileWatcher {
9    /// Check if there are any pending file change events.
10    ///
11    /// This is a non-blocking operation that returns `true` if any
12    /// relevant file modifications have been detected since the last check.
13    /// Changed paths are stored internally and can be retrieved with
14    /// [`get_changed_paths`](Self::get_changed_paths).
15    ///
16    /// # Returns
17    ///
18    /// `true` if file changes were detected, `false` otherwise.
19    ///
20    /// # Example
21    ///
22    /// ```no_run
23    /// use ratatui_toolkit::services::file_watcher::FileWatcher;
24    /// use std::path::Path;
25    ///
26    /// let mut watcher = FileWatcher::new().unwrap();
27    /// watcher.watch(Path::new("README.md")).unwrap();
28    ///
29    /// // In your event loop:
30    /// if watcher.check_for_changes() {
31    ///     println!("Files changed!");
32    ///     let paths = watcher.get_changed_paths();
33    ///     for path in paths {
34    ///         println!("  - {}", path.display());
35    ///     }
36    /// }
37    /// ```
38    pub fn check_for_changes(&mut self) -> bool {
39        let mut has_changes = false;
40
41        loop {
42            match self.rx.try_recv() {
43                Ok(Ok(event)) => {
44                    if is_relevant_event(&event) {
45                        has_changes = true;
46                        // Collect the paths that changed
47                        for path in event.paths {
48                            if !self.changed_paths.contains(&path) {
49                                self.changed_paths.push(path);
50                            }
51                        }
52                    }
53                }
54                Ok(Err(_)) => {
55                    // Watcher error, ignore
56                }
57                Err(TryRecvError::Empty) => break,
58                Err(TryRecvError::Disconnected) => break,
59            }
60        }
61
62        has_changes
63    }
64}