Reputation: 487
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?
Upvotes: 8
Views: 1893
Reputation: 487
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(())
}
Upvotes: 5