config.rs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. use super::{Draft, IClashTemp, IProfiles, IRuntime, IVerge};
  2. use crate::{
  3. enhance,
  4. utils::{dirs, help},
  5. };
  6. use anyhow::{anyhow, Result};
  7. use once_cell::sync::OnceCell;
  8. use std::{env::temp_dir, path::PathBuf};
  9. pub const RUNTIME_CONFIG: &str = "clash-verge.yaml";
  10. pub const CHECK_CONFIG: &str = "clash-verge-check.yaml";
  11. pub struct Config {
  12. clash_config: Draft<IClashTemp>,
  13. verge_config: Draft<IVerge>,
  14. profiles_config: Draft<IProfiles>,
  15. runtime_config: Draft<IRuntime>,
  16. }
  17. impl Config {
  18. pub fn global() -> &'static Config {
  19. static CONFIG: OnceCell<Config> = OnceCell::new();
  20. CONFIG.get_or_init(|| Config {
  21. clash_config: Draft::from(IClashTemp::new()),
  22. verge_config: Draft::from(IVerge::new()),
  23. profiles_config: Draft::from(IProfiles::new()),
  24. runtime_config: Draft::from(IRuntime::new()),
  25. })
  26. }
  27. pub fn clash() -> Draft<IClashTemp> {
  28. Self::global().clash_config.clone()
  29. }
  30. pub fn verge() -> Draft<IVerge> {
  31. Self::global().verge_config.clone()
  32. }
  33. pub fn profiles() -> Draft<IProfiles> {
  34. Self::global().profiles_config.clone()
  35. }
  36. pub fn runtime() -> Draft<IRuntime> {
  37. Self::global().runtime_config.clone()
  38. }
  39. /// 初始化配置
  40. pub fn init_config() -> Result<()> {
  41. crate::log_err!(Self::generate());
  42. if let Err(err) = Self::generate_file(ConfigType::Run) {
  43. log::error!(target: "app", "{err}");
  44. let runtime_path = dirs::app_home_dir()?.join(RUNTIME_CONFIG);
  45. // 如果不存在就将默认的clash文件拿过来
  46. if !runtime_path.exists() {
  47. help::save_yaml(
  48. &runtime_path,
  49. &Config::clash().latest().0,
  50. Some("# Clash Nyanpasu Runtime"),
  51. )?;
  52. }
  53. }
  54. Ok(())
  55. }
  56. /// 将配置丢到对应的文件中
  57. pub fn generate_file(typ: ConfigType) -> Result<PathBuf> {
  58. let path = match typ {
  59. ConfigType::Run => dirs::app_home_dir()?.join(RUNTIME_CONFIG),
  60. ConfigType::Check => temp_dir().join(CHECK_CONFIG),
  61. };
  62. let runtime = Config::runtime();
  63. let runtime = runtime.latest();
  64. let config = runtime
  65. .config
  66. .as_ref()
  67. .ok_or(anyhow!("failed to get runtime config"))?;
  68. help::save_yaml(&path, &config, Some("# Generated by Clash Nyanpasu"))?;
  69. Ok(path)
  70. }
  71. /// 生成配置存好
  72. pub fn generate() -> Result<()> {
  73. let (config, exists_keys, logs) = enhance::enhance();
  74. *Config::runtime().draft() = IRuntime {
  75. config: Some(config),
  76. exists_keys,
  77. chain_logs: logs,
  78. };
  79. Ok(())
  80. }
  81. }
  82. #[derive(Debug)]
  83. pub enum ConfigType {
  84. Run,
  85. Check,
  86. }