From 09d210bf6261bddb25e23c7aff9630cd4a718541 Mon Sep 17 00:00:00 2001 From: Jiahao XU Date: Fri, 22 Jul 2022 22:32:45 +1000 Subject: [PATCH] Simplify `helpers::create_if_not_exist` implementation Signed-off-by: Jiahao XU --- src/helpers.rs | 25 +++++-------------------- 1 file changed, 5 insertions(+), 20 deletions(-) diff --git a/src/helpers.rs b/src/helpers.rs index 6c209738..d240772e 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -54,27 +54,12 @@ pub fn cargo_home() -> Result<&'static Path, io::Error> { } pub fn create_if_not_exist(path: impl AsRef) -> io::Result { - let mut options = fs::File::options(); - options.create_new(true); + let path = path.as_ref(); - 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)) + fs::File::options() + .create_new(true) + .open(path) + .or_else(|_| fs::File::open(path)) } pub async fn await_task(task: tokio::task::JoinHandle>) -> miette::Result {