helm-rs 0.1.0

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
use std::ffi::{OsStr, OsString};
use std::fmt::Display;
use std::io::{self, Write};
use std::path::PathBuf;
use std::time::Duration;

use serde::de::DeserializeOwned;
use tempfile::NamedTempFile;

use crate::error::{Error, Result};
use crate::options::{Color, GlobalOptions, Secret};
use crate::values::{Values, ValuesFile};

/// What one `helm` run needs: argv, extra environment, stdin, and the temporary files that must
/// outlive the process.
#[derive(Debug, Default)]
pub(crate) struct Invocation {
    pub(super) args: Vec<OsString>,
    pub(super) env: Vec<(OsString, OsString)>,
    pub(super) stdin: Option<Vec<u8>>,
    #[allow(dead_code, reason = "held so the files outlive the process")]
    temp_files: Vec<NamedTempFile>,
}

/// Applies a table of `kind("--flag", field)` rows to an invocation.
macro_rules! flags {
    ($inv:ident, $o:ident; $($kind:ident($flag:literal, $field:ident);)*) => {
        $(flags!(@row $inv, $o, $kind, $flag, $field);)*
    };
    (@row $inv:ident, $o:ident, option, $flag:literal, $field:ident) => {
        $inv.option($flag, $o.$field.as_ref())
    };
    (@row $inv:ident, $o:ident, number, $flag:literal, $field:ident) => {
        $inv.number($flag, $o.$field.as_ref())
    };
    (@row $inv:ident, $o:ident, switch, $flag:literal, $field:ident) => {
        $inv.switch($flag, $o.$field)
    };
    (@row $inv:ident, $o:ident, each, $flag:literal, $field:ident) => {
        $inv.each($flag, &$o.$field)
    };
}

pub(crate) use flags;

/// Formats a duration the way Go's `time.ParseDuration` reads it: whole seconds as `300s`, whole
/// milliseconds as `1500ms`, anything finer in nanoseconds.
pub(crate) fn go_duration(duration: Duration) -> String {
    if duration.subsec_nanos() == 0 {
        format!("{}s", duration.as_secs())
    } else if duration.subsec_nanos().is_multiple_of(1_000_000) {
        format!("{}ms", duration.as_millis())
    } else {
        format!("{}ns", duration.as_nanos())
    }
}

/// Parses the JSON stdout of `command` into `T`.
pub(crate) fn parse_json<T: DeserializeOwned>(command: &'static str, stdout: &str) -> Result<T> {
    serde_json::from_str(stdout).map_err(|e| Error::Parse {
        command,
        message: e.to_string(),
    })
}

impl Invocation {
    /// Appends one argument.
    pub(crate) fn arg(&mut self, arg: impl Into<OsString>) {
        self.args.push(arg.into());
    }

    /// Appends the flag when `on`.
    pub(crate) fn switch(&mut self, flag: &str, on: bool) {
        if on {
            self.arg(flag);
        }
    }

    /// Appends `flag value` when set.
    pub(crate) fn option<T: AsRef<OsStr> + ?Sized>(&mut self, flag: &str, value: Option<&T>) {
        if let Some(value) = value {
            self.arg(flag);
            self.arg(value.as_ref());
        }
    }

    /// Appends `flag value` for a displayable value when set.
    pub(crate) fn number<T: Display>(&mut self, flag: &str, value: Option<&T>) {
        if let Some(value) = value {
            self.arg(flag);
            self.arg(value.to_string());
        }
    }

    /// Appends `flag value` once per item.
    pub(crate) fn each<T: AsRef<OsStr>>(&mut self, flag: &str, values: &[T]) {
        for value in values {
            self.arg(flag);
            self.arg(value.as_ref());
        }
    }

    /// Appends `flag=value` when set. Flags whose value is optional (`--dry-run`, `--wait`) or
    /// booleans that default to true need this form: Helm's flag parser would otherwise read the
    /// next word as a positional argument.
    pub(crate) fn equals(&mut self, flag: &str, value: Option<&str>) {
        if let Some(value) = value {
            self.arg(format!("{flag}={value}"));
        }
    }

    /// Appends `--timeout` as a Go duration when set.
    pub(crate) fn timeout(&mut self, timeout: Option<Duration>) {
        self.option("--timeout", timeout.map(go_duration).as_ref());
    }

    /// Requests Helm's JSON output (`-o json`).
    pub(crate) fn json_output(&mut self) {
        self.arg("-o");
        self.arg("json");
    }

    /// Sets an environment variable for the process.
    pub(crate) fn env(&mut self, key: &str, value: impl Into<OsString>) {
        self.env.push((key.into(), value.into()));
    }

    /// Sets an environment variable when the value is set.
    fn env_option<T: Into<OsString>>(&mut self, key: &str, value: Option<T>) {
        if let Some(value) = value {
            self.env(key, value);
        }
    }

    /// Writes `contents` to a `0600` temporary file that lives as long as the invocation and
    /// returns its path.
    pub(crate) fn temp_file(&mut self, contents: &[u8]) -> Result<PathBuf> {
        let mut temp = NamedTempFile::new()?;

        temp.write_all(contents)?;
        temp.flush()?;

        let path = temp.path().to_path_buf();

        self.temp_files.push(temp);

        Ok(path)
    }

    /// Applies the global options: flags as argv, the token and env-only settings as environment.
    pub(crate) fn globals(&mut self, o: &GlobalOptions) -> Result<()> {
        flags! { self, o;
            option("--kubeconfig", kubeconfig);
            option("--kube-context", kube_context);
            option("--namespace", namespace);
            option("--kube-apiserver", kube_apiserver);
            option("--kube-as-user", kube_as_user);
            each("--kube-as-group", kube_as_group);
            option("--kube-ca-file", kube_ca_file);
            switch("--kube-insecure-skip-tls-verify", kube_insecure_skip_tls_verify);
            option("--kube-tls-server-name", kube_tls_server_name);
            number("--qps", qps);
            number("--burst-limit", burst_limit);
            switch("--debug", debug);
            option("--registry-config", registry_config);
            option("--repository-config", repository_config);
            option("--repository-cache", repository_cache);
            option("--content-cache", content_cache);
        }

        self.option("--color", o.color.map(Color::as_str).as_ref());

        self.env_option("HELM_KUBETOKEN", o.kube_token.as_ref().map(Secret::expose));
        self.env_option("HELM_CACHE_HOME", o.cache_home.as_deref());
        self.env_option("HELM_CONFIG_HOME", o.config_home.as_deref());
        self.env_option("HELM_DATA_HOME", o.data_home.as_deref());
        self.env_option("HELM_DRIVER", o.driver.map(crate::options::Driver::as_str));
        self.env_option(
            "HELM_DRIVER_SQL_CONNECTION_STRING",
            o.driver_sql_connection_string.as_ref().map(Secret::expose),
        );
        self.env_option("HELM_MAX_HISTORY", o.max_history.map(|n| n.to_string()));
        self.env_option("HELM_PLUGINS", o.plugins.as_deref());
        self.env_option("HELM_NO_PLUGINS", o.no_plugins.then_some("1"));

        if !o.memory_driver_data.is_empty() {
            let joined = std::env::join_paths(&o.memory_driver_data)
                .map_err(|e| Error::Io(io::Error::new(io::ErrorKind::InvalidInput, e)))?;

            self.env("HELM_MEMORY_DRIVER_DATA", joined);
        }

        Ok(())
    }

    /// Appends the value sources as `-f` and `--set*` arguments in Helm's precedence order;
    /// in-memory documents go to `0600` temporary files kept alive with the invocation.
    pub(crate) fn values(&mut self, values: &Values) -> Result<()> {
        for file in &values.files {
            match file {
                ValuesFile::Path(path) => self.option("-f", Some(path)),
                ValuesFile::Url(url) => self.option("-f", Some(url)),
                ValuesFile::Json(value) => {
                    let path = self.temp_file(&serde_json::to_vec(value)?)?;

                    self.option("-f", Some(&path));
                }
            }
        }

        self.each("--set-json", &values.set_json);
        self.each("--set", &values.set);
        self.each("--set-string", &values.set_string);
        self.each("--set-file", &values.set_file);
        self.each("--set-literal", &values.set_literal);

        Ok(())
    }
}

#[cfg(test)]
mod tests;