git-next/crates/cli/src/file_watcher.rs

59 lines
1.8 KiB
Rust
Raw Normal View History

//
use actix::prelude::*;
use actix::Recipient;
use notify::event::ModifyKind;
use notify::Watcher;
use tracing::error;
use tracing::info;
use std::path::PathBuf;
use std::time::Duration;
#[derive(Debug, Message)]
#[rtype(result = "()")]
pub struct FileUpdated;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("io")]
Io(#[from] std::io::Error),
}
pub async fn watch_file(path: PathBuf, recipient: Recipient<FileUpdated>) {
let (tx, rx) = std::sync::mpsc::channel();
#[allow(clippy::expect_used)]
let mut handler = notify::recommended_watcher(tx).expect("file watcher");
#[allow(clippy::expect_used)]
handler
.watch(&path, notify::RecursiveMode::NonRecursive)
.expect("watch file");
info!("Watching: {:?}", path);
async move {
loop {
for result in rx.try_iter() {
match result {
Ok(event) => match event.kind {
notify::EventKind::Modify(ModifyKind::Data(_)) => {
tracing::info!("File modified");
recipient.do_send(FileUpdated);
break;
}
notify::EventKind::Modify(_)
| notify::EventKind::Create(_)
| notify::EventKind::Remove(_)
| notify::EventKind::Any
| notify::EventKind::Access(_)
| notify::EventKind::Other => { /* do nothing */ }
},
Err(err) => {
error!(?err, "Watching file: {path:?}");
}
}
}
actix_rt::time::sleep(Duration::from_millis(1000)).await;
}
}
.await;
}