helm-rs 0.1.0

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
use std::ffi::OsStr;
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
use std::time::Duration;

use serde_json::json;
use tempfile::TempDir;

use super::env::parse_env;
use super::version::parse_version;
use super::{Cli, CliCommand, Invocation, is_helm_var};
use crate::backend::Command;
use crate::command::{Env, Lint, Severity};
use crate::error::{Error, Result};
use crate::helm::Helm;
use crate::options::GlobalOptions;
use crate::values::Values;

const RECORD: &str = r#"#!/bin/sh
OUT="$(dirname "$0")"
printf '%s\n' "$@" > "$OUT/argv"
env > "$OUT/env"
cat > "$OUT/stdin"
prev=; n=0
for a in "$@"; do
  if [ "$prev" = -f ]; then n=$((n+1)); cp "$a" "$OUT/f$n"; stat -c %a "$a" > "$OUT/mode$n"; fi
  prev=$a
done
"#;

/// A fake `helm` script in a temp dir that records argv, env and stdin next to itself.
struct Fake {
    dir: TempDir,
}

impl Fake {
    fn new(body: &str) -> Self {
        Self::raw(&format!("{RECORD}{body}\n"))
    }

    fn raw(script: &str) -> Self {
        let dir = TempDir::new().expect("temp dir");
        let bin = dir.path().join("helm");

        fs::write(&bin, script).expect("write script");
        fs::set_permissions(&bin, fs::Permissions::from_mode(0o755)).expect("chmod");

        Self { dir }
    }

    fn bin(&self) -> PathBuf {
        self.dir.path().join("helm")
    }

    fn read(&self, name: &str) -> String {
        fs::read_to_string(self.dir.path().join(name)).expect("recorded file")
    }

    fn helm(&self) -> Helm<Cli> {
        Helm::new(Cli {
            binary: self.bin(),
            version: semver::Version::new(4, 3, 0),
        })
    }
}

/// A test command that feeds stdin and values and returns stdout verbatim.
#[derive(Clone)]
struct Probe<const MUTATES: bool = false> {
    stdin: Vec<u8>,
    values: Values,
}

impl<const MUTATES: bool> Command for Probe<MUTATES> {
    type Output = String;
}

impl<const M: bool> CliCommand for Probe<M> {
    const MUTATES: bool = M;

    fn build(&self, inv: &mut Invocation) -> Result<()> {
        inv.arg("probe");
        inv.values(&self.values)?;
        inv.stdin = Some(self.stdin.clone());

        Ok(())
    }

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

#[tokio::test]
async fn detect_accepts_helm_4_and_asks_for_the_version() {
    let fake = Fake::new("printf 'v4.3.0\\nabc\\nclean\\ngo1.27'");
    let cli = Cli::new(fake.bin()).await.expect("cli");

    assert_eq!(cli.version, semver::Version::new(4, 3, 0));
    assert!(fake.read("argv").starts_with("version\n--template\n"));
}

#[tokio::test]
async fn versions_before_4_are_refused() {
    let fake = Fake::new("printf 'v3.17.0\\nabc\\nclean\\ngo1.22'");
    let error = Cli::new(fake.bin()).await.expect_err("refused");

    assert!(matches!(error, Error::UnsupportedVersion { found } if found.major == 3));
}

#[tokio::test]
async fn a_missing_binary_is_reported() {
    let error = Cli::new("/nonexistent/helm").await.expect_err("missing");

    assert!(matches!(error, Error::BinaryNotFound(_)));
}

#[tokio::test]
async fn failures_are_classified_from_stderr() {
    type Check = fn(&Error) -> bool;

    let table: [(&str, Check); 5] = [
        (
            "Error: release: not found",
            |e| matches!(e, Error::ReleaseNotFound(m) if m == "release: not found"),
        ),
        (
            "Error: UPGRADE FAILED: another operation (install/upgrade/rollback) is in progress",
            |e| matches!(e, Error::OperationInProgress(_)),
        ),
        (
            "Error: context deadline exceeded",
            |e| matches!(e, Error::Timeout(m) if m == "context deadline exceeded"),
        ),
        ("Error: timed out waiting for the condition", |e| {
            matches!(e, Error::Timeout(_))
        }),
        (
            "Error: kaboom\nmore detail",
            |e| matches!(e, Error::Backend { exit_code: Some(3), stderr } if stderr == "Error: kaboom\nmore detail\n"),
        ),
    ];

    for (stderr, check) in table {
        let fake = Fake::new(&format!("cat >&2 <<'EOF'\n{stderr}\nEOF\nexit 3"));
        let error = fake.helm().run(Env).await.expect_err("fails");

        assert!(check(&error), "{stderr}: {error:?}");
    }
}

#[tokio::test]
async fn a_failed_lint_returns_its_findings_but_a_failure_before_linting_is_an_error() {
    let findings = Fake::new(
        "printf '==> Linting c\\n[ERROR] Chart.yaml: version is required\\n\\n'\n\
         echo 'Error: 1 chart(s) linted, 1 chart(s) failed' >&2\nexit 1",
    );
    let early = Fake::new("echo 'Error: bad values file' >&2\nexit 1");
    let report = findings.helm().run(Lint::new("c")).await.expect("report");
    let error = early.helm().run(Lint::new("c")).await.expect_err("fails");

    assert!(!report.passed());
    assert_eq!(report.charts[0].messages[0].severity, Severity::Error);
    assert_eq!(report.summary.expect("totals").failed, 1);
    assert!(matches!(
        error,
        Error::Backend {
            exit_code: Some(1),
            ..
        }
    ));
}

#[tokio::test]
async fn globals_reach_helm_without_the_token_in_argv() {
    let fake = Fake::new("echo 'HELM_DEBUG=\"false\"'");
    let helm = fake.helm().with_options(GlobalOptions {
        namespace: Some("prod".into()),
        kube_token: Some("s3cret".into()),
        ..GlobalOptions::default()
    });
    let env = helm.run(Env).await.expect("env");

    assert_eq!(env["HELM_DEBUG"], "false");
    assert_eq!(fake.read("argv"), "--namespace\nprod\nenv\n");
    assert!(
        fake.read("env")
            .lines()
            .any(|l| l == "HELM_KUBETOKEN=s3cret")
    );
    assert!(!fake.read("argv").contains("s3cret"));
}

#[tokio::test]
async fn stdin_and_in_memory_values_are_delivered() {
    let fake = Fake::new("echo done");
    let probe = Probe::<false> {
        stdin: b"pw\n".to_vec(),
        values: Values::new().json(json!({"k": "v"})),
    };
    let out = fake.helm().run(probe).await.expect("probe");

    assert_eq!(out, "done\n");
    assert_eq!(fake.read("stdin"), "pw\n");
    assert_eq!(fake.read("f1"), r#"{"k":"v"}"#);
    assert_eq!(fake.read("mode1").trim(), "600");
}

#[test]
fn only_helm_variables_are_stripped_and_kubeconfig_is_inherited() {
    for (key, stale) in [
        ("HELM_DEBUG", true),
        ("HELM_KUBETOKEN", true),
        ("KUBECONFIG", false),
        ("PATH", false),
        ("HOME", false),
        ("MY_HELM_X", false),
    ] {
        assert_eq!(is_helm_var(OsStr::new(key)), stale, "{key}");
    }
}

#[test]
fn version_output_is_parsed_and_bad_output_is_an_error() {
    let parsed = parse_version("v4.3.0\nabc\n\ngo1.27").expect("parse");

    assert_eq!(parsed.version, semver::Version::new(4, 3, 0));
    assert_eq!(parsed.git_commit, "abc");
    assert_eq!(parsed.git_tree_state, "");
    assert_eq!(parsed.go_version, "go1.27");
    assert!(parse_version("nope").is_err());
    assert!(parse_version("x\na\nb\nc").is_err());
}

#[test]
fn env_output_is_parsed_and_bad_lines_are_an_error() {
    let parsed = parse_env("HELM_A=\"\"\nHELM_B=\"/x y\"\n").expect("parse");

    assert_eq!(parsed["HELM_A"], "");
    assert_eq!(parsed["HELM_B"], "/x y");
    assert!(parse_env("HELM_A=unquoted\n").is_err());
}

#[tokio::test]
async fn large_stdin_and_stdout_do_not_deadlock() {
    let fake = Fake::raw("#!/bin/sh\nhead -c 1048576 /dev/zero\ncat > /dev/null\n");
    let probe = Probe::<false> {
        stdin: vec![b'x'; 1 << 20],
        values: Values::new(),
    };
    let helm = fake.helm();
    let run = tokio::time::timeout(Duration::from_secs(10), helm.run(probe));
    let out = run.await.expect("no deadlock").expect("probe");

    assert_eq!(out.len(), 1 << 20);
}

async fn wait_for(what: &str, mut ready: impl FnMut() -> bool) {
    for _ in 0..250 {
        if ready() {
            return;
        }

        tokio::time::sleep(Duration::from_millis(20)).await;
    }

    panic!("timed out waiting for {what}");
}

#[tokio::test]
async fn dropping_a_mutating_run_keeps_its_values_file_until_helm_exits() {
    let fake = Fake::raw(
        "#!/bin/sh\nOUT=\"$(dirname \"$0\")\"\nprev=\nfor a in \"$@\"; do\n  [ \"$prev\" = -f ] && F=$a\n  prev=$a\ndone\necho \"$F\" > \"$OUT/path\"\nsleep 1\ncat \"$F\" > \"$OUT/late\"\n",
    );
    let probe = Probe::<true> {
        stdin: Vec::new(),
        values: Values::new().json(json!({"k": "v"})),
    };
    let helm = fake.helm();
    let dropped = tokio::time::timeout(Duration::from_millis(200), helm.run(probe)).await;
    let path = PathBuf::from(fake.read("path").trim());

    assert!(dropped.is_err(), "the run was still going when dropped");
    assert!(path.exists(), "values file survives the dropped future");

    wait_for("helm to finish", || fake.dir.path().join("late").exists()).await;
    wait_for("temp file removal", || !path.exists()).await;

    assert_eq!(fake.read("late"), r#"{"k":"v"}"#);
}