ratatui_toolkit/services/git_watcher/methods/check_for_changes.rs
1//! Check for git change events.
2
3use std::sync::mpsc::TryRecvError;
4
5use crate::services::git_watcher::helpers::is_relevant_git_event;
6use crate::services::git_watcher::GitWatcher;
7
8impl GitWatcher {
9 /// Check if there are any pending git state changes.
10 ///
11 /// This is a non-blocking operation that returns `true` if any
12 /// relevant git changes have been detected since the last check.
13 ///
14 /// # Returns
15 ///
16 /// `true` if git changes were detected, `false` otherwise.
17 ///
18 /// # Example
19 ///
20 /// ```no_run
21 /// use ratatui_toolkit::services::git_watcher::GitWatcher;
22 /// use std::path::Path;
23 ///
24 /// let mut watcher = GitWatcher::new().unwrap();
25 /// watcher.watch(Path::new("/path/to/repo")).unwrap();
26 ///
27 /// // In your event loop:
28 /// if watcher.check_for_changes() {
29 /// println!("Git state changed, recompute stats!");
30 /// }
31 /// ```
32 pub fn check_for_changes(&mut self) -> bool {
33 // Drain all pending events
34 loop {
35 match self.rx.try_recv() {
36 Ok(Ok(event)) => {
37 if is_relevant_git_event(&event) {
38 self.has_pending_changes = true;
39 }
40 }
41 Ok(Err(_)) => {
42 // Watcher error, ignore
43 }
44 Err(TryRecvError::Empty) => break,
45 Err(TryRecvError::Disconnected) => break,
46 }
47 }
48
49 // Return and reset the pending changes flag
50 let had_changes = self.has_pending_changes;
51 self.has_pending_changes = false;
52 had_changes
53 }
54
55 /// Check if there are pending changes without consuming them.
56 ///
57 /// This is useful when you want to know if there are changes
58 /// but don't want to reset the flag yet.
59 ///
60 /// # Returns
61 ///
62 /// `true` if git changes are pending, `false` otherwise.
63 pub fn has_pending_changes(&self) -> bool {
64 self.has_pending_changes
65 }
66}