Skip to main content

helm_rs/manifest/diff/
fields.rs

1//! Field-level changes between two objects (`diff/structured.go` `calculateFieldChanges`).
2
3use std::collections::BTreeSet;
4use std::fmt;
5
6use serde_json::Value;
7
8/// One step of a [`FieldPath`].
9#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
10pub enum PathSegment {
11    /// A key of a mapping.
12    Key(String),
13    /// An index of a sequence.
14    Index(usize),
15}
16
17/// The location of a field inside an object. Displays like helm-diff's structured output:
18/// keys joined by `.` and indices as `[n]` on the key before them, as in
19/// `spec.containers[0].image`.
20#[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/// A field that differs between the two sides: added when `before` is `None`, removed when
38/// `after` is `None`, replaced otherwise.
39#[derive(Debug, Clone, PartialEq)]
40pub struct FieldChange {
41    /// Where the field is.
42    pub path: FieldPath,
43    /// The value before; `None` when the field did not exist.
44    pub before: Option<Value>,
45    /// The value after; `None` when the field no longer exists.
46    pub after: Option<Value>,
47}
48
49/// The field changes from `before` to `after`, mirroring helm-diff's walk of the JSON merge
50/// patch: mappings are compared key by key in sorted order, sequences index by index, a scalar,
51/// or a value whose type changed, is replaced as a whole, and `null` counts as absent.
52pub(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
65/// A value, or `None` for `null`.
66fn present(value: &Value) -> Option<&Value> {
67    Some(value).filter(|value| !value.is_null())
68}
69
70/// Compares two optional values at `path`, recording what differs.
71fn 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}