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 path is a directory, recursive_mode will be evaluated. If recursive_mode is RecursiveMode::Recursive events will be delivered for all files in that tree. Otherwise only the directory and its immediate children will be watched.

If the path is a file, recursive_mode will be ignored and events will be delivered only for the file.

Event paths are reported using the same root representation as path. If path is relative, emitted event paths are relative to the process current directory at the time this method is called. If path is absolute, emitted event paths are absolute. Convert path before 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::unwatch removes 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::watch can be unwatched. A recursive watch above path keeps reporting it, so unwatching cannot exclude a subtree from a recursive watch.

Errors

Returns an error in the case that path has 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 returns ErrorKind::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 in config applied to this watch alone. Backends that do not implement a given option ignore it, so the default implementation applies only WatchPathConfig::recursive_mode. All built-in event-producing backends support WatchPathConfig::with_user_data.

Errors

Returns an error in the case that path does not exist or if adding the watch fails. The error carries WatchPathConfig::user_data through Error::user_data.

fn update_paths(&mut self, ops: Vec<PathOp>) -> Result<(), UpdatePathsError>

Add/remove paths to watch in batch.

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. In particular, the FSEvents backend on macOS rebuilds its stream only once for the whole batch.

Errors

Returns UpdatePathsError if any operation fails. Operations are applied sequentially. When an error occurs, processing stops: operations before origin have been applied, origin is the operation that failed (if known), and remaining are the operations that were not attempted. remaining does not include origin.

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 Config struct 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::watch or Watcher::update_paths.

Errors

Returns an error if the watcher implementation cannot provide this information.

Implementors