helm_rs/manifest/diff/
fields.rs1use std::collections::BTreeSet;
4use std::fmt;
5
6use serde_json::Value;
7
8#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
10pub enum PathSegment {
11 Key(String),
13 Index(usize),
15}
16
17#[derive(Debug, Clone, PartialEq, Eq, Default)]
21pub struct FieldPath(pub Vec<PathSegment>);
22
23impl fmt::Display for FieldPath {
24 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25 for (position, segment) in self.0.iter().enumerate() {
26 match segment {
27 PathSegment::Key(key) if position == 0 => write!(f, "{key}")?,
28 PathSegment::Key(key) => write!(f, ".{key}")?,
29 PathSegment::Index(index) => write!(f, "[{index}]")?,
30 }
31 }
32
33 Ok(())
34 }
35}
36
37#[derive(Debug, Clone, PartialEq)]
40pub struct FieldChange {
41 pub path: FieldPath,
43 pub before: Option<Value>,
45 pub after: Option<Value>,
47}
48
49pub(super) fn field_changes(before: &Value, after: &Value) -> Vec<FieldChange> {
53 let mut changes = Vec::new();
54
55 walk(
56 &mut changes,
57 &mut Vec::new(),
58 present(before),
59 present(after),
60 );
61
62 changes
63}
64
65fn present(value: &Value) -> Option<&Value> {
67 Some(value).filter(|value| !value.is_null())
68}
69
70fn walk(
72 changes: &mut Vec<FieldChange>,
73 path: &mut Vec<PathSegment>,
74 before: Option<&Value>,
75 after: Option<&Value>,
76) {
77 match (before, after) {
78 (Some(Value::Object(before)), Some(Value::Object(after))) => {
79 let keys: BTreeSet<&String> = before.keys().chain(after.keys()).collect();
80
81 for key in keys {
82 path.push(PathSegment::Key(key.clone()));
83 walk(
84 changes,
85 path,
86 before.get(key).and_then(|value| present(value)),
87 after.get(key).and_then(|value| present(value)),
88 );
89 path.pop();
90 }
91 }
92 (Some(Value::Array(before)), Some(Value::Array(after))) => {
93 for index in 0..before.len().max(after.len()) {
94 path.push(PathSegment::Index(index));
95 walk(
96 changes,
97 path,
98 before.get(index).and_then(|value| present(value)),
99 after.get(index).and_then(|value| present(value)),
100 );
101 path.pop();
102 }
103 }
104 (None, None) => {}
105 (before, after) if before == after => {}
106 (before, after) => changes.push(FieldChange {
107 path: FieldPath(path.clone()),
108 before: before.cloned(),
109 after: after.cloned(),
110 }),
111 }
112}