use std::collections::BTreeSet;
use std::fmt;
use serde_json::Value;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum PathSegment {
Key(String),
Index(usize),
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct FieldPath(pub Vec<PathSegment>);
impl fmt::Display for FieldPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (position, segment) in self.0.iter().enumerate() {
match segment {
PathSegment::Key(key) if position == 0 => write!(f, "{key}")?,
PathSegment::Key(key) => write!(f, ".{key}")?,
PathSegment::Index(index) => write!(f, "[{index}]")?,
}
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct FieldChange {
pub path: FieldPath,
pub before: Option<Value>,
pub after: Option<Value>,
}
pub(super) fn field_changes(before: &Value, after: &Value) -> Vec<FieldChange> {
let mut changes = Vec::new();
walk(
&mut changes,
&mut Vec::new(),
present(before),
present(after),
);
changes
}
fn present(value: &Value) -> Option<&Value> {
Some(value).filter(|value| !value.is_null())
}
fn walk(
changes: &mut Vec<FieldChange>,
path: &mut Vec<PathSegment>,
before: Option<&Value>,
after: Option<&Value>,
) {
match (before, after) {
(Some(Value::Object(before)), Some(Value::Object(after))) => {
let keys: BTreeSet<&String> = before.keys().chain(after.keys()).collect();
for key in keys {
path.push(PathSegment::Key(key.clone()));
walk(
changes,
path,
before.get(key).and_then(|value| present(value)),
after.get(key).and_then(|value| present(value)),
);
path.pop();
}
}
(Some(Value::Array(before)), Some(Value::Array(after))) => {
for index in 0..before.len().max(after.len()) {
path.push(PathSegment::Index(index));
walk(
changes,
path,
before.get(index).and_then(|value| present(value)),
after.get(index).and_then(|value| present(value)),
);
path.pop();
}
}
(None, None) => {}
(before, after) if before == after => {}
(before, after) => changes.push(FieldChange {
path: FieldPath(path.clone()),
before: before.cloned(),
after: after.cloned(),
}),
}
}