helm-rs 0.1.0

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! Charts as data: `Chart.yaml`, `Chart.lock`, values, schema, templates and subcharts, loaded
//! natively from a directory or a `.tgz` archive without the `helm` binary.
//!
//! Everything mirrors Helm v4.3.0 (`pkg/chart/loader`, `pkg/chart/v2`, `pkg/ignore`):
//!
//! - Helm 4.3's loader dispatches on `apiVersion`: `v1`, `v2` and a missing one load as v2 charts,
//!   `v3` loads as an (internal, experimental) v3 chart, anything else is rejected. v3 differs in
//!   defaulting `apiVersion` to `v3` and not understanding `requirements.yaml`. Helm 4.3's actions
//!   (`install`, `template`, ...) still reject v3 charts.
//! - A directory honours `.helmignore` (plus the default `templates/.?*`); an archive does not.
//! - Loading stops at 100 MiB of decompressed content; archive paths are checked for absolute
//!   paths, `..`, drive letters and a stray top-level `Chart.yaml`.
//! - A leading UTF-8 byte order mark is dropped from every file.

mod digest;
mod fetch;
mod ignore;
mod loader;
mod metadata;
mod yaml;

use std::path::{Path, PathBuf};

use jiff::Timestamp;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

use crate::go_json;

pub use digest::{archive_digest, hash_dependencies, hash_dependencies_v2};
pub use ignore::{HELM_IGNORE, IgnoreError, Rules};
pub use loader::MAX_DECOMPRESSED_SIZE;
pub use metadata::{Dependency, Lock, Maintainer, Metadata, ValidationError, is_valid_semver};
pub use yaml::YamlError;

/// Everything that can go wrong reading a chart.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// A file or directory could not be read.
    #[error("{path}: {source}")]
    Io {
        /// The path involved.
        path: PathBuf,
        /// The underlying error.
        source: std::io::Error,
    },
    /// A directory has no readable `Chart.yaml`.
    #[error("unable to detect chart at {path}: {source}")]
    NoChart {
        /// The `Chart.yaml` that was looked for.
        path: PathBuf,
        /// The underlying error.
        source: std::io::Error,
    },
    /// A file of the chart is not valid YAML or does not fit its model.
    #[error("cannot load {file}: {detail}")]
    Load {
        /// The chart file, for example `Chart.yaml`.
        file: String,
        /// What was wrong with it.
        detail: String,
    },
    /// The chart's metadata failed validation.
    #[error(transparent)]
    Validation(#[from] ValidationError),
    /// The `apiVersion` is not one Helm 4.3 loads.
    #[error("unsupported chart version")]
    UnsupportedApiVersion,
    /// The chart has no `Chart.yaml`.
    #[error("Chart.yaml file is missing")]
    MissingChartYaml,
    /// The file is not a gzip archive.
    #[error("{0}")]
    NotAnArchive(String),
    /// The archive holds no files.
    #[error("no files in chart archive")]
    EmptyArchive,
    /// The archive or chart directory is unsafe or malformed.
    #[error("{0}")]
    Archive(String),
    /// The chart is larger than [`MAX_DECOMPRESSED_SIZE`].
    #[error("decompressed chart is larger than the maximum size {limit}")]
    TooLarge {
        /// The limit that was exceeded, in bytes.
        limit: i64,
    },
    /// A symlink in the chart directory leads back to a directory that is being walked.
    #[error("symlink cycle in chart directory at {}", .path.display())]
    SymlinkCycle {
        /// The directory that was entered a second time.
        path: PathBuf,
    },
    /// A `.helmignore` rule is invalid.
    #[error("invalid .helmignore: {0}")]
    Ignore(#[from] IgnoreError),
    /// A subchart could not be loaded.
    #[error("error unpacking subchart {name} in {parent}: {source}")]
    Subchart {
        /// The entry under `charts/`.
        name: String,
        /// The parent chart's name.
        parent: String,
        /// Why it failed.
        source: Box<Error>,
    },
}

/// A file of a chart: its path relative to the chart root, slash separated, and its bytes.
///
/// Serializes as Helm's `common.File` (`name`, base64 `data`, `modtime`).
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct File {
    /// Path relative to the chart root, for example `templates/deployment.yaml`.
    #[serde(default)]
    pub name: String,
    /// Content, without a leading byte order mark.
    #[serde(default, with = "go_json::bytes")]
    pub data: Vec<u8>,
    /// The modification time Helm recorded; the loader leaves it unset.
    #[serde(
        default,
        rename = "modtime",
        with = "go_json::omit_zero",
        skip_serializing_if = "Option::is_none"
    )]
    pub mod_time: Option<Timestamp>,
}

/// A chart: loaded from a directory or archive, or decoded from the chart embedded in a release
/// record (Go `chart.Chart` JSON, which [`Serialize`] and [`Deserialize`] mirror exactly).
///
/// The record does not carry `values_raw` or the subcharts, so those stay empty after decoding.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Chart {
    /// `Chart.yaml`, validated and sanitised.
    #[serde(default, deserialize_with = "go_json::null_default")]
    pub metadata: Metadata,
    /// `Chart.lock` (or `requirements.lock`).
    #[serde(default)]
    pub lock: Option<Lock>,
    /// The files under `templates/` (partials and `NOTES.txt` included).
    #[serde(default, deserialize_with = "go_json::null_default")]
    pub templates: Vec<File>,
    /// Parsed `values.yaml` with Helm's YAML semantics; `{}` when absent (`null` in records of
    /// charts without values).
    #[serde(default)]
    pub values: Value,
    /// The bytes of `values.schema.json`. Helm parses it only when validating, so loading does
    /// not fail on invalid JSON; see [`Chart::schema`].
    #[serde(default, rename = "schema", with = "go_json::option_bytes")]
    pub schema_raw: Option<Vec<u8>>,
    /// The modification time of the schema (Go's zero time reads as `None`).
    #[serde(default, rename = "schemamodtime", with = "go_json::always")]
    pub schema_mod_time: Option<Timestamp>,
    /// Every other file, as in Helm: README, LICENSE, `crds/`, `*.prov` of subcharts, ...
    /// (v1 charts also keep `requirements.yaml` and `requirements.lock` here).
    #[serde(default, deserialize_with = "go_json::null_default")]
    pub files: Vec<File>,
    /// The modification time of the chart.
    #[serde(
        default,
        rename = "modtime",
        with = "go_json::omit_zero",
        skip_serializing_if = "Option::is_none"
    )]
    pub mod_time: Option<Timestamp>,
    /// The bytes of `values.yaml`, comments and all (what `helm show values` prints). Not part
    /// of a release record.
    #[serde(skip)]
    pub values_raw: Option<Vec<u8>>,
    /// Subcharts from `charts/`, directories and `.tgz` archives, loaded recursively. Helm keeps
    /// them unexported, so a release record has none.
    #[serde(skip)]
    pub dependencies: Vec<Chart>,
}

impl Chart {
    /// Loads a chart from a directory or a `.tgz` archive, detecting which.
    ///
    /// # Errors
    /// See [`Error`].
    pub fn load(path: impl AsRef<Path>) -> Result<Self, Error> {
        loader::load(path.as_ref(), MAX_DECOMPRESSED_SIZE)
    }

    /// Loads a chart from the bytes of a `.tgz` archive.
    ///
    /// # Errors
    /// See [`Error`].
    pub fn load_archive(bytes: &[u8]) -> Result<Self, Error> {
        loader::load_archive_bytes(bytes, MAX_DECOMPRESSED_SIZE)
    }

    /// The chart name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.metadata.name
    }

    /// The chart's own default values (`values.yaml`), without any subchart or user values.
    #[must_use]
    pub fn default_values(&self) -> &Value {
        &self.values
    }

    /// The parsed `values.schema.json`, if the chart has one.
    ///
    /// # Errors
    /// Fails when the file is not valid JSON.
    pub fn schema(&self) -> Result<Option<Value>, serde_json::Error> {
        self.schema_raw
            .as_deref()
            .map(serde_json::from_slice)
            .transpose()
    }

    /// The CRD manifests of this chart: `crds/` files ending in `.yaml`, `.yml` or `.json`.
    pub fn crds(&self) -> impl Iterator<Item = &File> {
        self.files.iter().filter(|f| {
            let lower = f.name.to_ascii_lowercase();

            f.name.starts_with("crds/")
                && [".yaml", ".yml", ".json"]
                    .iter()
                    .any(|e| lower.ends_with(e))
        })
    }

    /// Reports whether `Chart.lock` is out of date with `Chart.yaml`, like `helm dependency build`
    /// ("the lock file (Chart.lock) is out of sync with the dependencies file"). `None` without a
    /// lock. Exact only when repositories are written as URLs: Helm resolves `@alias` names from
    /// its repository config before hashing.
    #[must_use]
    pub fn lock_is_stale(&self) -> Option<bool> {
        let lock = self.lock.as_ref()?;
        let current = hash_dependencies(&self.metadata.dependencies, &lock.dependencies);
        let v1 = self.metadata.api_version == "v1"
            && hash_dependencies_v2(&self.metadata.dependencies) == lock.digest;

        Some(current != lock.digest && !v1)
    }
}

/// Reads a values file (`.yaml` or `.json`) the way Helm reads `-f` files and `values.yaml`.
///
/// Documents are merged in order (maps deep-merged, anything else replaced), an empty file is
/// `{}`, and the top level must be a mapping. YAML is read with Helm's YAML 1.1 and number
/// semantics: `yes`/`no`/`on`/`off` are booleans, `0777` is octal, integers beyond 2^53 become
/// floats.
///
/// # Errors
/// On unreadable, malformed or non-mapping input.
pub fn read_values_file(path: impl AsRef<Path>) -> Result<Value, Error> {
    let path = path.as_ref();
    let data = std::fs::read(path).map_err(|source| Error::Io {
        path: path.to_owned(),
        source,
    })?;

    read_values(&data)
}

/// Parses the text of a values file; see [`read_values_file`].
///
/// # Errors
/// On malformed or non-mapping input.
pub fn read_values(data: &[u8]) -> Result<Value, Error> {
    parse_values(data).map_err(|e| Error::Load {
        file: "values".into(),
        detail: e.to_string(),
    })
}

/// Merges all YAML documents of a values file.
fn parse_values(data: &[u8]) -> Result<Value, YamlError> {
    let mut values = Map::new();

    for document in yaml::parse_documents(data)? {
        merge_maps(&mut values, yaml::into_map(document)?);
    }

    Ok(Value::Object(values))
}

/// Helm's `MergeMaps`: keys of `b` win, mappings present in both are merged recursively.
fn merge_maps(a: &mut Map<String, Value>, b: Map<String, Value>) {
    for (key, value) in b {
        match (a.get_mut(&key), value) {
            (Some(Value::Object(existing)), Value::Object(incoming)) => {
                merge_maps(existing, incoming);
            }
            (_, value) => {
                a.insert(key, value);
            }
        }
    }
}

#[cfg(test)]
mod tests;