refactor: convert synchronous file operations to asynchronous for improved performance (#5059)

* refactor: convert synchronous file operations to asynchronous for improved performance

* fix: update copy_icon_file to use asynchronous directory creation

* refactor: remove unnecessary variable assignments in shortcut management functions
This commit is contained in:
Tunglies
2025-10-14 19:55:22 +08:00
committed by GitHub
Unverified
parent 8760ed17dc
commit 7c71d07ad2
7 changed files with 75 additions and 77 deletions

View File

@@ -1,10 +1,15 @@
use super::CmdResult;
use crate::{
feat, logging,
utils::{dirs, logging::Type},
utils::{
dirs::{self, PathBufExec},
logging::Type,
},
wrap_err,
};
use std::path::Path;
use tauri::{AppHandle, Manager};
use tokio::fs;
/// 打开应用程序所在目录
#[tauri::command]
@@ -131,19 +136,19 @@ pub async fn download_icon_cache(url: String, name: String) -> CmdResult<String>
match std::fs::rename(&temp_path, &icon_path) {
Ok(_) => {}
Err(_) => {
let _ = std::fs::remove_file(&temp_path);
let _ = temp_path.remove_if_exists().await;
if icon_path.exists() {
return Ok(icon_path.to_string_lossy().into());
}
}
}
} else {
let _ = std::fs::remove_file(&temp_path);
let _ = temp_path.remove_if_exists().await;
}
Ok(icon_path.to_string_lossy().into())
} else {
let _ = std::fs::remove_file(&temp_path);
let _ = temp_path.remove_if_exists().await;
Err(format!("下载的内容不是有效图片: {url}"))
}
}
@@ -157,14 +162,12 @@ pub struct IconInfo {
/// 复制图标文件
#[tauri::command]
pub fn copy_icon_file(path: String, icon_info: IconInfo) -> CmdResult<String> {
use std::{fs, path::Path};
pub async fn copy_icon_file(path: String, icon_info: IconInfo) -> CmdResult<String> {
let file_path = Path::new(&path);
let icon_dir = wrap_err!(dirs::app_home_dir())?.join("icons");
if !icon_dir.exists() {
let _ = fs::create_dir_all(&icon_dir);
let _ = fs::create_dir_all(&icon_dir).await;
}
let ext: String = match file_path.extension() {
Some(e) => e.to_string_lossy().into(),
@@ -177,14 +180,16 @@ pub fn copy_icon_file(path: String, icon_info: IconInfo) -> CmdResult<String> {
));
if file_path.exists() {
if icon_info.previous_t.trim() != "" {
fs::remove_file(
icon_dir.join(format!("{0}-{1}.png", icon_info.name, icon_info.previous_t)),
)
.unwrap_or_default();
fs::remove_file(
icon_dir.join(format!("{0}-{1}.ico", icon_info.name, icon_info.previous_t)),
)
.unwrap_or_default();
icon_dir
.join(format!("{0}-{1}.png", icon_info.name, icon_info.previous_t))
.remove_if_exists()
.await
.unwrap_or_default();
icon_dir
.join(format!("{0}-{1}.ico", icon_info.name, icon_info.previous_t))
.remove_if_exists()
.await
.unwrap_or_default();
}
logging!(
info,
@@ -193,7 +198,7 @@ pub fn copy_icon_file(path: String, icon_info: IconInfo) -> CmdResult<String> {
path,
dest_path
);
match fs::copy(file_path, &dest_path) {
match fs::copy(file_path, &dest_path).await {
Ok(_) => Ok(dest_path.to_string_lossy().into()),
Err(err) => Err(err.to_string()),
}

View File

@@ -4,8 +4,8 @@ use feat::LocalBackupFile;
/// Create a local backup
#[tauri::command]
pub fn create_local_backup() -> CmdResult<()> {
wrap_err!(feat::create_local_backup())
pub async fn create_local_backup() -> CmdResult<()> {
wrap_err!(feat::create_local_backup().await)
}
/// List local backups
@@ -16,8 +16,8 @@ pub fn list_local_backup() -> CmdResult<Vec<LocalBackupFile>> {
/// Delete local backup
#[tauri::command]
pub fn delete_local_backup(filename: String) -> CmdResult<()> {
wrap_err!(feat::delete_local_backup(filename))
pub async fn delete_local_backup(filename: String) -> CmdResult<()> {
wrap_err!(feat::delete_local_backup(filename).await)
}
/// Restore local backup

View File

@@ -495,7 +495,7 @@ impl IProfiles {
}
/// 以 app 中的 profile 列表为准,删除不再需要的文件
pub fn cleanup_orphaned_files(&self) -> Result<CleanupResult> {
pub async fn cleanup_orphaned_files(&self) -> Result<CleanupResult> {
let profiles_dir = dirs::app_profiles_dir()?;
if !profiles_dir.exists() {
@@ -538,7 +538,7 @@ impl IProfiles {
// 检查是否为活跃文件
if !active_files.contains(file_name) {
match std::fs::remove_file(&path) {
match path.to_path_buf().remove_if_exists().await {
Ok(_) => {
deleted_files.push(file_name.into());
log::info!(target: "app", "已清理冗余文件: {file_name}");

View File

@@ -241,14 +241,14 @@ impl Sysopt {
#[cfg(target_os = "windows")]
{
if is_enable {
if let Err(e) = startup_shortcut::create_shortcut() {
if let Err(e) = startup_shortcut::create_shortcut().await {
log::error!(target: "app", "创建启动快捷方式失败: {e}");
// 如果快捷方式创建失败,回退到原来的方法
self.try_original_autostart_method(is_enable);
} else {
return Ok(());
}
} else if let Err(e) = startup_shortcut::remove_shortcut() {
} else if let Err(e) = startup_shortcut::remove_shortcut().await {
log::error!(target: "app", "删除启动快捷方式失败: {e}");
self.try_original_autostart_method(is_enable);
} else {

View File

@@ -3,7 +3,7 @@ use crate::{
core::backup,
logging, logging_error,
utils::{
dirs::{app_home_dir, local_backup_dir},
dirs::{PathBufExec, app_home_dir, local_backup_dir},
logging::Type,
},
};
@@ -38,7 +38,7 @@ pub async fn create_backup_and_upload_webdav() -> Result<()> {
return Err(err);
}
if let Err(err) = std::fs::remove_file(&temp_file_path) {
if let Err(err) = temp_file_path.remove_if_exists().await {
logging!(warn, Type::Backup, "Failed to remove temp file: {err:#?}");
}
@@ -112,12 +112,12 @@ pub async fn restore_webdav_backup(filename: String) -> Result<()> {
.await
);
// 最后删除临时文件
fs::remove_file(backup_storage_path)?;
backup_storage_path.remove_if_exists().await?;
Ok(())
}
/// Create a backup and save to local storage
pub fn create_local_backup() -> Result<()> {
pub async fn create_local_backup() -> Result<()> {
let (file_name, temp_file_path) = backup::create_backup().map_err(|err| {
logging!(
error,
@@ -137,7 +137,7 @@ pub fn create_local_backup() -> Result<()> {
"Failed to move local backup file: {err:#?}"
);
// 清理临时文件
if let Err(clean_err) = std::fs::remove_file(&temp_file_path) {
if let Err(clean_err) = temp_file_path.remove_if_exists().await {
logging!(
warn,
Type::Backup,
@@ -208,7 +208,7 @@ pub fn list_local_backup() -> Result<Vec<LocalBackupFile>> {
}
/// Delete local backup
pub fn delete_local_backup(filename: String) -> Result<()> {
pub async fn delete_local_backup(filename: String) -> Result<()> {
let backup_dir = local_backup_dir()?;
let target_path = backup_dir.join(&filename);
if !target_path.exists() {
@@ -220,7 +220,7 @@ pub fn delete_local_backup(filename: String) -> Result<()> {
);
return Ok(());
}
fs::remove_file(target_path)?;
target_path.remove_if_exists().await?;
Ok(())
}

View File

@@ -4,7 +4,7 @@ use anyhow::{Result, anyhow};
use log::info;
#[cfg(target_os = "windows")]
use std::{fs, os::windows::process::CommandExt, path::Path, path::PathBuf};
use std::{os::windows::process::CommandExt, path::Path, path::PathBuf};
/// Windows 下的开机启动文件夹路径
#[cfg(target_os = "windows")]
@@ -36,20 +36,24 @@ pub fn get_exe_path() -> Result<PathBuf> {
/// 创建快捷方式
#[cfg(target_os = "windows")]
pub fn create_shortcut() -> Result<()> {
pub async fn create_shortcut() -> Result<()> {
use crate::utils::dirs::PathBufExec;
let exe_path = get_exe_path()?;
let startup_dir = get_startup_dir()?;
let old_shortcut_path = startup_dir.join("Clash-Verge.lnk");
let new_shortcut_path = startup_dir.join("Clash Verge.lnk");
// 移除旧的快捷方式
if old_shortcut_path.exists() {
if let Err(e) = fs::remove_file(&old_shortcut_path) {
info!(target: "app", "移除旧快捷方式失败: {e}");
} else {
info!(target: "app", "成功移除旧快捷方式");
}
}
let _ = old_shortcut_path
.remove_if_exists()
.await
.inspect(|_| {
info!(target: "app", "成功移除旧启动快捷方式");
})
.inspect_err(|err| {
log::error!(target: "app", "移除旧启动快捷方式失败: {err}");
});
// 如果新快捷方式已存在,直接返回成功
if new_shortcut_path.exists() {
@@ -85,30 +89,36 @@ pub fn create_shortcut() -> Result<()> {
/// 删除快捷方式
#[cfg(target_os = "windows")]
pub fn remove_shortcut() -> Result<()> {
pub async fn remove_shortcut() -> Result<()> {
use crate::utils::dirs::PathBufExec;
let startup_dir = get_startup_dir()?;
let old_shortcut_path = startup_dir.join("Clash-Verge.lnk");
let new_shortcut_path = startup_dir.join("Clash Verge.lnk");
let mut removed_any = false;
// 删除旧的快捷方式
if old_shortcut_path.exists() {
fs::remove_file(&old_shortcut_path).map_err(|e| anyhow!("删除旧快捷方式失败: {}", e))?;
info!(target: "app", "成功删除旧启动快捷方式");
removed_any = true;
}
let _ = old_shortcut_path
.remove_if_exists()
.await
.inspect(|_| {
info!(target: "app", "成功删除旧启动快捷方式");
removed_any = true;
})
.inspect_err(|err| {
log::error!(target: "app", "删除旧启动快捷方式失败: {err}");
});
// 删除新的快捷方式
if new_shortcut_path.exists() {
fs::remove_file(&new_shortcut_path).map_err(|e| anyhow!("删除快捷方式失败: {}", e))?;
info!(target: "app", "成功删除启动快捷方式");
removed_any = true;
}
if !removed_any {
info!(target: "app", "启动快捷方式不存在,无需删除");
}
let _ = new_shortcut_path
.remove_if_exists()
.await
.inspect(|_| {
info!(target: "app", "成功删除启动快捷方式");
removed_any = true;
})
.inspect_err(|err| {
log::error!(target: "app", "删除启动快捷方式失败: {err}");
});
Ok(())
}
@@ -121,19 +131,3 @@ pub fn is_shortcut_enabled() -> Result<bool> {
Ok(new_shortcut_path.exists())
}
// 非 Windows 平台使用的空方法
// #[cfg(not(target_os = "windows"))]
// pub fn create_shortcut() -> Result<()> {
// Ok(())
// }
// #[cfg(not(target_os = "windows"))]
// pub fn remove_shortcut() -> Result<()> {
// Ok(())
// }
// #[cfg(not(target_os = "windows"))]
// pub fn is_shortcut_enabled() -> Result<bool> {
// Ok(false)
// }

View File

@@ -6,7 +6,7 @@ use crate::{
logging,
process::AsyncHandler,
utils::{
dirs::{self, service_log_dir, sidecar_log_dir},
dirs::{self, PathBufExec, service_log_dir, sidecar_log_dir},
help,
logging::Type,
},
@@ -167,8 +167,7 @@ pub async fn delete_log() -> Result<()> {
let duration = now.signed_duration_since(file_time);
if duration.num_days() > day {
let file_path = file.path();
let _ = fs::remove_file(file_path).await;
let _ = file.path().remove_if_exists().await;
logging!(info, Type::Setup, "delete log file: {}", file_name);
}
}