notify 9.0.0

Cross-platform filesystem notification library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! Configuration types

use notify_types::event::EventKindMask;
use std::{
    path::{Path, PathBuf},
    time::Duration,
};

/// Indicates whether only the provided directory or its sub-directories as well should be watched
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
pub enum RecursiveMode {
    /// Watch all sub-directories as well, including directories created after installing the watch
    Recursive,

    /// Watch only the provided directory
    NonRecursive,
}

impl RecursiveMode {
    pub(crate) fn is_recursive(&self) -> bool {
        match *self {
            RecursiveMode::Recursive => true,
            RecursiveMode::NonRecursive => false,
        }
    }
}

/// Controls how path separators are represented in emitted event paths on Windows.
///
/// This applies to `ReadDirectoryChangesWatcher`.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Default)]
pub enum WindowsPathSeparatorStyle {
    /// Infer separator style from each watched input path.
    ///
    /// For example, watching `C:/tmp` yields paths with `/`, while watching `C:\tmp`
    /// yields paths with `\`.
    #[default]
    Auto,

    /// Always use `/` in emitted event paths.
    Slash,

    /// Always use `\` in emitted event paths.
    Backslash,
}

/// Watcher Backend configuration
///
/// This contains multiple settings that may relate to only one specific backend,
/// such as to correctly configure each backend regardless of what is selected during runtime.
///
/// ```rust
/// # use std::time::Duration;
/// # use notify::Config;
/// let config = Config::default()
///     .with_poll_interval(Duration::from_secs(2))
///     .with_compare_contents(true);
/// ```
///
/// Some options can be changed during runtime, others have to be set when creating the watcher backend.
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
pub struct Config {
    /// See [Config::with_poll_interval]
    poll_interval: Option<Duration>,

    /// See [Config::with_compare_contents]
    compare_contents: bool,

    follow_symlinks: bool,

    /// See [Config::with_event_kinds]
    event_kinds: EventKindMask,

    /// See [Config::with_windows_path_separator_style]
    windows_path_separator_style: WindowsPathSeparatorStyle,

    /// See [Config::with_windows_extended_information]
    windows_extended_information: bool,

    /// See [Config::with_fsevent_latency]
    fsevent_latency: Duration,
}

impl Config {
    /// For the [`PollWatcher`](crate::PollWatcher) backend.
    ///
    /// Interval between each re-scan attempt. This can be extremely expensive for large
    /// file trees so it is recommended to measure and tune accordingly.
    ///
    /// The default poll frequency is 30 seconds.
    ///
    /// This will enable automatic polling, overwriting [`with_manual_polling()`](Config::with_manual_polling).
    #[must_use]
    pub fn with_poll_interval(mut self, dur: Duration) -> Self {
        self.poll_interval = Some(dur);
        self
    }

    /// Returns current setting
    #[must_use]
    pub fn poll_interval(&self) -> Option<Duration> {
        self.poll_interval
    }

    /// For the [`PollWatcher`](crate::PollWatcher) backend.
    ///
    /// Disable automatic polling. Requires calling [`crate::PollWatcher::poll()`] manually.
    ///
    /// This will disable automatic polling, overwriting [`with_poll_interval()`](Config::with_poll_interval).
    #[must_use]
    pub fn with_manual_polling(mut self) -> Self {
        self.poll_interval = None;
        self
    }

    /// Compare file contents for [`PollWatcher`](crate::PollWatcher).
    ///
    /// When enabled, each scan reads and hashes every regular file, increasing I/O and CPU usage.
    /// Content changes produce `Modify(Data(Any))`; modification time changes with identical
    /// contents produce `Modify(Metadata(WriteTime))`.
    ///
    /// Without it, changes to a regular file's size or modification time produce `Modify(Data(Any))`,
    /// including `touch`. Changes preserving both go undetected, as can happen on `/proc` and `/sys`.
    ///
    /// Disabled by default; cannot be changed at runtime.
    #[must_use]
    pub fn with_compare_contents(mut self, compare_contents: bool) -> Self {
        self.compare_contents = compare_contents;
        self
    }

    /// Returns current setting
    #[must_use]
    pub fn compare_contents(&self) -> bool {
        self.compare_contents
    }

    /// For the `INotifyWatcher`, `KqueueWatcher`, and [`PollWatcher`](crate::PollWatcher).
    ///
    /// Determine if symbolic links should be followed when recursively watching a directory.
    ///
    /// This can't be changed during runtime. On by default.
    #[must_use]
    pub fn with_follow_symlinks(mut self, follow_symlinks: bool) -> Self {
        self.follow_symlinks = follow_symlinks;
        self
    }

    /// Returns current setting
    #[must_use]
    pub fn follow_symlinks(&self) -> bool {
        self.follow_symlinks
    }

    /// Filter which event kinds are monitored.
    ///
    /// This allows you to control which types of filesystem events are delivered
    /// to your event handler. On backends that support kernel-level filtering
    /// (inotify), the mask is translated to native flags for optimal
    /// performance. On other backends (kqueue, Windows, FSEvents, PollWatcher),
    /// filtering is applied in userspace.
    ///
    /// The default is `CORE | ACCESS_OPEN | ACCESS_CLOSE`, the events that notify v8 reported.
    /// [`EventKindMask::ALL`] (also `EventKindMask::default()`) adds `ACCESS_CLOSE_NOWRITE`,
    /// which reports closing a file or directory that was opened without write access.
    /// Recursive registration itself generates access events as it reads directories.
    /// Use [`EventKindMask::CORE`] to exclude access events, or `CORE | ACCESS_CLOSE`
    /// to keep close-after-write notifications without these directory access events.
    ///
    /// This can't be changed during runtime.
    ///
    /// # Example
    ///
    /// ```rust
    /// use notify::{Config, EventKindMask};
    ///
    /// // Only monitor file creation and deletion
    /// let config = Config::default()
    ///     .with_event_kinds(EventKindMask::CREATE | EventKindMask::REMOVE);
    ///
    /// // Monitor everything including access events
    /// let config_all = Config::default()
    ///     .with_event_kinds(EventKindMask::ALL);
    /// ```
    #[must_use]
    pub fn with_event_kinds(mut self, event_kinds: EventKindMask) -> Self {
        self.event_kinds = event_kinds;
        self
    }

    /// Returns current setting
    #[must_use]
    pub fn event_kinds(&self) -> EventKindMask {
        self.event_kinds
    }

    /// For the `ReadDirectoryChangesWatcher` backend.
    ///
    /// Controls path separator normalization for emitted event paths on Windows.
    ///
    /// The default is [`WindowsPathSeparatorStyle::Auto`], which preserves the
    /// separator style implied by each watched input path.
    ///
    /// This can't be changed during runtime.
    #[must_use]
    pub fn with_windows_path_separator_style(mut self, style: WindowsPathSeparatorStyle) -> Self {
        self.windows_path_separator_style = style;
        self
    }

    /// Returns current setting.
    #[must_use]
    pub fn windows_path_separator_style(&self) -> WindowsPathSeparatorStyle {
        self.windows_path_separator_style
    }

    /// Use `ReadDirectoryChangesExW` to classify created and removed entries as files or folders.
    /// Reparse points are not followed; modification events remain `ModifyKind::Any`.
    ///
    /// Requires Windows 10 1709 / Windows Server 2019 or later and NTFS. Unsupported APIs
    /// fail at construction; unsupported filesystems fail at `watch()` or via the event handler.
    /// No automatic fallback: use a default-configured watcher for unsupported paths.
    ///
    /// Off by default and ignored by other backends. Cannot be changed via
    /// [`Watcher::configure`](crate::Watcher::configure); create a new watcher to switch modes.
    /// Both notification modes use a 64 KiB read buffer per OS watch.
    #[must_use]
    pub fn with_windows_extended_information(mut self, extended_information: bool) -> Self {
        self.windows_extended_information = extended_information;
        self
    }

    /// Returns whether extended directory notifications are enabled on Windows.
    #[must_use]
    pub fn windows_extended_information(&self) -> bool {
        self.windows_extended_information
    }

    /// For the `FsEventWatcher` backend.
    ///
    /// The latency passed to `FSEventStreamCreate`: how long the FSEvents service waits
    /// after hearing about an event from the kernel before invoking the callback. A larger
    /// value lets the system coalesce bursts of changes into fewer callbacks at the cost of
    /// higher delivery latency.
    ///
    /// This watcher is created with `kFSEventStreamCreateFlagNoDefer`, so the first event in
    /// an idle period is delivered immediately; only subsequent events get coalesced within
    /// the latency window.
    ///
    /// The default is [`Duration::ZERO`].
    ///
    /// This can't be changed during runtime.
    #[must_use]
    pub fn with_fsevent_latency(mut self, latency: Duration) -> Self {
        self.fsevent_latency = latency;
        self
    }

    /// Returns current setting
    #[must_use]
    pub fn fsevent_latency(&self) -> Duration {
        self.fsevent_latency
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            poll_interval: Some(Duration::from_secs(30)),
            compare_contents: false,
            follow_symlinks: true,
            event_kinds: EventKindMask::CORE
                | EventKindMask::ACCESS_OPEN
                | EventKindMask::ACCESS_CLOSE,
            windows_path_separator_style: WindowsPathSeparatorStyle::Auto,
            windows_extended_information: false,
            fsevent_latency: Duration::ZERO,
        }
    }
}

/// Single watch backend configuration
///
/// This contains some settings that may relate to only one specific backend,
/// such as to correctly configure each backend regardless of what is selected during runtime.
#[derive(Clone, Debug)]
pub struct WatchPathConfig {
    recursive_mode: RecursiveMode,
    dereference_symlinks: bool,
    user_data: Option<u64>,
}

impl WatchPathConfig {
    /// Creates new instance with provided [`RecursiveMode`]
    #[must_use]
    pub fn new(recursive_mode: RecursiveMode) -> Self {
        Self {
            recursive_mode,
            dereference_symlinks: true,
            user_data: None,
        }
    }

    /// Set [`RecursiveMode`] for the watch
    #[must_use]
    pub fn with_recursive_mode(mut self, recursive_mode: RecursiveMode) -> Self {
        self.recursive_mode = recursive_mode;
        self
    }

    /// Returns current setting
    #[must_use]
    pub fn recursive_mode(&self) -> RecursiveMode {
        self.recursive_mode
    }

    /// Set whether a symbolic link is followed to its destination, for
    /// [`RecursiveMode::NonRecursive`] watches on the `INotifyWatcher`.
    #[must_use]
    pub fn with_dereference_symlinks(mut self, dereference_symlinks: bool) -> Self {
        self.dereference_symlinks = dereference_symlinks;
        self
    }

    /// Returns current setting
    #[must_use]
    pub fn dereference_symlinks(&self) -> bool {
        self.dereference_symlinks
    }

    /// Attaches an application-defined value to events and errors from this watch.
    ///
    /// All built-in backends expose it through [`Event::user_data`](crate::Event::user_data)
    /// and [`Error::user_data`](crate::Error::user_data).
    /// Recursive descendants inherit the value; explicitly registered watches keep their own.
    /// Rewatching replaces it, and [`Watcher::watch`](crate::Watcher::watch) resets it to `None`.
    ///
    /// ```no_run
    /// use notify::{Event, RecursiveMode, Result, WatchPathConfig, Watcher};
    /// use std::path::Path;
    ///
    /// # fn main() -> Result<()> {
    /// let mut watcher = notify::recommended_watcher(|result: Result<Event>| {
    ///     if let Ok(event) = result {
    ///         println!("watch {:?}: {:?}", event.user_data(), event.paths);
    ///     }
    /// })?;
    /// watcher.watch_with(
    ///     Path::new("src"),
    ///     WatchPathConfig::new(RecursiveMode::Recursive).with_user_data(42),
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn with_user_data(mut self, user_data: u64) -> Self {
        self.user_data = Some(user_data);
        self
    }

    /// Returns the value attached to this watch, or `None` if none was set.
    #[must_use]
    pub fn user_data(&self) -> Option<u64> {
        self.user_data
    }
}

/// A registered path and its recursive mode, returned by
/// [`Watcher::watched_paths`](crate::Watcher::watched_paths).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct WatchedPath {
    /// The watched path, as it was passed to the watcher.
    pub path: PathBuf,
    /// Whether the watch covers the path's descendants.
    pub recursive_mode: RecursiveMode,
}

impl WatchedPath {
    /// Creates a watched path with the given path and recursive mode.
    ///
    /// # Examples
    ///
    /// ```
    /// use notify::{RecursiveMode, WatchedPath};
    ///
    /// let watched = WatchedPath::new("src".into(), RecursiveMode::Recursive);
    /// ```
    #[must_use]
    pub fn new(path: PathBuf, recursive_mode: RecursiveMode) -> Self {
        Self {
            path,
            recursive_mode,
        }
    }
}

/// An operation to apply to a watcher
///
/// See [`Watcher::update_paths`](crate::Watcher::update_paths) for more information.
#[derive(Debug)]
#[non_exhaustive]
pub enum PathOp {
    /// Path should be watched
    Watch(PathBuf, WatchPathConfig),

    /// Path should be unwatched
    Unwatch(PathBuf),
}

impl PathOp {
    /// Watch the path with [`RecursiveMode::Recursive`]
    #[must_use]
    pub fn watch_recursive<P: Into<PathBuf>>(path: P) -> Self {
        Self::Watch(path.into(), WatchPathConfig::new(RecursiveMode::Recursive))
    }

    /// Watch the path with [`RecursiveMode::NonRecursive`]
    #[must_use]
    pub fn watch_non_recursive<P: Into<PathBuf>>(path: P) -> Self {
        Self::Watch(
            path.into(),
            WatchPathConfig::new(RecursiveMode::NonRecursive),
        )
    }

    /// Unwatch the path
    #[must_use]
    pub fn unwatch<P: Into<PathBuf>>(path: P) -> Self {
        Self::Unwatch(path.into())
    }

    /// Returns the path associated with this operation.
    #[must_use]
    pub fn as_path(&self) -> &Path {
        match self {
            PathOp::Watch(p, _) => p,
            PathOp::Unwatch(p) => p,
        }
    }

    /// Returns the path associated with this operation.
    #[must_use]
    pub fn into_path(self) -> PathBuf {
        match self {
            PathOp::Watch(p, _) => p,
            PathOp::Unwatch(p) => p,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use notify_types::event::EventKindMask;

    #[test]
    fn config_default_event_kinds_excludes_close_nowrite() {
        let config = Config::default();
        assert_eq!(
            config.event_kinds(),
            EventKindMask::ALL - EventKindMask::ACCESS_CLOSE_NOWRITE
        );
    }

    #[test]
    fn config_with_event_kinds() {
        let mask = EventKindMask::CREATE | EventKindMask::REMOVE;
        let config = Config::default().with_event_kinds(mask);
        assert_eq!(config.event_kinds(), mask);
    }

    #[test]
    fn config_with_all_events_includes_access() {
        let config = Config::default().with_event_kinds(EventKindMask::ALL);
        assert!(config.event_kinds().intersects(EventKindMask::ALL_ACCESS));
    }

    #[test]
    fn config_with_empty_mask() {
        let config = Config::default().with_event_kinds(EventKindMask::empty());
        assert!(config.event_kinds().is_empty());
    }

    #[test]
    fn config_default_windows_separator_style_is_auto() {
        let config = Config::default();
        assert_eq!(
            config.windows_path_separator_style(),
            WindowsPathSeparatorStyle::Auto
        );
    }

    #[test]
    fn config_with_windows_separator_style() {
        let config =
            Config::default().with_windows_path_separator_style(WindowsPathSeparatorStyle::Slash);
        assert_eq!(
            config.windows_path_separator_style(),
            WindowsPathSeparatorStyle::Slash
        );
    }

    #[test]
    fn config_default_fsevent_latency_is_zero() {
        assert_eq!(Config::default().fsevent_latency(), Duration::ZERO);
    }

    #[test]
    fn config_with_fsevent_latency() {
        let latency = Duration::from_millis(250);
        let config = Config::default().with_fsevent_latency(latency);
        assert_eq!(config.fsevent_latency(), latency);
    }
}