helm-rs 0.1.1

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
use super::verification::{parse_signature, require_signature};
use super::{CliCommand, Invocation, flags};
use crate::command::{
    Passphrase, Plugin, PluginInstall, PluginInstalled, PluginList, PluginPackage, PluginUninstall,
    PluginUpdate, PluginVerification, PluginVerify,
};
use crate::error::{Error, Result};

#[cfg(test)]
mod tests;

/// The columns of the `helm plugin list` table, in order (`pkg/cmd/plugin_list.go`, Helm v4.3.0).
const COLUMNS: [&str; 6] = [
    "NAME",
    "VERSION",
    "TYPE",
    "APIVERSION",
    "PROVENANCE",
    "SOURCE",
];

/// Adds `plugin <verb>` and the names, which Helm requires at least one of.
fn named(inv: &mut Invocation, verb: &str, names: &[String]) -> Result<()> {
    if names.is_empty() {
        return Err(Error::InvalidCommand(format!(
            "plugin {verb} needs at least one plugin name"
        )));
    }

    inv.arg("plugin");
    inv.arg(verb);

    for name in names {
        inv.arg(name);
    }

    Ok(())
}

impl CliCommand for PluginInstall {
    fn build(&self, inv: &mut Invocation) -> Result<()> {
        inv.arg("plugin");
        inv.arg("install");
        inv.arg(&self.source);

        flags! { inv, self;
            option("--version", version);
            option("--keyring", keyring);
            option("--cert-file", cert_file);
            option("--key-file", key_file);
            option("--ca-file", ca_file);
            switch("--insecure-skip-tls-verify", insecure_skip_tls_verify);
            switch("--plain-http", plain_http);
            option("--username", username);
        }

        inv.switch("--verify=false", !self.verify);

        Ok(())
    }

    fn parse(&self, stdout: String) -> Result<PluginInstalled> {
        let name = stdout
            .lines()
            .find_map(|line| line.strip_prefix("Installed plugin: "))
            .ok_or_else(|| Error::Parse {
                command: "helm plugin install",
                message: format!("no \"Installed plugin: \" line in {stdout:?}"),
            })?;
        let verification =
            parse_signature("helm plugin install", &stdout, "Plugin Hash Verified: ")?.map(
                |(signed_by, fingerprint, hash)| PluginVerification {
                    signed_by,
                    fingerprint,
                    hash,
                },
            );

        Ok(PluginInstalled {
            name: name.to_owned(),
            verification,
        })
    }
}

impl CliCommand for PluginList {
    fn build(&self, inv: &mut Invocation) -> Result<()> {
        inv.arg("plugin");
        inv.arg("list");

        flags! { inv, self;
            option("--type", kind);
        }

        Ok(())
    }

    fn parse(&self, stdout: String) -> Result<Vec<Plugin>> {
        parse_plugins(&stdout)
    }
}

/// Parses the tab-separated table: Helm pads every cell with spaces and joins the cells with
/// tabs, and a cell may itself contain spaces (`local dev`).
pub(super) fn parse_plugins(stdout: &str) -> Result<Vec<Plugin>> {
    let parse_error = |message: String| Error::Parse {
        command: "helm plugin list",
        message,
    };
    let mut lines = stdout.lines().filter(|line| !line.trim().is_empty());
    let header: Vec<&str> = lines
        .next()
        .map(|line| line.split('\t').map(str::trim).collect())
        .unwrap_or_default();

    if header != COLUMNS {
        return Err(parse_error(format!("unexpected header {header:?}")));
    }

    lines
        .map(|line| {
            let cells: Vec<&str> = line.split('\t').map(str::trim).collect();
            let [name, version, kind, api_version, provenance, source] = cells[..] else {
                return Err(parse_error(format!("expected 6 columns: {line:?}")));
            };

            Ok(Plugin {
                name: name.to_owned(),
                version: version.to_owned(),
                kind: kind.to_owned(),
                api_version: api_version.to_owned(),
                provenance: provenance.to_owned(),
                source: Some(source.to_owned()).filter(|s| s != "unknown"),
            })
        })
        .collect()
}

impl CliCommand for PluginPackage {
    fn build(&self, inv: &mut Invocation) -> Result<()> {
        inv.arg("plugin");
        inv.arg("package");
        inv.arg(&self.path);

        flags! { inv, self;
            option("--destination", destination);
            option("--key", key);
            option("--keyring", keyring);
        }

        inv.switch("--sign=false", !self.sign);

        match &self.passphrase {
            Some(Passphrase::File(path)) => inv.option("--passphrase-file", Some(path)),
            Some(Passphrase::Stdin(secret)) => {
                inv.option("--passphrase-file", Some("-"));
                inv.stdin = Some(secret.expose().as_bytes().to_vec());
            }
            None => {}
        }

        Ok(())
    }

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

impl CliCommand for PluginUninstall {
    fn build(&self, inv: &mut Invocation) -> Result<()> {
        named(inv, "uninstall", &self.names)
    }

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

impl CliCommand for PluginUpdate {
    fn build(&self, inv: &mut Invocation) -> Result<()> {
        named(inv, "update", &self.names)
    }

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

impl CliCommand for PluginVerify {
    fn build(&self, inv: &mut Invocation) -> Result<()> {
        inv.arg("plugin");
        inv.arg("verify");
        inv.arg(&self.path);

        flags! { inv, self;
            option("--keyring", keyring);
        }

        Ok(())
    }

    fn parse(&self, stdout: String) -> Result<PluginVerification> {
        let (signed_by, fingerprint, hash) =
            require_signature("helm plugin verify", &stdout, "Plugin Hash Verified: ")?;

        Ok(PluginVerification {
            signed_by,
            fingerprint,
            hash,
        })
    }
}