helm-rs 0.1.1

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! Turning a manifest into the indexed objects helm-diff compares (`manifest/parse.go` `Parse`).

use std::collections::BTreeMap;
use std::collections::btree_map::Entry;

use serde_json::Value;

use super::{DiffOptions, ObjectId};
use crate::manifest::{Error, Manifest};

/// The annotation naming a hook's events.
const HOOK: &str = "helm.sh/hook";
/// The annotation that keeps a removed object from being reported.
const RESOURCE_POLICY: &str = "helm.sh/resource-policy";

/// The Kubernetes built-in `(group, kind)` pairs that have no namespace.
const CLUSTER_SCOPED: [(&str, &str); 28] = [
    ("", "Namespace"),
    ("", "Node"),
    ("", "PersistentVolume"),
    ("", "ComponentStatus"),
    ("apiextensions.k8s.io", "CustomResourceDefinition"),
    ("apiregistration.k8s.io", "APIService"),
    ("storage.k8s.io", "StorageClass"),
    ("storage.k8s.io", "CSIDriver"),
    ("storage.k8s.io", "CSINode"),
    ("storage.k8s.io", "VolumeAttachment"),
    ("scheduling.k8s.io", "PriorityClass"),
    ("node.k8s.io", "RuntimeClass"),
    ("networking.k8s.io", "IngressClass"),
    ("rbac.authorization.k8s.io", "ClusterRole"),
    ("rbac.authorization.k8s.io", "ClusterRoleBinding"),
    (
        "admissionregistration.k8s.io",
        "MutatingWebhookConfiguration",
    ),
    (
        "admissionregistration.k8s.io",
        "ValidatingWebhookConfiguration",
    ),
    ("admissionregistration.k8s.io", "ValidatingAdmissionPolicy"),
    (
        "admissionregistration.k8s.io",
        "ValidatingAdmissionPolicyBinding",
    ),
    ("admissionregistration.k8s.io", "MutatingAdmissionPolicy"),
    (
        "admissionregistration.k8s.io",
        "MutatingAdmissionPolicyBinding",
    ),
    ("certificates.k8s.io", "CertificateSigningRequest"),
    ("flowcontrol.apiserver.k8s.io", "FlowSchema"),
    ("flowcontrol.apiserver.k8s.io", "PriorityLevelConfiguration"),
    ("policy", "PodSecurityPolicy"),
    ("authentication.k8s.io", "TokenReview"),
    ("authorization.k8s.io", "SubjectAccessReview"),
    ("authorization.k8s.io", "SelfSubjectAccessReview"),
];

/// An object as shown: its text, and its parsed form for field changes. Both are rewritten
/// together when a Secret is hidden.
#[derive(Clone)]
pub(super) struct View {
    /// The text the line diff compares.
    pub text: String,
    /// The object the field changes compare.
    pub value: Value,
}

/// One object of a manifest, ready to compare.
pub(super) struct Object {
    /// Who the object is.
    pub id: ObjectId,
    /// The object as rendered.
    pub view: View,
    /// Whether `helm.sh/resource-policy` is `keep`.
    pub keep: bool,
}

impl View {
    /// The leading `# Source:` style comment line of the text, with its newline; empty when the
    /// text does not start with a comment (`getComment`).
    fn comment(&self) -> &str {
        match self.text.split_once('\n') {
            Some((first, _)) if first.starts_with('#') => &self.text[..=first.len()],
            _ => "",
        }
    }

    /// Renders the text again from `value` (any serialisable form of the object), keeping the
    /// leading comment.
    pub fn render<T: serde::Serialize>(&mut self, value: &T) -> Result<(), Error> {
        self.text = format!("{}{}", self.comment(), yaml(value)?);

        Ok(())
    }
}

/// Serialises a value as YAML, keys sorted, ending with a newline like Go's `yaml.Marshal`.
pub(super) fn yaml<T: serde::Serialize>(value: &T) -> Result<String, Error> {
    serde_norway::to_string(value).map_err(|error| Error::Serialize(error.to_string()))
}

/// The object's annotation `key`.
fn annotation<'a>(value: &'a Value, key: &str) -> Option<&'a str> {
    value.pointer("/metadata/annotations")?.get(key)?.as_str()
}

/// Builds the identity of `value`: apiVersion split into group and version, the namespace
/// defaulted to `namespace` unless the kind is cluster scoped.
fn identify(value: &Value, namespace: &str) -> ObjectId {
    let text = |pointer: &str| {
        value
            .pointer(pointer)
            .and_then(Value::as_str)
            .unwrap_or_default()
    };
    let group = text("/apiVersion")
        .rsplit_once('/')
        .map_or("", |(group, _)| group);
    let kind = text("/kind");
    let explicit = text("/metadata/namespace");
    let namespace = if CLUSTER_SCOPED.contains(&(group, kind)) {
        None
    } else {
        Some(if explicit.is_empty() {
            namespace
        } else {
            explicit
        })
        .filter(|name| !name.is_empty())
    };

    ObjectId {
        group: group.to_owned(),
        kind: kind.to_owned(),
        namespace: namespace.map(str::to_owned),
        name: text("/metadata/name").to_owned(),
    }
}

/// Drops `labels` and `annotations` from the text when they are `null` or empty
/// (`stripEmptyMetadataKeys`, see helm-diff issue 1064): Kubernetes treats them as absent, so
/// a chart that renders the empty key must not diff against one that omits it. The removal is
/// line based so the rest keeps its formatting; the parsed `value` only says which keys are
/// empty.
///
/// Unlike the plugin, which matches every line of the document, only the lines of the top-level
/// `metadata:` block are candidates (up to the next line without indentation), so a `labels:`
/// line in a `data` block or anywhere else is never dropped.
fn strip_empty_metadata_keys(text: &str, value: &Value) -> String {
    let empty = |key: &str| match value.pointer("/metadata")?.get(key)? {
        Value::Null => Some(()),
        Value::Object(map) if map.is_empty() => Some(()),
        _ => None,
    };
    let keys: Vec<&str> = ["labels", "annotations"]
        .into_iter()
        .filter(|key| empty(key).is_some())
        .collect();
    let lines: Vec<&str> = text.split('\n').collect();
    let Some(start) = lines.iter().position(|line| is_metadata_line(line)) else {
        return text.to_owned();
    };
    let indent = lines[start + 1..]
        .iter()
        .find(|line| is_content(line))
        .map_or(0, |line| {
            line.len() - line.trim_start_matches([' ', '\t']).len()
        });

    if keys.is_empty() || indent == 0 {
        return text.to_owned();
    }

    let end = lines[start + 1..]
        .iter()
        .position(|line| is_content(line) && !line.starts_with([' ', '\t']))
        .map_or(lines.len(), |offset| start + 1 + offset);

    lines
        .iter()
        .enumerate()
        .filter(|(position, line)| {
            !(*position > start
                && *position < end
                && keys.iter().any(|key| is_empty_key_line(line, indent, key)))
        })
        .map(|(_, line)| *line)
        .collect::<Vec<_>>()
        .join("\n")
}

/// Whether the line holds YAML content: not blank and not only a comment. A comment, even an
/// unindented one, neither ends the `metadata` block nor sets its children's indent.
fn is_content(line: &str) -> bool {
    let line = line.trim();

    !line.is_empty() && !line.starts_with('#')
}

/// `^metadata:[ \t]*(#.*)?$`.
fn is_metadata_line(line: &str) -> bool {
    line.strip_prefix("metadata:").is_some_and(|rest| {
        let rest = rest.trim_start_matches([' ', '\t']);

        rest.is_empty() || rest.starts_with('#')
    })
}

/// `^ {indent}key:[ \t]*(\{\}[ \t]*)?(#.*)?$`.
fn is_empty_key_line(line: &str, indent: usize, key: &str) -> bool {
    let Some(rest) = line
        .strip_prefix(&" ".repeat(indent))
        .and_then(|rest| rest.strip_prefix(key))
        .and_then(|rest| rest.strip_prefix(':'))
    else {
        return false;
    };
    let rest = rest.trim_start_matches([' ', '\t']);
    let rest = rest
        .strip_prefix("{}")
        .map_or(rest, |rest| rest.trim_start_matches([' ', '\t']));

    rest.is_empty() || rest.starts_with('#')
}

/// Removes `null` and empty `labels` and `annotations` from the object's metadata.
fn strip_empty_metadata_values(value: &mut Value) {
    let Some(Value::Object(metadata)) = value.get_mut("metadata") else {
        return;
    };

    for key in ["labels", "annotations"] {
        if metadata.get(key).is_some_and(|entry| {
            entry.is_null() || entry.as_object().is_some_and(serde_json::Map::is_empty)
        }) {
            metadata.remove(key);
        }
    }
}

/// The items of a list wrapper (`v1/List`, `ConfigMapList`): a document whose kind ends in
/// `List`, that has an `items` array and no `metadata.name`. The plugin expands every kind that
/// ends in `List`, which makes a custom resource such as `TodoList` vanish; here anything else
/// is an ordinary object.
fn list_items<'a>(value: &'a Value, kind: &str) -> Option<&'a Vec<Value>> {
    let named = value
        .pointer("/metadata/name")
        .and_then(Value::as_str)
        .is_some_and(|name| !name.is_empty());

    if !kind.ends_with("List") || named {
        return None;
    }

    value.get("items")?.as_array()
}

/// Adds the object (or, for a `...List`, its items) to `index` (`parseContent`).
fn add(
    index: &mut BTreeMap<String, Object>,
    value: &Value,
    text: String,
    namespace: &str,
    options: &DiffOptions,
) -> Result<(), Error> {
    let kind = value
        .get("kind")
        .and_then(Value::as_str)
        .unwrap_or_default();
    let api_version = value
        .get("apiVersion")
        .and_then(Value::as_str)
        .unwrap_or_default();

    if api_version.is_empty() && kind.is_empty() {
        return Ok(());
    }

    if let Some(items) = list_items(value, kind) {
        for item in items {
            add(index, item, yaml(item)?, namespace, options)?;
        }

        return Ok(());
    }

    let text = if options.normalize_manifests {
        yaml(value)?
    } else {
        text
    };
    let text = strip_empty_metadata_keys(&text, value);
    let hook = annotation(value, HOOK);
    let skipped = hook.is_some() && options.no_hooks
        || !options.include_tests && matches!(hook, Some("test" | "test-success"));

    if skipped {
        return Ok(());
    }

    let id = identify(value, namespace);
    let mut value = value.clone();

    strip_empty_metadata_values(&mut value);
    match index.entry(id.to_string()) {
        Entry::Occupied(slot) => tracing::warn!(key = slot.key(), "duplicate object in manifest"),
        Entry::Vacant(slot) => {
            slot.insert(Object {
                keep: annotation(&value, RESOURCE_POLICY) == Some("keep"),
                id,
                view: View { text, value },
            });
        }
    }

    Ok(())
}

/// Indexes `manifest` by object identity; the first of two objects with the same identity wins
/// (`Parse` logs the duplicate and keeps the first).
pub(super) fn index(
    manifest: &Manifest,
    namespace: &str,
    options: &DiffOptions,
) -> Result<BTreeMap<String, Object>, Error> {
    let mut index = BTreeMap::new();

    for object in &manifest.objects {
        let text = match &object.source {
            Some(source) => format!("# Source: {source}\n{}", object.raw.trim()),
            None => object.raw.trim().to_owned(),
        };

        add(&mut index, &object.value, text, namespace, options)?;
    }

    Ok(index)
}