helm-rs 0.1.1

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! A chart repository's `index.yaml`, read natively.
//!
//! Mirrors `pkg/repo/v1/index.go` (Helm v4.3.0): the data model, the loader (YAML or JSON, entries
//! sorted newest first) and the `Get` lookup, with Masterminds semver constraints
//! ([`version`](crate::version)). One difference: entries are not validated the way Helm drops
//! invalid ones.

use std::collections::BTreeMap;
use std::path::Path;

use jiff::Timestamp;
use serde::{Deserialize, Deserializer};

use crate::chart::Metadata;
use crate::version::{Constraints, Version};

#[cfg(test)]
mod tests;

/// Everything that can go wrong reading or querying an index.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The file could not be read.
    #[error(transparent)]
    Io(#[from] std::io::Error),

    /// The content is neither valid YAML nor valid JSON for an index.
    #[error(transparent)]
    Yaml(#[from] serde_norway::Error),

    /// The index file is empty (Helm's `ErrEmptyIndexYaml`).
    #[error("empty index.yaml file")]
    Empty,

    /// The index has no `apiVersion` (Helm's `ErrNoAPIVersion`).
    #[error("no API version specified")]
    NoApiVersion,

    /// The index has no entry for the chart (Helm's `ErrNoChartName`).
    #[error("no chart name found: {0}")]
    NoChartName(String),

    /// The chart has no version that matches (Helm's `ErrNoChartVersion`); empty `version` means
    /// the chart has no stable version at all.
    #[error("no chart version found for {name}-{version}")]
    NoChartVersion {
        /// The chart name.
        name: String,
        /// The requested version or constraint.
        version: String,
    },

    /// The requested constraint does not parse.
    #[error("invalid version constraint {constraint:?}: {source}")]
    InvalidConstraint {
        /// The constraint as given.
        constraint: String,
        /// Why it did not parse.
        source: crate::version::Error,
    },
}

/// A repository index (`IndexFile`).
#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
pub struct Index {
    /// The index format version, `v1`.
    #[serde(default, rename = "apiVersion")]
    pub api_version: String,
    /// When the index was generated.
    #[serde(default)]
    pub generated: Option<Timestamp>,
    /// The versions of each chart, newest first once loaded.
    #[serde(default, deserialize_with = "entries")]
    pub entries: BTreeMap<String, Vec<ChartVersion>>,
    /// The signing public keys the repository advertises.
    #[serde(default, rename = "publicKeys", deserialize_with = "null_default")]
    pub public_keys: Vec<String>,
    /// Annotations Helm does not interpret.
    #[serde(default, deserialize_with = "null_default")]
    pub annotations: BTreeMap<String, String>,
}

/// One chart version in an index (`ChartVersion`): the chart's metadata plus where to get it.
#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
pub struct ChartVersion {
    /// The `Chart.yaml` metadata.
    #[serde(flatten)]
    pub metadata: Metadata,
    /// Where the chart archive can be downloaded (relative to the repository or absolute).
    #[serde(default, deserialize_with = "null_default")]
    pub urls: Vec<String>,
    /// When the version was added to the index.
    #[serde(default)]
    pub created: Option<Timestamp>,
    /// Whether the version was removed from the repository.
    #[serde(default)]
    pub removed: bool,
    /// The SHA-256 digest of the archive.
    #[serde(default)]
    pub digest: String,
}

/// Reads a possibly `null` value as its default.
fn null_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de> + Default,
{
    Ok(Option::deserialize(deserializer)?.unwrap_or_default())
}

/// Reads the entries, dropping `null` versions as Helm does.
fn entries<'de, D: Deserializer<'de>>(
    deserializer: D,
) -> Result<BTreeMap<String, Vec<ChartVersion>>, D::Error> {
    let raw: BTreeMap<String, Option<Vec<Option<ChartVersion>>>> = null_default(deserializer)?;

    Ok(raw
        .into_iter()
        .map(|(name, versions)| (name, versions.into_iter().flatten().flatten().collect()))
        .collect())
}

impl Index {
    /// Reads an index file (`LoadIndexFile`): YAML or JSON, versions sorted newest first.
    pub fn load(path: impl AsRef<Path>) -> Result<Self, Error> {
        Self::parse(&std::fs::read_to_string(path)?)
    }

    /// Parses the text of an index (`loadIndex`).
    pub fn parse(text: &str) -> Result<Self, Error> {
        if text.trim().is_empty() {
            return Err(Error::Empty);
        }

        let mut index: Self = serde_norway::from_str(text)?;

        index.sort_entries();

        if index.api_version.is_empty() {
            return Err(Error::NoApiVersion);
        }

        Ok(index)
    }

    /// Sorts every chart's versions newest first (`SortEntries`); versions that are not semantic
    /// versions go last.
    pub fn sort_entries(&mut self) {
        for versions in self.entries.values_mut() {
            versions.sort_by(|a, b| {
                let a = Version::parse(&a.metadata.version).ok();
                let b = Version::parse(&b.metadata.version).ok();

                match (a, b) {
                    (Some(a), Some(b)) => b.compare(&a),
                    (a, b) => b.is_some().cmp(&a.is_some()),
                }
            });
        }
    }

    /// Finds a chart version (`Get`): an empty `version` selects the newest stable one; otherwise
    /// an exact version string wins, then the newest version that satisfies the constraint.
    pub fn get(&self, name: &str, version: &str) -> Result<&ChartVersion, Error> {
        let versions = self
            .entries
            .get(name)
            .ok_or_else(|| Error::NoChartName(name.to_owned()))?;
        let not_found = || Error::NoChartVersion {
            name: name.to_owned(),
            version: version.to_owned(),
        };

        if versions.is_empty() {
            return Err(not_found());
        }

        let requirement = if version.is_empty() {
            Constraints::parse("*")
        } else {
            Constraints::parse(version)
        }
        .map_err(|source| Error::InvalidConstraint {
            constraint: version.to_owned(),
            source,
        })?;

        if !version.is_empty()
            && let Some(exact) = versions.iter().find(|v| v.metadata.version == version)
        {
            return Ok(exact);
        }

        versions
            .iter()
            .find(|v| Version::parse(&v.metadata.version).is_ok_and(|v| requirement.matches(&v)))
            .ok_or_else(not_found)
    }

    /// True when the index has exactly this chart version (`Has`).
    #[must_use]
    pub fn has(&self, name: &str, version: &str) -> bool {
        self.get(name, version).is_ok()
    }
}