helm-rs 0.1.0

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! A native diff of two manifests, mirroring the `helm diff` plugin
//! ([databus23/helm-diff](https://github.com/databus23/helm-diff) v3.15.15).
//!
//! The rendering comes from a backend (`helm template`, or a dry run); comparing two renderings
//! is pure data. [`Diff::between`] mirrors `manifest/parse.go` `Parse` (identity, hooks,
//! normalisation) and `diff/diff.go` `generateReport` (what is added, removed and changed, the
//! text diff, Secret redaction), and `diff/structured.go` for the field changes.
//!
//! Differences from the plugin are deliberate and listed where they occur: the group of an
//! object, not its API version, is part of its identity; the built-in cluster-scoped kinds get
//! no namespace; field changes are produced for every changed object, not only in a separate
//! output format; a type change at a path is one replacement; only the `metadata:` block loses
//! its empty `labels:` and `annotations:` lines (the plugin strips matching lines anywhere in
//! the document, `stripEmptyMetadataKeys`); and only a nameless `...List` document with an
//! `items` array is expanded into its items (the plugin expands every kind ending in `List`, so
//! a custom `TodoList` resource disappears, `parseContent`).

mod fields;
mod mask;
mod object;
mod options;
mod secret;
mod text;

use std::fmt;

use serde_json::Value;

pub use fields::{FieldChange, FieldPath, PathSegment};
pub use mask::{MaskedValue, SecretMasker, SecretSide};
pub use options::{DiffOptions, DiffOptionsBuilder, SecretMode};

use super::{Error, Manifest, push_document};
use crate::release::Release;
use object::{Object, View};

/// The kind that holds secret values.
const SECRET: &str = "Secret";

/// Who an object is: its API group, kind, namespace and name. The plugin keys objects the same
/// way (`metadata.String()` in `manifest/parse.go`), except that it uses the API version without
/// its last segment where this uses the group, so core objects have the empty group.
///
/// An object without a `metadata.namespace` takes the namespace given to [`Diff::between`], as
/// in the plugin (`parseContent`), because the namespace of a custom kind cannot be known without
/// a cluster. Objects of the built-in cluster-scoped kinds have no namespace at all.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ObjectId {
    /// The API group; empty for the core group.
    pub group: String,
    /// The kind.
    pub kind: String,
    /// The namespace; `None` for a cluster-scoped object or an empty default namespace.
    pub namespace: Option<String>,
    /// `metadata.name`.
    pub name: String,
}

impl fmt::Display for ObjectId {
    /// The plugin's key: `namespace, name, Kind (group)`, with `v1` standing for the core group.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let group = if self.group.is_empty() {
            "v1"
        } else {
            &self.group
        };

        write!(
            f,
            "{}, {}, {} ({group})",
            self.namespace.as_deref().unwrap_or_default(),
            self.name,
            self.kind
        )
    }
}

/// How an object differs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChangeKind {
    /// Only in the new manifest.
    Added,
    /// Only in the old manifest.
    Removed,
    /// In both, with different content.
    Changed,
}

/// One object that differs.
#[derive(Debug, Clone, PartialEq)]
pub struct ObjectChange {
    /// The object.
    pub id: ObjectId,
    /// How it differs.
    pub kind: ChangeKind,
    /// The changed fields; empty unless `kind` is [`ChangeKind::Changed`], when the object is
    /// suppressed, and when only formatting changed (the text diff shows it, as in the plugin;
    /// [`DiffOptions::normalize_manifests`] hides it).
    pub fields: Vec<FieldChange>,
    /// The text diff as the plugin prints it: `+ `, `- ` and two spaces before each line, `...`
    /// for omitted context. One line saying so when the kind is suppressed. An added object
    /// starts with an empty removed line, as in the plugin.
    pub text: String,
    /// Whether the kind is in [`DiffOptions::suppress`].
    pub suppressed: bool,
}

impl fmt::Display for ObjectChange {
    /// The plugin's report entry: the key, what happened, then the text diff.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let message = match self.kind {
            ChangeKind::Added => "has been added:",
            ChangeKind::Removed => "has been removed:",
            ChangeKind::Changed => "has changed:",
        };

        write!(f, "{} {message}\n{}", self.id, self.text)
    }
}

/// The differences between two manifests, in the plugin's order: changed objects, then removed
/// ones, then added ones, each by key.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Diff {
    /// The objects that differ.
    pub changes: Vec<ObjectChange>,
}

impl Diff {
    /// Whether nothing differs (the plugin's `--detailed-exitcode` exits non-zero when this is
    /// false).
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.changes.is_empty()
    }

    /// The objects with the given `kind`.
    pub fn of_kind(&self, kind: ChangeKind) -> impl Iterator<Item = &ObjectChange> {
        self.changes
            .iter()
            .filter(move |change| change.kind == kind)
    }

    /// Compares `before` with `after`. An object is identified by [`ObjectId`] after taking
    /// `namespace` as the default; an object only in `before` is removed unless it has the
    /// annotation `helm.sh/resource-policy: keep` (`generateReport`), one only in `after` is
    /// added, and one in both is changed when its text differs (after the options). Hooks are
    /// ordinary objects keyed the same way, with `helm.sh/hook: test` ones left out by default.
    ///
    /// The same identity in a manifest twice keeps the first, as the plugin does.
    pub fn between(
        before: &Manifest,
        after: &Manifest,
        namespace: &str,
        options: &DiffOptions,
    ) -> Result<Self, Error> {
        let old = object::index(before, namespace, options)?;
        let new = object::index(after, namespace, options)?;
        let mut changed = Vec::new();
        let mut removed = Vec::new();

        for (key, entry) in &old {
            let counterpart = new.get(key);

            if counterpart.is_none() && entry.keep {
                continue;
            }

            let target = if counterpart.is_some() {
                &mut changed
            } else {
                &mut removed
            };

            target.extend(change(Some(entry), counterpart, options)?);
        }

        let added = new
            .iter()
            .filter(|(key, _)| !old.contains_key(*key))
            .map(|(_, entry)| change(None, Some(entry), options))
            .collect::<Result<Vec<_>, _>>()?;

        Ok(Self {
            changes: changed
                .into_iter()
                .chain(removed)
                .chain(added.into_iter().flatten())
                .collect(),
        })
    }

    /// Compares what `deployed` holds (its manifest and its hooks, as `helm get manifest` and
    /// `helm get hooks` print them) with a fresh render of the chart, in the release's
    /// namespace: the plugin's `helm diff upgrade`. `rendered` is `helm template` output, which
    /// includes the hooks.
    pub fn against_release(
        deployed: &Release,
        rendered: &Manifest,
        options: &DiffOptions,
    ) -> Result<Self, Error> {
        let mut text = format!("{}\n", deployed.manifest);

        for hook in &deployed.hooks {
            push_document(&mut text, Some(&hook.path), &hook.manifest);
        }

        Self::between(
            &Manifest::parse(&text)?,
            rendered,
            &deployed.namespace,
            options,
        )
    }
}

/// The change from `old` to `new` (one of them may be missing), or `None` when the text does
/// not differ (`doDiff`).
fn change(
    old: Option<&Object>,
    new: Option<&Object>,
    options: &DiffOptions,
) -> Result<Option<ObjectChange>, Error> {
    let (id, kind) = match (old, new) {
        (Some(old), Some(new)) if old.view.text == new.view.text => return Ok(None),
        (Some(old), Some(_)) => (&old.id, ChangeKind::Changed),
        (Some(old), None) => (&old.id, ChangeKind::Removed),
        (None, Some(new)) => (&new.id, ChangeKind::Added),
        (None, None) => return Ok(None),
    };
    let mut old_view = old.map(|entry| entry.view.clone());
    let mut new_view = new.map(|entry| entry.view.clone());

    let mut forced = Vec::new();

    if id.kind == SECRET {
        forced = secret::apply(&options.secrets, id, old_view.as_mut(), new_view.as_mut())?;
    }

    let empty = View {
        text: String::new(),
        value: Value::Null,
    };
    let before = old_view.as_ref().unwrap_or(&empty);
    let after = new_view.as_ref().unwrap_or(&empty);
    let lines = text::diff_lines(&before.text, &after.text, options.strip_trailing_cr);

    if kind == ChangeKind::Changed && !text::has_changes(&lines) && forced.is_empty() {
        return Ok(None);
    }

    let suppressed = options.suppress.contains(&id.kind);
    let (text, fields) = if suppressed {
        (
            format!(
                "+ Changes suppressed on sensitive content of type {}\n",
                id.kind
            ),
            Vec::new(),
        )
    } else {
        (
            text::render(&lines, options.context),
            if kind == ChangeKind::Changed {
                let mut fields = fields::field_changes(&before.value, &after.value);

                secret::add_forced(
                    &mut fields,
                    &forced,
                    &options.secrets,
                    &before.value,
                    &after.value,
                );

                fields
            } else {
                Vec::new()
            },
        )
    };

    Ok(Some(ObjectChange {
        id: id.clone(),
        kind,
        fields,
        text,
        suppressed,
    }))
}

#[cfg(test)]
mod tests;