helm-rs 0.1.1

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! Reading charts from directories and archives: Helm's `pkg/chart/loader` (`load.go`,
//! `archive/archive.go`, `archive/budget.go`) and `pkg/chart/v2/loader`.

use std::path::Path;

use serde::de::DeserializeOwned;
use serde_json::Value;

mod archive;
mod dir;

use self::archive::{ensure_archive, read_archive};
use self::dir::load_dir;
use super::yaml;
use super::{Chart, Error, File, metadata::Dependency, parse_values};

/// Helm's `archive.MaxDecompressedChartSize`: 100 MiB of decompressed content per chart (shared
/// by a chart's whole tree for directories, per archive for archives).
pub const MAX_DECOMPRESSED_SIZE: i64 = 100 * 1024 * 1024;

/// The chart loader flavour, chosen by `apiVersion`: v1/v2 or the internal v3.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Flavor {
    V2,
    V3,
}

/// Picks the flavour from a `Chart.yaml`'s `apiVersion`, like `loader.LoadDir`/`LoadFile`.
fn flavor_of(chart_yaml: &[u8]) -> Result<Flavor, Error> {
    let document = yaml::parse_first(chart_yaml).map_err(|e| load_error("Chart.yaml", &e))?;

    match document.get("apiVersion").and_then(Value::as_str) {
        Some("v1" | "v2" | "") | None => Ok(Flavor::V2),
        Some("v3") => Ok(Flavor::V3),
        Some(_) => Err(Error::UnsupportedApiVersion),
    }
}

/// Wraps a YAML or typed-decode failure.
fn load_error(file: &str, detail: &dyn std::fmt::Display) -> Error {
    Error::Load {
        file: file.to_owned(),
        detail: detail.to_string(),
    }
}

/// Loads a directory or an archive file.
pub(super) fn load(path: &Path, budget: i64) -> Result<Chart, Error> {
    let io = |source| Error::Io {
        path: path.to_owned(),
        source,
    };

    if std::fs::metadata(path).map_err(io)?.is_dir() {
        return load_dir(path, budget);
    }

    let bytes = std::fs::read(path).map_err(io)?;

    ensure_archive(path, &bytes)?;
    load_archive_bytes(&bytes, budget)
}

/// Loads a chart from archive bytes, dispatching on the `Chart.yaml` inside.
pub(super) fn load_archive_bytes(bytes: &[u8], budget: i64) -> Result<Chart, Error> {
    let files = read_archive(bytes, budget)?;
    let chart_yaml = files
        .iter()
        .find(|f| f.name == "Chart.yaml")
        .ok_or_else(|| {
            Error::Archive("unable to detect chart version, no Chart.yaml found".into())
        })?;
    let flavor = flavor_of(&chart_yaml.data)?;

    load_files(files, flavor)
}

/// Decodes a YAML file into a typed model through JSON, like `sigs.k8s.io/yaml`.
fn decode<T: DeserializeOwned>(file: &str, data: &[u8]) -> Result<T, Error> {
    let value = yaml::parse_first(data).map_err(|e| load_error(file, &e))?;
    let value = strip_nulls(value);

    serde_json::from_value(value)
        .map_err(|e| load_error(file, &format!("error unmarshaling JSON: {e}")))
}

/// Drops `null` object members, which Go's JSON decoder leaves at their zero value.
fn strip_nulls(value: Value) -> Value {
    match value {
        Value::Object(map) => Value::Object(
            map.into_iter()
                .filter(|(_, v)| !v.is_null())
                .map(|(k, v)| (k, strip_nulls(v)))
                .collect(),
        ),
        Value::Array(items) => Value::Array(items.into_iter().map(strip_nulls).collect()),
        other => other,
    }
}

/// Helm's `LoadFiles`: classifies the files of one chart and loads its subcharts recursively.
fn load_files(files: Vec<File>, flavor: Flavor) -> Result<Chart, Error> {
    let mut chart = Chart::default();
    let mut subcharts: Vec<(String, Vec<File>)> = Vec::new();
    let mut have_metadata = false;

    for file in &files {
        if file.name == "Chart.yaml" {
            chart.metadata = decode("Chart.yaml", &file.data)?;
            have_metadata = true;
            if chart.metadata.api_version.is_empty() {
                chart.metadata.api_version = if flavor == Flavor::V3 { "v3" } else { "v1" }.into();
            }
        }
    }

    chart.values = Value::Object(serde_json::Map::new());

    for file in files {
        let v1 = chart.metadata.api_version == "v1";

        match file.name.as_str() {
            "Chart.yaml" => {}
            "Chart.lock" => chart.lock = Some(decode("Chart.lock", &file.data)?),
            "values.yaml" => {
                chart.values =
                    parse_values(&file.data).map_err(|e| load_error("values.yaml", &e))?;
                chart.values_raw = Some(file.data);
            }
            "values.schema.json" => chart.schema_raw = Some(file.data),
            "requirements.yaml" if flavor == Flavor::V2 => {
                let requirements: Requirements = decode("requirements.yaml", &file.data)?;

                if let Some(dependencies) = requirements.dependencies {
                    chart.metadata.dependencies = dependencies;
                }
                if v1 {
                    chart.files.push(file);
                }
            }
            "requirements.lock" if flavor == Flavor::V2 => {
                chart.lock = Some(decode("requirements.lock", &file.data)?);
                if v1 {
                    chart.files.push(file);
                }
            }
            name if name.starts_with("templates/") => chart.templates.push(file),
            name if name.starts_with("charts/") => {
                let rest = &name["charts/".len()..];

                if Path::new(name).extension().is_some_and(|e| e == "prov") {
                    chart.files.push(file);

                    continue;
                }

                let key = rest.split('/').next().unwrap_or(rest).to_owned();
                let entry = File {
                    name: rest.to_owned(),
                    data: file.data,
                    mod_time: None,
                };

                match subcharts.iter_mut().find(|(k, _)| *k == key) {
                    Some((_, group)) => group.push(entry),
                    None => subcharts.push((key, vec![entry])),
                }
            }
            _ => chart.files.push(file),
        }
    }

    if !have_metadata {
        return Err(Error::MissingChartYaml);
    }

    chart.metadata.validate()?;

    for (name, group) in subcharts {
        let loaded = load_subchart(&name, group, flavor).map_err(|source| Error::Subchart {
            name: name.clone(),
            parent: chart.metadata.name.clone(),
            source: Box::new(source),
        })?;

        if let Some(subchart) = loaded {
            chart.dependencies.push(subchart);
        }
    }

    Ok(chart)
}

/// Loads one entry of `charts/`; entries starting with `_` or `.` are skipped.
fn load_subchart(name: &str, mut files: Vec<File>, flavor: Flavor) -> Result<Option<Chart>, Error> {
    if name.starts_with(['_', '.']) {
        return Ok(None);
    }

    if Path::new(name).extension().is_some_and(|e| e == "tgz") {
        let first = files.swap_remove(0);

        if first.name != name {
            return Err(Error::Archive(format!(
                "error unpacking subchart tar: expected {name}, got {}",
                first.name
            )));
        }

        let files = read_archive(&first.data, MAX_DECOMPRESSED_SIZE)?;

        return load_files(files, flavor).map(Some);
    }

    let inner: Vec<File> = files
        .into_iter()
        .filter_map(|f| {
            f.name.split_once('/').map(|(_, rest)| File {
                name: rest.to_owned(),
                data: f.data,
                mod_time: None,
            })
        })
        .collect();

    load_files(inner, flavor).map(Some)
}

/// The part of `requirements.yaml` Helm's v2 loader uses: `dependencies`.
#[derive(serde::Deserialize)]
struct Requirements {
    dependencies: Option<Vec<Option<Dependency>>>,
}

#[cfg(test)]
mod tests;