43 lines
1 KiB
Rust
43 lines
1 KiB
Rust
|
use std::path::Path;
|
||
|
|
||
|
use notify::{Config, Event, RecommendedWatcher, RecursiveMode, Watcher};
|
||
|
use tokio::sync::mpsc::channel;
|
||
|
use tracing::{error, info, instrument};
|
||
|
|
||
|
use crate::Besult;
|
||
|
|
||
|
pub type FileWatcher = RecommendedWatcher;
|
||
|
|
||
|
pub mod prelude {
|
||
|
pub use super::{file_watcher, FileWatcher};
|
||
|
}
|
||
|
|
||
|
pub fn file_watcher<P, F>(dir: P, cb: F) -> Besult<FileWatcher>
|
||
|
where
|
||
|
P: AsRef<Path>,
|
||
|
F: Fn(Event) -> () + std::marker::Send + 'static,
|
||
|
{
|
||
|
let (tx, mut rx) = channel(1);
|
||
|
let mut watcher = RecommendedWatcher::new(
|
||
|
move |res| match res {
|
||
|
Ok(e) => futures::executor::block_on(async {
|
||
|
tx.send(e).await.unwrap();
|
||
|
}),
|
||
|
Err(e) => error!("Error from file_watcher: {e}"),
|
||
|
},
|
||
|
Config::default(),
|
||
|
)?;
|
||
|
|
||
|
info!("Watching directory '{}'", dir.as_ref().display());
|
||
|
|
||
|
tokio::spawn(async move {
|
||
|
while let Some(ev) = rx.recv().await {
|
||
|
cb(ev)
|
||
|
}
|
||
|
});
|
||
|
|
||
|
watcher.watch(dir.as_ref(), RecursiveMode::Recursive)?;
|
||
|
|
||
|
Ok(watcher)
|
||
|
}
|