Add new fn helpers::create_if_not_exist

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
This commit is contained in:
Jiahao XU 2022-07-22 22:12:16 +10:00
parent 7311f77f29
commit 05115641ff
No known key found for this signature in database
GPG key ID: 591C0B03040416D6

View file

@ -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<Path>) -> io::Result<fs::File> {
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<T>(task: tokio::task::JoinHandle<miette::Result<T>>) -> miette::Result<T> {
match task.await {
Ok(res) => res,