Skip to main content

notify_types/
event.rs

1//! The `Event` type and the hierarchical `EventKind` descriptor.
2
3use std::{
4    fmt,
5    hash::{Hash, Hasher},
6    path::PathBuf,
7};
8
9use bitflags::bitflags;
10
11#[cfg(feature = "serde")]
12use serde::{Deserialize, Serialize};
13
14/// An event describing open or close operations on files.
15#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
16#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
17#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
18pub enum AccessMode {
19    /// The catch-all case, to be used when the specific kind of event is unknown.
20    Any,
21
22    /// An event emitted when the file is executed, or the folder opened.
23    Execute,
24
25    /// An event emitted when the file is opened for reading.
26    Read,
27
28    /// An event emitted when the file is opened for writing.
29    Write,
30
31    /// An event which specific kind is known but cannot be represented otherwise.
32    Other,
33}
34
35/// An event describing non-mutating access operations on files.
36#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
37#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
38#[cfg_attr(feature = "serde", serde(tag = "kind", content = "mode"))]
39#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
40pub enum AccessKind {
41    /// The catch-all case, to be used when the specific kind of event is unknown.
42    Any,
43
44    /// An event emitted when the file is read.
45    Read,
46
47    /// An event emitted when the file, or a handle to the file, is opened.
48    Open(AccessMode),
49
50    /// An event emitted when the file, or a handle to the file, is closed.
51    Close(AccessMode),
52
53    /// An event which specific kind is known but cannot be represented otherwise.
54    Other,
55}
56
57/// An event describing creation operations on files.
58#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
59#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
60#[cfg_attr(feature = "serde", serde(tag = "kind"))]
61#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
62pub enum CreateKind {
63    /// The catch-all case, to be used when the specific kind of event is unknown.
64    Any,
65
66    /// An event which results in the creation of a file.
67    File,
68
69    /// An event which results in the creation of a folder.
70    Folder,
71
72    /// An event which specific kind is known but cannot be represented otherwise.
73    Other,
74}
75
76/// An event emitted when the data content of a file is changed.
77#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
78#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
79#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
80pub enum DataChange {
81    /// The catch-all case, to be used when the specific kind of event is unknown.
82    Any,
83
84    /// An event emitted when the size of the data is changed.
85    Size,
86
87    /// An event emitted when the content of the data is changed.
88    Content,
89
90    /// An event which specific kind is known but cannot be represented otherwise.
91    Other,
92}
93
94/// An event emitted when the metadata of a file or folder is changed.
95#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
96#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
97#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
98pub enum MetadataKind {
99    /// The catch-all case, to be used when the specific kind of event is unknown.
100    Any,
101
102    /// An event emitted when the access time of the file or folder is changed.
103    AccessTime,
104
105    /// An event emitted when the write or modify time of the file or folder is changed.
106    WriteTime,
107
108    /// An event emitted when the permissions of the file or folder are changed.
109    Permissions,
110
111    /// An event emitted when the ownership of the file or folder is changed.
112    Ownership,
113
114    /// An event emitted when an extended attribute of the file or folder is changed.
115    ///
116    /// If the extended attribute's name or type is known, it should be provided in the
117    /// `Info` event attribute.
118    Extended,
119
120    /// An event which specific kind is known but cannot be represented otherwise.
121    Other,
122}
123
124/// An event emitted when the name of a file or folder is changed.
125#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
126#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
127#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
128pub enum RenameMode {
129    /// The catch-all case, to be used when the specific kind of event is unknown.
130    Any,
131
132    /// An event emitted on the file or folder resulting from a rename.
133    To,
134
135    /// An event emitted on the file or folder that was renamed.
136    From,
137
138    /// A single event emitted with both the `From` and `To` paths.
139    ///
140    /// This event should be emitted when both source and target are known. The paths should be
141    /// provided in this exact order (from, to).
142    Both,
143
144    /// An event which specific kind is known but cannot be represented otherwise.
145    Other,
146}
147
148/// An event describing mutation of content, name, or metadata.
149#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
150#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
151#[cfg_attr(feature = "serde", serde(tag = "kind", content = "mode"))]
152#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
153pub enum ModifyKind {
154    /// The catch-all case, to be used when the specific kind of event is unknown.
155    Any,
156
157    /// An event emitted when the data content of a file is changed.
158    Data(DataChange),
159
160    /// An event emitted when the metadata of a file or folder is changed.
161    Metadata(MetadataKind),
162
163    /// An event emitted when the name of a file or folder is changed.
164    #[cfg_attr(feature = "serde", serde(rename = "rename"))]
165    Name(RenameMode),
166
167    /// An event which specific kind is known but cannot be represented otherwise.
168    Other,
169}
170
171/// An event describing removal operations on files.
172#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
173#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
174#[cfg_attr(feature = "serde", serde(tag = "kind"))]
175#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
176pub enum RemoveKind {
177    /// The catch-all case, to be used when the specific kind of event is unknown.
178    Any,
179
180    /// An event emitted when a file is removed.
181    File,
182
183    /// An event emitted when a folder is removed.
184    Folder,
185
186    /// An event which specific kind is known but cannot be represented otherwise.
187    Other,
188}
189
190/// Top-level event kind.
191///
192/// This is arguably the most important classification for events. All subkinds below this one
193/// represent details that may or may not be available for any particular backend, but most tools
194/// and Notify systems will only care about which of these four general kinds an event is about.
195#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
196#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
197#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
198#[cfg_attr(
199    all(feature = "serde", not(feature = "serialization-compat-6")),
200    serde(tag = "type")
201)]
202pub enum EventKind {
203    /// The catch-all event kind, for unsupported/unknown events.
204    ///
205    /// This variant should be used as the "else" case when mapping native kernel bitmasks or
206    /// bitmaps, such that if the mask is ever extended with new event types the backend will not
207    /// gain bugs due to not matching new unknown event types.
208    ///
209    /// This variant is also the default variant used when Notify is in "imprecise" mode.
210    #[default]
211    Any,
212
213    /// An event describing non-mutating access operations on files.
214    ///
215    /// This event is about opening and closing file handles, as well as executing files, and any
216    /// other such event that is about accessing files, folders, or other structures rather than
217    /// mutating them.
218    ///
219    /// Only some platforms are capable of generating these.
220    Access(AccessKind),
221
222    /// An event describing creation operations on files.
223    ///
224    /// This event is about the creation of files, folders, or other structures but not about e.g.
225    /// writing new content into them.
226    Create(CreateKind),
227
228    /// An event describing mutation of content, name, or metadata.
229    ///
230    /// This event is about the mutation of files', folders', or other structures' content, name
231    /// (path), or associated metadata (attributes).
232    Modify(ModifyKind),
233
234    /// An event describing removal operations on files.
235    ///
236    /// This event is about the removal of files, folders, or other structures but not e.g. erasing
237    /// content from them. This may also be triggered for renames/moves that move files _out of the
238    /// watched subpath_.
239    ///
240    /// Some editors also trigger Remove events when saving files as they may opt for removing (or
241    /// renaming) the original then creating a new file in-place.
242    Remove(RemoveKind),
243
244    /// An event not fitting in any of the above four categories.
245    ///
246    /// This may be used for meta-events about the watch itself.
247    Other,
248}
249
250impl EventKind {
251    /// Indicates whether an event is an Access variant.
252    #[must_use]
253    pub fn is_access(&self) -> bool {
254        matches!(self, EventKind::Access(_))
255    }
256
257    /// Indicates whether an event is a Create variant.
258    #[must_use]
259    pub fn is_create(&self) -> bool {
260        matches!(self, EventKind::Create(_))
261    }
262
263    /// Indicates whether an event is a Modify variant.
264    #[must_use]
265    pub fn is_modify(&self) -> bool {
266        matches!(self, EventKind::Modify(_))
267    }
268
269    /// Indicates whether an event is a Remove variant.
270    #[must_use]
271    pub fn is_remove(&self) -> bool {
272        matches!(self, EventKind::Remove(_))
273    }
274
275    /// Indicates whether an event is an Other variant.
276    #[must_use]
277    pub fn is_other(&self) -> bool {
278        matches!(self, EventKind::Other)
279    }
280}
281
282bitflags! {
283    /// A bitmask specifying which event kinds to monitor.
284    ///
285    /// This type allows fine-grained control over which filesystem events are reported.
286    /// On backends that support kernel-level filtering (inotify), the mask is
287    /// translated to native flags for optimal performance. On other backends (kqueue,
288    /// Windows, FSEvents, PollWatcher), filtering is applied in userspace.
289    ///
290    /// # Examples
291    ///
292    /// ```
293    /// use notify_types::event::EventKindMask;
294    ///
295    /// // Monitor only file creations and deletions
296    /// let mask = EventKindMask::CREATE | EventKindMask::REMOVE;
297    ///
298    /// // Monitor everything including access events
299    /// let all = EventKindMask::ALL;
300    ///
301    /// // Default: includes all events (matches Config::default())
302    /// let default = EventKindMask::default();
303    /// assert_eq!(default, EventKindMask::ALL);
304    /// ```
305    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
306    #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
307    pub struct EventKindMask: u32 {
308        /// Monitor file/folder creation events.
309        const CREATE = 0b0000_0001;
310
311        /// Monitor file/folder removal events.
312        const REMOVE = 0b0000_0010;
313
314        /// Monitor data modification events (content/size changes).
315        const MODIFY_DATA = 0b0000_0100;
316
317        /// Monitor metadata modification events (permissions, timestamps, etc).
318        const MODIFY_META = 0b0000_1000;
319
320        /// Monitor name/rename events.
321        const MODIFY_NAME = 0b0001_0000;
322
323        /// Monitor file open events.
324        const ACCESS_OPEN = 0b0010_0000;
325
326        /// Monitor file close events after writing.
327        /// This fires when a file opened for writing is closed.
328        const ACCESS_CLOSE = 0b0100_0000;
329
330        /// Monitor file close events after read-only access.
331        /// This fires when a file opened for reading (not writing) is closed.
332        /// Note: This can be very noisy and may cause queue overflow on busy systems.
333        const ACCESS_CLOSE_NOWRITE = 0b1000_0000;
334
335        /// All modify events (data, metadata, and name changes).
336        const ALL_MODIFY = Self::MODIFY_DATA.bits() | Self::MODIFY_META.bits() | Self::MODIFY_NAME.bits();
337
338        /// All access events (open, close-write, and close-nowrite).
339        const ALL_ACCESS = Self::ACCESS_OPEN.bits() | Self::ACCESS_CLOSE.bits() | Self::ACCESS_CLOSE_NOWRITE.bits();
340
341        /// Core events: create, remove, and all modify events.
342        const CORE = Self::CREATE.bits() | Self::REMOVE.bits() | Self::ALL_MODIFY.bits();
343
344        /// All events including access events.
345        /// This is the default.
346        const ALL = Self::CORE.bits() | Self::ALL_ACCESS.bits();
347    }
348}
349
350impl Default for EventKindMask {
351    fn default() -> Self {
352        EventKindMask::ALL
353    }
354}
355
356impl EventKindMask {
357    /// Returns whether the given event kind matches this mask.
358    ///
359    /// `EventKind::Any` and `EventKind::Other` always pass regardless of the mask,
360    /// as they represent meta-events that should not be filtered.
361    ///
362    /// # Examples
363    ///
364    /// ```
365    /// use notify_types::event::{EventKindMask, EventKind, CreateKind, AccessKind, AccessMode};
366    ///
367    /// let mask = EventKindMask::CREATE;
368    /// assert!(mask.matches(&EventKind::Create(CreateKind::File)));
369    /// assert!(!mask.matches(&EventKind::Access(AccessKind::Open(AccessMode::Read))));
370    ///
371    /// // Any and Other always pass
372    /// let empty = EventKindMask::empty();
373    /// assert!(empty.matches(&EventKind::Any));
374    /// assert!(empty.matches(&EventKind::Other));
375    /// ```
376    #[must_use]
377    pub fn matches(&self, kind: &EventKind) -> bool {
378        match kind {
379            // Meta-events always pass
380            EventKind::Any | EventKind::Other => true,
381
382            // Create events
383            EventKind::Create(_) => self.intersects(EventKindMask::CREATE),
384
385            // Remove events
386            EventKind::Remove(_) => self.intersects(EventKindMask::REMOVE),
387
388            // Modify events - check subkind
389            EventKind::Modify(modify_kind) => match modify_kind {
390                ModifyKind::Data(_) => self.intersects(EventKindMask::MODIFY_DATA),
391                ModifyKind::Metadata(_) => self.intersects(EventKindMask::MODIFY_META),
392                ModifyKind::Name(_) => self.intersects(EventKindMask::MODIFY_NAME),
393                // ModifyKind::Any and ModifyKind::Other pass if any modify flag is set
394                ModifyKind::Any | ModifyKind::Other => self.intersects(EventKindMask::ALL_MODIFY),
395            },
396
397            // Access events - check subkind
398            EventKind::Access(access_kind) => match access_kind {
399                AccessKind::Open(_) => self.intersects(EventKindMask::ACCESS_OPEN),
400                // Close after write
401                AccessKind::Close(AccessMode::Write) => {
402                    self.intersects(EventKindMask::ACCESS_CLOSE)
403                }
404                // Close after read-only (no write)
405                AccessKind::Close(AccessMode::Read) => {
406                    self.intersects(EventKindMask::ACCESS_CLOSE_NOWRITE)
407                }
408                // Close with unknown mode - match if either close flag is set
409                AccessKind::Close(_) => self
410                    .intersects(EventKindMask::ACCESS_CLOSE | EventKindMask::ACCESS_CLOSE_NOWRITE),
411                // AccessKind::Read, Any, and Other pass if any access flag is set
412                AccessKind::Read | AccessKind::Any | AccessKind::Other => {
413                    self.intersects(EventKindMask::ALL_ACCESS)
414                }
415            },
416        }
417    }
418}
419
420/// Notify event.
421///
422/// You might want to check [`Event::need_rescan`] to make sure no event was missed before you
423/// received this one.
424#[derive(Clone)]
425#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
426pub struct Event {
427    /// Kind or type of the event.
428    ///
429    /// This is a hierarchy of enums describing the event as precisely as possible. All enums in
430    /// the hierarchy have two variants always present, `Any` and `Other`, accompanied by one or
431    /// more specific variants.
432    ///
433    /// `Any` should be used when more detail about the event is not known beyond the variant
434    /// already selected. For example, `AccessMode::Any` means a file has been accessed, but that's
435    /// all we know.
436    ///
437    /// `Other` should be used when more detail _is_ available, but cannot be encoded as one of the
438    /// defined variants. When specifying `Other`, the [`info`](EventAttributes::info) attribute
439    /// should contain a short string identifying this detail.
440    ///
441    /// For example, `CreateKind::Other` with `info()` returning `Some("mount")` may indicate the
442    /// binding of a mount. The documentation of the particular backend should indicate if any
443    /// `Other` events are generated, and what their description means.
444    ///
445    /// The `EventKind::Any` variant should be used as the "else" case when mapping native kernel
446    /// bitmasks or bitmaps, such that if the mask is ever extended with new event types the
447    /// backend will not gain bugs due to not matching new unknown event types.
448    #[cfg_attr(
449        all(feature = "serde", not(feature = "serialization-compat-6")),
450        serde(flatten)
451    )]
452    #[cfg_attr(
453        all(feature = "serde", feature = "serialization-compat-6"),
454        serde(rename = "type")
455    )]
456    pub kind: EventKind,
457
458    /// Paths the event is about, if known.
459    ///
460    /// Notify backends report paths using the same root representation that was passed to
461    /// `Watcher::watch`. For example, watching `src` reports paths like `src/lib.rs`, while
462    /// watching an absolute path reports absolute event paths.
463    ///
464    /// If an event concerns two or more paths, and the paths are known at the time of event
465    /// creation, they should all go in this `Vec`. Otherwise, using the
466    /// [`tracker`](EventAttributes::tracker) attribute may be more appropriate.
467    ///
468    /// The order of the paths is likely to be significant! For example, renames where both ends of
469    /// the name change are known will have the "source" path first, and the "target" path last.
470    pub paths: Vec<PathBuf>,
471
472    // "What should be in the struct" and "what can go in the attrs" is an interesting question.
473    //
474    // Technically, the paths could go in the attrs. That would reduce the type size to 4 pointer
475    // widths, instead of 7 like it is now. Anything 8 and below is probably good — on x64 that's
476    // the size of an L1 cache line. The entire kind classification fits in 3 bytes, and an AnyMap
477    // is 3 pointers. A Vec<PathBuf> is another 3 pointers.
478    //
479    // Type size aside, what's behind these structures? A Vec and a PathBuf is stored on the heap.
480    // An AnyMap is stored on the heap. But a Vec is directly there, requiring about one access to
481    // get, while retrieving anything in the AnyMap requires some accesses as overhead.
482    //
483    // So things that are used often should be on the struct, and things that are used more rarely
484    // should go in the attrs. Additionally, arbitrary data can _only_ go in the attrs.
485    //
486    // The kind and the paths vie for first place on this scale, depending on how downstream wishes
487    // to use the information. Everything else is secondary. So far, that's why paths live here.
488    //
489    // In the future, it might be possible to have more data and to benchmark things properly, so
490    // the performance can be actually quantified. Also, it might turn out that I have no idea what
491    // I was talking about, so the above may be discarded or reviewed. We'll see!
492    //
493    /// Additional attributes of the event.
494    ///
495    /// Arbitrary data may be added to this field, without restriction beyond the `Sync` and
496    /// `Clone` properties. Some data added here is considered for comparing and hashing, but not
497    /// all: at this writing this is `Tracker`, `Flag`, `Info`, and `Source`.
498    #[cfg_attr(feature = "serde", serde(default))]
499    pub attrs: EventAttributes,
500}
501
502/// Additional attributes of the event.
503///
504/// Attributes are optional and their availability depends on the backend and event. See
505/// [`tracker`](Self::tracker), [`info`](Self::info), and [`source`](Self::source) for details.
506#[derive(Clone, Default, Debug)]
507#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
508pub struct EventAttributes {
509    #[cfg_attr(feature = "serde", serde(flatten))]
510    inner: Option<Box<EventAttributesInner>>,
511}
512
513#[derive(Clone, Default, Debug)]
514#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
515struct EventAttributesInner {
516    /// See [`EventAttributes::tracker`].
517    #[cfg_attr(
518        feature = "serde",
519        serde(default, skip_serializing_if = "Option::is_none")
520    )]
521    tracker: Option<usize>,
522
523    /// Special Notify flag on the event.
524    #[cfg_attr(
525        feature = "serde",
526        serde(default, skip_serializing_if = "Option::is_none")
527    )]
528    flag: Option<Flag>,
529
530    /// See [`EventAttributes::info`].
531    #[cfg_attr(
532        feature = "serde",
533        serde(default, skip_serializing_if = "Option::is_none")
534    )]
535    info: Option<String>,
536
537    /// See [`EventAttributes::source`].
538    #[cfg_attr(
539        feature = "serde",
540        serde(default, skip_serializing_if = "Option::is_none")
541    )]
542    source: Option<String>,
543
544    /// The process ID of the originator of the event.
545    ///
546    /// This attribute is experimental and, while included in Notify itself, is not considered
547    /// stable or standard enough to be part of the serde, eq, hash, and debug representations.
548    #[cfg_attr(
549        feature = "serde",
550        serde(default, skip_serializing, skip_deserializing)
551    )]
552    process_id: Option<u32>,
553}
554
555impl EventAttributes {
556    /// Creates a new `EventAttributes`.
557    #[must_use]
558    pub fn new() -> Self {
559        Self { inner: None }
560    }
561
562    /// Returns a tracking ID (also called a cookie) for related events, if present.
563    ///
564    /// A backend may assign the same ID to multiple events that describe a single operation.
565    /// For example, the inotify backend uses a rename cookie to associate [`RenameMode::From`]
566    /// and [`RenameMode::To`] events for the same rename. If it also emits a [`RenameMode::Both`]
567    /// event, that event has the same ID.
568    ///
569    /// Use this value to match related events from the same watcher. Treat it as an opaque value:
570    /// its meaning and lifetime depend on the backend, and it is not a persistent file identifier
571    /// or a globally unique event ID.
572    ///
573    /// Returns `None` when the backend or event does not provide a tracking ID.
574    #[must_use]
575    pub fn tracker(&self) -> Option<usize> {
576        self.inner.as_ref().and_then(|inner| inner.tracker)
577    }
578
579    /// Retrieves the Notify flag for an event directly, if present.
580    #[must_use]
581    pub fn flag(&self) -> Option<Flag> {
582        self.inner.as_ref().and_then(|inner| inner.flag)
583    }
584
585    /// Returns additional, backend-provided information about this event, if present.
586    ///
587    /// This attribute is primarily used to disambiguate the various `Other` variants in the
588    /// [`EventKind`] hierarchy (for example [`EventKind::Other`], [`CreateKind::Other`],
589    /// [`ModifyKind::Other`], [`RemoveKind::Other`], [`MetadataKind::Other`], ...).
590    ///
591    /// When a backend emits an `Other` kind, it should also set this attribute to a short,
592    /// human-readable string explaining what happened. If an event kind indicates `Other` but
593    /// this value is missing, treat it as a backend bug.
594    ///
595    /// Backends may also set this attribute for non-`Other` kinds, if doing so provides useful
596    /// precision. For example, the `Modify(Metadata(Extended))` kind suggests using this
597    /// attribute when information about _what_ extended metadata changed is available.
598    ///
599    /// # Stability
600    ///
601    /// The exact string values are backend-defined. They are intended as a hint for consumers and
602    /// may change between notify versions.
603    ///
604    /// # Examples
605    ///
606    /// `notify` backends and debouncers currently use values such as:
607    ///
608    /// - `unmount` (inotify unmount events)
609    /// - `rescan: user dropped` / `rescan: kernel dropped` (FSEvents queue overflow hints)
610    /// - `root changed` (FSEvents watched root renamed or removed)
611    /// - `mount` (FSEvents mount or unmount events)
612    /// - `is: symlink`, `is: hardlink`, `is: clone` (FSEvents item type hints)
613    /// - `meta: finder info` (FSEvents Finder metadata changes)
614    /// - `override` (a synthetic removal from `notify-debouncer-full` when a rename replaces an
615    ///   existing target)
616    #[must_use]
617    pub fn info(&self) -> Option<&str> {
618        self.inner.as_ref().and_then(|inner| inner.info.as_deref())
619    }
620
621    /// Returns a string identifying the backend that produced the event, if present.
622    ///
623    /// This is intended to be a short, unambiguous backend name. A dynamically generated value
624    /// should include a prefix that identifies the backend.
625    ///
626    /// The built-in `notify` backends currently leave this attribute unset, so their events return
627    /// `None`. A value can be present in events deserialized with the `serde` feature.
628    #[must_use]
629    pub fn source(&self) -> Option<&str> {
630        self.inner
631            .as_ref()
632            .and_then(|inner| inner.source.as_deref())
633    }
634
635    /// The process ID of the originator of the event.
636    ///
637    /// This attribute is experimental and, while included in Notify itself, is not considered
638    /// stable or standard enough to be part of the serde, eq, hash, and debug representations.
639    #[must_use]
640    pub fn process_id(&self) -> Option<u32> {
641        self.inner.as_ref().and_then(|inner| inner.process_id)
642    }
643
644    /// Sets [`EventAttributes::tracker`].
645    pub fn set_tracker(&mut self, tracker: usize) {
646        self.inner_mut().tracker = Some(tracker);
647    }
648
649    /// Sets the Notify flag onto the event.
650    pub fn set_flag(&mut self, flag: Flag) {
651        self.inner_mut().flag = Some(flag);
652    }
653
654    /// Sets [`EventAttributes::info`].
655    ///
656    /// This should be a short, human-readable string.
657    pub fn set_info(&mut self, info: &str) {
658        self.inner_mut().info = Some(info.to_string());
659    }
660
661    /// Sets the process id onto the event.
662    pub fn set_process_id(&mut self, process_id: u32) {
663        self.inner_mut().process_id = Some(process_id)
664    }
665
666    fn inner_mut(&mut self) -> &mut EventAttributesInner {
667        self.inner.get_or_insert_with(Box::default)
668    }
669}
670
671/// Special Notify flag on the event.
672///
673/// This attribute is used to flag certain kinds of events that Notify either marks or generates in
674/// particular ways.
675#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
676#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
677#[cfg_attr(
678    all(feature = "serde", not(feature = "serialization-compat-6")),
679    serde(rename_all = "camelCase")
680)]
681pub enum Flag {
682    /// Rescan notices are emitted by some platforms (and may also be emitted by Notify itself).
683    /// They indicate either a lapse in the events or a change in the filesystem such that events
684    /// received so far can no longer be relied on to represent the state of the filesystem now.
685    ///
686    /// An application that simply reacts to file changes may not care about this. An application
687    /// that keeps an in-memory representation of the filesystem will need to care, and will need
688    /// to refresh that representation directly from the filesystem.
689    Rescan,
690}
691
692impl Event {
693    /// Returns whether some events may have been missed. If true, you should assume any file or
694    /// folder might have been modified.
695    ///
696    /// See [`Flag::Rescan`] for more information.
697    #[must_use]
698    pub fn need_rescan(&self) -> bool {
699        matches!(self.flag(), Some(Flag::Rescan))
700    }
701    /// Returns [`EventAttributes::tracker`].
702    #[must_use]
703    pub fn tracker(&self) -> Option<usize> {
704        self.attrs.tracker()
705    }
706
707    /// Retrieves the Notify flag for an event directly, if present.
708    #[must_use]
709    pub fn flag(&self) -> Option<Flag> {
710        self.attrs.flag()
711    }
712
713    /// Returns [`EventAttributes::info`].
714    #[must_use]
715    pub fn info(&self) -> Option<&str> {
716        self.attrs.info()
717    }
718
719    /// Returns [`EventAttributes::source`].
720    #[must_use]
721    pub fn source(&self) -> Option<&str> {
722        self.attrs.source()
723    }
724
725    /// Creates a new `Event` given a kind.
726    #[must_use]
727    pub fn new(kind: EventKind) -> Self {
728        Self {
729            kind,
730            paths: Vec::new(),
731            attrs: EventAttributes::new(),
732        }
733    }
734
735    /// Sets the kind.
736    #[must_use]
737    pub fn set_kind(mut self, kind: EventKind) -> Self {
738        self.kind = kind;
739        self
740    }
741
742    /// Adds a path to the event.
743    #[must_use]
744    pub fn add_path(mut self, path: PathBuf) -> Self {
745        self.paths.push(path);
746        self
747    }
748
749    /// Adds a path to the event if the argument is Some.
750    #[must_use]
751    pub fn add_some_path(self, path: Option<PathBuf>) -> Self {
752        if let Some(path) = path {
753            self.add_path(path)
754        } else {
755            self
756        }
757    }
758
759    /// Sets [`EventAttributes::tracker`].
760    #[must_use]
761    pub fn set_tracker(mut self, tracker: usize) -> Self {
762        self.attrs.set_tracker(tracker);
763        self
764    }
765
766    /// Sets [`EventAttributes::info`].
767    #[must_use]
768    pub fn set_info(mut self, info: &str) -> Self {
769        self.attrs.set_info(info);
770        self
771    }
772
773    /// Sets the Notify flag onto the event.
774    #[must_use]
775    pub fn set_flag(mut self, flag: Flag) -> Self {
776        self.attrs.set_flag(flag);
777        self
778    }
779
780    /// Sets the process id onto the event.
781    #[must_use]
782    pub fn set_process_id(mut self, process_id: u32) -> Self {
783        self.attrs.set_process_id(process_id);
784        self
785    }
786}
787
788impl fmt::Debug for Event {
789    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
790        f.debug_struct("Event")
791            .field("kind", &self.kind)
792            .field("paths", &self.paths)
793            .field("attr:tracker", &self.tracker())
794            .field("attr:flag", &self.flag())
795            .field("attr:info", &self.info())
796            .field("attr:source", &self.source())
797            .finish()
798    }
799}
800impl Default for Event {
801    fn default() -> Self {
802        Self {
803            kind: EventKind::default(),
804            paths: Vec::new(),
805            attrs: EventAttributes::new(),
806        }
807    }
808}
809
810impl Eq for Event {}
811impl PartialEq for Event {
812    fn eq(&self, other: &Self) -> bool {
813        self.kind.eq(&other.kind)
814            && self.paths.eq(&other.paths)
815            && self.tracker().eq(&other.tracker())
816            && self.flag().eq(&other.flag())
817            && self.info().eq(&other.info())
818            && self.source().eq(&other.source())
819    }
820}
821
822impl Hash for Event {
823    fn hash<H: Hasher>(&self, state: &mut H) {
824        self.kind.hash(state);
825        self.paths.hash(state);
826        self.tracker().hash(state);
827        self.flag().hash(state);
828        self.info().hash(state);
829        self.source().hash(state);
830    }
831}
832
833#[cfg(test)]
834mod event_kind_mask_tests {
835    use super::*;
836
837    #[test]
838    fn default_is_all() {
839        assert_eq!(EventKindMask::default(), EventKindMask::ALL);
840    }
841
842    #[test]
843    fn matches_create_events() {
844        let mask = EventKindMask::CREATE;
845        assert!(mask.matches(&EventKind::Create(CreateKind::File)));
846        assert!(mask.matches(&EventKind::Create(CreateKind::Folder)));
847        assert!(mask.matches(&EventKind::Create(CreateKind::Any)));
848        assert!(mask.matches(&EventKind::Create(CreateKind::Other)));
849        assert!(!mask.matches(&EventKind::Remove(RemoveKind::File)));
850    }
851
852    #[test]
853    fn matches_remove_events() {
854        let mask = EventKindMask::REMOVE;
855        assert!(mask.matches(&EventKind::Remove(RemoveKind::File)));
856        assert!(mask.matches(&EventKind::Remove(RemoveKind::Folder)));
857        assert!(mask.matches(&EventKind::Remove(RemoveKind::Any)));
858        assert!(!mask.matches(&EventKind::Create(CreateKind::File)));
859    }
860
861    #[test]
862    fn matches_access_open_events() {
863        let mask = EventKindMask::ACCESS_OPEN;
864        assert!(mask.matches(&EventKind::Access(AccessKind::Open(AccessMode::Any))));
865        assert!(mask.matches(&EventKind::Access(AccessKind::Open(AccessMode::Read))));
866        assert!(mask.matches(&EventKind::Access(AccessKind::Open(AccessMode::Write))));
867        assert!(!mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Write))));
868        assert!(!mask.matches(&EventKind::Create(CreateKind::File)));
869    }
870
871    #[test]
872    fn matches_access_close_events() {
873        // ACCESS_CLOSE only matches Close(Write), not Close(Read)
874        let mask = EventKindMask::ACCESS_CLOSE;
875        assert!(mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Write))));
876        assert!(mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Any)))); // Any could be write
877        assert!(!mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Read)))); // Read goes to NOWRITE
878        assert!(!mask.matches(&EventKind::Access(AccessKind::Open(AccessMode::Any))));
879    }
880
881    #[test]
882    fn matches_access_close_nowrite_events() {
883        // ACCESS_CLOSE_NOWRITE matches Close(Read) - files opened read-only
884        let mask = EventKindMask::ACCESS_CLOSE_NOWRITE;
885        assert!(mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Read))));
886        assert!(mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Any)))); // Any could be read
887        assert!(!mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Write)))); // Write goes to ACCESS_CLOSE
888        assert!(!mask.matches(&EventKind::Access(AccessKind::Open(AccessMode::Any))));
889    }
890
891    #[test]
892    fn combined_close_masks_match_both() {
893        // When both ACCESS_CLOSE and ACCESS_CLOSE_NOWRITE are set, match both
894        let mask = EventKindMask::ACCESS_CLOSE | EventKindMask::ACCESS_CLOSE_NOWRITE;
895        assert!(mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Write))));
896        assert!(mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Read))));
897        assert!(mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Any))));
898    }
899
900    #[test]
901    fn all_access_matches_open_close_read_any_other() {
902        let mask = EventKindMask::ALL_ACCESS;
903        assert!(mask.matches(&EventKind::Access(AccessKind::Open(AccessMode::Read))));
904        assert!(mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Write))));
905        assert!(mask.matches(&EventKind::Access(AccessKind::Read)));
906        assert!(mask.matches(&EventKind::Access(AccessKind::Any)));
907        assert!(mask.matches(&EventKind::Access(AccessKind::Other)));
908    }
909
910    #[test]
911    fn matches_modify_data_events() {
912        let mask = EventKindMask::MODIFY_DATA;
913        assert!(mask.matches(&EventKind::Modify(ModifyKind::Data(DataChange::Any))));
914        assert!(mask.matches(&EventKind::Modify(ModifyKind::Data(DataChange::Size))));
915        assert!(mask.matches(&EventKind::Modify(ModifyKind::Data(DataChange::Content))));
916        assert!(!mask.matches(&EventKind::Modify(ModifyKind::Metadata(MetadataKind::Any))));
917        assert!(!mask.matches(&EventKind::Modify(ModifyKind::Name(RenameMode::From))));
918    }
919
920    #[test]
921    fn matches_modify_metadata_events() {
922        let mask = EventKindMask::MODIFY_META;
923        assert!(mask.matches(&EventKind::Modify(ModifyKind::Metadata(MetadataKind::Any))));
924        assert!(mask.matches(&EventKind::Modify(ModifyKind::Metadata(
925            MetadataKind::Permissions
926        ))));
927        assert!(!mask.matches(&EventKind::Modify(ModifyKind::Data(DataChange::Any))));
928    }
929
930    #[test]
931    fn matches_modify_name_events() {
932        let mask = EventKindMask::MODIFY_NAME;
933        assert!(mask.matches(&EventKind::Modify(ModifyKind::Name(RenameMode::From))));
934        assert!(mask.matches(&EventKind::Modify(ModifyKind::Name(RenameMode::To))));
935        assert!(mask.matches(&EventKind::Modify(ModifyKind::Name(RenameMode::Both))));
936        assert!(!mask.matches(&EventKind::Modify(ModifyKind::Data(DataChange::Any))));
937    }
938
939    #[test]
940    fn all_modify_matches_data_meta_name() {
941        let mask = EventKindMask::ALL_MODIFY;
942        assert!(mask.matches(&EventKind::Modify(ModifyKind::Data(DataChange::Any))));
943        assert!(mask.matches(&EventKind::Modify(ModifyKind::Metadata(MetadataKind::Any))));
944        assert!(mask.matches(&EventKind::Modify(ModifyKind::Name(RenameMode::From))));
945        assert!(mask.matches(&EventKind::Modify(ModifyKind::Any)));
946        assert!(mask.matches(&EventKind::Modify(ModifyKind::Other)));
947    }
948
949    #[test]
950    fn any_and_other_always_pass() {
951        let empty = EventKindMask::empty();
952        assert!(empty.matches(&EventKind::Any));
953        assert!(empty.matches(&EventKind::Other));
954    }
955
956    #[test]
957    fn core_excludes_access() {
958        let core = EventKindMask::CORE;
959        assert!(core.matches(&EventKind::Create(CreateKind::File)));
960        assert!(core.matches(&EventKind::Remove(RemoveKind::File)));
961        assert!(core.matches(&EventKind::Modify(ModifyKind::Data(DataChange::Any))));
962        assert!(core.matches(&EventKind::Modify(ModifyKind::Metadata(MetadataKind::Any))));
963        assert!(core.matches(&EventKind::Modify(ModifyKind::Name(RenameMode::From))));
964        assert!(!core.matches(&EventKind::Access(AccessKind::Open(AccessMode::Any))));
965        assert!(!core.matches(&EventKind::Access(AccessKind::Close(AccessMode::Write))));
966    }
967
968    #[test]
969    fn empty_mask_only_passes_any_other() {
970        let empty = EventKindMask::empty();
971        assert!(empty.matches(&EventKind::Any));
972        assert!(empty.matches(&EventKind::Other));
973        assert!(!empty.matches(&EventKind::Create(CreateKind::File)));
974        assert!(!empty.matches(&EventKind::Remove(RemoveKind::File)));
975        assert!(!empty.matches(&EventKind::Modify(ModifyKind::Data(DataChange::Any))));
976        assert!(!empty.matches(&EventKind::Access(AccessKind::Open(AccessMode::Any))));
977    }
978
979    #[test]
980    fn bitwise_or_combines_masks() {
981        let mask = EventKindMask::CREATE | EventKindMask::REMOVE;
982        assert!(mask.matches(&EventKind::Create(CreateKind::File)));
983        assert!(mask.matches(&EventKind::Remove(RemoveKind::Folder)));
984        assert!(!mask.matches(&EventKind::Modify(ModifyKind::Data(DataChange::Any))));
985        assert!(!mask.matches(&EventKind::Access(AccessKind::Open(AccessMode::Any))));
986    }
987
988    #[test]
989    fn all_matches_everything() {
990        let all = EventKindMask::ALL;
991        assert!(all.matches(&EventKind::Any));
992        assert!(all.matches(&EventKind::Other));
993        assert!(all.matches(&EventKind::Create(CreateKind::File)));
994        assert!(all.matches(&EventKind::Remove(RemoveKind::File)));
995        assert!(all.matches(&EventKind::Modify(ModifyKind::Data(DataChange::Any))));
996        assert!(all.matches(&EventKind::Access(AccessKind::Open(AccessMode::Any))));
997        assert!(all.matches(&EventKind::Access(AccessKind::Close(AccessMode::Write))));
998    }
999
1000    #[test]
1001    fn access_read_and_any_match_with_all_access() {
1002        // Edge case: AccessKind::Read and AccessKind::Any should match if ALL_ACCESS is set
1003        let mask = EventKindMask::ALL_ACCESS;
1004        assert!(mask.matches(&EventKind::Access(AccessKind::Read)));
1005        assert!(mask.matches(&EventKind::Access(AccessKind::Any)));
1006        assert!(mask.matches(&EventKind::Access(AccessKind::Other)));
1007    }
1008}
1009
1010#[cfg(all(test, feature = "serde", not(feature = "serialization-compat-6")))]
1011mod tests {
1012    use super::*;
1013
1014    use insta::assert_snapshot;
1015    use rstest::rstest;
1016
1017    #[rustfmt::skip]
1018    #[rstest]
1019    #[case("any", EventKind::Any)]
1020    #[case("access-any", EventKind::Access(AccessKind::Any))]
1021    #[case("access-read", EventKind::Access(AccessKind::Read))]
1022    #[case("access-open-any", EventKind::Access(AccessKind::Open(AccessMode::Any)))]
1023    #[case("access-open-execute", EventKind::Access(AccessKind::Open(AccessMode::Execute)))]
1024    #[case("access-open-read", EventKind::Access(AccessKind::Open(AccessMode::Read)))]
1025    #[case("access-open-write", EventKind::Access(AccessKind::Open(AccessMode::Write)))]
1026    #[case("access-open-other", EventKind::Access(AccessKind::Open(AccessMode::Other)))]
1027    #[case("access-close-any", EventKind::Access(AccessKind::Close(AccessMode::Any)))]
1028    #[case("access-close-execute", EventKind::Access(AccessKind::Close(AccessMode::Execute)))]
1029    #[case("access-close-read", EventKind::Access(AccessKind::Close(AccessMode::Read)))]
1030    #[case("access-close-write", EventKind::Access(AccessKind::Close(AccessMode::Write)))]
1031    #[case("access-close-other", EventKind::Access(AccessKind::Close(AccessMode::Other)))]
1032    #[case("access-other", EventKind::Access(AccessKind::Other))]
1033    #[case("create-any", EventKind::Create(CreateKind::Any))]
1034    #[case("create-file", EventKind::Create(CreateKind::File))]
1035    #[case("create-folder", EventKind::Create(CreateKind::Folder))]
1036    #[case("create-other", EventKind::Create(CreateKind::Other))]
1037    #[case("modify-any", EventKind::Modify(ModifyKind::Any))]
1038    #[case("modify-data-any", EventKind::Modify(ModifyKind::Data(DataChange::Any)))]
1039    #[case("modify-data-size", EventKind::Modify(ModifyKind::Data(DataChange::Size)))]
1040    #[case("modify-data-content", EventKind::Modify(ModifyKind::Data(DataChange::Content)))]
1041    #[case("modify-data-other", EventKind::Modify(ModifyKind::Data(DataChange::Other)))]
1042    #[case("modify-metadata-any", EventKind::Modify(ModifyKind::Metadata(MetadataKind::Any)))]
1043    #[case("modify-metadata-accesstime", EventKind::Modify(ModifyKind::Metadata(MetadataKind::AccessTime)))]
1044    #[case("modify-metadata-writetime", EventKind::Modify(ModifyKind::Metadata(MetadataKind::WriteTime)))]
1045    #[case("modify-metadata-permissions", EventKind::Modify(ModifyKind::Metadata(MetadataKind::Permissions)))]
1046    #[case("modify-metadata-ownership", EventKind::Modify(ModifyKind::Metadata(MetadataKind::Ownership)))]
1047    #[case("modify-metadata-extended", EventKind::Modify(ModifyKind::Metadata(MetadataKind::Extended)))]
1048    #[case("modify-metadata-other", EventKind::Modify(ModifyKind::Metadata(MetadataKind::Other)))]
1049    #[case("modify-name-any", EventKind::Modify(ModifyKind::Name(RenameMode::Any)))]
1050    #[case("modify-name-to", EventKind::Modify(ModifyKind::Name(RenameMode::To)))]
1051    #[case("modify-name-from", EventKind::Modify(ModifyKind::Name(RenameMode::From)))]
1052    #[case("modify-name-both", EventKind::Modify(ModifyKind::Name(RenameMode::Both)))]
1053    #[case("modify-name-other", EventKind::Modify(ModifyKind::Name(RenameMode::Other)))]
1054    #[case("modify-other", EventKind::Modify(ModifyKind::Other))]
1055    #[case("remove-any", EventKind::Remove(RemoveKind::Any))]
1056    #[case("remove-file", EventKind::Remove(RemoveKind::File))]
1057    #[case("remove-folder", EventKind::Remove(RemoveKind::Folder))]
1058    #[case("remove-other", EventKind::Remove(RemoveKind::Other))]
1059    #[case("other", EventKind::Other)]
1060    fn serialize_event_kind(
1061        #[case] name: &str,
1062        #[case] event_kind: EventKind,
1063    ) {
1064        let event = Event::new(event_kind);
1065        let json = serde_json::to_string(&event).unwrap();
1066        assert_snapshot!(name, json);
1067    }
1068
1069    #[test]
1070    fn serialize_event_with_attrs() {
1071        let event = Event::new(EventKind::Any)
1072            .set_tracker(123)
1073            .set_flag(Flag::Rescan)
1074            .set_info("test event")
1075            .set_process_id(0);
1076        let json = serde_json::to_string(&event).unwrap();
1077        assert_snapshot!(json);
1078    }
1079}