From 00c1febf33f33028b7556312868ff90b9b54836d Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:12:50 +0800 Subject: [PATCH] refactor(config): centralize Mihomo YAML output --- .../clash-verge-runtime-bundle/src/error.rs | 2 - crates/clash-verge-runtime-bundle/src/lib.rs | 28 +++------ src-tauri/src/cmd/clash.rs | 6 +- src-tauri/src/cmd/runtime.rs | 10 ++- src-tauri/src/config/clash.rs | 5 +- src-tauri/src/config/config.rs | 4 +- .../yaml_emitter.rs => config/mihomo_yaml.rs} | 62 +++++++++---------- src-tauri/src/config/mod.rs | 1 + src-tauri/src/core/manager/config.rs | 5 +- src-tauri/src/core/manager/state.rs | 3 +- src-tauri/src/core/service.rs | 4 +- src-tauri/src/utils/mod.rs | 1 - 12 files changed, 60 insertions(+), 71 deletions(-) rename src-tauri/src/{utils/yaml_emitter.rs => config/mihomo_yaml.rs} (59%) diff --git a/crates/clash-verge-runtime-bundle/src/error.rs b/crates/clash-verge-runtime-bundle/src/error.rs index b09f2c040..55c672d1f 100644 --- a/crates/clash-verge-runtime-bundle/src/error.rs +++ b/crates/clash-verge-runtime-bundle/src/error.rs @@ -18,8 +18,6 @@ pub enum RuntimeBundleError { }, #[error("runtime config has no parent directory")] MissingConfigDirectory, - #[error("failed to serialize service runtime config")] - SerializeConfig(#[source] serde_yaml_ng::Error), #[error("runtime provider destination {0:?} is declared for two different sources")] DifferentSources(String), #[error("runtime provider destination {0:?} is claimed more than once")] diff --git a/crates/clash-verge-runtime-bundle/src/lib.rs b/crates/clash-verge-runtime-bundle/src/lib.rs index e1244f7cd..24902c6e4 100644 --- a/crates/clash-verge-runtime-bundle/src/lib.rs +++ b/crates/clash-verge-runtime-bundle/src/lib.rs @@ -33,17 +33,11 @@ pub struct RuntimeAsset { } pub struct RuntimeBundlePlan { - pub yaml: String, + pub config: Value, pub assets: Vec, pub remote_providers: Vec, } -struct RuntimeParts { - config: Value, - assets: Vec, - remote_providers: Vec, -} - type Result = std::result::Result; pub async fn collect_runtime_bundle(config_file: &Path) -> Result { @@ -58,12 +52,7 @@ pub async fn collect_runtime_bundle(config_file: &Path) -> Result Result> { @@ -158,7 +147,7 @@ fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut Ha } } -fn collect_runtime_parts(mut config: Value, config_root: &Path) -> Result { +fn collect_runtime_parts(mut config: Value, config_root: &Path) -> Result { let config_root = std::fs::canonicalize(config_root)?; let mut assets = Vec::new(); let mut destinations = HashSet::new(); @@ -191,7 +180,7 @@ fn collect_runtime_parts(mut config: Value, config_root: &Path) -> Result(&bundle.yaml)?, config); + assert_eq!(bundle.config.as_mapping(), Some(&config)); let readback = remote_providers_of(&config, &root)?; assert_eq!(bundle.remote_providers.len(), 2); for declared in readback { @@ -539,7 +528,7 @@ mod tests { let bundle = collect_runtime_bundle(&config).await?; - let bundled_config: serde_yaml_ng::Value = serde_yaml_ng::from_str(&bundle.yaml)?; + let bundled_config = &bundle.config; assert_eq!( bundled_config["proxy-providers"]["local"]["path"].as_str(), Some("providers/local.yaml") @@ -548,7 +537,7 @@ mod tests { bundled_config["proxy-providers"]["remote"]["path"].as_str(), Some("providers/remote.yaml") ); - assert!(!bundle.yaml.contains(&root.to_string_lossy().into_owned())); + assert!(!serde_yaml_ng::to_string(bundled_config)?.contains(root.to_string_lossy().as_ref())); assert!( bundle .assets @@ -639,9 +628,8 @@ mod tests { "only the provider that could be classified is declared" ); assert_eq!(bundle.remote_providers[0].destination, "rules/g.yaml"); - let reserialized: serde_yaml_ng::Value = serde_yaml_ng::from_str(&bundle.yaml)?; assert_eq!( - reserialized["rule-providers"]["nourl"]["path"].as_str(), + bundle.config["rule-providers"]["nourl"]["path"].as_str(), Some("./rules/nourl.yaml"), "an unclassifiable provider keeps the path the core was given" ); diff --git a/src-tauri/src/cmd/clash.rs b/src-tauri/src/cmd/clash.rs index 8c6468955..57719a3de 100644 --- a/src-tauri/src/cmd/clash.rs +++ b/src-tauri/src/cmd/clash.rs @@ -1,10 +1,10 @@ use super::{CmdResult, CommandFailure, WithErrorCode as _, proxy_aware_coded_error, proxy_aware_error}; use crate::core::notify::NoticeStatus; use crate::feat; -use crate::utils::{dirs, yaml_emitter}; +use crate::utils::dirs; use crate::{ cmd::StringifyErr as _, - config::{ClashInfo, Config, profiles::profiles_save_file_safe}, + config::{ClashInfo, Config, mihomo_yaml, profiles::profiles_save_file_safe}, constants, core::{ CoreManager, handle, @@ -132,7 +132,7 @@ pub async fn save_dns_config(dns_config: crate::ipc::YamlMapping) -> CmdResult { let dns_path = dirs::app_home_dir().stringify_err()?.join(constants::files::DNS_CONFIG); - let yaml_str = yaml_emitter::to_mihomo_config_string(&dns_config.0).stringify_err()?; + let yaml_str = mihomo_yaml::serialize_for_export(&dns_config.0).stringify_err()?; fs::write(&dns_path, yaml_str).await.stringify_err()?; logging!(info, Type::Config, "DNS config saved to {dns_path:?}"); diff --git a/src-tauri/src/cmd/runtime.rs b/src-tauri/src/cmd/runtime.rs index fa2972b4a..cb4f27524 100644 --- a/src-tauri/src/cmd/runtime.rs +++ b/src-tauri/src/cmd/runtime.rs @@ -1,5 +1,9 @@ use super::CmdResult; -use crate::{cmd::StringifyErr as _, config::Config, core::CoreManager, utils::yaml_emitter}; +use crate::{ + cmd::StringifyErr as _, + config::{Config, mihomo_yaml}, + core::CoreManager, +}; use anyhow::{Context as _, anyhow}; use std::collections::HashMap; use tristr::alias::String; @@ -24,7 +28,7 @@ pub async fn get_runtime_yaml() -> CmdResult { let config = runtime.config.as_ref(); config .ok_or_else(|| anyhow!("failed to parse config to yaml file")) - .and_then(|config| yaml_emitter::to_mihomo_config_string(config).context("failed to convert config to yaml")) + .and_then(|config| mihomo_yaml::serialize_for_export(config).context("failed to convert config to yaml")) .stringify_err() } @@ -87,7 +91,7 @@ pub async fn get_runtime_proxy_chain_config( config.insert("proxies".into(), proxies_chain); - yaml_emitter::to_mihomo_config_string(&config) + mihomo_yaml::serialize_for_export(&config) .context("YAML generation failed") .stringify_err() } else { diff --git a/src-tauri/src/config/clash.rs b/src-tauri/src/config/clash.rs index 8c8de6798..7bcecd125 100644 --- a/src-tauri/src/config/clash.rs +++ b/src-tauri/src/config/clash.rs @@ -1,3 +1,4 @@ +use super::mihomo_yaml; use crate::constants::{network, tun as tun_const}; use crate::utils::dirs::{path_to_str, sidecar_ipc_path}; use crate::utils::{dirs, help}; @@ -150,7 +151,9 @@ impl IClashTemp { } pub async fn save_config(&self) -> Result<()> { - help::save_yaml(&dirs::clash_path()?, &self.0, Some("# Generated by Clash Verge")).await + let path = dirs::clash_path()?; + let yaml = mihomo_yaml::serialize(&self.0)?; + help::save_yaml_str(&path, &yaml, Some("# Generated by Clash Verge")).await } pub fn get_mixed_port(&self) -> u16 { diff --git a/src-tauri/src/config/config.rs b/src-tauri/src/config/config.rs index e31aec897..fec0de45f 100644 --- a/src-tauri/src/config/config.rs +++ b/src-tauri/src/config/config.rs @@ -1,4 +1,4 @@ -use super::{IClashTemp, IProfiles, IVerge, MixedPort}; +use super::{IClashTemp, IProfiles, IVerge, MixedPort, mihomo_yaml}; use crate::core::notify::NoticeStatus; use crate::{ config::{ @@ -232,7 +232,7 @@ impl Config { { return Ok(std::sync::Arc::clone(cached)); } - let yaml_str = std::sync::Arc::new(serde_yaml_ng::to_string(config)?); + let yaml_str = std::sync::Arc::new(mihomo_yaml::serialize(config)?); *RUNTIME_YAML_CACHE.lock() = Some((key, std::sync::Arc::clone(&yaml_str))); Ok(yaml_str) }) diff --git a/src-tauri/src/utils/yaml_emitter.rs b/src-tauri/src/config/mihomo_yaml.rs similarity index 59% rename from src-tauri/src/utils/yaml_emitter.rs rename to src-tauri/src/config/mihomo_yaml.rs index 9cf287dc1..18689c6d2 100644 --- a/src-tauri/src/utils/yaml_emitter.rs +++ b/src-tauri/src/config/mihomo_yaml.rs @@ -1,9 +1,10 @@ use serde::Serialize; use serde_yaml_ng::Result; -pub fn to_mihomo_config_string(data: &T) -> Result { - let yaml = serde_yaml_ng::to_string(data)?; - Ok(quote_fake_ip_filter_wildcards(&yaml)) +pub(crate) use serde_yaml_ng::to_string as serialize; + +pub(crate) fn serialize_for_export(data: &T) -> Result { + Ok(quote_fake_ip_filter_wildcards(&serialize(data)?)) } fn quote_fake_ip_filter_wildcards(yaml: &str) -> String { @@ -12,7 +13,7 @@ fn quote_fake_ip_filter_wildcards(yaml: &str) -> String { let mut fake_ip_filter_indent = 0; for line in yaml.lines() { - let indent = leading_spaces(line); + let indent = line.len() - line.trim_start_matches(' ').len(); let trimmed = &line[indent..]; if in_fake_ip_filter && indent <= fake_ip_filter_indent && !trimmed.starts_with("- ") { @@ -22,54 +23,47 @@ fn quote_fake_ip_filter_wildcards(yaml: &str) -> String { if !in_fake_ip_filter && trimmed == "fake-ip-filter:" { in_fake_ip_filter = true; fake_ip_filter_indent = indent; + } + + if in_fake_ip_filter + && indent >= fake_ip_filter_indent + && let Some(item) = trimmed.strip_prefix("- ") + && needs_quotes(item) + { + result.push_str(&line[..indent + 2]); + push_quoted(&mut result, item); + } else { result.push_str(line); - result.push('\n'); - continue; } - - if in_fake_ip_filter && indent >= fake_ip_filter_indent && trimmed.starts_with("- ") { - result.push_str(&line[..indent]); - result.push_str("- "); - result.push_str("e_wildcard_item(&trimmed[2..])); - result.push('\n'); - continue; - } - - result.push_str(line); result.push('\n'); } result } -fn leading_spaces(line: &str) -> usize { - line.len() - line.trim_start_matches(' ').len() +fn needs_quotes(item: &str) -> bool { + !item.starts_with(['"', '\'']) && (item.contains('*') || item.starts_with(['+', '.'])) } -fn quote_wildcard_item(item: &str) -> String { - if !item.starts_with('\"') && !item.starts_with('\'') && contains_wildcard(item) { - quote_string(item) - } else { - item.to_string() +fn push_quoted(output: &mut String, item: &str) { + output.push('\''); + for (index, part) in item.split('\'').enumerate() { + if index != 0 { + output.push_str("''"); + } + output.push_str(part); } -} - -fn quote_string(s: &str) -> String { - "\'".to_string() + s.replace('\'', "''").as_str() + "\'" -} - -fn contains_wildcard(value: &str) -> bool { - value.contains('*') || value.starts_with('+') || value.starts_with('.') + output.push('\''); } #[cfg(test)] #[allow(clippy::expect_used)] mod tests { - use super::to_mihomo_config_string; + use super::serialize_for_export; fn roundtrip(input: &str) { let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(input).expect("input yaml should parse"); - let output = to_mihomo_config_string(&value).expect("yaml should serialize"); + let output = serialize_for_export(&value).expect("yaml should serialize"); let reparsed: serde_yaml_ng::Value = serde_yaml_ng::from_str(&output).expect("serialized yaml should parse"); assert_eq!(reparsed, value); @@ -90,7 +84,7 @@ dns: roundtrip(input); let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(input).expect("input yaml should parse"); - let output = to_mihomo_config_string(&value).expect("yaml should serialize"); + let output = serialize_for_export(&value).expect("yaml should serialize"); assert!(output.contains("- '*.lan'")); assert!(output.contains("- '+.market.xiaomi.com'")); diff --git a/src-tauri/src/config/mod.rs b/src-tauri/src/config/mod.rs index f1bb4f325..aeaad049d 100644 --- a/src-tauri/src/config/mod.rs +++ b/src-tauri/src/config/mod.rs @@ -3,6 +3,7 @@ mod clash; mod config; pub(crate) mod dns; mod encrypt; +pub(crate) mod mihomo_yaml; mod mixed_port; mod port; mod prfitem; diff --git a/src-tauri/src/core/manager/config.rs b/src-tauri/src/core/manager/config.rs index 7dd783758..a4f991331 100644 --- a/src-tauri/src/core/manager/config.rs +++ b/src-tauri/src/core/manager/config.rs @@ -2,7 +2,7 @@ use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode}; use crate::core::notify::NoticeStatus; use crate::core::service::StageRequest; use crate::{ - config::{Config, IProfiles, profiles::save_profiles, runtime::IRuntime}, + config::{Config, IProfiles, mihomo_yaml, profiles::save_profiles, runtime::IRuntime}, constants::timing, core::{ handle, @@ -170,7 +170,8 @@ impl CoreManager { } }); - help::save_yaml(&runtime_path, &clash_config, Some("# Clash Verge Runtime")).await?; + let yaml = mihomo_yaml::serialize(clash_config)?; + help::save_yaml_str(&runtime_path, &yaml, Some("# Clash Verge Runtime")).await?; handle::Handle::notice(status, message); Ok(()) } diff --git a/src-tauri/src/core/manager/state.rs b/src-tauri/src/core/manager/state.rs index 538212ca5..ca9e6e6f1 100644 --- a/src-tauri/src/core/manager/state.rs +++ b/src-tauri/src/core/manager/state.rs @@ -35,6 +35,7 @@ pub(super) fn explain_core_occupancy(error: anyhow::Error) -> anyhow::Error { #[cfg(target_os = "windows")] fn sidecar_config_without_tun(yaml: &str) -> Result { + use crate::config::mihomo_yaml; use serde_yaml_ng::{Mapping, Value}; let mut config: Mapping = serde_yaml_ng::from_str(yaml)?; @@ -47,7 +48,7 @@ fn sidecar_config_without_tun(yaml: &str) -> Result { tun.as_mapping_mut() .context("invalid Sidecar TUN configuration")? .insert(Value::from("enable"), Value::Bool(false)); - Ok(serde_yaml_ng::to_string(&config)?) + Ok(mihomo_yaml::serialize(&config)?) } const SIDECAR_READINESS_ATTEMPTS: usize = 30; diff --git a/src-tauri/src/core/service.rs b/src-tauri/src/core/service.rs index 5b743dcd1..445ddc71e 100644 --- a/src-tauri/src/core/service.rs +++ b/src-tauri/src/core/service.rs @@ -1,7 +1,7 @@ use crate::core::notify::NoticeStatus; use crate::utils::dirs; use crate::{ - config::{Config, runtime::IRuntime}, + config::{Config, mihomo_yaml, runtime::IRuntime}, constants, core::{ CoreManager, @@ -613,7 +613,7 @@ async fn collect_service_runtime_bundle(config_file: &Path) -> Result