clash-verge/src-tauri/src/utils/config.rs

60 lines
1.7 KiB
Rust
Raw Normal View History

2022-02-27 20:34:25 +03:00
use anyhow::{Context, Result};
2021-12-13 19:40:41 +03:00
use serde::{de::DeserializeOwned, Serialize};
2022-09-21 17:15:24 +03:00
use serde_yaml::{Mapping, Value};
2021-12-13 19:40:41 +03:00
use std::{fs, path::PathBuf};
/// read data from yaml as struct T
2021-12-19 18:56:16 +03:00
pub fn read_yaml<T: DeserializeOwned + Default>(path: PathBuf) -> T {
2022-06-13 20:40:02 +03:00
if !path.exists() {
2022-07-17 12:39:44 +03:00
log::error!(target: "app", "file not found \"{}\"", path.display());
2022-06-13 20:40:02 +03:00
return T::default();
}
let yaml_str = fs::read_to_string(&path).unwrap_or("".into());
match serde_yaml::from_str::<T>(&yaml_str) {
Ok(val) => val,
Err(_) => {
2022-07-17 12:39:44 +03:00
log::error!(target: "app", "failed to read yaml file \"{}\"", path.display());
2022-06-13 20:40:02 +03:00
T::default()
}
}
2021-12-13 19:40:41 +03:00
}
2022-09-21 17:15:24 +03:00
/// read mapping from yaml fix #165
pub fn read_merge_mapping(path: PathBuf) -> Mapping {
let map = Mapping::new();
if !path.exists() {
log::error!(target: "app", "file not found \"{}\"", path.display());
return map;
}
let yaml_str = fs::read_to_string(&path).unwrap_or("".into());
match serde_yaml::from_str::<Value>(&yaml_str) {
Ok(mut val) => {
crate::log_if_err!(val.apply_merge());
val.as_mapping().unwrap_or(&map).to_owned()
}
Err(_) => {
log::error!(target: "app", "failed to read yaml file \"{}\"", path.display());
map
}
}
}
2022-02-27 20:34:25 +03:00
/// save the data to the file
/// can set `prefix` string to add some comments
pub fn save_yaml<T: Serialize>(path: PathBuf, data: &T, prefix: Option<&str>) -> Result<()> {
let data_str = serde_yaml::to_string(data)?;
2022-01-07 18:29:20 +03:00
2022-02-27 20:34:25 +03:00
let yaml_str = match prefix {
Some(prefix) => format!("{prefix}{data_str}"),
None => data_str,
};
let path_str = path.as_os_str().to_string_lossy().to_string();
fs::write(path, yaml_str.as_bytes()).context(format!("failed to save file \"{path_str}\""))
2021-12-13 19:40:41 +03:00
}