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    /// // The mask defaults to all events, including ACCESS_CLOSE_NOWRITE.
302    /// // notify's Config::default() excludes ACCESS_CLOSE_NOWRITE.
303    /// let default = EventKindMask::default();
304    /// assert_eq!(default, EventKindMask::ALL);
305    /// ```
306    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
307    #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
308    pub struct EventKindMask: u32 {
309        /// Monitor file/folder creation events.
310        const CREATE = 0b0000_0001;
311
312        /// Monitor file/folder removal events.
313        const REMOVE = 0b0000_0010;
314
315        /// Monitor data modification events (content/size changes).
316        const MODIFY_DATA = 0b0000_0100;
317
318        /// Monitor metadata modification events (permissions, timestamps, etc).
319        const MODIFY_META = 0b0000_1000;
320
321        /// Monitor name/rename events.
322        const MODIFY_NAME = 0b0001_0000;
323
324        /// Monitor file open events.
325        const ACCESS_OPEN = 0b0010_0000;
326
327        /// Monitor file close events after writing.
328        /// This fires when a file opened for writing is closed.
329        const ACCESS_CLOSE = 0b0100_0000;
330
331        /// Monitor file close events after read-only access.
332        /// This fires when a file opened for reading (not writing) is closed.
333        /// Note: This can be very noisy and may cause queue overflow on busy systems.
334        const ACCESS_CLOSE_NOWRITE = 0b1000_0000;
335
336        /// All modify events (data, metadata, and name changes).
337        const ALL_MODIFY = Self::MODIFY_DATA.bits() | Self::MODIFY_META.bits() | Self::MODIFY_NAME.bits();
338
339        /// All access events (open, close-write, and close-nowrite).
340        const ALL_ACCESS = Self::ACCESS_OPEN.bits() | Self::ACCESS_CLOSE.bits() | Self::ACCESS_CLOSE_NOWRITE.bits();
341
342        /// Core events: create, remove, and all modify events.
343        const CORE = Self::CREATE.bits() | Self::REMOVE.bits() | Self::ALL_MODIFY.bits();
344
345        /// All events including access events.
346        /// This is the default for `EventKindMask`; notify's `Config` excludes
347        /// `ACCESS_CLOSE_NOWRITE` by default.
348        const ALL = Self::CORE.bits() | Self::ALL_ACCESS.bits();
349    }
350}
351
352impl Default for EventKindMask {
353    fn default() -> Self {
354        EventKindMask::ALL
355    }
356}
357
358impl EventKindMask {
359    /// Returns whether the given event kind matches this mask.
360    ///
361    /// `EventKind::Any` and `EventKind::Other` always pass regardless of the mask,
362    /// as they represent meta-events that should not be filtered.
363    ///
364    /// # Examples
365    ///
366    /// ```
367    /// use notify_types::event::{EventKindMask, EventKind, CreateKind, AccessKind, AccessMode};
368    ///
369    /// let mask = EventKindMask::CREATE;
370    /// assert!(mask.matches(&EventKind::Create(CreateKind::File)));
371    /// assert!(!mask.matches(&EventKind::Access(AccessKind::Open(AccessMode::Read))));
372    ///
373    /// // Any and Other always pass
374    /// let empty = EventKindMask::empty();
375    /// assert!(empty.matches(&EventKind::Any));
376    /// assert!(empty.matches(&EventKind::Other));
377    /// ```
378    #[must_use]
379    pub fn matches(&self, kind: &EventKind) -> bool {
380        match kind {
381            // Meta-events always pass
382            EventKind::Any | EventKind::Other => true,
383
384            // Create events
385            EventKind::Create(_) => self.intersects(EventKindMask::CREATE),
386
387            // Remove events
388            EventKind::Remove(_) => self.intersects(EventKindMask::REMOVE),
389
390            // Modify events - check subkind
391            EventKind::Modify(modify_kind) => match modify_kind {
392                ModifyKind::Data(_) => self.intersects(EventKindMask::MODIFY_DATA),
393                ModifyKind::Metadata(_) => self.intersects(EventKindMask::MODIFY_META),
394                ModifyKind::Name(_) => self.intersects(EventKindMask::MODIFY_NAME),
395                // ModifyKind::Any and ModifyKind::Other pass if any modify flag is set
396                ModifyKind::Any | ModifyKind::Other => self.intersects(EventKindMask::ALL_MODIFY),
397            },
398
399            // Access events - check subkind
400            EventKind::Access(access_kind) => match access_kind {
401                AccessKind::Open(_) => self.intersects(EventKindMask::ACCESS_OPEN),
402                // Close after write
403                AccessKind::Close(AccessMode::Write) => {
404                    self.intersects(EventKindMask::ACCESS_CLOSE)
405                }
406                // Close after read-only (no write)
407                AccessKind::Close(AccessMode::Read) => {
408                    self.intersects(EventKindMask::ACCESS_CLOSE_NOWRITE)
409                }
410                // Close with unknown mode - match if either close flag is set
411                AccessKind::Close(_) => self
412                    .intersects(EventKindMask::ACCESS_CLOSE | EventKindMask::ACCESS_CLOSE_NOWRITE),
413                // AccessKind::Read, Any, and Other pass if any access flag is set
414                AccessKind::Read | AccessKind::Any | AccessKind::Other => {
415                    self.intersects(EventKindMask::ALL_ACCESS)
416                }
417            },
418        }
419    }
420}
421
422/// Notify event.
423///
424/// You might want to check [`Event::need_rescan`] to make sure no event was missed before you
425/// received this one.
426#[derive(Clone)]
427#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
428pub struct Event {
429    /// Kind or type of the event.
430    ///
431    /// This is a hierarchy of enums describing the event as precisely as possible. All enums in
432    /// the hierarchy have two variants always present, `Any` and `Other`, accompanied by one or
433    /// more specific variants.
434    ///
435    /// `Any` should be used when more detail about the event is not known beyond the variant
436    /// already selected. For example, `AccessMode::Any` means a file has been accessed, but that's
437    /// all we know.
438    ///
439    /// `Other` should be used when more detail _is_ available, but cannot be encoded as one of the
440    /// defined variants. When specifying `Other`, the [`info`](EventAttributes::info) attribute
441    /// should contain a short string identifying this detail.
442    ///
443    /// For example, `CreateKind::Other` with `info()` returning `Some("mount")` may indicate the
444    /// binding of a mount. The documentation of the particular backend should indicate if any
445    /// `Other` events are generated, and what their description means.
446    ///
447    /// The `EventKind::Any` variant should be used as the "else" case when mapping native kernel
448    /// bitmasks or bitmaps, such that if the mask is ever extended with new event types the
449    /// backend will not gain bugs due to not matching new unknown event types.
450    #[cfg_attr(
451        all(feature = "serde", not(feature = "serialization-compat-6")),
452        serde(flatten)
453    )]
454    #[cfg_attr(
455        all(feature = "serde", feature = "serialization-compat-6"),
456        serde(rename = "type")
457    )]
458    pub kind: EventKind,
459
460    /// Paths the event is about, if known.
461    ///
462    /// Notify backends report paths using the same root representation that was passed to
463    /// `Watcher::watch`. For example, watching `src` reports paths like `src/lib.rs`, while
464    /// watching an absolute path reports absolute event paths.
465    ///
466    /// If an event concerns two or more paths, and the paths are known at the time of event
467    /// creation, they should all go in this `Vec`. Otherwise, using the
468    /// [`tracker`](EventAttributes::tracker) attribute may be more appropriate.
469    ///
470    /// The order of the paths is likely to be significant! For example, renames where both ends of
471    /// the name change are known will have the "source" path first, and the "target" path last.
472    pub paths: Vec<PathBuf>,
473
474    // "What should be in the struct" and "what can go in the attrs" is an interesting question.
475    //
476    // Technically, the paths could go in the attrs. That would reduce the type size to 4 pointer
477    // widths, instead of 7 like it is now. Anything 8 and below is probably good — on x64 that's
478    // the size of an L1 cache line. The entire kind classification fits in 3 bytes, and an AnyMap
479    // is 3 pointers. A Vec<PathBuf> is another 3 pointers.
480    //
481    // Type size aside, what's behind these structures? A Vec and a PathBuf is stored on the heap.
482    // An AnyMap is stored on the heap. But a Vec is directly there, requiring about one access to
483    // get, while retrieving anything in the AnyMap requires some accesses as overhead.
484    //
485    // So things that are used often should be on the struct, and things that are used more rarely
486    // should go in the attrs. Additionally, arbitrary data can _only_ go in the attrs.
487    //
488    // The kind and the paths vie for first place on this scale, depending on how downstream wishes
489    // to use the information. Everything else is secondary. So far, that's why paths live here.
490    //
491    // In the future, it might be possible to have more data and to benchmark things properly, so
492    // the performance can be actually quantified. Also, it might turn out that I have no idea what
493    // I was talking about, so the above may be discarded or reviewed. We'll see!
494    //
495    /// Additional attributes of the event.
496    ///
497    /// Arbitrary data may be added to this field, without restriction beyond the `Sync` and
498    /// `Clone` properties. Some data added here is considered for comparing and hashing, but not
499    /// all: at this writing this is `Tracker`, `Flag`, `Info`, `Source`, and `UserData`.
500    #[cfg_attr(feature = "serde", serde(default))]
501    pub attrs: EventAttributes,
502}
503
504/// Additional attributes of the event.
505///
506/// Attributes are optional and their availability depends on the backend and event. See
507/// [`tracker`](Self::tracker), [`info`](Self::info), and [`source`](Self::source) for details.
508#[derive(Clone, Default, Debug)]
509#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
510pub struct EventAttributes {
511    #[cfg_attr(feature = "serde", serde(flatten))]
512    inner: Option<Box<EventAttributesInner>>,
513
514    // Keep this inline so attaching a watch's value does not require an allocation.
515    #[cfg_attr(
516        feature = "serde",
517        serde(default, skip_serializing_if = "Option::is_none")
518    )]
519    user_data: Option<u64>,
520}
521
522#[derive(Clone, Default, Debug)]
523#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
524struct EventAttributesInner {
525    /// See [`EventAttributes::tracker`].
526    #[cfg_attr(
527        feature = "serde",
528        serde(default, skip_serializing_if = "Option::is_none")
529    )]
530    tracker: Option<usize>,
531
532    /// Special Notify flag on the event.
533    #[cfg_attr(
534        feature = "serde",
535        serde(default, skip_serializing_if = "Option::is_none")
536    )]
537    flag: Option<Flag>,
538
539    /// See [`EventAttributes::info`].
540    #[cfg_attr(
541        feature = "serde",
542        serde(default, skip_serializing_if = "Option::is_none")
543    )]
544    info: Option<String>,
545
546    /// See [`EventAttributes::source`].
547    #[cfg_attr(
548        feature = "serde",
549        serde(default, skip_serializing_if = "Option::is_none")
550    )]
551    source: Option<String>,
552
553    /// The process ID of the originator of the event.
554    ///
555    /// This attribute is experimental and, while included in Notify itself, is not considered
556    /// stable or standard enough to be part of the serde, eq, hash, and debug representations.
557    #[cfg_attr(
558        feature = "serde",
559        serde(default, skip_serializing, skip_deserializing)
560    )]
561    process_id: Option<u32>,
562}
563
564impl EventAttributes {
565    /// Creates a new `EventAttributes`.
566    #[must_use]
567    pub fn new() -> Self {
568        Self {
569            inner: None,
570            user_data: None,
571        }
572    }
573
574    /// Returns the application-defined value of the watch that reported this event.
575    ///
576    /// The value is set when registering the watch. It participates in [`Event`]'s equality
577    /// and hashing, so otherwise identical events with different values remain distinct.
578    /// Values need not be unique. `None` means this attribute does not identify the reporting
579    /// watch, either because no value was configured or because the event has no specific watch.
580    ///
581    /// For renames, [`RenameMode::From`] carries the source watch's value, while
582    /// [`RenameMode::To`] and [`RenameMode::Both`] carry the destination watch's value.
583    ///
584    /// On a [`Flag::Rescan`] event, `Some(value)` identifies the reporting watch by its
585    /// configured value. It does not guarantee that other watches are unaffected; the recovery
586    /// requirements of [`Flag::Rescan`] still apply.
587    #[must_use]
588    pub fn user_data(&self) -> Option<u64> {
589        self.user_data
590    }
591
592    /// Sets [`EventAttributes::user_data`].
593    pub fn set_user_data(&mut self, user_data: u64) {
594        self.user_data = Some(user_data);
595    }
596
597    /// Returns a tracking ID (also called a cookie) for related events, if present.
598    ///
599    /// A backend may assign the same ID to multiple events that describe a single operation.
600    /// For example, the inotify backend uses a rename cookie to associate [`RenameMode::From`]
601    /// and [`RenameMode::To`] events for the same rename. If it also emits a [`RenameMode::Both`]
602    /// event, that event has the same ID.
603    /// When several watches reach the renamed file under different paths, for example through a
604    /// symbolic link, inotify reports the rename once for each of those watches, with the same ID.
605    /// Pair a [`RenameMode::From`] event with the [`RenameMode::To`] event below the same watch,
606    /// if there is one.
607    ///
608    /// Use this value to match related events from the same watcher. Treat it as an opaque value:
609    /// its meaning and lifetime depend on the backend, and it is not a persistent file identifier
610    /// or a globally unique event ID.
611    ///
612    /// Returns `None` when the backend or event does not provide a tracking ID.
613    #[must_use]
614    pub fn tracker(&self) -> Option<usize> {
615        self.inner.as_ref().and_then(|inner| inner.tracker)
616    }
617
618    /// Retrieves the Notify flag for an event directly, if present.
619    #[must_use]
620    pub fn flag(&self) -> Option<Flag> {
621        self.inner.as_ref().and_then(|inner| inner.flag)
622    }
623
624    /// Returns additional, backend-provided information about this event, if present.
625    ///
626    /// This attribute is primarily used to disambiguate the various `Other` variants in the
627    /// [`EventKind`] hierarchy (for example [`EventKind::Other`], [`CreateKind::Other`],
628    /// [`ModifyKind::Other`], [`RemoveKind::Other`], [`MetadataKind::Other`], ...).
629    ///
630    /// When a backend emits an `Other` kind, it should also set this attribute to a short,
631    /// human-readable string explaining what happened. If an event kind indicates `Other` but
632    /// this value is missing, treat it as a backend bug.
633    ///
634    /// Backends may also set this attribute for non-`Other` kinds, if doing so provides useful
635    /// precision. For example, the `Modify(Metadata(Extended))` kind suggests using this
636    /// attribute when information about _what_ extended metadata changed is available.
637    ///
638    /// # Stability
639    ///
640    /// The exact string values are backend-defined. They are intended as a hint for consumers and
641    /// may change between notify versions.
642    ///
643    /// # Examples
644    ///
645    /// `notify` backends and debouncers currently use values such as:
646    ///
647    /// - `unmount` (inotify unmount events)
648    /// - `rescan: user dropped` / `rescan: kernel dropped` (FSEvents queue overflow hints)
649    /// - `root changed` (FSEvents watched root renamed or removed)
650    /// - `mount` (FSEvents mount or unmount events)
651    /// - `is: symlink`, `is: hardlink`, `is: clone` (FSEvents item type hints)
652    /// - `meta: finder info` (FSEvents Finder metadata changes)
653    /// - `override` (a synthetic removal from `notify-debouncer-full` when a rename replaces an
654    ///   existing target)
655    #[must_use]
656    pub fn info(&self) -> Option<&str> {
657        self.inner.as_ref().and_then(|inner| inner.info.as_deref())
658    }
659
660    /// Returns a string identifying the backend that produced the event, if present.
661    ///
662    /// This is intended to be a short, unambiguous backend name. A dynamically generated value
663    /// should include a prefix that identifies the backend.
664    ///
665    /// The built-in `notify` backends currently leave this attribute unset, so their events return
666    /// `None`. A value can be present in events deserialized with the `serde` feature.
667    #[must_use]
668    pub fn source(&self) -> Option<&str> {
669        self.inner
670            .as_ref()
671            .and_then(|inner| inner.source.as_deref())
672    }
673
674    /// The process ID of the originator of the event.
675    ///
676    /// This attribute is experimental and, while included in Notify itself, is not considered
677    /// stable or standard enough to be part of the serde, eq, hash, and debug representations.
678    #[must_use]
679    pub fn process_id(&self) -> Option<u32> {
680        self.inner.as_ref().and_then(|inner| inner.process_id)
681    }
682
683    /// Sets [`EventAttributes::tracker`].
684    pub fn set_tracker(&mut self, tracker: usize) {
685        self.inner_mut().tracker = Some(tracker);
686    }
687
688    /// Sets the Notify flag onto the event.
689    pub fn set_flag(&mut self, flag: Flag) {
690        self.inner_mut().flag = Some(flag);
691    }
692
693    /// Sets [`EventAttributes::info`].
694    ///
695    /// This should be a short, human-readable string.
696    pub fn set_info(&mut self, info: &str) {
697        self.inner_mut().info = Some(info.to_string());
698    }
699
700    /// Sets the process id onto the event.
701    pub fn set_process_id(&mut self, process_id: u32) {
702        self.inner_mut().process_id = Some(process_id)
703    }
704
705    fn inner_mut(&mut self) -> &mut EventAttributesInner {
706        self.inner.get_or_insert_with(Box::default)
707    }
708}
709
710/// Special Notify flag on the event.
711///
712/// This attribute is used to flag certain kinds of events that Notify either marks or generates in
713/// particular ways.
714#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
715#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
716#[cfg_attr(
717    all(feature = "serde", not(feature = "serialization-compat-6")),
718    serde(rename_all = "camelCase")
719)]
720pub enum Flag {
721    /// Rescan notices are emitted by some platforms (and may also be emitted by Notify itself).
722    /// They indicate either a lapse in the events or a change in the filesystem such that events
723    /// received so far can no longer be relied on to represent the state of the filesystem now.
724    ///
725    /// An application that simply reacts to file changes may not care about this. An application
726    /// that keeps an in-memory representation of the filesystem will need to care, and will need
727    /// to refresh that representation directly from the filesystem.
728    Rescan,
729}
730
731impl Event {
732    /// Returns whether some events may have been missed. If true, you should assume any file or
733    /// folder might have been modified.
734    ///
735    /// See [`Flag::Rescan`] for more information.
736    #[must_use]
737    pub fn need_rescan(&self) -> bool {
738        matches!(self.flag(), Some(Flag::Rescan))
739    }
740    /// Returns [`EventAttributes::tracker`].
741    #[must_use]
742    pub fn tracker(&self) -> Option<usize> {
743        self.attrs.tracker()
744    }
745
746    /// Returns [`EventAttributes::user_data`].
747    #[must_use]
748    pub fn user_data(&self) -> Option<u64> {
749        self.attrs.user_data()
750    }
751
752    /// Retrieves the Notify flag for an event directly, if present.
753    #[must_use]
754    pub fn flag(&self) -> Option<Flag> {
755        self.attrs.flag()
756    }
757
758    /// Returns [`EventAttributes::info`].
759    #[must_use]
760    pub fn info(&self) -> Option<&str> {
761        self.attrs.info()
762    }
763
764    /// Returns [`EventAttributes::source`].
765    #[must_use]
766    pub fn source(&self) -> Option<&str> {
767        self.attrs.source()
768    }
769
770    /// Creates a new `Event` given a kind.
771    #[must_use]
772    pub fn new(kind: EventKind) -> Self {
773        Self {
774            kind,
775            paths: Vec::new(),
776            attrs: EventAttributes::new(),
777        }
778    }
779
780    /// Sets the kind.
781    #[must_use]
782    pub fn set_kind(mut self, kind: EventKind) -> Self {
783        self.kind = kind;
784        self
785    }
786
787    /// Adds a path to the event.
788    #[must_use]
789    pub fn add_path(mut self, path: PathBuf) -> Self {
790        self.paths.push(path);
791        self
792    }
793
794    /// Adds a path to the event if the argument is Some.
795    #[must_use]
796    pub fn add_some_path(self, path: Option<PathBuf>) -> Self {
797        if let Some(path) = path {
798            self.add_path(path)
799        } else {
800            self
801        }
802    }
803
804    /// Sets [`EventAttributes::tracker`].
805    #[must_use]
806    pub fn set_tracker(mut self, tracker: usize) -> Self {
807        self.attrs.set_tracker(tracker);
808        self
809    }
810
811    /// Sets [`EventAttributes::user_data`].
812    #[must_use]
813    pub fn set_user_data(mut self, user_data: u64) -> Self {
814        self.attrs.set_user_data(user_data);
815        self
816    }
817
818    /// Sets [`EventAttributes::info`].
819    #[must_use]
820    pub fn set_info(mut self, info: &str) -> Self {
821        self.attrs.set_info(info);
822        self
823    }
824
825    /// Sets the Notify flag onto the event.
826    #[must_use]
827    pub fn set_flag(mut self, flag: Flag) -> Self {
828        self.attrs.set_flag(flag);
829        self
830    }
831
832    /// Sets the process id onto the event.
833    #[must_use]
834    pub fn set_process_id(mut self, process_id: u32) -> Self {
835        self.attrs.set_process_id(process_id);
836        self
837    }
838}
839
840impl fmt::Debug for Event {
841    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
842        f.debug_struct("Event")
843            .field("kind", &self.kind)
844            .field("paths", &self.paths)
845            .field("attr:tracker", &self.tracker())
846            .field("attr:flag", &self.flag())
847            .field("attr:info", &self.info())
848            .field("attr:source", &self.source())
849            .field("attr:user_data", &self.user_data())
850            .finish()
851    }
852}
853impl Default for Event {
854    fn default() -> Self {
855        Self {
856            kind: EventKind::default(),
857            paths: Vec::new(),
858            attrs: EventAttributes::new(),
859        }
860    }
861}
862
863impl Eq for Event {}
864impl PartialEq for Event {
865    fn eq(&self, other: &Self) -> bool {
866        self.kind.eq(&other.kind)
867            && self.paths.eq(&other.paths)
868            && self.tracker().eq(&other.tracker())
869            && self.flag().eq(&other.flag())
870            && self.info().eq(&other.info())
871            && self.source().eq(&other.source())
872            && self.user_data().eq(&other.user_data())
873    }
874}
875
876impl Hash for Event {
877    fn hash<H: Hasher>(&self, state: &mut H) {
878        self.kind.hash(state);
879        self.paths.hash(state);
880        self.tracker().hash(state);
881        self.flag().hash(state);
882        self.info().hash(state);
883        self.source().hash(state);
884        self.user_data().hash(state);
885    }
886}
887
888#[cfg(test)]
889mod event_kind_mask_tests {
890    use super::*;
891
892    #[test]
893    fn default_is_all() {
894        assert_eq!(EventKindMask::default(), EventKindMask::ALL);
895    }
896
897    #[test]
898    fn matches_create_events() {
899        let mask = EventKindMask::CREATE;
900        assert!(mask.matches(&EventKind::Create(CreateKind::File)));
901        assert!(mask.matches(&EventKind::Create(CreateKind::Folder)));
902        assert!(mask.matches(&EventKind::Create(CreateKind::Any)));
903        assert!(mask.matches(&EventKind::Create(CreateKind::Other)));
904        assert!(!mask.matches(&EventKind::Remove(RemoveKind::File)));
905    }
906
907    #[test]
908    fn matches_remove_events() {
909        let mask = EventKindMask::REMOVE;
910        assert!(mask.matches(&EventKind::Remove(RemoveKind::File)));
911        assert!(mask.matches(&EventKind::Remove(RemoveKind::Folder)));
912        assert!(mask.matches(&EventKind::Remove(RemoveKind::Any)));
913        assert!(!mask.matches(&EventKind::Create(CreateKind::File)));
914    }
915
916    #[test]
917    fn matches_access_open_events() {
918        let mask = EventKindMask::ACCESS_OPEN;
919        assert!(mask.matches(&EventKind::Access(AccessKind::Open(AccessMode::Any))));
920        assert!(mask.matches(&EventKind::Access(AccessKind::Open(AccessMode::Read))));
921        assert!(mask.matches(&EventKind::Access(AccessKind::Open(AccessMode::Write))));
922        assert!(!mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Write))));
923        assert!(!mask.matches(&EventKind::Create(CreateKind::File)));
924    }
925
926    #[test]
927    fn matches_access_close_events() {
928        // ACCESS_CLOSE only matches Close(Write), not Close(Read)
929        let mask = EventKindMask::ACCESS_CLOSE;
930        assert!(mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Write))));
931        assert!(mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Any)))); // Any could be write
932        assert!(!mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Read)))); // Read goes to NOWRITE
933        assert!(!mask.matches(&EventKind::Access(AccessKind::Open(AccessMode::Any))));
934    }
935
936    #[test]
937    fn matches_access_close_nowrite_events() {
938        // ACCESS_CLOSE_NOWRITE matches Close(Read) - files opened read-only
939        let mask = EventKindMask::ACCESS_CLOSE_NOWRITE;
940        assert!(mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Read))));
941        assert!(mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Any)))); // Any could be read
942        assert!(!mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Write)))); // Write goes to ACCESS_CLOSE
943        assert!(!mask.matches(&EventKind::Access(AccessKind::Open(AccessMode::Any))));
944    }
945
946    #[test]
947    fn combined_close_masks_match_both() {
948        // When both ACCESS_CLOSE and ACCESS_CLOSE_NOWRITE are set, match both
949        let mask = EventKindMask::ACCESS_CLOSE | EventKindMask::ACCESS_CLOSE_NOWRITE;
950        assert!(mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Write))));
951        assert!(mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Read))));
952        assert!(mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Any))));
953    }
954
955    #[test]
956    fn all_access_matches_open_close_read_any_other() {
957        let mask = EventKindMask::ALL_ACCESS;
958        assert!(mask.matches(&EventKind::Access(AccessKind::Open(AccessMode::Read))));
959        assert!(mask.matches(&EventKind::Access(AccessKind::Close(AccessMode::Write))));
960        assert!(mask.matches(&EventKind::Access(AccessKind::Read)));
961        assert!(mask.matches(&EventKind::Access(AccessKind::Any)));
962        assert!(mask.matches(&EventKind::Access(AccessKind::Other)));
963    }
964
965    #[test]
966    fn matches_modify_data_events() {
967        let mask = EventKindMask::MODIFY_DATA;
968        assert!(mask.matches(&EventKind::Modify(ModifyKind::Data(DataChange::Any))));
969        assert!(mask.matches(&EventKind::Modify(ModifyKind::Data(DataChange::Size))));
970        assert!(mask.matches(&EventKind::Modify(ModifyKind::Data(DataChange::Content))));
971        assert!(!mask.matches(&EventKind::Modify(ModifyKind::Metadata(MetadataKind::Any))));
972        assert!(!mask.matches(&EventKind::Modify(ModifyKind::Name(RenameMode::From))));
973    }
974
975    #[test]
976    fn matches_modify_metadata_events() {
977        let mask = EventKindMask::MODIFY_META;
978        assert!(mask.matches(&EventKind::Modify(ModifyKind::Metadata(MetadataKind::Any))));
979        assert!(mask.matches(&EventKind::Modify(ModifyKind::Metadata(
980            MetadataKind::Permissions
981        ))));
982        assert!(!mask.matches(&EventKind::Modify(ModifyKind::Data(DataChange::Any))));
983    }
984
985    #[test]
986    fn matches_modify_name_events() {
987        let mask = EventKindMask::MODIFY_NAME;
988        assert!(mask.matches(&EventKind::Modify(ModifyKind::Name(RenameMode::From))));
989        assert!(mask.matches(&EventKind::Modify(ModifyKind::Name(RenameMode::To))));
990        assert!(mask.matches(&EventKind::Modify(ModifyKind::Name(RenameMode::Both))));
991        assert!(!mask.matches(&EventKind::Modify(ModifyKind::Data(DataChange::Any))));
992    }
993
994    #[test]
995    fn all_modify_matches_data_meta_name() {
996        let mask = EventKindMask::ALL_MODIFY;
997        assert!(mask.matches(&EventKind::Modify(ModifyKind::Data(DataChange::Any))));
998        assert!(mask.matches(&EventKind::Modify(ModifyKind::Metadata(MetadataKind::Any))));
999        assert!(mask.matches(&EventKind::Modify(ModifyKind::Name(RenameMode::From))));
1000        assert!(mask.matches(&EventKind::Modify(ModifyKind::Any)));
1001        assert!(mask.matches(&EventKind::Modify(ModifyKind::Other)));
1002    }
1003
1004    #[test]
1005    fn any_and_other_always_pass() {
1006        let empty = EventKindMask::empty();
1007        assert!(empty.matches(&EventKind::Any));
1008        assert!(empty.matches(&EventKind::Other));
1009    }
1010
1011    #[test]
1012    fn core_excludes_access() {
1013        let core = EventKindMask::CORE;
1014        assert!(core.matches(&EventKind::Create(CreateKind::File)));
1015        assert!(core.matches(&EventKind::Remove(RemoveKind::File)));
1016        assert!(core.matches(&EventKind::Modify(ModifyKind::Data(DataChange::Any))));
1017        assert!(core.matches(&EventKind::Modify(ModifyKind::Metadata(MetadataKind::Any))));
1018        assert!(core.matches(&EventKind::Modify(ModifyKind::Name(RenameMode::From))));
1019        assert!(!core.matches(&EventKind::Access(AccessKind::Open(AccessMode::Any))));
1020        assert!(!core.matches(&EventKind::Access(AccessKind::Close(AccessMode::Write))));
1021    }
1022
1023    #[test]
1024    fn empty_mask_only_passes_any_other() {
1025        let empty = EventKindMask::empty();
1026        assert!(empty.matches(&EventKind::Any));
1027        assert!(empty.matches(&EventKind::Other));
1028        assert!(!empty.matches(&EventKind::Create(CreateKind::File)));
1029        assert!(!empty.matches(&EventKind::Remove(RemoveKind::File)));
1030        assert!(!empty.matches(&EventKind::Modify(ModifyKind::Data(DataChange::Any))));
1031        assert!(!empty.matches(&EventKind::Access(AccessKind::Open(AccessMode::Any))));
1032    }
1033
1034    #[test]
1035    fn bitwise_or_combines_masks() {
1036        let mask = EventKindMask::CREATE | EventKindMask::REMOVE;
1037        assert!(mask.matches(&EventKind::Create(CreateKind::File)));
1038        assert!(mask.matches(&EventKind::Remove(RemoveKind::Folder)));
1039        assert!(!mask.matches(&EventKind::Modify(ModifyKind::Data(DataChange::Any))));
1040        assert!(!mask.matches(&EventKind::Access(AccessKind::Open(AccessMode::Any))));
1041    }
1042
1043    #[test]
1044    fn all_matches_everything() {
1045        let all = EventKindMask::ALL;
1046        assert!(all.matches(&EventKind::Any));
1047        assert!(all.matches(&EventKind::Other));
1048        assert!(all.matches(&EventKind::Create(CreateKind::File)));
1049        assert!(all.matches(&EventKind::Remove(RemoveKind::File)));
1050        assert!(all.matches(&EventKind::Modify(ModifyKind::Data(DataChange::Any))));
1051        assert!(all.matches(&EventKind::Access(AccessKind::Open(AccessMode::Any))));
1052        assert!(all.matches(&EventKind::Access(AccessKind::Close(AccessMode::Write))));
1053    }
1054
1055    #[test]
1056    fn access_read_and_any_match_with_all_access() {
1057        // Edge case: AccessKind::Read and AccessKind::Any should match if ALL_ACCESS is set
1058        let mask = EventKindMask::ALL_ACCESS;
1059        assert!(mask.matches(&EventKind::Access(AccessKind::Read)));
1060        assert!(mask.matches(&EventKind::Access(AccessKind::Any)));
1061        assert!(mask.matches(&EventKind::Access(AccessKind::Other)));
1062    }
1063}
1064
1065#[cfg(test)]
1066mod user_data_tests {
1067    use super::*;
1068    use std::collections::HashSet;
1069
1070    #[test]
1071    fn user_data_distinguishes_otherwise_identical_events() {
1072        let event = Event::new(EventKind::Create(CreateKind::File)).add_path("file".into());
1073        let zero = event.clone().set_user_data(0);
1074        let max = event.clone().set_user_data(u64::MAX);
1075        assert_eq!(zero.user_data(), Some(0));
1076        assert_eq!(zero.attrs.user_data(), Some(0));
1077        assert!(
1078            zero.attrs.inner.is_none(),
1079            "user data should not allocate attributes"
1080        );
1081        assert_eq!(zero, zero.clone());
1082        assert_ne!(zero, max);
1083        assert_ne!(zero, event);
1084        assert_eq!(HashSet::from([event, zero.clone(), zero, max]).len(), 3);
1085        assert!(
1086            format!("{:?}", Event::default().set_user_data(42))
1087                .contains("attr:user_data: Some(42)")
1088        );
1089    }
1090
1091    #[cfg(feature = "serde")]
1092    #[test]
1093    fn user_data_serialization_preserves_existing_attributes() {
1094        let base = Event::default().set_tracker(123).set_info("test");
1095        let old = serde_json::to_value(&base).unwrap();
1096        assert!(old["attrs"].get("user_data").is_none());
1097        assert_eq!(serde_json::from_value::<Event>(old.clone()).unwrap(), base);
1098        for value in [0, u64::MAX] {
1099            let event = base.clone().set_user_data(value);
1100            let mut expected = old.clone();
1101            expected["attrs"]["user_data"] = value.into();
1102            assert_eq!(serde_json::to_value(&event).unwrap(), expected);
1103            assert_eq!(serde_json::from_value::<Event>(expected).unwrap(), event);
1104            let event = Event::default().set_user_data(value);
1105            assert_eq!(
1106                serde_json::from_value::<Event>(serde_json::to_value(&event).unwrap()).unwrap(),
1107                event
1108            );
1109        }
1110    }
1111}
1112
1113#[cfg(all(test, feature = "serde", not(feature = "serialization-compat-6")))]
1114mod tests {
1115    use super::*;
1116
1117    use insta::assert_snapshot;
1118    use rstest::rstest;
1119
1120    #[rustfmt::skip]
1121    #[rstest]
1122    #[case("any", EventKind::Any)]
1123    #[case("access-any", EventKind::Access(AccessKind::Any))]
1124    #[case("access-read", EventKind::Access(AccessKind::Read))]
1125    #[case("access-open-any", EventKind::Access(AccessKind::Open(AccessMode::Any)))]
1126    #[case("access-open-execute", EventKind::Access(AccessKind::Open(AccessMode::Execute)))]
1127    #[case("access-open-read", EventKind::Access(AccessKind::Open(AccessMode::Read)))]
1128    #[case("access-open-write", EventKind::Access(AccessKind::Open(AccessMode::Write)))]
1129    #[case("access-open-other", EventKind::Access(AccessKind::Open(AccessMode::Other)))]
1130    #[case("access-close-any", EventKind::Access(AccessKind::Close(AccessMode::Any)))]
1131    #[case("access-close-execute", EventKind::Access(AccessKind::Close(AccessMode::Execute)))]
1132    #[case("access-close-read", EventKind::Access(AccessKind::Close(AccessMode::Read)))]
1133    #[case("access-close-write", EventKind::Access(AccessKind::Close(AccessMode::Write)))]
1134    #[case("access-close-other", EventKind::Access(AccessKind::Close(AccessMode::Other)))]
1135    #[case("access-other", EventKind::Access(AccessKind::Other))]
1136    #[case("create-any", EventKind::Create(CreateKind::Any))]
1137    #[case("create-file", EventKind::Create(CreateKind::File))]
1138    #[case("create-folder", EventKind::Create(CreateKind::Folder))]
1139    #[case("create-other", EventKind::Create(CreateKind::Other))]
1140    #[case("modify-any", EventKind::Modify(ModifyKind::Any))]
1141    #[case("modify-data-any", EventKind::Modify(ModifyKind::Data(DataChange::Any)))]
1142    #[case("modify-data-size", EventKind::Modify(ModifyKind::Data(DataChange::Size)))]
1143    #[case("modify-data-content", EventKind::Modify(ModifyKind::Data(DataChange::Content)))]
1144    #[case("modify-data-other", EventKind::Modify(ModifyKind::Data(DataChange::Other)))]
1145    #[case("modify-metadata-any", EventKind::Modify(ModifyKind::Metadata(MetadataKind::Any)))]
1146    #[case("modify-metadata-accesstime", EventKind::Modify(ModifyKind::Metadata(MetadataKind::AccessTime)))]
1147    #[case("modify-metadata-writetime", EventKind::Modify(ModifyKind::Metadata(MetadataKind::WriteTime)))]
1148    #[case("modify-metadata-permissions", EventKind::Modify(ModifyKind::Metadata(MetadataKind::Permissions)))]
1149    #[case("modify-metadata-ownership", EventKind::Modify(ModifyKind::Metadata(MetadataKind::Ownership)))]
1150    #[case("modify-metadata-extended", EventKind::Modify(ModifyKind::Metadata(MetadataKind::Extended)))]
1151    #[case("modify-metadata-other", EventKind::Modify(ModifyKind::Metadata(MetadataKind::Other)))]
1152    #[case("modify-name-any", EventKind::Modify(ModifyKind::Name(RenameMode::Any)))]
1153    #[case("modify-name-to", EventKind::Modify(ModifyKind::Name(RenameMode::To)))]
1154    #[case("modify-name-from", EventKind::Modify(ModifyKind::Name(RenameMode::From)))]
1155    #[case("modify-name-both", EventKind::Modify(ModifyKind::Name(RenameMode::Both)))]
1156    #[case("modify-name-other", EventKind::Modify(ModifyKind::Name(RenameMode::Other)))]
1157    #[case("modify-other", EventKind::Modify(ModifyKind::Other))]
1158    #[case("remove-any", EventKind::Remove(RemoveKind::Any))]
1159    #[case("remove-file", EventKind::Remove(RemoveKind::File))]
1160    #[case("remove-folder", EventKind::Remove(RemoveKind::Folder))]
1161    #[case("remove-other", EventKind::Remove(RemoveKind::Other))]
1162    #[case("other", EventKind::Other)]
1163    fn serialize_event_kind(
1164        #[case] name: &str,
1165        #[case] event_kind: EventKind,
1166    ) {
1167        let event = Event::new(event_kind);
1168        let json = serde_json::to_string(&event).unwrap();
1169        assert_snapshot!(name, json);
1170    }
1171
1172    #[test]
1173    fn serialize_event_with_attrs() {
1174        let event = Event::new(EventKind::Any)
1175            .set_tracker(123)
1176            .set_flag(Flag::Rescan)
1177            .set_info("test event")
1178            .set_process_id(0);
1179        let json = serde_json::to_string(&event).unwrap();
1180        assert_snapshot!(json);
1181    }
1182}