refactor(config): centralize Mihomo YAML output

This commit is contained in:
Tunglies
2026-11-30 19:12:50 +08:00
parent c95c8ac2ce
commit 00c1febf33
12 changed files with 60 additions and 71 deletions
@@ -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")]
+8 -20
View File
@@ -33,17 +33,11 @@ pub struct RuntimeAsset {
}
pub struct RuntimeBundlePlan {
pub yaml: String,
pub config: Value,
pub assets: Vec<RuntimeAsset>,
pub remote_providers: Vec<RemoteProviderRef>,
}
struct RuntimeParts {
config: Value,
assets: Vec<RuntimeAsset>,
remote_providers: Vec<RemoteProviderRef>,
}
type Result<T> = std::result::Result<T, RuntimeBundleError>;
pub async fn collect_runtime_bundle(config_file: &Path) -> Result<RuntimeBundlePlan> {
@@ -58,12 +52,7 @@ pub async fn collect_runtime_bundle(config_file: &Path) -> Result<RuntimeBundleP
source,
})?;
let config_root = config_file.parent().ok_or(RuntimeBundleError::MissingConfigDirectory)?;
let parts = collect_runtime_parts(config, config_root)?;
Ok(RuntimeBundlePlan {
yaml: serde_yaml_ng::to_string(&parts.config).map_err(RuntimeBundleError::SerializeConfig)?,
assets: parts.assets,
remote_providers: parts.remote_providers,
})
collect_runtime_parts(config, config_root)
}
pub fn remote_providers_of(config: &Mapping, config_root: &Path) -> Result<Vec<RemoteProviderRef>> {
@@ -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<RuntimeParts> {
fn collect_runtime_parts(mut config: Value, config_root: &Path) -> Result<RuntimeBundlePlan> {
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<Runtim
}
}
Ok(RuntimeParts {
Ok(RuntimeBundlePlan {
config,
assets,
remote_providers,
@@ -465,7 +454,7 @@ mod tests {
"resolving an already generated config must be idempotent"
);
assert_eq!(serde_yaml_ng::from_str::<serde_yaml_ng::Mapping>(&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"
);
+3 -3
View File
@@ -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:?}");
+7 -3
View File
@@ -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<std::string::String> {
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 {
+4 -1
View File
@@ -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 {
+2 -2
View File
@@ -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)
})
@@ -1,9 +1,10 @@
use serde::Serialize;
use serde_yaml_ng::Result;
pub fn to_mihomo_config_string<T: Serialize>(data: &T) -> Result<String> {
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<T: Serialize>(data: &T) -> Result<String> {
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(&quote_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'"));
+1
View File
@@ -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;
+3 -2
View File
@@ -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(())
}
+2 -1
View File
@@ -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<std::string::String> {
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<std::string::String> {
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;
+2 -2
View File
@@ -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<RuntimeBun
let bin_path = service_core_path(&clash_core, bin_ext)?;
let plan = collect_runtime_bundle(config_file).await?;
Ok(RuntimeBundle {
yaml: plan.yaml,
yaml: mihomo_yaml::serialize(&plan.config).context("failed to serialize service runtime config")?,
assets: plan
.assets
.into_iter()
-1
View File
@@ -21,4 +21,3 @@ pub mod tmpl;
#[cfg(target_os = "macos")]
pub mod tray_speed;
pub mod window_manager;
pub mod yaml_emitter;