From c7965ceb4f01681814307ef72936eb00135de7e1 Mon Sep 17 00:00:00 2001 From: Jiahao XU Date: Wed, 8 Jun 2022 20:23:03 +1000 Subject: [PATCH] Use `ScopeGuard` to auto remove file on failure Signed-off-by: Jiahao XU --- src/helpers.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/helpers.rs b/src/helpers.rs index e37cf89e..e735c2d0 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -10,6 +10,7 @@ use flate2::read::GzDecoder; use futures_util::stream::StreamExt; use log::{debug, info}; use reqwest::Method; +use scopeguard::ScopeGuard; use serde::Serialize; use tar::Archive; use tinytemplate::TinyTemplate; @@ -63,11 +64,17 @@ pub async fn download>(url: &str, path: P) -> Result<(), Binstall let mut bytes_stream = resp.bytes_stream(); let writer = AsyncFileWriter::new(path)?; + let guard = scopeguard::guard(path, |path| { + fs::remove_file(path).ok(); + }); + while let Some(res) = bytes_stream.next().await { writer.write(res?).await; } writer.done().await?; + // Disarm as it is successfully downloaded and written to file. + ScopeGuard::into_inner(guard); debug!("Download OK, written to file: '{}'", path.display());