Skip to main content

notify/
config.rs

1//! Configuration types
2
3use crate::filter::{EntryKind, IgnoreFilter};
4use std::{path::Path, time::Duration};
5
6/// Default maximum number of paths to pass to FSEvents, chosen to stay
7/// well under the macOS default file descriptor soft limit (256).
8pub const DEFAULT_MAX_FSEVENT_PATHS: usize = 128;
9
10/// Indicates how the path should be watched
11#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
12pub struct WatchMode {
13    /// Indicates whether to watch sub-directories as well
14    pub recursive_mode: RecursiveMode,
15    /// Indicates what happens when the relationship of the physical entity and the file path changes
16    pub target_mode: TargetMode,
17}
18
19impl WatchMode {
20    /// Creates a WatchMode that watches directories recursively and tracks the file path
21    #[must_use]
22    pub fn recursive() -> Self {
23        Self {
24            recursive_mode: RecursiveMode::Recursive,
25            target_mode: TargetMode::TrackPath,
26        }
27    }
28
29    /// Creates a WatchMode that watches only the provided directory and tracks the file path
30    #[must_use]
31    pub fn non_recursive() -> Self {
32        Self {
33            recursive_mode: RecursiveMode::NonRecursive,
34            target_mode: TargetMode::TrackPath,
35        }
36    }
37
38    pub(crate) fn upgrade_with(&mut self, other: WatchMode) {
39        self.recursive_mode = self.recursive_mode.upgraded_with(other.recursive_mode);
40        self.target_mode = self.target_mode.upgraded_with(other.target_mode);
41    }
42}
43
44/// Indicates whether only the provided directory or its sub-directories as well should be watched
45#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
46pub enum RecursiveMode {
47    /// Watch all sub-directories as well, including directories created after installing the watch
48    Recursive,
49
50    /// Watch only the provided directory
51    NonRecursive,
52}
53
54impl RecursiveMode {
55    #[expect(clippy::trivially_copy_pass_by_ref)]
56    pub(crate) fn is_recursive(&self) -> bool {
57        match *self {
58            RecursiveMode::Recursive => true,
59            RecursiveMode::NonRecursive => false,
60        }
61    }
62
63    pub(crate) fn upgraded_with(self, other: Self) -> Self {
64        match self {
65            RecursiveMode::Recursive => self,
66            RecursiveMode::NonRecursive => {
67                if other == RecursiveMode::Recursive {
68                    other
69                } else {
70                    self
71                }
72            }
73        }
74    }
75}
76
77/// Indicates what happens when the relationship of the physical entity and the file path changes
78#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
79pub enum TargetMode {
80    /// Tracks the file path.
81    ///
82    /// If the underlying physical entity (inode/File ID) at this path is replaced
83    /// (e.g., by a move/rename operation), the watch continues to monitor the new entity
84    /// that now occupies the path.
85    ///
86    /// TODO: watching nested non-existent paths is not implemented yet. <https://github.com/rolldown/notify/issues/32>
87    TrackPath,
88
89    /// Does not track the file path, nor the physical entity.
90    ///
91    /// If the underlying physical entity (inode/File ID) is replaced
92    /// (e.g., by a move/rename operation), the watch stops monitoring.
93    ///
94    /// TODO: fsevents backend and Windows backend and polling backend does not unwatch on physical entity change yet. <https://github.com/rolldown/notify/issues/33>
95    NoTrack,
96}
97
98impl TargetMode {
99    pub(crate) fn upgraded_with(self, other: Self) -> Self {
100        match self {
101            TargetMode::TrackPath => self,
102            TargetMode::NoTrack => {
103                if other == TargetMode::TrackPath {
104                    other
105                } else {
106                    self
107                }
108            }
109        }
110    }
111}
112
113/// Watcher Backend configuration
114///
115/// This contains multiple settings that may relate to only one specific backend,
116/// such as to correctly configure each backend regardless of what is selected during runtime.
117///
118/// ```rust
119/// # use std::time::Duration;
120/// # use notify::Config;
121/// let config = Config::default()
122///     .with_poll_interval(Duration::from_secs(2))
123///     .with_compare_contents(true);
124/// ```
125///
126/// Some options can be changed during runtime, others have to be set when creating the watcher backend.
127#[derive(Clone, Debug)]
128pub struct Config {
129    /// See [Config::with_poll_interval]
130    poll_interval: Option<Duration>,
131
132    /// See [Config::with_compare_contents]
133    compare_contents: bool,
134
135    follow_symlinks: bool,
136
137    /// See [Config::with_max_fsevent_paths]
138    max_fsevent_paths: usize,
139
140    /// See [Config::with_ignored]
141    ignored: IgnoreFilter,
142}
143
144impl Config {
145    /// For the [`PollWatcher`](crate::PollWatcher) backend.
146    ///
147    /// Interval between each re-scan attempt. This can be extremely expensive for large
148    /// file trees so it is recommended to measure and tune accordingly.
149    ///
150    /// The default poll frequency is 30 seconds.
151    ///
152    /// This will enable automatic polling, overwriting [`with_manual_polling()`](Config::with_manual_polling).
153    #[must_use]
154    pub fn with_poll_interval(mut self, dur: Duration) -> Self {
155        // TODO: v7.0 break signature to option
156        self.poll_interval = Some(dur);
157        self
158    }
159
160    /// Returns current setting
161    #[must_use]
162    pub fn poll_interval(&self) -> Option<Duration> {
163        // Changed Signature to Option
164        self.poll_interval
165    }
166
167    /// For the [`PollWatcher`](crate::PollWatcher) backend.
168    ///
169    /// Disable automatic polling. Requires calling [`crate::PollWatcher::poll()`] manually.
170    ///
171    /// This will disable automatic polling, overwriting [`with_poll_interval()`](Config::with_poll_interval).
172    #[must_use]
173    pub fn with_manual_polling(mut self) -> Self {
174        self.poll_interval = None;
175        self
176    }
177
178    /// For the [`PollWatcher`](crate::PollWatcher) backend.
179    ///
180    /// Optional feature that will evaluate the contents of changed files to determine if
181    /// they have indeed changed using a fast hashing algorithm.  This is especially important
182    /// for pseudo filesystems like those on Linux under /sys and /proc which are not obligated
183    /// to respect any other filesystem norms such as modification timestamps, file sizes, etc.
184    /// By enabling this feature, performance will be significantly impacted as all files will
185    /// need to be read and hashed at each `poll_interval`.
186    ///
187    /// This can't be changed during runtime. Off by default.
188    #[must_use]
189    pub fn with_compare_contents(mut self, compare_contents: bool) -> Self {
190        self.compare_contents = compare_contents;
191        self
192    }
193
194    /// Returns current setting
195    #[must_use]
196    pub fn compare_contents(&self) -> bool {
197        self.compare_contents
198    }
199
200    /// For the [INotifyWatcher](crate::INotifyWatcher), [KqueueWatcher](crate::KqueueWatcher),
201    /// and [PollWatcher](crate::PollWatcher).
202    ///
203    /// Determine if symbolic links should be followed when recursively watching a directory.
204    ///
205    /// This can't be changed during runtime. On by default.
206    #[must_use]
207    pub fn with_follow_symlinks(mut self, follow_symlinks: bool) -> Self {
208        self.follow_symlinks = follow_symlinks;
209        self
210    }
211
212    /// Returns current setting
213    #[must_use]
214    pub fn follow_symlinks(&self) -> bool {
215        self.follow_symlinks
216    }
217
218    /// For the [`FsEventWatcher`](crate::FsEventWatcher) backend.
219    ///
220    /// Maximum number of paths to pass to FSEvents. When the number of
221    /// watched paths exceeds this limit, the watcher automatically watches
222    /// parent directories instead of individual paths to reduce file
223    /// descriptor usage.
224    ///
225    /// The default is [`DEFAULT_MAX_FSEVENT_PATHS`]. Set to `0` to disable
226    /// consolidation.
227    ///
228    /// This can't be changed during runtime.
229    #[must_use]
230    pub fn with_max_fsevent_paths(mut self, max_paths: usize) -> Self {
231        self.max_fsevent_paths = max_paths;
232        self
233    }
234
235    /// Returns current setting.
236    ///
237    /// `0` means consolidation is disabled.
238    #[must_use]
239    pub fn max_fsevent_paths(&self) -> usize {
240        self.max_fsevent_paths
241    }
242
243    /// Ignore the paths for which `ignored` returns `true`.
244    ///
245    /// An ignored path is never watched, scanned or reported. This also applies to the paths
246    /// passed to [`Watcher::watch`](crate::Watcher::watch): watching or unwatching an ignored
247    /// path succeeds and does nothing. Only the non-ignored side of a rename is reported.
248    ///
249    /// The filter is called with one path at a time and gets no information about the parent
250    /// directories. To ignore a directory with everything inside it, it must return `true` for
251    /// every path below that directory, as a glob over the whole path does. `kind` says whether
252    /// the path is a directory, or [`EntryKind::Unknown`] if the watcher cannot tell: for a path
253    /// that does not exist, and for every event on Windows.
254    ///
255    /// inotify, kqueue and poll do not descend into ignored directories, so no watch resources
256    /// are spent on them. FSEvents and Windows watch recursively in the kernel and drop the
257    /// events of ignored paths instead.
258    ///
259    /// The filter runs on the watcher thread and on the thread that calls
260    /// [`Watcher::watch`](crate::Watcher::watch): it must be fast, must not block, and must
261    /// always return the same answer for the same arguments.
262    ///
263    /// This can't be changed during runtime. Nothing is ignored by default.
264    ///
265    /// ```
266    /// use notify::Config;
267    ///
268    /// // ignore every `node_modules` directory and everything inside it
269    /// let config = Config::default().with_ignored(|path, _kind| {
270    ///     path.components().any(|component| component.as_os_str() == "node_modules")
271    /// });
272    /// ```
273    #[must_use]
274    pub fn with_ignored(
275        mut self,
276        ignored: impl Fn(&Path, EntryKind) -> bool + Send + Sync + 'static,
277    ) -> Self {
278        self.ignored = IgnoreFilter::new(ignored);
279        self
280    }
281
282    /// Returns current setting.
283    #[must_use]
284    pub fn ignored(&self) -> &IgnoreFilter {
285        &self.ignored
286    }
287
288    /// Returns a copy without the ignore filter.
289    pub(crate) fn without_ignored(&self) -> Self {
290        Self {
291            ignored: IgnoreFilter::default(),
292            ..self.clone()
293        }
294    }
295}
296
297impl Default for Config {
298    fn default() -> Self {
299        Self {
300            poll_interval: Some(Duration::from_secs(30)),
301            compare_contents: false,
302            follow_symlinks: true,
303            max_fsevent_paths: DEFAULT_MAX_FSEVENT_PATHS,
304            ignored: IgnoreFilter::default(),
305        }
306    }
307}