Simplify helpers::create_if_not_exist implementation

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
This commit is contained in:
Jiahao XU 2022-07-22 22:32:45 +10:00
parent d7bd96660e
commit 09d210bf62
No known key found for this signature in database
GPG key ID: 591C0B03040416D6

View file

@ -54,27 +54,12 @@ pub fn cargo_home() -> Result<&'static Path, io::Error> {
} }
pub fn create_if_not_exist(path: impl AsRef<Path>) -> io::Result<fs::File> { pub fn create_if_not_exist(path: impl AsRef<Path>) -> io::Result<fs::File> {
let mut options = fs::File::options(); let path = path.as_ref();
options.create_new(true);
for _ in 0..3 { fs::File::options()
match options.open(path.as_ref()) { .create_new(true)
Ok(file) => return Ok(file), .open(path)
Err(io_err) if io_err.kind() == io::ErrorKind::AlreadyExists => { .or_else(|_| fs::File::open(path))
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<T>(task: tokio::task::JoinHandle<miette::Result<T>>) -> miette::Result<T> { pub async fn await_task<T>(task: tokio::task::JoinHandle<miette::Result<T>>) -> miette::Result<T> {