mirror of
https://github.com/clash-verge-rev/clash-verge-rev
synced 2025-05-05 17:13:45 +08:00
49 lines
1.5 KiB
Rust
49 lines
1.5 KiB
Rust
use anyhow::{anyhow, bail, Context, Result};
|
|
use serde::{de::DeserializeOwned, Serialize};
|
|
use serde_yaml::{Mapping, Value};
|
|
use std::{fs, path::PathBuf};
|
|
|
|
/// read data from yaml as struct T
|
|
pub fn read_yaml<T: DeserializeOwned>(path: &PathBuf) -> Result<T> {
|
|
if !path.exists() {
|
|
bail!("file not found \"{}\"", path.display());
|
|
}
|
|
|
|
let yaml_str = fs::read_to_string(&path)
|
|
.context(format!("failed to read the file \"{}\"", path.display()))?;
|
|
|
|
serde_yaml::from_str::<T>(&yaml_str).context(format!(
|
|
"failed to read the file with yaml format \"{}\"",
|
|
path.display()
|
|
))
|
|
}
|
|
|
|
/// read mapping from yaml fix #165
|
|
pub fn read_merge_mapping(path: &PathBuf) -> Result<Mapping> {
|
|
let mut val: Value = read_yaml(path)?;
|
|
val.apply_merge()
|
|
.context(format!("failed to apply merge \"{}\"", path.display()))?;
|
|
|
|
Ok(val
|
|
.as_mapping()
|
|
.ok_or(anyhow!(
|
|
"failed to transform to yaml mapping \"{}\"",
|
|
path.display()
|
|
))?
|
|
.to_owned())
|
|
}
|
|
|
|
/// 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)?;
|
|
|
|
let yaml_str = match prefix {
|
|
Some(prefix) => format!("{prefix}\n{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}\""))
|
|
}
|