forked from notify-rs/notify
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync_monitor.rs
More file actions
56 lines (46 loc) · 1.54 KB
/
Copy pathasync_monitor.rs
File metadata and controls
56 lines (46 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#![allow(clippy::print_stdout)]
use futures::{
SinkExt, StreamExt,
channel::mpsc::{Receiver, channel},
};
use notify::{Config, Event, RecommendedWatcher, WatchMode, Watcher};
use std::path::Path;
/// Async, futures channel based event watching
fn main() {
let path = std::env::args()
.nth(1)
.expect("Argument 1 needs to be a path");
println!("watching {path}");
futures::executor::block_on(async {
if let Err(e) = async_watch(path).await {
println!("error: {e:?}");
}
});
}
fn async_watcher() -> notify::Result<(RecommendedWatcher, Receiver<notify::Result<Event>>)> {
let (mut tx, rx) = channel(1);
// Automatically select the best implementation for your platform.
// You can also access each implementation directly e.g. INotifyWatcher.
let watcher = RecommendedWatcher::new(
move |res| {
futures::executor::block_on(async {
tx.send(res).await.unwrap();
});
},
Config::default(),
)?;
Ok((watcher, rx))
}
async fn async_watch<P: AsRef<Path>>(path: P) -> notify::Result<()> {
let (mut watcher, mut rx) = async_watcher()?;
// 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(), WatchMode::recursive())?;
while let Some(res) = rx.next().await {
match res {
Ok(event) => println!("changed: {event:?}"),
Err(e) => println!("watch error: {e:?}"),
}
}
Ok(())
}