The file may or may not be created before my program starts, so I need to ensure that this file exists before proceeding. What is the most idiomatic way to do that?
Taking into account suggestions from comments I've written the following code:
fn wait_until_file_created(file_path: &PathBuf) -> Result<(), Box<Error>> {
let (tx, rx) = mpsc::channel();
let mut watcher = notify::raw_watcher(tx)?;
// Watcher can't be registered for file that don't exists.
// I use its parent directory instead, because I'm sure that it always exists
let file_dir = file_path.parent().unwrap();
watcher.watch(&file_dir, RecursiveMode::NonRecursive)?;
if !file_path.exists() {
loop {
match rx.recv_timeout(Duration::from_secs(2))? {
RawEvent { path: Some(p), op: Ok(op::CREATE), .. } =>
if p == file_path {
break
},
_ => continue,
}
}
}
watcher.unwatch(file_dir)?;
Ok(())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With