helm-rs 0.1.2

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! Field-level changes between two objects (`diff/structured.go` `calculateFieldChanges`).

use std::collections::BTreeSet;
use std::fmt;

use serde_json::Value;

/// One step of a [`FieldPath`].
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum PathSegment {
    /// A key of a mapping.
    Key(String),
    /// An index of a sequence.
    Index(usize),
}

/// The location of a field inside an object. Displays like helm-diff's structured output:
/// keys joined by `.` and indices as `[n]` on the key before them, as in
/// `spec.containers[0].image`.
#[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(())
    }
}

/// A field that differs between the two sides: added when `before` is `None`, removed when
/// `after` is `None`, replaced otherwise.
#[derive(Debug, Clone, PartialEq)]
pub struct FieldChange {
    /// Where the field is.
    pub path: FieldPath,
    /// The value before; `None` when the field did not exist.
    pub before: Option<Value>,
    /// The value after; `None` when the field no longer exists.
    pub after: Option<Value>,
}

/// The field changes from `before` to `after`, mirroring helm-diff's walk of the JSON merge
/// patch: mappings are compared key by key in sorted order, sequences index by index, a scalar,
/// or a value whose type changed, is replaced as a whole, and `null` counts as absent.
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
}

/// A value, or `None` for `null`.
fn present(value: &Value) -> Option<&Value> {
    Some(value).filter(|value| !value.is_null())
}

/// Compares two optional values at `path`, recording what differs.
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(),
        }),
    }
}