如何递归地查看Rust中的文件更改?

时间:2019-03-31 11:08:12

标签: linux rust

我想开发一个解析器,该解析器在某个目录下的文件更改(递归)时触发。最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

notify crate的示例代码可以满足您的要求。它使用RecursiveMode::Recursive指定监视提供的路径中的所有文件和子目录。

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),
        }
    }
}