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