1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
use crate::{Error, Result};
use serde::Deserialize;
use serde_json::{Map, Value};
use super::function_parser::FunctionCall;
use super::functions::execute_function;
use super::evaluator::evaluate_arg;
/// Modifier operation variant
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "kebab-case")]
#[allow(clippy::enum_variant_names)]
pub enum ModifierVariant {
OverwriteBeta,
DefaultBeta,
DefineBeta,
}
/// Modifier specification
#[derive(Debug, Clone, PartialEq)]
pub struct ModifierSpec {
pub variant: ModifierVariant,
pub spec: Value,
}
impl ModifierSpec {
#[cfg(test)]
pub fn new(variant: ModifierVariant, spec: Value) -> Self {
Self { variant, spec }
}
/// Apply the modifier transformation to the input
pub fn apply(&self, mut input: Value) -> Result<Value> {
// Get context if present
let context = input.get("context").cloned();
// Clone input to use as root for path resolution
let root = input.clone();
// Apply the spec recursively
self.apply_spec_to_value(&mut input, &root, &self.spec, context.as_ref(), &[])?;
Ok(input)
}
fn apply_spec_to_value(
&self,
target: &mut Value,
root: &Value,
spec: &Value,
context: Option<&Value>,
path: &[String],
) -> Result<()> {
match spec {
Value::Object(spec_map) => {
// Ensure target is an object
if !target.is_object() {
*target = Value::Object(Map::new());
}
// Clone spec_map to avoid borrow issues
let spec_entries: Vec<(String, Value)> = spec_map
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
for (key, value) in spec_entries {
match &value {
Value::String(s) if s.starts_with('=') => {
// This is a function call
let function_call = FunctionCall::parse(s)?;
// Clone target for evaluation to avoid borrow issues
let target_clone = target.clone();
// Evaluate all arguments
let mut evaluated_args = Vec::new();
for arg in &function_call.args {
let evaluated =
evaluate_arg(arg, &target_clone, root, context, path)?;
evaluated_args.push(evaluated);
}
// Execute the function
let result = execute_function(&function_call.name, &evaluated_args)?;
// Get mutable reference to target_map after evaluation
let target_map = target.as_object_mut().unwrap();
// Apply based on variant
match self.variant {
ModifierVariant::OverwriteBeta => {
// Always write
target_map.insert(key.clone(), result);
}
ModifierVariant::DefaultBeta => {
// Only write if key doesn't exist
target_map.entry(key.clone()).or_insert(result);
}
ModifierVariant::DefineBeta => {
// Only write if key doesn't exist or is null
if !target_map.contains_key(&key) || target_map[&key].is_null()
{
target_map.insert(key.clone(), result);
}
}
}
}
Value::Object(_) => {
// Nested spec, recurse
let mut new_path = path.to_vec();
new_path.push(key.clone());
// Get or create the nested value
let target_map = target.as_object_mut().unwrap();
let nested_target = target_map
.entry(key.clone())
.or_insert(Value::Object(Map::new()));
self.apply_spec_to_value(
nested_target,
root,
&value,
context,
&new_path,
)?;
}
_ => {
// Regular value, just copy it
let target_map = target.as_object_mut().unwrap();
match self.variant {
ModifierVariant::OverwriteBeta => {
target_map.insert(key.clone(), value.clone());
}
ModifierVariant::DefaultBeta => {
target_map.entry(key.clone()).or_insert(value.clone());
}
ModifierVariant::DefineBeta => {
if !target_map.contains_key(&key) || target_map[&key].is_null()
{
target_map.insert(key.clone(), value.clone());
}
}
}
}
}
}
Ok(())
}
_ => {
// Spec is not an object, can't apply
Err(Error::ParseError(format!(
"Modifier spec must be an object, got: {:?}",
spec
)))
}
}
}
}
// Deserialization support for ModifierSpec
impl<'de> Deserialize<'de> for ModifierSpec {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = Value::deserialize(deserializer)?;
Ok(ModifierSpec {
variant: ModifierVariant::OverwriteBeta, // Default variant
spec: value,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_simple_concat() {
let input = json!({
"name": ["John", "Doe"]
});
let spec = json!({
"fullName": "=concat(@(1,name[0]),' ',@(1,name[1]))"
});
let modifier = ModifierSpec::new(ModifierVariant::OverwriteBeta, spec);
let result = modifier.apply(input).unwrap();
assert_eq!(result["fullName"], json!("John Doe"));
assert_eq!(result["name"], json!(["John", "Doe"]));
}
#[test]
fn test_to_lower() {
let input = json!({
"text": "HELLO WORLD"
});
let spec = json!({
"lower": "=toLower(@(1,text))"
});
let modifier = ModifierSpec::new(ModifierVariant::OverwriteBeta, spec);
let result = modifier.apply(input).unwrap();
assert_eq!(result["lower"], json!("hello world"));
}
#[test]
fn test_nested_spec() {
let input = json!({
"string": "the QuIcK brOwn fox"
});
let spec = json!({
"lower": {
"leading": "=toLower(@(2,string))"
}
});
let modifier = ModifierSpec::new(ModifierVariant::OverwriteBeta, spec);
let result = modifier.apply(input).unwrap();
assert_eq!(result["lower"]["leading"], json!("the quick brown fox"));
}
}