helm-rs 0.1.1

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! Rendered manifest parsing.
//!
//! Helm renders resources as one YAML stream: every document is introduced by `---` and a
//! `# Source: <chart>/templates/<file>` comment (`pkg/action/action.go` `renderResources`,
//! `pkg/cmd/template.go`). [`Manifest`] parses such a stream, whether it is a release's
//! `manifest`, `helm template` output, `helm get manifest` output or a hook manifest.
//! [`Rendered`] additionally sorts a full `helm template` output into resources, hooks and CRDs.

mod diff;
mod order;
mod rendered;

use std::fmt::Write;

use serde_json::Value;
use sha2::{Digest, Sha256};

pub use diff::{
    ChangeKind, Diff, DiffOptions, DiffOptionsBuilder, FieldChange, FieldPath, MaskedValue,
    ObjectChange, ObjectId, PathSegment, SecretMasker, SecretMode, SecretSide,
};
pub use order::{INSTALL_ORDER, UNINSTALL_ORDER};
pub use rendered::Rendered;

/// Failures parsing rendered manifests.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// A document is not valid YAML.
    #[error("YAML parse error in {source_name}: {error}")]
    Yaml {
        /// The document's `# Source:` (or its position when it has none).
        source_name: String,
        /// The parser's message.
        error: String,
    },
    /// A document is YAML but not a mapping, so it is not a Kubernetes object.
    #[error("document {0} is not a Kubernetes object")]
    NotAnObject(String),
    /// An object cannot be serialised back to YAML (while diffing).
    #[error("cannot serialise object: {0}")]
    Serialize(String),
    /// An object does not deserialize into the requested type.
    #[cfg(feature = "kube")]
    #[error("cannot convert object: {0}")]
    Convert(#[from] serde_json::Error),
}

/// An ordered stream of rendered Kubernetes objects.
#[derive(Debug, Clone, PartialEq)]
pub struct Manifest {
    /// The objects, in the order they appear.
    pub objects: Vec<ManifestObject>,
    text: String,
}

/// One document of a manifest stream.
#[derive(Debug, Clone, PartialEq)]
pub struct ManifestObject {
    /// The `# Source:` path (`<chart>/templates/<file>`), when the document has one.
    pub source: Option<String>,
    /// The parsed object.
    pub value: Value,
    /// The document text as Helm splits it: leading whitespace and the `# Source:` header line
    /// removed, the rest unchanged.
    pub raw: String,
}

impl Manifest {
    /// Parses a manifest stream the way Helm splits it (`releaseutil.SplitManifests`): on lines
    /// starting with `---` (text after the dashes stays in the next document), skipping empty and
    /// comment-only documents. A document's leading `# Source:` comment becomes
    /// [`ManifestObject::source`].
    pub fn parse(yaml: &str) -> Result<Self, Error> {
        let objects = split_documents(yaml)
            .into_iter()
            .enumerate()
            .map(|(index, document)| ManifestObject::parse(index, document))
            .collect::<Result<Vec<_>, _>>()?
            .into_iter()
            .flatten()
            .collect();

        Ok(Self {
            objects,
            text: yaml.to_owned(),
        })
    }

    /// The SHA-256 of the exact text given to [`Manifest::parse`], as lowercase hex. For a
    /// release that is its `manifest` string as Helm stores it, byte for byte, so the digest
    /// changes with any rendered change and is stable otherwise. Helm itself defines no manifest
    /// digest; this is a content hash, not a Helm value.
    #[must_use]
    pub fn digest(&self) -> String {
        let mut hex = String::new();

        for byte in Sha256::digest(self.text.as_bytes()) {
            write!(hex, "{byte:02x}").expect("writing to a String cannot fail");
        }

        hex
    }

    /// The objects ordered for installation: by [`INSTALL_ORDER`] position, unlisted kinds last
    /// in alphabetical order of kind, the original order kept among equals
    /// (`sortManifestsByKind` with `InstallOrder`).
    #[must_use]
    pub fn sorted_for_install(&self) -> Vec<&ManifestObject> {
        self.sorted(&INSTALL_ORDER)
    }

    /// The objects ordered for uninstallation ([`UNINSTALL_ORDER`], same rules).
    #[must_use]
    pub fn sorted_for_uninstall(&self) -> Vec<&ManifestObject> {
        self.sorted(&UNINSTALL_ORDER)
    }

    /// The objects of kind `K`, converted. Matches on `apiVersion` and `kind`.
    #[cfg(feature = "kube")]
    pub fn typed<K>(&self) -> impl Iterator<Item = Result<K, Error>> + '_
    where
        K: kube::Resource + serde::de::DeserializeOwned,
        K::DynamicType: Default,
    {
        let dynamic_type = K::DynamicType::default();
        let api_version = K::api_version(&dynamic_type).into_owned();
        let kind = K::kind(&dynamic_type).into_owned();

        self.objects
            .iter()
            .filter(move |object| {
                object.api_version() == Some(api_version.as_str())
                    && object.kind() == Some(kind.as_str())
            })
            .map(|object| K::deserialize(&object.value).map_err(Error::from))
    }

    /// Sorts by `order` with Helm's `lessByKind`.
    fn sorted(&self, order: &[&str]) -> Vec<&ManifestObject> {
        let mut objects: Vec<&ManifestObject> = self.objects.iter().collect();

        objects
            .sort_by(|a, b| order::compare(order, a.kind().unwrap_or(""), b.kind().unwrap_or("")));

        objects
    }
}

impl ManifestObject {
    /// `apiVersion`.
    #[must_use]
    pub fn api_version(&self) -> Option<&str> {
        self.value.get("apiVersion")?.as_str()
    }

    /// `kind`.
    #[must_use]
    pub fn kind(&self) -> Option<&str> {
        self.value.get("kind")?.as_str()
    }

    /// `metadata.name`.
    #[must_use]
    pub fn name(&self) -> Option<&str> {
        self.value.pointer("/metadata/name")?.as_str()
    }

    /// `metadata.namespace`.
    #[must_use]
    pub fn namespace(&self) -> Option<&str> {
        self.value.pointer("/metadata/namespace")?.as_str()
    }

    /// Converts to a kube [`DynamicObject`](kube::api::DynamicObject).
    #[cfg(feature = "kube")]
    pub fn to_dynamic(&self) -> Result<kube::api::DynamicObject, Error> {
        use serde::Deserialize;

        Ok(kube::api::DynamicObject::deserialize(&self.value)?)
    }

    /// Parses one split document; `None` when it holds no object (empty or comments only).
    fn parse(index: usize, document: &str) -> Result<Option<Self>, Error> {
        let (source, raw) = take_source(document);
        let label = source.map_or_else(|| format!("#{index}"), str::to_owned);
        let value: Value = serde_norway::from_str(raw).map_err(|error| Error::Yaml {
            source_name: label.clone(),
            error: error.to_string(),
        })?;

        match value {
            Value::Null => Ok(None),
            Value::Object(_) => Ok(Some(Self {
                source: source.map(str::to_owned),
                value,
                raw: raw.to_owned(),
            })),
            _ => Err(Error::NotAnObject(label)),
        }
    }
}

/// Appends one document to a manifest stream the way Helm prints it (`---`, the `# Source:`
/// header when there is a source, the body).
pub(crate) fn push_document(text: &mut String, source: Option<&str>, body: &str) {
    text.push_str("---\n");

    if let Some(source) = source {
        writeln!(text, "# Source: {source}").expect("writing to a String cannot fail");
    }

    text.push_str(body);
    text.push('\n');
}

/// Splits on lines that start with `---` like `SplitManifests`: the text after the dashes (and
/// following spaces or tabs) belongs to the next document, whitespace-only documents are dropped
/// and each document loses its leading whitespace.
fn split_documents(text: &str) -> Vec<&str> {
    let mut documents = Vec::new();
    let mut start = 0;
    let mut offset = 0;

    for line in text.split_inclusive('\n') {
        if let Some(rest) = line.strip_prefix("---") {
            documents.push(&text[start..offset]);
            start = offset + line.len() - rest.trim_start_matches([' ', '\t']).len();
        }
        offset += line.len();
    }
    documents.push(&text[start..]);

    documents
        .into_iter()
        .map(str::trim_start)
        .filter(|document| !document.trim().is_empty())
        .collect()
}

/// Separates a leading `# Source: <path>` line from the rest of the document.
fn take_source(document: &str) -> (Option<&str>, &str) {
    let first = document.lines().next().unwrap_or_default();

    match first.strip_prefix("# Source: ") {
        Some(path) => (
            Some(path.trim_end()),
            document[first.len()..].trim_start_matches(['\r', '\n']),
        ),
        None => (None, document),
    }
}

#[cfg(test)]
mod tests;