notify/lib.rs
1//! Cross-platform file system notification library
2//!
3//! # Installation
4//!
5//! ```toml
6//! [dependencies]
7//! notify = "8.1.0"
8//! ```
9//!
10//! If you want debounced events (or don't need them in-order), see [notify-debouncer-mini](https://docs.rs/notify-debouncer-mini/latest/notify_debouncer_mini/)
11//! or [notify-debouncer-full](https://docs.rs/notify-debouncer-full/latest/notify_debouncer_full/).
12//!
13//! ## Features
14//!
15//! List of compilation features, see below for details
16//!
17//! - `serde` for serialization of events
18//! - `macos_fsevent` enabled by default, for fsevent backend on macos
19//! - `macos_kqueue` for kqueue backend on macos
20//! - `serialization-compat-6` restores the serialization behavior of notify 6, off by default
21//!
22//! ### Serde
23//!
24//! Events are serializable via [serde](https://serde.rs) if the `serde` feature is enabled:
25//!
26//! ```toml
27//! notify = { version = "8.1.0", features = ["serde"] }
28//! ```
29//!
30//! # Known Problems
31//!
32//! ### Network filesystems
33//!
34//! Network mounted filesystems like NFS may not emit any events for notify to listen to.
35//! This applies especially to WSL programs watching windows paths ([issue #254](https://github.com/notify-rs/notify/issues/254)).
36//!
37//! A workaround is the [`PollWatcher`] backend.
38//!
39//! ### Docker with Linux on macOS M1
40//!
41//! Docker on macOS M1 [throws](https://github.com/notify-rs/notify/issues/423) `Function not implemented (os error 38)`.
42//! You have to manually use the [`PollWatcher`], as the native backend isn't available inside the emulation.
43//!
44//! ### macOS, FSEvents and unowned files
45//!
46//! Due to the inner security model of FSEvents (see [FileSystemEventSecurity](https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/FSEvents_ProgGuide/FileSystemEventSecurity/FileSystemEventSecurity.html)),
47//! some events cannot be observed easily when trying to follow files that do not
48//! belong to you. In this case, reverting to the pollwatcher can fix the issue,
49//! with a slight performance cost.
50//!
51//! ### macOS/APFS: `std::fs::copy` can trigger events on the source path
52//!
53//! On APFS, `std::fs::copy` may use copy-on-write cloning (`fclonefileat`/`clonefile`).
54//! This can update inode metadata on the source file, and FSEvents may report a metadata change
55//! for the source path (see [issue #259](https://github.com/notify-rs/notify/issues/259) and
56//! [issue #465](https://github.com/notify-rs/notify/issues/465)).
57//!
58//! Workarounds are to avoid `std::fs::copy` (use `std::io::copy` or `read`/`write` instead), or
59//! filter out metadata-only events if they're not relevant (e.g. don't include
60//! `EventKindMask::MODIFY_META` in [`Config::with_event_kinds`]).
61//!
62//! ### Editor Behaviour
63//!
64//! If you rely on precise events (Write/Delete/Create..), you will notice that the actual events
65//! can differ a lot between file editors. Some truncate the file on save, some create a new one and replace the old one.
66//! See also [this](https://github.com/notify-rs/notify/issues/247) and [this](https://github.com/notify-rs/notify/issues/113#issuecomment-281836995) issues for example.
67//!
68//! ### Parent folder deletion
69//!
70//! If you want to receive an event for a deletion of folder `b` for the path `/a/b/..`, you will have to watch its parent `/a`.
71//! See [here](https://github.com/notify-rs/notify/issues/403) for more details.
72//!
73//! ### Pseudo Filesystems like /proc, /sys
74//!
75//! Some filesystems like `/proc` and `/sys` on *nix do not emit change events or use correct file change dates.
76//! To circumvent that problem you can use the [`PollWatcher`] with the `compare_contents` option.
77//!
78//! ### Linux: Bad File Descriptor / No space left on device
79//!
80//! This may be the case of running into the max-files watched limits of your user or system.
81//! (Files also includes folders.) Note that for recursive watched folders each file and folder inside counts towards the limit.
82//!
83//! You may increase this limit in linux via
84//! ```sh
85//! sudo sysctl fs.inotify.max_user_instances=8192 # example number
86//! sudo sysctl fs.inotify.max_user_watches=524288 # example number
87//! sudo sysctl -p
88//! ```
89//!
90//! Note that the [`PollWatcher`] is not restricted by this limitation, so it may be an alternative if your users can't increase the limit.
91//!
92//! ### Watching large directories
93//!
94//! When watching a very large amount of files, notify may fail to receive all events.
95//! For example the linux backend is documented to not be a 100% reliable source. See also issue [#412](https://github.com/notify-rs/notify/issues/412).
96//!
97//! # Examples
98//!
99//! For more examples visit the [examples folder](https://github.com/notify-rs/notify/tree/main/examples) in the repository.
100//!
101//! ```rust
102//! use notify::{Event, Result, WatchMode, Watcher};
103//! use std::{path::Path, sync::mpsc};
104//!
105//! fn main() -> Result<()> {
106//! let (tx, rx) = mpsc::channel::<Result<Event>>();
107//!
108//! // Use recommended_watcher() to automatically select the best implementation
109//! // for your platform. The `EventHandler` passed to this constructor can be a
110//! // closure, a `std::sync::mpsc::Sender`, a `crossbeam_channel::Sender`, or
111//! // another type the trait is implemented for.
112//! let mut watcher = notify::recommended_watcher(tx)?;
113//!
114//! // Add a path to be watched. All files and directories at that path and
115//! // below will be monitored for changes.
116//! # #[cfg(not(any(
117//! # target_family = "wasm",
118//! # target_os = "freebsd",
119//! # target_os = "openbsd",
120//! # target_os = "dragonfly",
121//! # target_os = "netbsd")))]
122//! # { // "." doesn't exist on BSD for some reason in CI
123//! watcher.watch(Path::new("."), WatchMode::recursive())?;
124//! # }
125//! # #[cfg(any())]
126//! # { // don't run this in doctests, it blocks forever
127//! // Block forever, printing out events as they come in
128//! for res in rx {
129//! match res {
130//! Ok(event) => println!("event: {:?}", event),
131//! Err(e) => println!("watch error: {:?}", e),
132//! }
133//! }
134//! # }
135//!
136//! Ok(())
137//! }
138//! ```
139//!
140//! ## With different configurations
141//!
142//! It is possible to create several watchers with different configurations or implementations that
143//! all call the same event function. This can accommodate advanced behaviour or work around limits.
144//!
145//! ```rust
146//! # use notify::{Result, WatchMode, Watcher};
147//! # use std::path::Path;
148//! #
149//! # fn main() -> Result<()> {
150//! fn event_fn(res: Result<notify::Event>) {
151//! match res {
152//! Ok(event) => println!("event: {:?}", event),
153//! Err(e) => println!("watch error: {:?}", e),
154//! }
155//! }
156//!
157//! let mut watcher1 = notify::recommended_watcher(event_fn)?;
158//! // we will just use the same watcher kind again here
159//! let mut watcher2 = notify::recommended_watcher(event_fn)?;
160//! # #[cfg(not(any(
161//! # target_family = "wasm",
162//! # target_os = "freebsd",
163//! # target_os = "openbsd",
164//! # target_os = "dragonfly",
165//! # target_os = "netbsd")))]
166//! # { // "." doesn't exist on BSD for some reason in CI
167//! # watcher1.watch(Path::new("."), WatchMode::recursive())?;
168//! # watcher2.watch(Path::new("."), WatchMode::recursive())?;
169//! # }
170//! // dropping the watcher1/2 here (no loop etc) will end the program
171//! #
172//! # Ok(())
173//! # }
174//! ```
175
176#![deny(missing_docs)]
177
178pub use config::{Config, RecursiveMode, TargetMode, WatchMode};
179pub use error::{Error, ErrorKind, Result};
180pub use filter::{EntryKind, IgnoreFilter};
181pub use notify_types::event::{self, Event, EventKind};
182#[cfg(test)]
183use std::collections::HashSet;
184use std::path::Path;
185
186pub(crate) type Receiver<T> = std::sync::mpsc::Receiver<T>;
187pub(crate) type Sender<T> = std::sync::mpsc::Sender<T>;
188#[cfg(any(
189 target_os = "linux",
190 target_os = "android",
191 target_os = "windows",
192 all(target_os = "macos", feature = "macos_kqueue", test)
193))]
194pub(crate) type BoundSender<T> = std::sync::mpsc::SyncSender<T>;
195
196#[inline]
197pub(crate) fn unbounded<T>() -> (Sender<T>, Receiver<T>) {
198 std::sync::mpsc::channel()
199}
200
201#[cfg(any(
202 target_os = "linux",
203 target_os = "android",
204 target_os = "windows",
205 all(target_os = "macos", feature = "macos_kqueue", test)
206))]
207#[inline]
208pub(crate) fn bounded<T>(cap: usize) -> (BoundSender<T>, Receiver<T>) {
209 std::sync::mpsc::sync_channel(cap)
210}
211
212#[cfg(all(target_os = "macos", not(feature = "macos_kqueue")))]
213pub use crate::fsevent::FsEventWatcher;
214#[cfg(any(target_os = "linux", target_os = "android"))]
215pub use crate::inotify::INotifyWatcher;
216#[cfg(any(
217 target_os = "freebsd",
218 target_os = "openbsd",
219 target_os = "netbsd",
220 target_os = "dragonfly",
221 target_os = "ios",
222 all(target_os = "macos", feature = "macos_kqueue")
223))]
224pub use crate::kqueue::KqueueWatcher;
225pub use null::NullWatcher;
226pub use poll::PollWatcher;
227#[cfg(target_os = "windows")]
228pub use windows::ReadDirectoryChangesWatcher;
229
230#[cfg(all(target_os = "macos", not(feature = "macos_kqueue")))]
231pub mod fsevent;
232#[cfg(any(target_os = "linux", target_os = "android"))]
233pub mod inotify;
234#[cfg(any(
235 target_os = "freebsd",
236 target_os = "openbsd",
237 target_os = "dragonfly",
238 target_os = "netbsd",
239 target_os = "ios",
240 all(target_os = "macos", feature = "macos_kqueue")
241))]
242pub mod kqueue;
243#[cfg(target_os = "windows")]
244pub mod windows;
245
246pub mod null;
247pub mod poll;
248
249mod bimap;
250mod config;
251mod consolidating_path_trie;
252mod error;
253mod filter;
254
255#[cfg(test)]
256pub(crate) mod test;
257
258/// The set of requirements for watcher event handling functions.
259///
260/// # Example implementation
261///
262/// ```no_run
263/// use notify::{Event, Result, EventHandler};
264///
265/// /// Prints received events
266/// struct EventPrinter;
267///
268/// impl EventHandler for EventPrinter {
269/// fn handle_event(&mut self, event: Result<Event>) {
270/// if let Ok(event) = event {
271/// println!("Event: {:?}", event);
272/// }
273/// }
274/// }
275/// ```
276pub trait EventHandler: Send + 'static {
277 /// Handles an event.
278 fn handle_event(&mut self, event: Result<Event>);
279}
280
281impl<F> EventHandler for F
282where
283 F: FnMut(Result<Event>) + Send + 'static,
284{
285 fn handle_event(&mut self, event: Result<Event>) {
286 (self)(event);
287 }
288}
289
290#[cfg(feature = "crossbeam-channel")]
291impl EventHandler for crossbeam_channel::Sender<Result<Event>> {
292 fn handle_event(&mut self, event: Result<Event>) {
293 let _ = self.send(event);
294 }
295}
296
297#[cfg(feature = "flume")]
298impl EventHandler for flume::Sender<Result<Event>> {
299 fn handle_event(&mut self, event: Result<Event>) {
300 let _ = self.send(event);
301 }
302}
303
304impl EventHandler for std::sync::mpsc::Sender<Result<Event>> {
305 fn handle_event(&mut self, event: Result<Event>) {
306 let _ = self.send(event);
307 }
308}
309
310/// Watcher kind enumeration
311#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
312#[non_exhaustive]
313pub enum WatcherKind {
314 /// inotify backend (linux)
315 Inotify,
316 /// FS-Event backend (mac)
317 Fsevent,
318 /// KQueue backend (bsd,optionally mac)
319 Kqueue,
320 /// Polling based backend (fallback)
321 PollWatcher,
322 /// Windows backend
323 ReadDirectoryChangesWatcher,
324 /// Fake watcher for testing
325 NullWatcher,
326}
327
328/// Providing methods for adding and removing paths to watch.
329///
330/// `Box<dyn PathsMut>` is created by [`Watcher::paths_mut`]. See its documentation for more.
331pub trait PathsMut {
332 /// Add a new path to watch. See [`Watcher::watch`] for more.
333 fn add(&mut self, path: &Path, watch_mode: WatchMode) -> Result<()>;
334
335 /// Remove a path from watching. See [`Watcher::unwatch`] for more.
336 fn remove(&mut self, path: &Path) -> Result<()>;
337
338 /// Ensure added/removed paths are applied.
339 ///
340 /// The behaviour of dropping a [`PathsMut`] without calling [`commit`] is unspecified.
341 /// The implementation is free to ignore the changes or not, and may leave the watcher in a started or stopped state.
342 fn commit(self: Box<Self>) -> Result<()>;
343}
344
345/// Type that can deliver file activity notifications
346///
347/// `Watcher` is implemented per platform using the best implementation available on that platform.
348/// In addition to such event driven implementations, a polling implementation is also provided
349/// that should work on any platform.
350///
351/// # Creating a watcher
352///
353/// Because `Watcher` is a trait, Rust usually can't infer the concrete watcher type when calling
354/// `Watcher::new(...)` directly. Prefer [`recommended_watcher`] / [`RecommendedWatcher`] (or a
355/// specific backend like [`PollWatcher`]) when constructing a watcher.
356///
357/// ```no_run
358/// use notify::{Event, Result, WatchMode, Watcher};
359/// use std::{path::Path, sync::mpsc};
360///
361/// fn main() -> Result<()> {
362/// let (tx, _rx) = mpsc::channel::<Result<Event>>();
363/// let mut watcher = notify::recommended_watcher(tx)?;
364/// watcher.watch(Path::new("."), WatchMode::recursive())?;
365/// Ok(())
366/// }
367/// ```
368pub trait Watcher {
369 /// Create a new watcher with an initial Config.
370 fn new<F: EventHandler>(event_handler: F, config: config::Config) -> Result<Self>
371 where
372 Self: Sized;
373 /// Begin watching a new path.
374 ///
375 /// If the `path` is a directory, `watch_mode.recursive_mode` will be evaluated. If `watch_mode.recursive_mode` is
376 /// `RecursiveMode::Recursive` events will be delivered for all files in that tree. Otherwise
377 /// only the directory and its immediate children will be watched.
378 ///
379 /// If the `path` is a file, `watch_mode.recursive_mode` will be ignored and events will be delivered only
380 /// for the file.
381 ///
382 /// Paths that are ignored by [`Config::with_ignored`] are not watched.
383 fn watch(&mut self, path: &Path, watch_mode: WatchMode) -> Result<()>;
384
385 /// Stop watching a path.
386 ///
387 /// # Errors
388 ///
389 /// Returns an error in the case that `path` has not been watched or if removing the watch
390 /// fails. Unwatching a path that is ignored by [`Config::with_ignored`] is not an error.
391 fn unwatch(&mut self, path: &Path) -> Result<()>;
392
393 /// Add/remove paths to watch.
394 ///
395 /// For some watcher implementations this method provides better performance than multiple calls to [`Watcher::watch`] and [`Watcher::unwatch`] if you want to add/remove many paths at once.
396 ///
397 /// # Examples
398 ///
399 /// ```
400 /// # use notify::{Watcher, WatchMode, Result};
401 /// # use std::path::Path;
402 /// # fn main() -> Result<()> {
403 /// # let many_paths_to_add = vec![];
404 /// let mut watcher = notify::recommended_watcher(|_event| { /* event handler */ })?;
405 /// let mut watcher_paths = watcher.paths_mut();
406 /// for path in many_paths_to_add {
407 /// watcher_paths.add(path, WatchMode::recursive())?;
408 /// }
409 /// watcher_paths.commit()?;
410 /// # Ok(())
411 /// # }
412 /// ```
413 fn paths_mut<'me>(&'me mut self) -> Box<dyn PathsMut + 'me> {
414 struct DefaultPathsMut<'a, T: ?Sized>(&'a mut T);
415 impl<T: Watcher + ?Sized> PathsMut for DefaultPathsMut<'_, T> {
416 fn add(&mut self, path: &Path, watch_mode: WatchMode) -> Result<()> {
417 self.0.watch(path, watch_mode)
418 }
419 fn remove(&mut self, path: &Path) -> Result<()> {
420 self.0.unwatch(path)
421 }
422 fn commit(self: Box<Self>) -> Result<()> {
423 Ok(())
424 }
425 }
426 Box::new(DefaultPathsMut(self))
427 }
428
429 /// Configure the watcher at runtime.
430 ///
431 /// See the [`Config`](config/struct.Config.html) struct for all configuration options.
432 ///
433 /// # Returns
434 ///
435 /// - `Ok(true)` on success.
436 /// - `Ok(false)` if the watcher does not support or implement the option.
437 /// - `Err(notify::Error)` on failure.
438 fn configure(&mut self, _option: Config) -> Result<bool> {
439 Ok(false)
440 }
441
442 /// Returns the watcher kind, allowing to perform backend-specific tasks
443 fn kind() -> WatcherKind
444 where
445 Self: Sized;
446
447 /// Get the list of watch handles that are currently being watched.
448 #[cfg(test)]
449 fn get_watch_handles(&self) -> HashSet<std::path::PathBuf> {
450 HashSet::default()
451 }
452}
453
454/// The recommended [`Watcher`] implementation for the current platform
455#[cfg(any(target_os = "linux", target_os = "android"))]
456pub type RecommendedWatcher = INotifyWatcher;
457/// The recommended [`Watcher`] implementation for the current platform
458#[cfg(all(target_os = "macos", not(feature = "macos_kqueue")))]
459pub type RecommendedWatcher = FsEventWatcher;
460/// The recommended [`Watcher`] implementation for the current platform
461#[cfg(target_os = "windows")]
462pub type RecommendedWatcher = ReadDirectoryChangesWatcher;
463/// The recommended [`Watcher`] implementation for the current platform
464#[cfg(any(
465 target_os = "freebsd",
466 target_os = "openbsd",
467 target_os = "netbsd",
468 target_os = "dragonfly",
469 target_os = "ios",
470 all(target_os = "macos", feature = "macos_kqueue")
471))]
472pub type RecommendedWatcher = KqueueWatcher;
473/// The recommended [`Watcher`] implementation for the current platform
474#[cfg(not(any(
475 target_os = "linux",
476 target_os = "android",
477 target_os = "macos",
478 target_os = "windows",
479 target_os = "freebsd",
480 target_os = "openbsd",
481 target_os = "netbsd",
482 target_os = "dragonfly",
483 target_os = "ios"
484)))]
485pub type RecommendedWatcher = PollWatcher;
486
487/// Convenience method for creating the [`RecommendedWatcher`] for the current platform.
488///
489/// This is often the most ergonomic way to construct a watcher, because calling `Watcher::new(...)`
490/// requires specifying the concrete watcher type.
491///
492/// ```no_run
493/// use notify::{Result, WatchMode, Watcher};
494/// use std::path::Path;
495///
496/// fn main() -> Result<()> {
497/// let mut watcher = notify::recommended_watcher(|res| println!("event: {res:?}"))?;
498/// watcher.watch(Path::new("."), WatchMode::recursive())?;
499/// Ok(())
500/// }
501/// ```
502pub fn recommended_watcher<F>(event_handler: F) -> Result<RecommendedWatcher>
503where
504 F: EventHandler,
505{
506 // All recommended watchers currently implement `new`, so just call that.
507 RecommendedWatcher::new(event_handler, Config::default())
508}
509
510// wasm uses polling watcher which requires a different code to avoid flaky failures
511#[cfg(all(test, not(target_family = "wasm")))]
512mod tests {
513 use std::{
514 fs, iter,
515 sync::mpsc,
516 time::{Duration, Instant},
517 };
518
519 use super::{Config, Event, RecommendedWatcher, Result, Watcher};
520 use crate::{config::WatchMode, test::*};
521
522 fn iter_with_timeout(rx: &mpsc::Receiver<Result<Event>>) -> impl Iterator<Item = Event> + '_ {
523 // wait for up to 10 seconds for the events
524 let deadline = Instant::now() + Duration::from_secs(10);
525 iter::from_fn(move || {
526 if Instant::now() >= deadline {
527 return None;
528 }
529 Some(
530 rx.recv_timeout(deadline - Instant::now())
531 .expect("did not receive expected event")
532 .expect("received an error"),
533 )
534 })
535 }
536
537 #[expect(clippy::print_stdout)]
538 #[test]
539 fn integration() -> std::result::Result<(), Box<dyn std::error::Error>> {
540 let dir = testdir();
541
542 // set up the watcher
543 let (tx, rx) = std::sync::mpsc::channel();
544 let mut watcher = RecommendedWatcher::new(tx, Config::default())?;
545 watcher.watch(dir.path(), WatchMode::recursive())?;
546
547 // create a new file
548 let file_path = dir.path().join("file.txt");
549 fs::write(&file_path, b"Lorem ipsum")?;
550
551 println!("waiting for event at {}", file_path.display());
552
553 // wait for the create event, ignore all other events
554 for event in iter_with_timeout(&rx) {
555 if event.paths == vec![file_path.clone()]
556 || event.paths == vec![file_path.canonicalize()?]
557 {
558 return Ok(());
559 }
560
561 println!("unexpected event: {event:?}");
562 }
563
564 panic!("did not receive expected event");
565 }
566
567 #[test]
568 fn test_paths_mut() -> std::result::Result<(), Box<dyn std::error::Error>> {
569 let dir = testdir();
570
571 let dir_a = dir.path().join("a");
572 let dir_b = dir.path().join("b");
573
574 fs::create_dir(&dir_a)?;
575 fs::create_dir(&dir_b)?;
576
577 let (tx, rx) = std::sync::mpsc::channel();
578 let mut watcher = RecommendedWatcher::new(tx, Config::default())?;
579
580 // start watching a and b
581 {
582 let mut watcher_paths = watcher.paths_mut();
583 watcher_paths.add(&dir_a, WatchMode::recursive())?;
584 watcher_paths.add(&dir_b, WatchMode::recursive())?;
585 watcher_paths.commit()?;
586 }
587
588 // create file1 in both a and b
589 let a_file1 = dir_a.join("file1");
590 let b_file1 = dir_b.join("file1");
591 fs::write(&a_file1, b"Lorem ipsum")?;
592 fs::write(&b_file1, b"Lorem ipsum")?;
593
594 // wait for create events of a/file1 and b/file1
595 let mut a_file1_encountered: bool = false;
596 let mut b_file1_encountered: bool = false;
597 for event in iter_with_timeout(&rx) {
598 for path in event.paths {
599 a_file1_encountered =
600 a_file1_encountered || (path == a_file1 || path == a_file1.canonicalize()?);
601 b_file1_encountered =
602 b_file1_encountered || (path == b_file1 || path == b_file1.canonicalize()?);
603 }
604 if a_file1_encountered && b_file1_encountered {
605 break;
606 }
607 }
608 assert!(a_file1_encountered, "Did not receive event of {a_file1:?}");
609 assert!(b_file1_encountered, "Did not receive event of {b_file1:?}");
610
611 // stop watching a
612 {
613 let mut watcher_paths = watcher.paths_mut();
614 watcher_paths.remove(&dir_a)?;
615 watcher_paths.commit()?;
616 }
617
618 // create file2 in both a and b
619 let a_file2 = dir_a.join("file2");
620 let b_file2 = dir_b.join("file2");
621 fs::write(&a_file2, b"Lorem ipsum")?;
622 fs::write(&b_file2, b"Lorem ipsum")?;
623
624 // wait for the create event of b/file2 only
625 for event in iter_with_timeout(&rx) {
626 for path in event.paths {
627 assert!(
628 path != a_file2 || path != a_file2.canonicalize()?,
629 "Event of {a_file2:?} should not be received"
630 );
631 if path == b_file2 || path == b_file2.canonicalize()? {
632 return Ok(());
633 }
634 }
635 }
636 panic!("Did not receive the event of {b_file2:?}");
637 }
638
639 #[test]
640 fn create_file() {
641 let tmpdir = testdir();
642 let (mut watcher, rx) = recommended_channel();
643 watcher.watch_recursively(&tmpdir);
644
645 let path = tmpdir.path().join("entry");
646 std::fs::File::create_new(&path).expect("create");
647
648 rx.wait_unordered([expected(path).create()]);
649 }
650
651 #[test]
652 fn create_dir() {
653 let tmpdir = testdir();
654 let (mut watcher, rx) = recommended_channel();
655 watcher.watch_recursively(&tmpdir);
656
657 let path = tmpdir.path().join("entry");
658 std::fs::create_dir(&path).expect("create");
659
660 rx.wait_unordered([expected(path).create()]);
661 }
662
663 #[test]
664 fn modify_file() {
665 let tmpdir = testdir();
666 let (mut watcher, rx) = recommended_channel();
667
668 let path = tmpdir.path().join("entry");
669 std::fs::File::create_new(&path).expect("create");
670
671 watcher.watch_recursively(&tmpdir);
672 std::fs::write(&path, b"123").expect("write");
673
674 rx.wait_unordered([expected(path).modify()]);
675 }
676
677 #[test]
678 fn remove_file() {
679 let tmpdir = testdir();
680 let (mut watcher, rx) = recommended_channel();
681
682 let path = tmpdir.path().join("entry");
683 std::fs::File::create_new(&path).expect("create");
684
685 watcher.watch_recursively(&tmpdir);
686 std::fs::remove_file(&path).expect("remove");
687
688 rx.wait_unordered([expected(path).remove()]);
689 }
690}
691
692#[cfg(test)]
693mod tests_other {
694 use super::{
695 Config, Error, ErrorKind, NullWatcher, PollWatcher, RecommendedWatcher, RecursiveMode,
696 Watcher, WatcherKind,
697 };
698
699 #[test]
700 fn test_object_safe() {
701 let _: &dyn Watcher = &NullWatcher;
702 }
703
704 #[test]
705 fn test_debug_impl() {
706 macro_rules! assert_debug_impl {
707 ($t:ty) => {{
708 #[expect(clippy::allow_attributes)]
709 #[allow(dead_code)]
710 trait NeedsDebug: std::fmt::Debug {}
711 impl NeedsDebug for $t {}
712 }};
713 }
714
715 assert_debug_impl!(Config);
716 assert_debug_impl!(Error);
717 assert_debug_impl!(ErrorKind);
718 assert_debug_impl!(NullWatcher);
719 assert_debug_impl!(PollWatcher);
720 assert_debug_impl!(RecommendedWatcher);
721 assert_debug_impl!(RecursiveMode);
722 assert_debug_impl!(WatcherKind);
723 }
724}