helm-rs 0.1.2

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! The `helm` binary backend.
//!
//! [`Cli`] runs the `helm` executable (Helm 4 only) once per command. Every run inherits the parent
//! environment (exec credential plugins need `PATH` and `HOME`), except that all `HELM_*`
//! variables are removed first; the [`GlobalOptions`] then set what Helm should see, so a run does
//! not depend on the caller's Helm settings. `KUBECONFIG` is inherited: without
//! [`GlobalOptions::kubeconfig`], helm resolves the cluster exactly like `kubectl` and
//! `kube::Client::try_default` in the same process, so the two never target different clusters.
//! The kube token travels only as `HELM_KUBETOKEN`, never in argv.
//!
//! Cancellation: dropping the future of a read-only command kills the process. Commands that
//! mutate a release (install, upgrade, rollback, uninstall, test) are not killed on drop and run
//! to completion in the background, because killing an upgrade leaves the release
//! `pending-upgrade`. That background
//! task also owns the invocation's `0600` values files, so they are deleted only after the process
//! has exited, never while helm may still read them.
//!
//! ```no_run
//! # async fn demo() -> helm_rs::Result<()> {
//! use helm_rs::{Helm, command::Version};
//!
//! let helm = Helm::detect().await?.with_namespace("prod");
//! let version = helm.run(Version).await?;
//!
//! println!("{}", version.version);
//! # Ok(()) }
//! ```

#[cfg(test)]
#[macro_use]
mod chart_rows;
mod chart_path;
mod classify;
mod dependency;
mod env;
mod fetch;
mod invocation;
mod plugin;
mod registry;
mod release;
mod render;
mod repo;
mod search;
mod show;
mod verification;
mod version;

#[cfg(test)]
mod testing;

#[cfg(test)]
mod tests;

use std::ffi::OsStr;
use std::io;
use std::path::PathBuf;
use std::process::Stdio;

use tokio::io::AsyncWriteExt;
use tokio::process::{Child, Command as Process};
use tracing::debug;

use crate::backend::{Backend, Command, Execute};
use crate::command::Version;
use crate::error::{Error, Result};
use crate::options::GlobalOptions;

pub(crate) use chart_path::{chart_path, oci_host, oci_hosts, registry_auth};
pub(crate) use invocation::{Invocation, flags, parse_json};

/// A command the CLI backend can run: how to build its argv and how to read its stdout.
pub(crate) trait CliCommand: Command {
    /// True when the command changes a release. Such a run is executed in a detached tokio task
    /// that owns the child process and the invocation's temporary values files: dropping the
    /// caller's future neither kills helm nor deletes the files; they are removed when the process
    /// exits. Read-only commands run inline and are killed on drop.
    const MUTATES: bool = false;

    /// Adds the arguments (after the global flags), stdin and values to the invocation.
    fn build(&self, inv: &mut Invocation) -> Result<()>;

    /// Parses the standard output of a successful run.
    fn parse(&self, stdout: String) -> Result<Self::Output>;

    /// Reads the output of a run that exited non-zero, for commands whose exit status reports a
    /// finding rather than a failure (`helm lint`). `None`, the default, leaves the run an error.
    fn parse_failure(&self, _stdout: &str, _stderr: &str) -> Option<Result<Self::Output>> {
        None
    }
}

/// The `helm` binary backend. Obtain one with [`Cli::detect`] or [`Cli::new`], which check the
/// version.
#[derive(Debug, Clone)]
pub struct Cli {
    /// The `helm` executable.
    pub binary: PathBuf,
    /// The version it reported.
    pub version: semver::Version,
}

impl Cli {
    /// Finds `helm` on `PATH` and checks that it is Helm 4.
    pub async fn detect() -> Result<Self> {
        Self::new("helm").await
    }

    /// Uses `binary`, running `helm version` to check that it is Helm 4 or newer.
    pub async fn new(binary: impl Into<PathBuf>) -> Result<Self> {
        let binary = binary.into();
        let found = run(&binary, &GlobalOptions::default(), &Version)
            .await?
            .version;

        if found.major < 4 {
            return Err(Error::UnsupportedVersion { found });
        }

        Ok(Self {
            binary,
            version: found,
        })
    }
}

impl Backend for Cli {}

impl<C: CliCommand> Execute<C> for Cli {
    async fn execute(&self, options: &GlobalOptions, command: &C) -> Result<C::Output> {
        run(&self.binary, options, command).await
    }
}

/// True for the variables a run must not inherit: `HELM_*`, which [`GlobalOptions`] models.
fn is_helm_var(key: &OsStr) -> bool {
    key.to_string_lossy().starts_with("HELM_")
}

/// Runs one command: builds the invocation, spawns `binary`, classifies failures, parses stdout.
async fn run<C: CliCommand>(
    binary: &PathBuf,
    options: &GlobalOptions,
    command: &C,
) -> Result<C::Output> {
    let mut inv = Invocation::default();
    let mut process = Process::new(binary);

    inv.globals(options)?;
    command.build(&mut inv)?;

    for (key, _) in std::env::vars_os().filter(|(key, _)| is_helm_var(key)) {
        process.env_remove(key);
    }

    process
        .args(&inv.args)
        .envs(inv.env.iter().map(|(k, v)| (k, v)))
        .stdin(if inv.stdin.is_some() {
            Stdio::piped()
        } else {
            Stdio::null()
        })
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(!C::MUTATES);

    debug!(binary = %binary.display(), args = ?inv.args, "running helm");

    let child = process.spawn().map_err(|e| match e.kind() {
        io::ErrorKind::NotFound => Error::BinaryNotFound(binary.clone()),
        _ => Error::Io(e),
    })?;
    let finished = if C::MUTATES {
        tokio::spawn(finish(child, inv))
            .await
            .map_err(|e| Error::Io(io::Error::other(e)))??
    } else {
        finish(child, inv).await?
    };

    if !finished.success {
        if let Some(parsed) = command.parse_failure(&finished.stdout, &finished.stderr) {
            return parsed;
        }

        return Err(classify::classify(finished.exit_code, finished.stderr));
    }

    command.parse(finished.stdout)
}

/// What a finished process left behind.
struct Finished {
    success: bool,
    exit_code: Option<i32>,
    stdout: String,
    stderr: String,
}

/// Feeds stdin while collecting the output (so neither side can block the other on a full pipe)
/// and returns what the process printed. Owns the invocation, so its temporary files live until
/// the process has exited.
async fn finish(mut child: Child, inv: Invocation) -> Result<Finished> {
    let mut stdin = child.stdin.take();
    let input = inv.stdin.as_deref().unwrap_or_default();
    let feed = async {
        if let Some(stdin) = stdin.as_mut() {
            // A helm that exits before reading its stdin is reported through its exit status.
            let _ = stdin.write_all(input).await;
        }

        drop(stdin.take());
    };
    let ((), output) = tokio::join!(feed, child.wait_with_output());
    let output = output?;

    debug!(status = %output.status, "helm finished");

    if !output.status.success() {
        return Ok(Finished {
            success: false,
            exit_code: output.status.code(),
            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
        });
    }

    let stdout = String::from_utf8(output.stdout)
        .map_err(|e| Error::Io(io::Error::new(io::ErrorKind::InvalidData, e)))?;

    Ok(Finished {
        success: true,
        exit_code: output.status.code(),
        stdout,
        stderr: String::new(),
    })
}