Trait Watcher
pub trait Watcher
Type that can deliver file activity notifications
Watcher is implemented per platform using the best implementation available on that platform.
In addition to such event driven implementations, a polling implementation is also provided
that should work on any platform.
Creating a watcher
Because Watcher is a trait, Rust usually can't infer the concrete watcher type when calling
Watcher::new(...) directly. Prefer recommended_watcher / RecommendedWatcher (or a
specific backend like PollWatcher) when constructing a watcher.
use notify::{Event, RecursiveMode, Result, Watcher};
use std::{path::Path, sync::mpsc};
fn main() -> Result<()> {
let (tx, _rx) = mpsc::channel::<Result<Event>>();
let mut watcher = notify::recommended_watcher(tx)?;
watcher.watch(Path::new("."), RecursiveMode::Recursive)?;
Ok(())
}
Required Methods
fn new<F: EventHandler>(event_handler: F, config: Config) -> Result<Self> where Self: Sized,Create a new watcher with an initial Config.
fn watch(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()>Begin watching a new path.
If the
pathis a directory,recursive_modewill be evaluated. Ifrecursive_modeisRecursiveMode::Recursiveevents will be delivered for all files in that tree. Otherwise only the directory and its immediate children will be watched.If the
pathis a file,recursive_modewill be ignored and events will be delivered only for the file.Event paths are reported using the same root representation as
path. Ifpathis relative, emitted event paths are relative to the process current directory at the time this method is called. Ifpathis absolute, emitted event paths are absolute. Convertpathbefore calling this method if your application needs a specific representation.On success, calling this method again for the same backend-resolved path replaces the existing watch for that path. The recursive mode is updated to the new value, a second independent watch is not added, and a single call to
Watcher::unwatchremoves the watched path.To add many paths at once, use
Watcher::update_paths. On macOS, this avoids rebuilding the FSEvents stream for each path.For rename, move, and deletion behavior, see Changes to watched paths.
fn unwatch(&mut self, path: &Path) -> Result<()>Stop watching a path.
Only a path that was passed to
Watcher::watchcan be unwatched. A recursive watch abovepathkeeps reporting it, so unwatching cannot exclude a subtree from a recursive watch.Errors
Returns an error in the case that
pathhas not been watched or if removing the watch fails. A path that only a recursive watch above it covers has not been watched, and unwatching it returnsErrorKind::WatchNotFound.fn kind() -> WatcherKind where Self: Sized,Returns the watcher kind, allowing to perform backend-specific tasks
Provided Methods
fn watch_with(&mut self, path: &Path, config: WatchPathConfig) -> Result<()>Begin watching a path with per-path settings.
Behaves like
Watcher::watch, with the options inconfigapplied to this watch alone. Backends that do not implement a given option ignore it, so the default implementation applies onlyWatchPathConfig::recursive_mode. All built-in event-producing backends supportWatchPathConfig::with_user_data.Errors
Returns an error in the case that
pathdoes not exist or if adding the watch fails. The error carriesWatchPathConfig::user_datathroughError::user_data.fn update_paths(&mut self, ops: Vec<PathOp>) -> Result<(), UpdatePathsError>Add/remove paths to watch in batch.
For some
Watcherimplementations this method provides better performance than multiple calls toWatcher::watchandWatcher::unwatchif you want to add/remove many paths at once. In particular, the FSEvents backend on macOS rebuilds its stream only once for the whole batch.Errors
Returns
UpdatePathsErrorif any operation fails. Operations are applied sequentially. When an error occurs, processing stops: operations beforeoriginhave been applied,originis the operation that failed (if known), andremainingare the operations that were not attempted.remainingdoes not includeorigin.Examples
# use notify::{Watcher, RecursiveMode, PathOp}; # use std::path::{Path, PathBuf}; # fn main() -> Result<(), Box<dyn std::error::Error>> { # let many_paths_to_add: Vec<PathBuf> = vec![]; # let many_paths_to_remove: Vec<PathBuf> = vec![]; let mut watcher = notify::NullWatcher; let mut batch = Vec::new(); for path in many_paths_to_add { batch.push(PathOp::watch_recursive(path)); } for path in many_paths_to_remove { batch.push(PathOp::unwatch(path)); } // real work is done there watcher.update_paths(batch)?; # Ok(()) # }fn configure(&mut self, _option: Config) -> Result<bool>Configure the watcher at runtime.
See the
Configstruct for all configuration options.Returns
Ok(true)on success.Ok(false)if the watcher does not support or implement the option.Err(notify::Error)on failure.
fn watched_paths(&self) -> Result<Vec<WatchedPath>>Returns the currently watched paths and their recursive modes.
Returned paths use the same representation that was passed to
Watcher::watchorWatcher::update_paths.Errors
Returns an error if the watcher implementation cannot provide this information.
Implementors
impl Watcher for INotifyWatcherimpl Watcher for NullWatcherimpl Watcher for PollWatcher