mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-05 05:50:04 +08:00
82 lines
2.7 KiB
Rust
82 lines
2.7 KiB
Rust
use super::{ResultLog, ScriptOutcome, field::use_lowercase};
|
|
use serde_yaml_ng::Mapping;
|
|
use tristr::alias::String;
|
|
|
|
type ScriptResult = (Mapping, Vec<String>, ResultLog);
|
|
|
|
/// Never fails: exceptions are logged and the input config is returned unchanged.
|
|
pub(super) async fn use_script<Fut: Future<Output = ScriptOutcome> + Send>(
|
|
script: String,
|
|
config: Mapping,
|
|
name: String,
|
|
execute: impl FnOnce(String, serde_json::Value, String) -> Fut + Send,
|
|
) -> ScriptResult {
|
|
// The template is identity-plus-lowercasing; skip the Boa round-trip.
|
|
if script == super::ITEM_SCRIPT {
|
|
return (use_lowercase(config), vec![], vec![]);
|
|
}
|
|
|
|
let json = match serde_json::to_value(&config) {
|
|
Ok(mut json) => {
|
|
if let Some(map) = json.as_object_mut() {
|
|
let mut lowered = serde_json::Map::with_capacity(map.len());
|
|
for (key, value) in std::mem::take(map) {
|
|
let mut key = key;
|
|
key.make_ascii_lowercase();
|
|
lowered.insert(key, value);
|
|
}
|
|
*map = lowered;
|
|
}
|
|
json
|
|
}
|
|
Err(err) => return (config, vec![], vec![("exception".into(), err.to_string().into())]),
|
|
};
|
|
|
|
let (outcome, mut logs) = execute(script, json, name).await;
|
|
match outcome {
|
|
Ok(result) => {
|
|
let result = use_lowercase(result);
|
|
// Compared against the config as handed in, not the lowercased copy the script saw.
|
|
let changed_keys = result
|
|
.iter()
|
|
.filter(|(key, value)| config.get(key) != Some(value))
|
|
.filter_map(|(key, _)| {
|
|
let mut key: String = key.as_str()?.into();
|
|
key.make_ascii_lowercase();
|
|
Some(key)
|
|
})
|
|
.collect();
|
|
(result, changed_keys, logs)
|
|
}
|
|
Err(reason) => {
|
|
logs.push(("exception".into(), reason.into()));
|
|
(config, vec![], logs)
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use std::future::ready;
|
|
|
|
use super::{Mapping, use_script};
|
|
|
|
#[tokio::test]
|
|
async fn default_template_skips_the_executor() {
|
|
let mut called = false;
|
|
let mut config = Mapping::new();
|
|
config.insert("MiXeD".into(), true.into());
|
|
let (config, changed_keys, logs) =
|
|
use_script(crate::ITEM_SCRIPT.into(), config, "profile".into(), |_, _, _| {
|
|
called = true;
|
|
ready((Ok(Mapping::new()), vec![]))
|
|
})
|
|
.await;
|
|
|
|
assert!(!called);
|
|
assert_eq!(config["mixed"], serde_yaml_ng::Value::Bool(true));
|
|
assert!(changed_keys.is_empty());
|
|
assert!(logs.is_empty());
|
|
}
|
|
}
|