From 91ceec21c49dcfb8268e1a519345c1f7b4fbb468 Mon Sep 17 00:00:00 2001 From: cat_or_not <41955154+catornot@users.noreply.github.com> Date: Sat, 6 May 2023 06:54:31 -0400 Subject: refactor: Always remove zip files (#304) * refactor: Always remove zip files * docs: Add comment explaining the use of the struct --- src-tauri/src/mod_management/mod.rs | 47 ++++++++++++++++++++++++++++++------- 1 file changed, 39 insertions(+), 8 deletions(-) diff --git a/src-tauri/src/mod_management/mod.rs b/src-tauri/src/mod_management/mod.rs index 25dea2bb..ce4c16c2 100644 --- a/src-tauri/src/mod_management/mod.rs +++ b/src-tauri/src/mod_management/mod.rs @@ -6,8 +6,7 @@ use async_recursion::async_recursion; use anyhow::{anyhow, Result}; use app::NorthstarMod; use serde::{Deserialize, Serialize}; -use std::io::Read; -use std::path::PathBuf; +use std::{fs, io::Read, path::PathBuf}; use app::get_enabled_mods; use app::GameInstall; @@ -53,6 +52,37 @@ pub struct ModJson { version: Option, } +/// A wrapper around a temporary file handle and its path. +/// +/// This struct is designed to be used for temporary files that should be automatically deleted +/// when the `TempFile` instance goes out of scope. +#[derive(Debug)] +pub struct TempFile(fs::File, PathBuf); + +impl TempFile { + pub fn new(file: fs::File, path: PathBuf) -> Self { + Self(file, path) + } + + pub fn file(&self) -> &fs::File { + &self.0 + } +} + +impl Drop for TempFile { + fn drop(&mut self) { + _ = fs::remove_file(&self.1) + } +} + +impl std::ops::Deref for TempFile { + type Target = fs::File; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + /// Gets all currently installed and enabled/disabled mods to rebuild `enabledmods.json` pub fn rebuild_enabled_mods_json(game_install: &GameInstall) -> Result<(), String> { let enabledmods_json_path = format!("{}/R2Northstar/enabledmods.json", game_install.game_path); @@ -370,8 +400,8 @@ pub async fn fc_download_mod_and_install( ); // Download the mod - let f = match thermite::core::manage::download_file(download_url, path.clone()) { - Ok(f) => f, + let temp_file = match thermite::core::manage::download_file(download_url, &path) { + Ok(f) => TempFile::new(f, path.into()), Err(e) => return Err(e.to_string()), }; @@ -379,14 +409,15 @@ pub async fn fc_download_mod_and_install( let author = thunderstore_mod_string.split('-').next().unwrap(); // Extract the mod to the mods directory - match thermite::core::manage::install_mod(author, &f, std::path::Path::new(&mods_directory)) { + match thermite::core::manage::install_mod( + author, + temp_file.file(), + std::path::Path::new(&mods_directory), + ) { Ok(()) => (), Err(err) => return Err(err.to_string()), }; - // Delete downloaded zip file - std::fs::remove_file(path).unwrap(); - Ok(()) } -- cgit v1.2.3