fix: make profile deletion rollback-safe

This commit is contained in:
Tunglies
2026-08-03 20:00:01 +08:00
parent 903410c12e
commit c5b641e421
14 changed files with 264 additions and 113 deletions
+14 -3
View File
@@ -4,9 +4,10 @@ use clash_verge_logging::{Type, logging};
use nanoid::nanoid;
use serde::{Serialize, de::DeserializeOwned};
use serde_yaml_ng::{Mapping, Value};
#[cfg(target_os = "windows")]
use std::path::Path;
use std::{path::PathBuf, str::FromStr};
use std::{
path::{Path, PathBuf},
str::FromStr,
};
/// read data from yaml as struct T
pub async fn read_yaml<T: DeserializeOwned>(path: &PathBuf) -> Result<T> {
@@ -73,6 +74,16 @@ pub async fn save_yaml<T: Serialize + Sync>(path: &PathBuf, data: &T, prefix: Op
Ok(())
}
pub async fn save_yaml_atomic<T: Serialize + Sync>(path: &Path, data: &T, prefix: Option<&str>) -> Result<()> {
let temporary = path.with_extension("delete.tmp");
save_yaml(&temporary, data, prefix).await?;
if let Err(error) = super::server::replace_file_atomic(&temporary, path) {
let _ = tokio::fs::remove_file(&temporary).await;
return Err(error).with_context(|| format!("failed to replace file \"{}\"", path.display()));
}
Ok(())
}
const ALPHABET: [char; 62] = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',