mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-06 23:00:15 +08:00
refactor(config): move Mihomo YAML fidelity rules into clash-verge-config-render
Short-id-safe YAML parsing and the export quoting of fake-ip-filter wildcards are Mihomo output rules without app dependencies. They now live beside the other Mihomo YAML rules, and the app calls them from the parse and export entry points. The plain serializer re-export is replaced by serde_yaml_ng::to_string at its five call sites.
This commit is contained in:
@@ -3,8 +3,10 @@ mod merge;
|
||||
mod script;
|
||||
mod seq;
|
||||
mod tun;
|
||||
mod yaml;
|
||||
|
||||
pub use seq::SeqMap;
|
||||
pub use yaml::{parse_short_id_safe, serialize_for_export};
|
||||
|
||||
use self::{
|
||||
field::{lowercase_config_keys, use_lowercase, use_sort},
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use serde::Serialize;
|
||||
use serde_yaml_ng::Value;
|
||||
use std::path::Path;
|
||||
|
||||
/// A float like `1234e123` loses its hex text, so retry with short-ids quoted and keep that only if nothing else changed.
|
||||
pub fn parse_short_id_safe(yaml: &str, path: &Path) -> serde_yaml_ng::Result<Value> {
|
||||
let value = serde_yaml_ng::from_str::<Value>(yaml)?;
|
||||
if !has_numeric_short_id(&value) {
|
||||
return Ok(value);
|
||||
}
|
||||
match serde_yaml_ng::from_str::<Value>("e_short_ids(yaml)) {
|
||||
Ok(quoted) if same_except_short_id(&value, "ed) => Ok(quoted),
|
||||
_ => {
|
||||
logging!(warn, Type::Config, "kept numeric short-id in {}", path.display());
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn quote_short_ids(yaml: &str) -> String {
|
||||
let mut quoted = String::with_capacity(yaml.len());
|
||||
let mut rest = yaml;
|
||||
while let Some((head, tail)) = rest.split_once("short-id:") {
|
||||
let (gap, value) = tail.split_at(tail.len() - tail.trim_start_matches([' ', '\t']).len());
|
||||
let (id, after) = value.split_at(value.bytes().take_while(u8::is_ascii_hexdigit).count());
|
||||
quoted.push_str(head);
|
||||
quoted.push_str("short-id:");
|
||||
quoted.push_str(gap);
|
||||
if !id.is_empty() && (after.is_empty() || after.starts_with([' ', '\t', '\r', '\n', ',', '}'])) {
|
||||
quoted.push('"');
|
||||
quoted.push_str(id);
|
||||
quoted.push('"');
|
||||
} else {
|
||||
quoted.push_str(id);
|
||||
}
|
||||
rest = after;
|
||||
}
|
||||
quoted.push_str(rest);
|
||||
quoted
|
||||
}
|
||||
|
||||
fn has_numeric_short_id(value: &Value) -> bool {
|
||||
match value {
|
||||
Value::Mapping(map) => map
|
||||
.iter()
|
||||
.any(|(key, value)| (is_short_id(key) && matches!(value, Value::Number(_))) || has_numeric_short_id(value)),
|
||||
Value::Sequence(seq) => seq.iter().any(has_numeric_short_id),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn same_except_short_id(old: &Value, new: &Value) -> bool {
|
||||
match (old, new) {
|
||||
(Value::Mapping(old), Value::Mapping(new)) => {
|
||||
old.len() == new.len()
|
||||
&& old.iter().zip(new).all(|((key, old), (new_key, new))| {
|
||||
key == new_key
|
||||
&& (same_except_short_id(old, new)
|
||||
|| (is_short_id(key) && matches!((old, new), (Value::Number(_), Value::String(_)))))
|
||||
})
|
||||
}
|
||||
(Value::Sequence(old), Value::Sequence(new)) => {
|
||||
old.len() == new.len() && old.iter().zip(new).all(|(old, new)| same_except_short_id(old, new))
|
||||
}
|
||||
_ => old == new,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_short_id(key: &Value) -> bool {
|
||||
key.as_str() == Some("short-id")
|
||||
}
|
||||
|
||||
pub fn serialize_for_export<T: Serialize>(data: &T) -> serde_yaml_ng::Result<String> {
|
||||
Ok(quote_fake_ip_filter_wildcards(&serde_yaml_ng::to_string(data)?))
|
||||
}
|
||||
|
||||
fn quote_fake_ip_filter_wildcards(yaml: &str) -> String {
|
||||
let mut result = String::with_capacity(yaml.len());
|
||||
let mut in_fake_ip_filter = false;
|
||||
let mut fake_ip_filter_indent = 0;
|
||||
|
||||
for line in yaml.lines() {
|
||||
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("- ") {
|
||||
in_fake_ip_filter = false;
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
fn needs_quotes(item: &str) -> bool {
|
||||
!item.starts_with(['"', '\'']) && (item.contains('*') || item.starts_with(['+', '.']))
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
output.push('\'');
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used)]
|
||||
mod tests {
|
||||
use super::{parse_short_id_safe, serialize_for_export};
|
||||
use serde_yaml_ng::Value;
|
||||
use std::path::Path;
|
||||
|
||||
fn roundtrip(input: &str) -> Value {
|
||||
let value: Value = serde_yaml_ng::from_str(input).expect("input yaml should parse");
|
||||
let output = serialize_for_export(&value).expect("yaml should serialize");
|
||||
let reparsed: Value = serde_yaml_ng::from_str(&output).expect("serialized yaml should parse");
|
||||
|
||||
assert_eq!(reparsed, value);
|
||||
reparsed
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quotes_fake_ip_filter_wildcards_without_changing_values() {
|
||||
let input = r#"
|
||||
dns:
|
||||
fake-ip-filter:
|
||||
- "*.lan"
|
||||
- "+.market.xiaomi.com"
|
||||
- ".example.com"
|
||||
- "time.*.com"
|
||||
- "plain.example.com"
|
||||
"#;
|
||||
|
||||
roundtrip(input);
|
||||
|
||||
let value: Value = serde_yaml_ng::from_str(input).expect("input yaml should parse");
|
||||
let output = serialize_for_export(&value).expect("yaml should serialize");
|
||||
|
||||
assert!(output.contains("- '*.lan'"));
|
||||
assert!(output.contains("- '+.market.xiaomi.com'"));
|
||||
assert!(output.contains("- '.example.com'"));
|
||||
assert!(output.contains("- 'time.*.com'"));
|
||||
assert!(output.contains("- plain.example.com"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_multiline_strings_roundtrip() {
|
||||
roundtrip(
|
||||
r"
|
||||
items:
|
||||
- name: demo
|
||||
desc: |
|
||||
line1
|
||||
line2
|
||||
",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_id_quoting_changing_other_values_is_dropped() {
|
||||
let profile = "\
|
||||
proxies:
|
||||
- name: a
|
||||
reality-opts:
|
||||
short-id: 1234e123
|
||||
note: |
|
||||
short-id: 1234e123
|
||||
";
|
||||
let today = serde_yaml_ng::from_str::<Value>(profile).expect("profile should parse");
|
||||
let value = parse_short_id_safe(profile, Path::new("profile.yaml")).expect("profile should parse");
|
||||
assert_eq!(value, today);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numeric_short_ids_parse_as_text() {
|
||||
let value =
|
||||
parse_short_id_safe("tunnels: [{short-id: 1234e123}, {short-id: 0e5}]", Path::new("p.yaml")).expect("yaml");
|
||||
let tunnels = value["tunnels"].as_sequence().expect("sequence");
|
||||
assert_eq!(tunnels[0]["short-id"], Value::String("1234e123".into()));
|
||||
assert_eq!(tunnels[1]["short-id"], Value::String("0e5".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn already_quoted_short_ids_are_left_alone() {
|
||||
let yaml = "tunnels: [{short-id: \"1234e123\"}]";
|
||||
assert_eq!(
|
||||
parse_short_id_safe(yaml, Path::new("p.yaml")).expect("yaml"),
|
||||
serde_yaml_ng::from_str::<Value>(yaml).expect("yaml")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_yaml_still_gets_quoted_wildcards_and_roundtrips() {
|
||||
let yaml =
|
||||
"dns:\r\n fake-ip-filter:\r\n - '*.lan'\r\n - +.market.xiaomi.com\r\n - plain.example.com\r\n";
|
||||
let out = serialize_for_export(&serde_yaml_ng::from_str::<Value>(yaml).expect("yaml")).expect("yaml");
|
||||
assert_eq!(roundtrip(&out), roundtrip(yaml));
|
||||
assert!(out.contains("'+.market.xiaomi.com'"));
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ use crate::feat;
|
||||
use crate::utils::dirs;
|
||||
use crate::{
|
||||
cmd::StringifyErr as _,
|
||||
config::{ClashInfo, Config, mihomo_yaml, profiles::save_committed_profiles},
|
||||
config::{ClashInfo, Config, profiles::save_committed_profiles},
|
||||
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 = mihomo_yaml::serialize_for_export(&dns_config.0).stringify_err()?;
|
||||
let yaml_str = clash_verge_config_render::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:?}");
|
||||
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
use super::CmdResult;
|
||||
use crate::{
|
||||
cmd::StringifyErr as _,
|
||||
config::{Config, mihomo_yaml},
|
||||
core::CoreManager,
|
||||
};
|
||||
use crate::{cmd::StringifyErr as _, config::Config, core::CoreManager};
|
||||
use anyhow::{Context as _, anyhow};
|
||||
use std::collections::HashMap;
|
||||
use tristr::alias::String;
|
||||
@@ -28,7 +24,9 @@ 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| mihomo_yaml::serialize_for_export(config).context("failed to convert config to yaml"))
|
||||
.and_then(|config| {
|
||||
clash_verge_config_render::serialize_for_export(config).context("failed to convert config to yaml")
|
||||
})
|
||||
.stringify_err()
|
||||
}
|
||||
|
||||
@@ -91,7 +89,7 @@ pub async fn get_runtime_proxy_chain_config(
|
||||
|
||||
config.insert("proxies".into(), proxies_chain);
|
||||
|
||||
mihomo_yaml::serialize_for_export(&config)
|
||||
clash_verge_config_render::serialize_for_export(&config)
|
||||
.context("YAML generation failed")
|
||||
.stringify_err()
|
||||
} else {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
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};
|
||||
@@ -152,7 +151,7 @@ impl IClashTemp {
|
||||
|
||||
pub async fn save_config(&self) -> Result<()> {
|
||||
let path = dirs::clash_path()?;
|
||||
let yaml = mihomo_yaml::serialize(&self.0)?;
|
||||
let yaml = serde_yaml_ng::to_string(&self.0)?;
|
||||
help::save_yaml_str(&path, &yaml, Some("# Generated by Clash Verge")).await
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{IClashTemp, IProfiles, IVerge, MixedPort, mihomo_yaml};
|
||||
use super::{IClashTemp, IProfiles, IVerge, MixedPort};
|
||||
use crate::core::notify::NoticeStatus;
|
||||
use crate::{
|
||||
config::{
|
||||
@@ -230,7 +230,7 @@ impl Config {
|
||||
{
|
||||
return Ok(std::sync::Arc::clone(cached));
|
||||
}
|
||||
let yaml_str = std::sync::Arc::new(mihomo_yaml::serialize(config)?);
|
||||
let yaml_str = std::sync::Arc::new(serde_yaml_ng::to_string(config)?);
|
||||
*RUNTIME_YAML_CACHE.lock() = Some((key, std::sync::Arc::clone(&yaml_str)));
|
||||
Ok(yaml_str)
|
||||
})
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
use serde::Serialize;
|
||||
use serde_yaml_ng::Result;
|
||||
|
||||
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 {
|
||||
let mut result = String::with_capacity(yaml.len());
|
||||
let mut in_fake_ip_filter = false;
|
||||
let mut fake_ip_filter_indent = 0;
|
||||
|
||||
for line in yaml.lines() {
|
||||
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("- ") {
|
||||
in_fake_ip_filter = false;
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
fn needs_quotes(item: &str) -> bool {
|
||||
!item.starts_with(['"', '\'']) && (item.contains('*') || item.starts_with(['+', '.']))
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
output.push('\'');
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used)]
|
||||
mod tests {
|
||||
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 = 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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quotes_fake_ip_filter_wildcards_without_changing_values() {
|
||||
let input = r#"
|
||||
dns:
|
||||
fake-ip-filter:
|
||||
- "*.lan"
|
||||
- "+.market.xiaomi.com"
|
||||
- ".example.com"
|
||||
- "time.*.com"
|
||||
- "plain.example.com"
|
||||
"#;
|
||||
|
||||
roundtrip(input);
|
||||
|
||||
let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(input).expect("input yaml should parse");
|
||||
let output = serialize_for_export(&value).expect("yaml should serialize");
|
||||
|
||||
assert!(output.contains("- '*.lan'"));
|
||||
assert!(output.contains("- '+.market.xiaomi.com'"));
|
||||
assert!(output.contains("- '.example.com'"));
|
||||
assert!(output.contains("- 'time.*.com'"));
|
||||
assert!(output.contains("- plain.example.com"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_multiline_strings_roundtrip() {
|
||||
roundtrip(
|
||||
r"
|
||||
items:
|
||||
- name: demo
|
||||
desc: |
|
||||
line1
|
||||
line2
|
||||
",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ mod clash;
|
||||
mod config;
|
||||
pub(crate) mod dns;
|
||||
mod encrypt;
|
||||
pub(crate) mod mihomo_yaml;
|
||||
mod mixed_port;
|
||||
mod port;
|
||||
mod prfitem;
|
||||
|
||||
@@ -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, mihomo_yaml, profiles::save_profiles, runtime::IRuntime},
|
||||
config::{Config, IProfiles, profiles::save_profiles, runtime::IRuntime},
|
||||
constants::timing,
|
||||
core::{
|
||||
handle,
|
||||
@@ -170,7 +170,7 @@ impl CoreManager {
|
||||
}
|
||||
});
|
||||
|
||||
let yaml = mihomo_yaml::serialize(clash_config)?;
|
||||
let yaml = serde_yaml_ng::to_string(clash_config)?;
|
||||
help::save_yaml_str(&runtime_path, &yaml, Some("# Clash Verge Runtime")).await?;
|
||||
handle::Handle::notice(status, message);
|
||||
Ok(())
|
||||
|
||||
@@ -35,7 +35,6 @@ 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)?;
|
||||
@@ -48,7 +47,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(mihomo_yaml::serialize(&config)?)
|
||||
Ok(serde_yaml_ng::to_string(&config)?)
|
||||
}
|
||||
|
||||
const SIDECAR_READINESS_ATTEMPTS: usize = 30;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::core::notify::NoticeStatus;
|
||||
use crate::utils::dirs;
|
||||
use crate::{
|
||||
config::{Config, mihomo_yaml, runtime::IRuntime},
|
||||
config::{Config, 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: mihomo_yaml::serialize(&plan.config).context("failed to serialize service runtime config")?,
|
||||
yaml: serde_yaml_ng::to_string(&plan.config).context("failed to serialize service runtime config")?,
|
||||
assets: plan
|
||||
.assets
|
||||
.into_iter()
|
||||
|
||||
@@ -44,7 +44,7 @@ pub async fn read_mapping(path: &Path) -> Result<Mapping> {
|
||||
}
|
||||
|
||||
fn parse_mapping(yaml_str: String, path: PathBuf) -> Result<Mapping> {
|
||||
match parse_short_id_text(&yaml_str, &path) {
|
||||
match clash_verge_config_render::parse_short_id_safe(&yaml_str, &path) {
|
||||
Ok(mut val) => {
|
||||
val.apply_merge()
|
||||
.with_context(|| format!("failed to apply merge \"{}\"", path.display()))?;
|
||||
@@ -65,74 +65,6 @@ fn parse_mapping(yaml_str: String, path: PathBuf) -> Result<Mapping> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A float like `1234e123` loses its hex text, so retry with short-ids quoted and keep that only if nothing else changed.
|
||||
fn parse_short_id_text(yaml: &str, path: &Path) -> serde_yaml_ng::Result<Value> {
|
||||
let value = serde_yaml_ng::from_str::<Value>(yaml)?;
|
||||
if !has_numeric_short_id(&value) {
|
||||
return Ok(value);
|
||||
}
|
||||
match serde_yaml_ng::from_str::<Value>("e_short_ids(yaml)) {
|
||||
Ok(quoted) if same_except_short_id(&value, "ed) => Ok(quoted),
|
||||
_ => {
|
||||
logging!(warn, Type::Config, "kept numeric short-id in {}", path.display());
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn quote_short_ids(yaml: &str) -> String {
|
||||
let mut quoted = String::with_capacity(yaml.len());
|
||||
let mut rest = yaml;
|
||||
while let Some((head, tail)) = rest.split_once("short-id:") {
|
||||
let (gap, value) = tail.split_at(tail.len() - tail.trim_start_matches([' ', '\t']).len());
|
||||
let (id, after) = value.split_at(value.bytes().take_while(u8::is_ascii_hexdigit).count());
|
||||
quoted.push_str(head);
|
||||
quoted.push_str("short-id:");
|
||||
quoted.push_str(gap);
|
||||
if !id.is_empty() && (after.is_empty() || after.starts_with([' ', '\t', '\r', '\n', ',', '}'])) {
|
||||
quoted.push('"');
|
||||
quoted.push_str(id);
|
||||
quoted.push('"');
|
||||
} else {
|
||||
quoted.push_str(id);
|
||||
}
|
||||
rest = after;
|
||||
}
|
||||
quoted.push_str(rest);
|
||||
quoted
|
||||
}
|
||||
|
||||
fn has_numeric_short_id(value: &Value) -> bool {
|
||||
match value {
|
||||
Value::Mapping(map) => map
|
||||
.iter()
|
||||
.any(|(key, value)| (is_short_id(key) && matches!(value, Value::Number(_))) || has_numeric_short_id(value)),
|
||||
Value::Sequence(seq) => seq.iter().any(has_numeric_short_id),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn same_except_short_id(old: &Value, new: &Value) -> bool {
|
||||
match (old, new) {
|
||||
(Value::Mapping(old), Value::Mapping(new)) => {
|
||||
old.len() == new.len()
|
||||
&& old.iter().zip(new).all(|((key, old), (new_key, new))| {
|
||||
key == new_key
|
||||
&& (same_except_short_id(old, new)
|
||||
|| (is_short_id(key) && matches!((old, new), (Value::Number(_), Value::String(_)))))
|
||||
})
|
||||
}
|
||||
(Value::Sequence(old), Value::Sequence(new)) => {
|
||||
old.len() == new.len() && old.iter().zip(new).all(|(old, new)| same_except_short_id(old, new))
|
||||
}
|
||||
_ => old == new,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_short_id(key: &Value) -> bool {
|
||||
key.as_str() == Some("short-id")
|
||||
}
|
||||
|
||||
pub async fn save_yaml<T: Serialize + Sync>(path: &Path, data: &T, prefix: Option<&str>) -> Result<()> {
|
||||
let data_str = with_encryption(|| async { serde_yaml_ng::to_string(data) }).await?;
|
||||
|
||||
@@ -380,9 +312,8 @@ pub fn snapshot_path(original_path: &Path) -> Result<PathBuf> {
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
|
||||
mod tests {
|
||||
use super::{parse_mapping, parse_short_id_text};
|
||||
use serde_yaml_ng::Value;
|
||||
use std::path::{Path, PathBuf};
|
||||
use super::parse_mapping;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn plain_short_id_stays_text() {
|
||||
@@ -398,19 +329,4 @@ proxies:
|
||||
assert!(output.contains("short-id: '1234e123'"), "{output}");
|
||||
assert!(output.contains("short-id: '0e5'"), "{output}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_id_quoting_changing_other_values_is_dropped() {
|
||||
let profile = "\
|
||||
proxies:
|
||||
- name: a
|
||||
reality-opts:
|
||||
short-id: 1234e123
|
||||
note: |
|
||||
short-id: 1234e123
|
||||
";
|
||||
let today = serde_yaml_ng::from_str::<Value>(profile).expect("profile should parse");
|
||||
let value = parse_short_id_text(profile, Path::new("profile.yaml")).expect("profile should parse");
|
||||
assert_eq!(value, today);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user