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, RecursiveMode, Result, 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("."), RecursiveMode::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::{RecursiveMode, Result, 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("."), RecursiveMode::Recursive)?;
155//! #     watcher2.watch(Path::new("."), RecursiveMode::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};
166pub use error::{Error, ErrorKind, Result};
167pub use notify_types::event::{self, Event, EventKind};
168use std::path::Path;
169
170pub(crate) type Receiver<T> = std::sync::mpsc::Receiver<T>;
171pub(crate) type Sender<T> = std::sync::mpsc::Sender<T>;
172#[cfg(any(target_os = "linux", target_os = "android", target_os = "windows"))]
173pub(crate) type BoundSender<T> = std::sync::mpsc::SyncSender<T>;
174
175#[inline]
176pub(crate) fn unbounded<T>() -> (Sender<T>, Receiver<T>) {
177    std::sync::mpsc::channel()
178}
179
180#[cfg(any(target_os = "linux", target_os = "android", target_os = "windows"))]
181#[inline]
182pub(crate) fn bounded<T>(cap: usize) -> (BoundSender<T>, Receiver<T>) {
183    std::sync::mpsc::sync_channel(cap)
184}
185
186#[cfg(all(target_os = "macos", not(feature = "macos_kqueue")))]
187pub use crate::fsevent::FsEventWatcher;
188#[cfg(any(target_os = "linux", target_os = "android"))]
189pub use crate::inotify::INotifyWatcher;
190#[cfg(any(
191    target_os = "freebsd",
192    target_os = "openbsd",
193    target_os = "netbsd",
194    target_os = "dragonfly",
195    target_os = "ios",
196    all(target_os = "macos", feature = "macos_kqueue")
197))]
198pub use crate::kqueue::KqueueWatcher;
199pub use null::NullWatcher;
200pub use poll::PollWatcher;
201#[cfg(target_os = "windows")]
202pub use windows::ReadDirectoryChangesWatcher;
203
204#[cfg(all(target_os = "macos", not(feature = "macos_kqueue")))]
205pub mod fsevent;
206#[cfg(any(target_os = "linux", target_os = "android"))]
207pub mod inotify;
208#[cfg(any(
209    target_os = "freebsd",
210    target_os = "openbsd",
211    target_os = "dragonfly",
212    target_os = "netbsd",
213    target_os = "ios",
214    all(target_os = "macos", feature = "macos_kqueue")
215))]
216pub mod kqueue;
217#[cfg(target_os = "windows")]
218pub mod windows;
219
220pub mod null;
221pub mod poll;
222
223mod config;
224mod error;
225
226/// The set of requirements for watcher event handling functions.
227///
228/// # Example implementation
229///
230/// ```no_run
231/// use notify::{Event, Result, EventHandler};
232///
233/// /// Prints received events
234/// struct EventPrinter;
235///
236/// impl EventHandler for EventPrinter {
237///     fn handle_event(&mut self, event: Result<Event>) {
238///         if let Ok(event) = event {
239///             println!("Event: {:?}", event);
240///         }
241///     }
242/// }
243/// ```
244pub trait EventHandler: Send + 'static {
245    /// Handles an event.
246    fn handle_event(&mut self, event: Result<Event>);
247}
248
249impl<F> EventHandler for F
250where
251    F: FnMut(Result<Event>) + Send + 'static,
252{
253    fn handle_event(&mut self, event: Result<Event>) {
254        (self)(event);
255    }
256}
257
258#[cfg(feature = "crossbeam-channel")]
259impl EventHandler for crossbeam_channel::Sender<Result<Event>> {
260    fn handle_event(&mut self, event: Result<Event>) {
261        let _ = self.send(event);
262    }
263}
264
265#[cfg(feature = "flume")]
266impl EventHandler for flume::Sender<Result<Event>> {
267    fn handle_event(&mut self, event: Result<Event>) {
268        let _ = self.send(event);
269    }
270}
271
272impl EventHandler for std::sync::mpsc::Sender<Result<Event>> {
273    fn handle_event(&mut self, event: Result<Event>) {
274        let _ = self.send(event);
275    }
276}
277
278/// Watcher kind enumeration
279#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
280#[non_exhaustive]
281pub enum WatcherKind {
282    /// inotify backend (linux)
283    Inotify,
284    /// FS-Event backend (mac)
285    Fsevent,
286    /// KQueue backend (bsd,optionally mac)
287    Kqueue,
288    /// Polling based backend (fallback)
289    PollWatcher,
290    /// Windows backend
291    ReadDirectoryChangesWatcher,
292    /// Fake watcher for testing
293    NullWatcher,
294}
295
296/// Providing methods for adding and removing paths to watch.
297///
298/// `Box<dyn PathsMut>` is created by [`Watcher::paths_mut`]. See its documentation for more.
299pub trait PathsMut {
300    /// Add a new path to watch. See [`Watcher::watch`] for more.
301    fn add(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()>;
302
303    /// Remove a path from watching. See [`Watcher::unwatch`] for more.
304    fn remove(&mut self, path: &Path) -> Result<()>;
305
306    /// Ensure added/removed paths are applied.
307    ///
308    /// The behaviour of dropping a [`PathsMut`] without calling [`commit`] is unspecified.
309    /// The implementation is free to ignore the changes or not, and may leave the watcher in a started or stopped state.
310    fn commit(self: Box<Self>) -> Result<()>;
311}
312
313/// Type that can deliver file activity notifications
314///
315/// `Watcher` is implemented per platform using the best implementation available on that platform.
316/// In addition to such event driven implementations, a polling implementation is also provided
317/// that should work on any platform.
318pub trait Watcher {
319    /// Create a new watcher with an initial Config.
320    fn new<F: EventHandler>(event_handler: F, config: config::Config) -> Result<Self>
321    where
322        Self: Sized;
323    /// Begin watching a new path.
324    ///
325    /// If the `path` is a directory, `recursive_mode` will be evaluated. If `recursive_mode` is
326    /// `RecursiveMode::Recursive` events will be delivered for all files in that tree. Otherwise
327    /// only the directory and its immediate children will be watched.
328    ///
329    /// If the `path` is a file, `recursive_mode` will be ignored and events will be delivered only
330    /// for the file.
331    ///
332    /// On some platforms, if the `path` is renamed or removed while being watched, behaviour may
333    /// be unexpected. See discussions in [#165] and [#166]. If less surprising behaviour is wanted
334    /// one may non-recursively watch the _parent_ directory as well and manage related events.
335    ///
336    /// [#165]: https://github.com/notify-rs/notify/issues/165
337    /// [#166]: https://github.com/notify-rs/notify/issues/166
338    fn watch(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()>;
339
340    /// Stop watching a path.
341    ///
342    /// # Errors
343    ///
344    /// Returns an error in the case that `path` has not been watched or if removing the watch
345    /// fails.
346    fn unwatch(&mut self, path: &Path) -> Result<()>;
347
348    /// Add/remove paths to watch.
349    ///
350    /// 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.
351    ///
352    /// # Examples
353    ///
354    /// ```
355    /// # use notify::{Watcher, RecursiveMode, Result};
356    /// # use std::path::Path;
357    /// # fn main() -> Result<()> {
358    /// # let many_paths_to_add = vec![];
359    /// let mut watcher = notify::recommended_watcher(|_event| { /* event handler */ })?;
360    /// let mut watcher_paths = watcher.paths_mut();
361    /// for path in many_paths_to_add {
362    ///     watcher_paths.add(path, RecursiveMode::Recursive)?;
363    /// }
364    /// watcher_paths.commit()?;
365    /// # Ok(())
366    /// # }
367    /// ```
368    fn paths_mut<'me>(&'me mut self) -> Box<dyn PathsMut + 'me> {
369        struct DefaultPathsMut<'a, T: ?Sized>(&'a mut T);
370        impl<'a, T: Watcher + ?Sized> PathsMut for DefaultPathsMut<'a, T> {
371            fn add(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> {
372                self.0.watch(path, recursive_mode)
373            }
374            fn remove(&mut self, path: &Path) -> Result<()> {
375                self.0.unwatch(path)
376            }
377            fn commit(self: Box<Self>) -> Result<()> {
378                Ok(())
379            }
380        }
381        Box::new(DefaultPathsMut(self))
382    }
383
384    /// Configure the watcher at runtime.
385    ///
386    /// See the [`Config`](config/struct.Config.html) struct for all configuration options.
387    ///
388    /// # Returns
389    ///
390    /// - `Ok(true)` on success.
391    /// - `Ok(false)` if the watcher does not support or implement the option.
392    /// - `Err(notify::Error)` on failure.
393    fn configure(&mut self, _option: Config) -> Result<bool> {
394        Ok(false)
395    }
396
397    /// Returns the watcher kind, allowing to perform backend-specific tasks
398    fn kind() -> WatcherKind
399    where
400        Self: Sized;
401}
402
403/// The recommended [`Watcher`] implementation for the current platform
404#[cfg(any(target_os = "linux", target_os = "android"))]
405pub type RecommendedWatcher = INotifyWatcher;
406/// The recommended [`Watcher`] implementation for the current platform
407#[cfg(all(target_os = "macos", not(feature = "macos_kqueue")))]
408pub type RecommendedWatcher = FsEventWatcher;
409/// The recommended [`Watcher`] implementation for the current platform
410#[cfg(target_os = "windows")]
411pub type RecommendedWatcher = ReadDirectoryChangesWatcher;
412/// The recommended [`Watcher`] implementation for the current platform
413#[cfg(any(
414    target_os = "freebsd",
415    target_os = "openbsd",
416    target_os = "netbsd",
417    target_os = "dragonfly",
418    target_os = "ios",
419    all(target_os = "macos", feature = "macos_kqueue")
420))]
421pub type RecommendedWatcher = KqueueWatcher;
422/// The recommended [`Watcher`] implementation for the current platform
423#[cfg(not(any(
424    target_os = "linux",
425    target_os = "android",
426    target_os = "macos",
427    target_os = "windows",
428    target_os = "freebsd",
429    target_os = "openbsd",
430    target_os = "netbsd",
431    target_os = "dragonfly",
432    target_os = "ios"
433)))]
434pub type RecommendedWatcher = PollWatcher;
435
436/// Convenience method for creating the [`RecommendedWatcher`] for the current platform.
437pub fn recommended_watcher<F>(event_handler: F) -> Result<RecommendedWatcher>
438where
439    F: EventHandler,
440{
441    // All recommended watchers currently implement `new`, so just call that.
442    RecommendedWatcher::new(event_handler, Config::default())
443}
444
445#[cfg(test)]
446mod tests {
447    use std::{
448        fs, iter,
449        time::{Duration, Instant},
450    };
451
452    use tempfile::tempdir;
453
454    use super::*;
455
456    #[test]
457    fn test_object_safe() {
458        let _watcher: &dyn Watcher = &NullWatcher;
459    }
460
461    #[test]
462    fn test_debug_impl() {
463        macro_rules! assert_debug_impl {
464            ($t:ty) => {{
465                #[allow(dead_code)]
466                trait NeedsDebug: std::fmt::Debug {}
467                impl NeedsDebug for $t {}
468            }};
469        }
470
471        assert_debug_impl!(Config);
472        assert_debug_impl!(Error);
473        assert_debug_impl!(ErrorKind);
474        assert_debug_impl!(NullWatcher);
475        assert_debug_impl!(PollWatcher);
476        assert_debug_impl!(RecommendedWatcher);
477        assert_debug_impl!(RecursiveMode);
478        assert_debug_impl!(WatcherKind);
479    }
480
481    fn iter_with_timeout(rx: &Receiver<Result<Event>>) -> impl Iterator<Item = Event> + '_ {
482        // wait for up to 10 seconds for the events
483        let deadline = Instant::now() + Duration::from_secs(10);
484        iter::from_fn(move || {
485            if Instant::now() >= deadline {
486                return None;
487            }
488            Some(
489                rx.recv_timeout(deadline - Instant::now())
490                    .expect("did not receive expected event")
491                    .expect("received an error"),
492            )
493        })
494    }
495
496    #[test]
497    fn integration() -> std::result::Result<(), Box<dyn std::error::Error>> {
498        let dir = tempdir()?;
499
500        // set up the watcher
501        let (tx, rx) = std::sync::mpsc::channel();
502        let mut watcher = RecommendedWatcher::new(tx, Config::default())?;
503        watcher.watch(dir.path(), RecursiveMode::Recursive)?;
504
505        // create a new file
506        let file_path = dir.path().join("file.txt");
507        fs::write(&file_path, b"Lorem ipsum")?;
508
509        println!("waiting for event at {}", file_path.display());
510
511        // wait for the create event, ignore all other events
512        for event in iter_with_timeout(&rx) {
513            if event.paths == vec![file_path.clone()]
514                || event.paths == vec![file_path.canonicalize()?]
515            {
516                return Ok(());
517            }
518
519            println!("unexpected event: {event:?}");
520        }
521
522        panic!("did not receive expected event");
523    }
524
525    #[test]
526    #[cfg(target_os = "windows")]
527    fn test_windows_trash_dir() -> std::result::Result<(), Box<dyn std::error::Error>> {
528        let dir = tempdir()?;
529        let child_dir = dir.path().join("child");
530        fs::create_dir(&child_dir)?;
531
532        let mut watcher = recommended_watcher(|_| {
533            // Do something with the event
534        })?;
535        watcher.watch(&child_dir, RecursiveMode::NonRecursive)?;
536
537        trash::delete(&child_dir)?;
538
539        watcher.watch(dir.path(), RecursiveMode::NonRecursive)?;
540
541        Ok(())
542    }
543
544    #[test]
545    fn test_paths_mut() -> std::result::Result<(), Box<dyn std::error::Error>> {
546        let dir = tempdir()?;
547
548        let dir_a = dir.path().join("a");
549        let dir_b = dir.path().join("b");
550
551        fs::create_dir(&dir_a)?;
552        fs::create_dir(&dir_b)?;
553
554        let (tx, rx) = std::sync::mpsc::channel();
555        let mut watcher = RecommendedWatcher::new(tx, Config::default())?;
556
557        // start watching a and b
558        {
559            let mut watcher_paths = watcher.paths_mut();
560            watcher_paths.add(&dir_a, RecursiveMode::Recursive)?;
561            watcher_paths.add(&dir_b, RecursiveMode::Recursive)?;
562            watcher_paths.commit()?;
563        }
564
565        // create file1 in both a and b
566        let a_file1 = dir_a.join("file1");
567        let b_file1 = dir_b.join("file1");
568        fs::write(&a_file1, b"Lorem ipsum")?;
569        fs::write(&b_file1, b"Lorem ipsum")?;
570
571        // wait for create events of a/file1 and b/file1
572        let mut a_file1_encountered: bool = false;
573        let mut b_file1_encountered: bool = false;
574        for event in iter_with_timeout(&rx) {
575            for path in event.paths {
576                a_file1_encountered =
577                    a_file1_encountered || (path == a_file1 || path == a_file1.canonicalize()?);
578                b_file1_encountered =
579                    b_file1_encountered || (path == b_file1 || path == b_file1.canonicalize()?);
580            }
581            if a_file1_encountered && b_file1_encountered {
582                break;
583            }
584        }
585        assert!(a_file1_encountered, "Did not receive event of {a_file1:?}");
586        assert!(b_file1_encountered, "Did not receive event of {b_file1:?}");
587
588        // stop watching a
589        {
590            let mut watcher_paths = watcher.paths_mut();
591            watcher_paths.remove(&dir_a)?;
592            watcher_paths.commit()?;
593        }
594
595        // create file2 in both a and b
596        let a_file2 = dir_a.join("file2");
597        let b_file2 = dir_b.join("file2");
598        fs::write(&a_file2, b"Lorem ipsum")?;
599        fs::write(&b_file2, b"Lorem ipsum")?;
600
601        // wait for the create event of b/file2 only
602        for event in iter_with_timeout(&rx) {
603            for path in event.paths {
604                assert!(
605                    path != a_file2 || path != a_file2.canonicalize()?,
606                    "Event of {a_file2:?} should not be received"
607                );
608                if path == b_file2 || path == b_file2.canonicalize()? {
609                    return Ok(());
610                }
611            }
612        }
613        panic!("Did not receive the event of {b_file2:?}");
614    }
615}