helm-rs 0.1.2

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
use std::path::Path;

use super::{CliCommand, Invocation, oci_hosts, registry_auth};
use crate::command::{
    DependencyBuild, DependencyList, DependencyListing, DependencyOptions, DependencyRow,
    DependencyStatus, DependencyUpdate,
};
use crate::error::{Error, Result};

#[cfg(test)]
mod tests;

/// The columns of the `helm dependency list` table, in order (`printDependencies`,
/// `pkg/action/dependency.go`, Helm v4.3.0).
const COLUMNS: [&str; 4] = ["NAME", "VERSION", "REPOSITORY", "STATUS"];

/// The widest column Helm accepts (`--max-col-width` is a `uint`; this fits its 32-bit minimum).
const MAX_COL_WIDTH: &str = "4294967295";

/// Writes the flags `dependency build` and `dependency update` share. A password becomes a
/// registry config entry for every `oci://` host of the chart's dependencies, never argv; Helm
/// feeds it only to its registry client.
fn dependency_flags(inv: &mut Invocation, chart: &Path, o: &DependencyOptions) -> Result<()> {
    let mut username = o.username.as_deref();

    if let Some(password) = &o.password {
        let user = username.take().ok_or_else(|| {
            Error::InvalidCommand("a registry password needs a username".to_owned())
        })?;
        let hosts = oci_hosts([chart])?;

        if hosts.is_empty() {
            return Err(Error::InvalidCommand(
                "Helm uses a dependency password only for oci:// dependencies, and this chart \
                 has none"
                    .to_owned(),
            ));
        }

        let hosts: Vec<&str> = hosts.iter().map(String::as_str).collect();

        registry_auth(inv, &hosts, user, password)?;
    }

    inv.switch("--verify", o.verify);
    inv.option("--keyring", o.keyring.as_ref());
    inv.option("--username", username);
    inv.option("--cert-file", o.cert_file.as_ref());
    inv.option("--key-file", o.key_file.as_ref());
    inv.option("--ca-file", o.ca_file.as_ref());
    inv.switch("--insecure-skip-tls-verify", o.insecure_skip_tls_verify);
    inv.switch("--plain-http", o.plain_http);
    inv.switch("--skip-refresh", o.skip_refresh);

    Ok(())
}

impl CliCommand for DependencyBuild {
    fn build(&self, inv: &mut Invocation) -> Result<()> {
        inv.arg("dependency");
        inv.arg("build");
        inv.arg(&self.chart);

        dependency_flags(inv, &self.chart, &self.options)
    }

    fn parse(&self, _stdout: String) -> Result<()> {
        Ok(())
    }
}

impl CliCommand for DependencyUpdate {
    fn build(&self, inv: &mut Invocation) -> Result<()> {
        inv.arg("dependency");
        inv.arg("update");
        inv.arg(&self.chart);

        dependency_flags(inv, &self.chart, &self.options)
    }

    fn parse(&self, _stdout: String) -> Result<()> {
        Ok(())
    }
}

impl CliCommand for DependencyList {
    fn build(&self, inv: &mut Invocation) -> Result<()> {
        inv.arg("dependency");
        inv.arg("list");
        inv.arg(&self.chart);
        inv.option("--max-col-width", Some(MAX_COL_WIDTH));

        Ok(())
    }

    fn parse(&self, stdout: String) -> Result<DependencyListing> {
        parse_listing(&stdout)
    }
}

/// The trimmed cells of one table line.
fn cells(line: &str) -> Vec<&str> {
    line.split('\t').map(str::trim).collect()
}

/// Parses the tab-separated table (uitable pads every cell with spaces and joins the cells with
/// tabs) and the warning lines after it. Without a table the output is warnings only.
pub(super) fn parse_listing(stdout: &str) -> Result<DependencyListing> {
    let parse_error = |message: String| Error::Parse {
        command: "helm dependency list",
        message,
    };
    let mut lines = stdout.lines().peekable();
    let mut listing = DependencyListing::default();

    if lines.peek().is_some_and(|line| cells(line) == COLUMNS) {
        lines.next();

        for line in lines.by_ref().take_while(|line| !line.trim().is_empty()) {
            let [name, version, repository, status] = cells(line)[..] else {
                return Err(parse_error(format!("expected 4 columns: {line:?}")));
            };
            let status = DependencyStatus::from_helm(status)
                .ok_or_else(|| parse_error(format!("unknown status {status:?}")))?;

            listing.dependencies.push(DependencyRow {
                name: name.to_owned(),
                version: version.to_owned(),
                repository: repository.to_owned(),
                status,
            });
        }
    }

    listing.warnings = lines
        .filter(|line| !line.trim().is_empty())
        .map(str::to_owned)
        .collect();

    Ok(listing)
}