Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I recursively watch file changes in Rust?

Tags:

linux

rust

How to watch for file/directory changes in Rust and how to integrate this in a non-blocking way? The canonical example (such as that provided by https://docs.rs/notify/4.0.15/notify/), shows how to watch the files, but it will block the rest of your main function execution. (I'm pursuing this https://doc.rust-lang.org/std/sync/mpsc/fn.channel.html)

like image 948
Rudolf Schmidt Avatar asked Mar 31 '19 11:03

Rudolf Schmidt


1 Answers

The example code for the notify crate does what you want. It uses RecursiveMode::Recursive to specify to watch all files and subdirectories within the provided path.

use notify::{Watcher, RecursiveMode, watcher};
use std::sync::mpsc::channel;
use std::time::Duration;

fn main() {
    // Create a channel to receive the events.
    let (sender, receiver) = channel();

    // Create a watcher object, delivering debounced events.
    // The notification back-end is selected based on the platform.
    let mut watcher = watcher(sender, Duration::from_secs(10)).unwrap();

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

    loop {
        match receiver.recv() {
           Ok(event) => println!("{:?}", event),
           Err(e) => println!("watch error: {:?}", e),
        }
    }
}
like image 79
Peter Hall Avatar answered Sep 22 '22 21:09

Peter Hall