ratatui_toolkit/services/file_watcher/mod.rs
1//! File watching service for detecting file system changes.
2//!
3//! A reusable, configurable file watcher that can be used across multiple
4//! components in the toolkit. Supports watching single files or entire
5//! directory trees.
6//!
7//! # Example
8//!
9//! ```no_run
10//! use ratatui_toolkit::services::file_watcher::{FileWatcher, WatchMode};
11//! use std::path::Path;
12//!
13//! // Watch a single file
14//! let mut watcher = FileWatcher::for_file().unwrap();
15//! watcher.watch(Path::new("README.md")).unwrap();
16//!
17//! // In your event loop:
18//! if watcher.check_for_changes() {
19//! println!("File changed!");
20//! }
21//!
22//! // Watch a directory recursively
23//! let mut dir_watcher = FileWatcher::for_directory().unwrap();
24//! dir_watcher.watch(Path::new("./src")).unwrap();
25//!
26//! // Get which paths changed
27//! let changed = dir_watcher.get_changed_paths();
28//! for path in changed {
29//! println!("Changed: {}", path.display());
30//! }
31//! ```
32
33mod constructors;
34mod helpers;
35mod methods;
36mod traits;
37
38use notify::{Event, RecommendedWatcher};
39use std::path::PathBuf;
40use std::sync::mpsc::Receiver;
41
42pub use constructors::*;
43
44/// Mode for file watching.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
46pub enum WatchMode {
47 /// Watch a single file (non-recursive).
48 #[default]
49 File,
50 /// Watch a directory tree recursively.
51 Recursive,
52}
53
54/// Configuration for the file watcher.
55#[derive(Debug, Clone)]
56pub struct WatchConfig {
57 /// Watch mode - single file or recursive directory.
58 pub mode: WatchMode,
59 /// Debounce interval in milliseconds.
60 pub debounce_ms: u64,
61}
62
63impl Default for WatchConfig {
64 fn default() -> Self {
65 Self {
66 mode: WatchMode::File,
67 debounce_ms: 100,
68 }
69 }
70}
71
72impl WatchConfig {
73 /// Create a new config with default settings.
74 pub fn new() -> Self {
75 Self::default()
76 }
77
78 /// Set the watch mode.
79 pub fn mode(mut self, mode: WatchMode) -> Self {
80 self.mode = mode;
81 self
82 }
83
84 /// Set the debounce interval in milliseconds.
85 pub fn debounce_ms(mut self, ms: u64) -> Self {
86 self.debounce_ms = ms;
87 self
88 }
89}
90
91/// A file watcher for detecting file system changes.
92///
93/// Uses the `notify` crate internally to watch files and directories
94/// for changes. Provides a non-blocking interface suitable for use
95/// in TUI event loops.
96pub struct FileWatcher {
97 /// The underlying file system watcher.
98 pub(crate) watcher: RecommendedWatcher,
99 /// Receiver for file change events.
100 pub(crate) rx: Receiver<Result<Event, notify::Error>>,
101 /// Configuration for the watcher.
102 pub(crate) config: WatchConfig,
103 /// Paths that have changed since last check.
104 pub(crate) changed_paths: Vec<PathBuf>,
105}