diff --git a/src/refresh.rs b/src/refresh.rs index ed5901f..937face 100644 --- a/src/refresh.rs +++ b/src/refresh.rs @@ -2,7 +2,7 @@ use anyhow::anyhow; use clap::Parser; use std::{ fs::File, - io::{Read, Write}, + io::Read, path::{Path, PathBuf}, time::SystemTime, }; @@ -25,6 +25,7 @@ pub fn main(cli: Cli) -> anyhow::Result<()> { let certs_obj_dir = certs_dir.with_added_extension(timestamp_ms()); std::fs::create_dir(&certs_obj_dir) .map_err(|e| anyhow!("failed to create \"{}\": {e}", certs_obj_dir.display()))?; + let certs_obj_dir_guard = SwpDirGuard(certs_obj_dir.clone()); let mut bundle_content = Vec::new(); @@ -45,14 +46,7 @@ pub fn main(cli: Cli) -> anyhow::Result<()> { bundle_content.push(b'\n'); let copy_dst = certs_obj_dir.join(it.file_name()); - let mut copy_dst_file = File::options() - .create(true) - .truncate(true) - .write(true) - .open(©_dst) - .map_err(|e| anyhow!("failed to open \"{}\": {e}", copy_dst.display()))?; - copy_dst_file - .write_all(&content) + std::fs::write(©_dst, &content) .map_err(|e| anyhow!("failed to write \"{}\": {e}", copy_dst.display()))?; } } @@ -80,9 +74,18 @@ pub fn main(cli: Cli) -> anyhow::Result<()> { _ = std::fs::remove_dir_all(&path); } + std::mem::forget(certs_obj_dir_guard); Ok(()) } +#[derive(Debug)] +struct SwpDirGuard(PathBuf); +impl Drop for SwpDirGuard { + fn drop(&mut self) { + _ = std::fs::remove_dir_all(&self.0); + } +} + fn read_file_limited(path: &Path, limit: u64) -> anyhow::Result> { let mut buf = Vec::with_capacity(limit as _); let file =