watchexec/crates/lib/examples/fs.rs

53 lines
1.2 KiB
Rust
Raw Normal View History

2021-08-19 10:31:29 +02:00
use std::time::Duration;
2021-08-16 15:15:17 +02:00
use async_priority_channel as priority;
2021-10-10 10:04:40 +02:00
use miette::{IntoDiagnostic, Result};
2021-08-16 15:37:01 +02:00
use tokio::{
sync::{mpsc, watch},
time::sleep,
};
use watchexec::{
event::{Event, Priority},
fs,
};
2021-08-16 15:15:17 +02:00
2021-08-16 15:37:01 +02:00
// Run with: `env RUST_LOG=debug cargo run --example fs`,
// then touch some files within the first 15 seconds, and afterwards.
2021-08-16 15:15:17 +02:00
#[tokio::main]
2021-10-10 10:04:40 +02:00
async fn main() -> Result<()> {
2021-08-16 15:15:17 +02:00
tracing_subscriber::fmt::init();
let (ev_s, ev_r) = priority::bounded::<Event, Priority>(1024);
2021-08-16 15:15:17 +02:00
let (er_s, mut er_r) = mpsc::channel(64);
let (wd_s, wd_r) = watch::channel(fs::WorkingData::default());
let mut wkd = fs::WorkingData::default();
wkd.pathset = vec![".".into()];
2021-10-10 10:04:40 +02:00
wd_s.send(wkd.clone()).into_diagnostic()?;
2021-08-16 15:15:17 +02:00
tokio::spawn(async move {
while let Ok((event, priority)) = ev_r.recv().await {
tracing::info!("event ({priority:?}): {event:?}");
2021-08-16 15:15:17 +02:00
}
});
tokio::spawn(async move {
while let Some(error) = er_r.recv().await {
tracing::error!("error: {error}");
2021-08-16 15:15:17 +02:00
}
});
2021-08-16 15:37:01 +02:00
let wd_sh = tokio::spawn(async move {
sleep(Duration::from_secs(15)).await;
wkd.pathset = Vec::new();
tracing::info!("turning off fs watcher without stopping it");
wd_s.send(wkd).unwrap();
wd_s
});
2021-08-16 15:15:17 +02:00
fs::worker(wd_r, er_s, ev_s).await?;
2021-10-10 10:04:40 +02:00
wd_sh.await.into_diagnostic()?;
2021-08-16 15:15:17 +02:00
Ok(())
}