notify_fork/
lib.rs

1//! Cross-platform file system notification library
2//!
3//! # Installation
4//!
5//! ```toml
6//! [dependencies]
7//! notify = "6.1.1"
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 = "6.1.1", 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 std::path::Path;
92//! use notify::{recommended_watcher, Event, RecursiveMode, Result, Watcher};
93//! use std::sync::mpsc;
94//!
95//! fn main() -> Result<()> {
96//!     let (tx, rx) = mpsc::channel::<Result<Event>>();
97//!
98//!     // Use recommended_watcher() to automatically select the best implementation
99//!     // for your platform. The `EventHandler` passed to this constructor can be a
100//!     // closure, a `std::sync::mpsc::Sender`, a `crossbeam_channel::Sender`, or
101//!     // another type the trait is implemented for.
102//!     let mut watcher = notify::recommended_watcher(tx)?;
103//!
104//!     // Add a path to be watched. All files and directories at that path and
105//!     // below will be monitored for changes.
106//! #     #[cfg(not(any(
107//! #     target_os = "freebsd",
108//! #     target_os = "openbsd",
109//! #     target_os = "dragonfly",
110//! #     target_os = "netbsd")))]
111//! #     { // "." doesn't exist on BSD for some reason in CI
112//!     watcher.watch(Path::new("."), RecursiveMode::Recursive)?;
113//! #     }
114//! #     #[cfg(any())]
115//! #     { // don't run this in doctests, it blocks forever
116//!     // Block forever, printing out events as they come in
117//!     for res in rx {
118//!         match res {
119//!             Ok(event) => println!("event: {:?}", event),
120//!             Err(e) => println!("watch error: {:?}", e),
121//!         }
122//!     }
123//! #     }
124//!
125//!     Ok(())
126//! }
127//! ```
128//!
129//! ## With different configurations
130//!
131//! It is possible to create several watchers with different configurations or implementations that
132//! all call the same event function. This can accommodate advanced behaviour or work around limits.
133//!
134//! ```rust
135//! # use notify::{RecommendedWatcher, RecursiveMode, Result, Watcher};
136//! # use std::path::Path;
137//! #
138//! # fn main() -> Result<()> {
139//!       fn event_fn(res: Result<notify::Event>) {
140//!           match res {
141//!              Ok(event) => println!("event: {:?}", event),
142//!              Err(e) => println!("watch error: {:?}", e),
143//!           }
144//!       }
145//!
146//!       let mut watcher1 = notify::recommended_watcher(event_fn)?;
147//!       // we will just use the same watcher kind again here
148//!       let mut watcher2 = notify::recommended_watcher(event_fn)?;
149//! #     #[cfg(not(any(
150//! #     target_os = "freebsd",
151//! #     target_os = "openbsd",
152//! #     target_os = "dragonfly",
153//! #     target_os = "netbsd")))]
154//! #     { // "." doesn't exist on BSD for some reason in CI
155//! #     watcher1.watch(Path::new("."), RecursiveMode::Recursive)?;
156//! #     watcher2.watch(Path::new("."), RecursiveMode::Recursive)?;
157//! #     }
158//!       // dropping the watcher1/2 here (no loop etc) will end the program
159//! #
160//! #     Ok(())
161//! # }
162//! ```
163
164#![deny(missing_docs)]
165
166pub use config::{Config, RecursiveMode};
167pub use error::{Error, ErrorKind, Result};
168pub use notify_types_fork::event::{self, Event, EventKind};
169use std::path::Path;
170
171pub(crate) type Receiver<T> = std::sync::mpsc::Receiver<T>;
172pub(crate) type Sender<T> = std::sync::mpsc::Sender<T>;
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#[inline]
181pub(crate) fn bounded<T>(cap: usize) -> (BoundSender<T>, Receiver<T>) {
182    std::sync::mpsc::sync_channel(cap)
183}
184
185#[cfg(all(target_os = "macos", not(feature = "macos_kqueue")))]
186pub use crate::fsevent::FsEventWatcher;
187#[cfg(any(target_os = "linux", target_os = "android"))]
188pub use crate::inotify::INotifyWatcher;
189#[cfg(any(
190    target_os = "freebsd",
191    target_os = "openbsd",
192    target_os = "netbsd",
193    target_os = "dragonfly",
194    target_os = "ios",
195    all(target_os = "macos", feature = "macos_kqueue")
196))]
197pub use crate::kqueue::KqueueWatcher;
198pub use null::NullWatcher;
199pub use poll::PollWatcher;
200#[cfg(target_os = "windows")]
201pub use windows::ReadDirectoryChangesWatcher;
202
203#[cfg(all(target_os = "macos", not(feature = "macos_kqueue")))]
204pub mod fsevent;
205#[cfg(any(target_os = "linux", target_os = "android"))]
206pub mod inotify;
207#[cfg(any(
208    target_os = "freebsd",
209    target_os = "openbsd",
210    target_os = "dragonfly",
211    target_os = "netbsd",
212    target_os = "ios",
213    all(target_os = "macos", feature = "macos_kqueue")
214))]
215pub mod kqueue;
216#[cfg(target_os = "windows")]
217pub mod windows;
218
219pub mod null;
220pub mod poll;
221
222mod config;
223mod error;
224
225/// The set of requirements for watcher event handling functions.
226///
227/// # Example implementation
228///
229/// ```no_run
230/// use notify::{Event, Result, EventHandler};
231///
232/// /// Prints received events
233/// struct EventPrinter;
234///
235/// impl EventHandler for EventPrinter {
236///     fn handle_event(&mut self, event: Result<Event>) {
237///         if let Ok(event) = event {
238///             println!("Event: {:?}", event);
239///         }
240///     }
241/// }
242/// ```
243pub trait EventHandler: Send + 'static {
244    /// Handles an event.
245    fn handle_event(&mut self, event: Result<Event>);
246}
247
248impl<F> EventHandler for F
249where
250    F: FnMut(Result<Event>) + Send + 'static,
251{
252    fn handle_event(&mut self, event: Result<Event>) {
253        (self)(event);
254    }
255}
256
257#[cfg(feature = "crossbeam-channel")]
258impl EventHandler for crossbeam_channel::Sender<Result<Event>> {
259    fn handle_event(&mut self, event: Result<Event>) {
260        let _ = self.send(event);
261    }
262}
263
264impl EventHandler for std::sync::mpsc::Sender<Result<Event>> {
265    fn handle_event(&mut self, event: Result<Event>) {
266        let _ = self.send(event);
267    }
268}
269
270/// Watcher kind enumeration
271#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
272#[non_exhaustive]
273pub enum WatcherKind {
274    /// inotify backend (linux)
275    Inotify,
276    /// FS-Event backend (mac)
277    Fsevent,
278    /// KQueue backend (bsd,optionally mac)
279    Kqueue,
280    /// Polling based backend (fallback)
281    PollWatcher,
282    /// Windows backend
283    ReadDirectoryChangesWatcher,
284    /// Fake watcher for testing
285    NullWatcher,
286}
287
288/// Type that can deliver file activity notifications
289///
290/// Watcher is implemented per platform using the best implementation available on that platform.
291/// In addition to such event driven implementations, a polling implementation is also provided
292/// that should work on any platform.
293pub trait Watcher {
294    /// Create a new watcher with an initial Config.
295    fn new<F: EventHandler>(event_handler: F, config: config::Config) -> Result<Self>
296    where
297        Self: Sized;
298    /// Begin watching a new path.
299    ///
300    /// If the `path` is a directory, `recursive_mode` will be evaluated. If `recursive_mode` is
301    /// `RecursiveMode::Recursive` events will be delivered for all files in that tree. Otherwise
302    /// only the directory and its immediate children will be watched.
303    ///
304    /// If the `path` is a file, `recursive_mode` will be ignored and events will be delivered only
305    /// for the file.
306    ///
307    /// On some platforms, if the `path` is renamed or removed while being watched, behaviour may
308    /// be unexpected. See discussions in [#165] and [#166]. If less surprising behaviour is wanted
309    /// one may non-recursively watch the _parent_ directory as well and manage related events.
310    ///
311    /// [#165]: https://github.com/notify-rs/notify/issues/165
312    /// [#166]: https://github.com/notify-rs/notify/issues/166
313    fn watch(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()>;
314
315    /// Stop watching a path.
316    ///
317    /// # Errors
318    ///
319    /// Returns an error in the case that `path` has not been watched or if removing the watch
320    /// fails.
321    fn unwatch(&mut self, path: &Path) -> Result<()>;
322
323    /// Configure the watcher at runtime.
324    ///
325    /// See the [`Config`](config/struct.Config.html) struct for all configuration options.
326    ///
327    /// # Returns
328    ///
329    /// - `Ok(true)` on success.
330    /// - `Ok(false)` if the watcher does not support or implement the option.
331    /// - `Err(notify::Error)` on failure.
332    fn configure(&mut self, _option: Config) -> Result<bool> {
333        Ok(false)
334    }
335
336    /// Returns the watcher kind, allowing to perform backend-specific tasks
337    fn kind() -> WatcherKind
338    where
339        Self: Sized;
340}
341
342/// The recommended `Watcher` implementation for the current platform
343#[cfg(any(target_os = "linux", target_os = "android"))]
344pub type RecommendedWatcher = INotifyWatcher;
345/// The recommended `Watcher` implementation for the current platform
346#[cfg(all(target_os = "macos", not(feature = "macos_kqueue")))]
347pub type RecommendedWatcher = FsEventWatcher;
348/// The recommended `Watcher` implementation for the current platform
349#[cfg(target_os = "windows")]
350pub type RecommendedWatcher = ReadDirectoryChangesWatcher;
351/// The recommended `Watcher` implementation for the current platform
352#[cfg(any(
353    target_os = "freebsd",
354    target_os = "openbsd",
355    target_os = "netbsd",
356    target_os = "dragonfly",
357    target_os = "ios",
358    all(target_os = "macos", feature = "macos_kqueue")
359))]
360pub type RecommendedWatcher = KqueueWatcher;
361/// The recommended `Watcher` implementation for the current platform
362#[cfg(not(any(
363    target_os = "linux",
364    target_os = "android",
365    target_os = "macos",
366    target_os = "windows",
367    target_os = "freebsd",
368    target_os = "openbsd",
369    target_os = "netbsd",
370    target_os = "dragonfly",
371    target_os = "ios"
372)))]
373pub type RecommendedWatcher = PollWatcher;
374
375/// Convenience method for creating the `RecommendedWatcher` for the current platform.
376pub fn recommended_watcher<F>(event_handler: F) -> Result<RecommendedWatcher>
377where
378    F: EventHandler,
379{
380    // All recommended watchers currently implement `new`, so just call that.
381    RecommendedWatcher::new(event_handler, Config::default())
382}
383
384#[cfg(test)]
385mod tests {
386    use super::*;
387
388    #[test]
389    fn test_object_safe() {
390        let _watcher: &dyn Watcher = &NullWatcher;
391    }
392
393    #[test]
394    fn test_debug_impl() {
395        macro_rules! assert_debug_impl {
396            ($t:ty) => {{
397                trait NeedsDebug: std::fmt::Debug {}
398                impl NeedsDebug for $t {}
399            }};
400        }
401
402        assert_debug_impl!(Config);
403        assert_debug_impl!(Error);
404        assert_debug_impl!(ErrorKind);
405        assert_debug_impl!(NullWatcher);
406        assert_debug_impl!(PollWatcher);
407        assert_debug_impl!(RecommendedWatcher);
408        assert_debug_impl!(RecursiveMode);
409        assert_debug_impl!(WatcherKind);
410    }
411}