helm-rs 0.1.0

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! Classification of a full `helm template` output (`releaseutil.SortManifests`).

use serde_json::Value;

use super::{Error, Manifest, ManifestObject, push_document};
use crate::release::{DeletePolicy, Hook, HookEvent, OutputLogPolicy};

/// The annotation naming a hook's events.
const HOOK: &str = "helm.sh/hook";
/// The annotation giving a hook's weight.
const HOOK_WEIGHT: &str = "helm.sh/hook-weight";
/// The annotation listing a hook's delete policies.
const HOOK_DELETE_POLICY: &str = "helm.sh/hook-delete-policy";
/// The annotation listing a hook's output log policies.
const HOOK_OUTPUT_LOG_POLICY: &str = "helm.sh/hook-output-log-policy";

/// A `helm template` output split into what Helm would install and what it would run.
///
/// `helm template` prints, in this order, CRDs (with `--include-crds`), the resources sorted by
/// kind, then the hooks (`pkg/cmd/template.go`); each document has its `# Source:` header.
/// `NOTES.txt` is never printed. With `--show-only` only the matching documents appear, and with
/// `--output-dir` the same documents go to files, each parseable on its own. A Secret hidden by
/// `--hide-secret` is a comment-only document and is skipped.
#[derive(Debug, Clone, PartialEq)]
pub struct Rendered {
    /// The CRDs from `crds/` directories (documents whose source is `<chart>/crds/<file>`,
    /// also below `charts/<sub>/`).
    pub crds: Vec<ManifestObject>,
    /// The regular resources, in the order printed.
    pub resources: Vec<ManifestObject>,
    /// The hooks (documents with a `helm.sh/hook` annotation), in the order printed.
    pub hooks: Vec<Hook>,
}

impl Rendered {
    /// Parses and classifies `helm template` output. A document with a `helm.sh/hook` annotation
    /// whose events are all known is a hook (the legacy `test-success` means `test`); Helm drops
    /// unknown hooks before printing, so one that does appear is kept as a resource.
    pub fn parse(output: &str) -> Result<Self, Error> {
        let mut rendered = Self {
            crds: Vec::new(),
            resources: Vec::new(),
            hooks: Vec::new(),
        };

        for object in Manifest::parse(output)?.objects {
            if let Some(hook) = hook_of(&object) {
                rendered.hooks.push(hook);
            } else if object.source.as_deref().is_some_and(is_crd_path) {
                rendered.crds.push(object);
            } else {
                rendered.resources.push(object);
            }
        }

        Ok(rendered)
    }

    /// The whole output as one [`Manifest`], in the order `helm template` prints it (CRDs,
    /// resources, hooks): what [`Diff::between`](super::Diff::between) compares.
    pub fn manifest(&self) -> Result<Manifest, Error> {
        let mut text = String::new();

        for object in self.crds.iter().chain(&self.resources) {
            push_document(&mut text, object.source.as_deref(), &object.raw);
        }

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

        Manifest::parse(&text)
    }
}

/// Builds the release hook for a document, mirroring `manifestFile.sort`.
fn hook_of(object: &ManifestObject) -> Option<Hook> {
    let annotation = |key: &str| {
        object
            .value
            .pointer("/metadata/annotations")
            .and_then(|annotations| annotations.get(key))
            .and_then(Value::as_str)
    };
    let events = annotation(HOOK)?
        .split(',')
        .map(|event| match event.trim().to_lowercase().as_str() {
            "test-success" => Some(HookEvent::Test),
            other => match HookEvent::from(other.to_owned()) {
                HookEvent::Other(_) => None,
                known => Some(known),
            },
        })
        .collect::<Option<Vec<_>>>()?;

    Some(Hook {
        name: object.name().unwrap_or_default().to_owned(),
        kind: object.kind().unwrap_or_default().to_owned(),
        path: object.source.clone().unwrap_or_default(),
        manifest: object.raw.clone(),
        events,
        weight: annotation(HOOK_WEIGHT)
            .and_then(|weight| weight.parse().ok())
            .unwrap_or(0),
        delete_policies: policies(annotation(HOOK_DELETE_POLICY), DeletePolicy::from),
        output_log_policies: policies(annotation(HOOK_OUTPUT_LOG_POLICY), OutputLogPolicy::from),
        ..Hook::default()
    })
}

/// Splits a comma-separated annotation into trimmed lowercase policies.
fn policies<T>(value: Option<&str>, convert: fn(String) -> T) -> Vec<T> {
    value
        .into_iter()
        .flat_map(|value| value.split(','))
        .map(|policy| convert(policy.trim().to_lowercase()))
        .collect()
}

/// Whether `path` is `<chart>(/charts/<sub>)*/crds/<file>`, the path of a CRD file.
pub(super) fn is_crd_path(path: &str) -> bool {
    let mut parts = path.split('/').skip(1).peekable();

    while parts.next_if_eq(&"charts").is_some() {
        if parts.next().is_none() {
            return false;
        }
    }

    parts.next() == Some("crds") && parts.peek().is_some()
}