Details from the events using the notify crate

I'm using the notify crate to track changes in a directory.

Here is the contents of Cargo.toml:

[package]
name = "foo"
version = "1.0.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
env_logger = "0.10.0"
log = "0.4.17"
notify = "6.1.1"

Here is the contents of main.rs, which is almost entirely copied from https://github.com/notify-rs/notify/blob/notify-6.1.1/examples/monitor_raw.rs:

use notify::{Config, RecommendedWatcher, RecursiveMode, Watcher};
use std::path::Path;

fn main() {
    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();

    let path = std::env::args()
        .nth(1)
        .expect("Argument 1 needs to be a path");

    log::info!("Watching {path}");

    if let Err(error) = watch(path) {
        log::error!("Error: {error:?}");
    }
}

fn watch<P: AsRef<Path>>(path: P) -> notify::Result<()> {
    let (tx, rx) = std::sync::mpsc::channel();

    // Automatically select the best implementation for your platform.
    // You can also access each implementation directly e.g. INotifyWatcher.
    let mut watcher = RecommendedWatcher::new(tx, Config::default())?;

    // Add a path to be watched. All files and directories at that path and
    // below will be monitored for changes.
    watcher.watch(path.as_ref(), RecursiveMode::Recursive)?;

    for res in rx {
        match res {
            Ok(event) => {
                log::info!("Change: {event:?}");
            },
            Err(error) => log::error!("Error: {error:?}"),
        }
    }

    Ok(())
}

I can see that the data of changes in files are passed by log::info!("Change: {event:?}");. My question is how I may obtain details from the changes, such as if the change is create, delete, or change in a file, and the file name.

From reading the docs I see the Event struct has a kind field that is the enum you're looking for. I don't know why the kind is not printing in debug format ('{event:?}), but you can print it yourself by printing the event.kind field.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.