mirror of
https://github.com/exoticorn/microw8.git
synced 2026-01-20 19:26:43 +01:00
implement watch mode
This commit is contained in:
40
src/main.rs
40
src/main.rs
@@ -1,18 +1,48 @@
|
||||
use anyhow::{anyhow, Result};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
use microw8::MicroW8;
|
||||
use notify::{DebouncedEvent, Watcher};
|
||||
use pico_args::Arguments;
|
||||
|
||||
mod microw8;
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let filename = std::env::args()
|
||||
.nth(1)
|
||||
.ok_or_else(|| anyhow!("Missing .uw8 file path"))?;
|
||||
let mut args = Arguments::from_env();
|
||||
|
||||
let watch_mode = args.contains(["-w", "--watch"]);
|
||||
|
||||
let filename = args.free_from_os_str::<PathBuf, bool>(|s| Ok(s.into()))?;
|
||||
|
||||
let mut uw8 = MicroW8::new()?;
|
||||
|
||||
uw8.load_from_file(filename)?;
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let mut watcher = notify::watcher(tx, Duration::from_millis(100))?;
|
||||
|
||||
if watch_mode {
|
||||
watcher.watch(&filename, notify::RecursiveMode::NonRecursive)?;
|
||||
}
|
||||
|
||||
if let Err(err) = uw8.load_from_file(&filename) {
|
||||
if !watch_mode {
|
||||
return Err(err);
|
||||
}
|
||||
eprintln!("Load error: {}", err);
|
||||
}
|
||||
|
||||
while uw8.is_open() {
|
||||
match rx.try_recv() {
|
||||
Ok(DebouncedEvent::Create(_) | DebouncedEvent::Write(_)) => {
|
||||
if let Err(err) = uw8.load_from_file(&filename) {
|
||||
eprintln!("Load error: {}", err)
|
||||
}
|
||||
}
|
||||
Err(mpsc::TryRecvError::Disconnected) => bail!("File watcher disconnected"),
|
||||
_ => (),
|
||||
}
|
||||
|
||||
uw8.run_frame()?;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user