From 05115641ff668be4268cd06541a8e5c23efa893b Mon Sep 17 00:00:00 2001 From: Jiahao XU Date: Fri, 22 Jul 2022 22:12:16 +1000 Subject: [PATCH] Add new fn `helpers::create_if_not_exist` Signed-off-by: Jiahao XU --- src/helpers.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/helpers.rs b/src/helpers.rs index 55593da3..6c209738 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -53,6 +53,30 @@ pub fn cargo_home() -> Result<&'static Path, io::Error> { .map(ops::Deref::deref) } +pub fn create_if_not_exist(path: impl AsRef) -> io::Result { + let mut options = fs::File::options(); + options.create_new(true); + + for _ in 0..3 { + match options.open(path.as_ref()) { + Ok(file) => return Ok(file), + Err(io_err) if io_err.kind() == io::ErrorKind::AlreadyExists => { + match fs::File::open(path.as_ref()) { + Ok(file) => return Ok(file), + Err(io_err) if io_err.kind() == io::ErrorKind::NotFound => (), + Err(err) => return Err(err), + } + } + Err(err) => return Err(err), + } + } + + let errmsg = "We tried to open this file three times but all attempts have failed + with creation returns AlreadyExists and opening returns NotFound"; + + Err(io::Error::new(io::ErrorKind::TimedOut, errmsg)) +} + pub async fn await_task(task: tokio::task::JoinHandle>) -> miette::Result { match task.await { Ok(res) => res,