mod spec;
mod shift;
mod default;
mod remove;
mod modifier;
mod pointer;
mod transform;
mod error;
pub mod dsl;
pub mod fuzz;
use serde_json::Value;
use transform::Transform;
use crate::default::default;
use crate::remove::remove;
use crate::modifier::modify;
use crate::spec::SpecEntry;
pub use spec::TransformSpec;
pub use error::{Error, Result};
pub fn transform(input: Value, spec: &TransformSpec) -> Result<Value> {
let mut result = input;
for entry in spec.entries() {
match entry {
SpecEntry::Shift(shift) => result = shift.apply(&result)?,
SpecEntry::Default(spec) => result = default(result, spec),
SpecEntry::Modify(spec) => result = modify(result, spec)?,
SpecEntry::Remove(spec) => result = remove(result, spec),
}
}
Ok(result)
}
#[cfg(test)]
mod test {
use serde_json::json;
use super::*;
#[test]
fn test_transform() {
let spec: TransformSpec = serde_json::from_value(json!(
[
{
"operation": "shift",
"spec": {
"a": "a_new",
"c": "c_new"
}
}
]
))
.expect("parsed spec");
let source = json!({
"a": "b",
"c": "d"
});
let result = transform(source, &spec).unwrap();
assert_eq!(
result,
json!({
"a_new": "b",
"c_new": "d"
})
);
}
#[test]
fn test_invalid_array_index_error_includes_raw_value() {
let spec: TransformSpec = serde_json::from_value(json!(
[
{
"operation": "shift",
"spec": {
"*": "out[&(0,0)]"
}
}
]
))
.expect("parsed spec");
let source = json!({
"not_numeric": 1
});
let result = transform(source, &spec);
assert!(
result.is_err(),
"Expected error when using non-numeric key as array index"
);
let err_msg = result.unwrap_err().to_string();
assert!(
err_msg.contains("not_numeric"),
"Error should include the invalid index value, got: {}",
err_msg
);
assert!(
err_msg.contains("Invalid index in expression"),
"Error should mention 'Invalid index in expression', got: {}",
err_msg
);
}
}