【问题标题】:Filesystem watch in RustRust 中的文件系统监视
【发布时间】:2023-03-24 14:20:01
【问题描述】:

我正在尝试在 Rust 中实现文件系统观察程序。当文件系统对象发生更改时,我可以接收事件,但确定所做的更改让我很难过。我在 Notify 包here 的最新发布版本上找到了代码,它几乎带我去了那里。

如何从event 中提取路径和类型?该事件是一个枚举类型,但不知何故,当它被打印时,我看到了我想要的所有信息。

我显然遗漏了一些非常基本的东西。

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

fn main() {
    let (tx, rx) = channel();
    let mut watcher = watcher(tx, Duration::from_secs(10)).unwrap();
    watcher
        .watch("/tmp/path", RecursiveMode::Recursive)
        .unwrap();

    loop {
        match rx.recv() {
            Ok(event) => {
                // **>> event.filename? event.type? how?
                println!("{:?}", event);
            }
            Err(e) => println!("watch error: {:?}", e),
        }
    }
}

【问题讨论】:

  • 我认为你需要在event 上然后match

标签: rust filesystemwatcher


【解决方案1】:

使用 debounced watcher,你得到的事件是 DebouncedEvent 类型的。枚举变体指定类型,其内容是路径。要将其排除在事件之外,您应该在事件上匹配所需的事件类型:

match &event {
    Read(path) => {
        // do thing
    }
    Rename(src, dest) => {
        // do other thing
    }
    _ => () // don't care about other types
}

【讨论】:

  • 谢谢,就是这样。 Rust 确实让我摸不着头脑,但是一旦我知道如何去做,它就有意义了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多