operate.rs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. use serde::{de::DeserializeOwned, Serialize};
  2. use std::{fs, path::PathBuf};
  3. use super::profiles::ProfilesConfig;
  4. use crate::init::app_home_dir;
  5. /// read data from yaml as struct T
  6. pub fn read_yaml<T: DeserializeOwned>(path: PathBuf) -> T {
  7. let yaml_str = fs::read_to_string(path).unwrap();
  8. serde_yaml::from_str::<T>(&yaml_str).unwrap()
  9. }
  10. /// - save the data to the file
  11. /// - can set `prefix` string to add some comments
  12. pub fn save_yaml<T: Serialize>(
  13. path: PathBuf,
  14. data: &T,
  15. prefix: Option<&str>,
  16. ) -> Result<(), String> {
  17. if let Ok(data_str) = serde_yaml::to_string(data) {
  18. let yaml_str = if prefix.is_some() {
  19. prefix.unwrap().to_string() + &data_str
  20. } else {
  21. data_str
  22. };
  23. if fs::write(path.clone(), yaml_str.as_bytes()).is_err() {
  24. Err(format!("can not save file `{:?}`", path))
  25. } else {
  26. Ok(())
  27. }
  28. } else {
  29. Err(String::from("can not convert the data to yaml"))
  30. }
  31. }
  32. // /// Get Clash Core Config
  33. // pub fn read_clash() -> Mapping {
  34. // read_yaml::<Mapping>(app_home_dir().join("config.yaml"))
  35. // }
  36. // /// Get Verge App Config
  37. // pub fn read_verge() -> ProfilesConfig {
  38. // read_from_yaml::<ProfilesConfig>(app_home_dir().join("verge.yaml"))
  39. // }
  40. // /// Save Verge App Config
  41. // pub fn save_verge(verge_config: &ProfilesConfig) {
  42. // let yaml_path = app_home_dir().join("verge.yaml");
  43. // let yaml_str = serde_yaml::to_string(&verge_config).unwrap();
  44. // let yaml_str = String::from("# Config File for Clash Verge\n\n") + &yaml_str;
  45. // fs::write(yaml_path, yaml_str.as_bytes()).unwrap();
  46. // }
  47. /// Get Profiles Config
  48. pub fn read_profiles() -> ProfilesConfig {
  49. read_yaml::<ProfilesConfig>(app_home_dir().join("profiles.yaml"))
  50. }
  51. /// Save Verge App Config
  52. pub fn save_profiles(profiles: &ProfilesConfig) {
  53. save_yaml(
  54. app_home_dir().join("profiles.yaml"),
  55. profiles,
  56. Some("# Profiles Config for Clash Verge\n\n"),
  57. )
  58. .unwrap();
  59. }