Skip to main content

greengate_runtime/hooks/
helm.rs

1//! pre-commit-helm-lint — `helm lint` on the charts a commit touches.
2
3use super::common::{fail, hl, ok, repo_root, staged_files, warn, which};
4use crate::check::Outcome;
5use std::process::{Command, Stdio};
6
7/// The extensions this check consumes. `.tpl` because a chart's templates are
8/// where most of its mistakes live, and editing one without touching a `.yaml`
9/// is the ordinary case.
10pub const EXTS: &[&str] = &[".yaml", ".yml", ".tpl"];
11
12/// What marks a directory as a chart. `helm lint` wants the chart DIRECTORY,
13/// so a staged `templates/deployment.yaml` has to be resolved upward to the
14/// directory holding this file.
15pub const MARKERS: &[&str] = &["Chart.yaml"];
16
17pub fn run(settings: &crate::config::Settings, _args: &[std::ffi::OsString]) -> Outcome {
18    let files = staged_files(EXTS);
19    if files.is_empty() {
20        return Outcome::Passed;
21    }
22    let root = repo_root();
23    // Resolve the staged files to the CHARTS they belong to, before asking
24    // whether helm exists: a repository with `.yaml` files and no chart at all
25    // must not be told to install anything.
26    let charts = super::k8s::marker_roots(&root, &files, MARKERS);
27    if charts.is_empty() {
28        return Outcome::Passed;
29    }
30    let Some(bin) = which("helm") else {
31        warn(&format!(
32            "This repo has charts but helm is not installed. Install {}",
33            hl("helm")
34        ));
35        return Outcome::Unavailable;
36    };
37    // ONE invocation per chart, not per file. `Perso/charts` holds ten of
38    // them, and a commit touching four files in one chart must lint that chart
39    // once — `marker_roots` dedupes precisely so this loop can be naive.
40    let mut bad: Vec<&str> = Vec::new();
41    for chart in &charts {
42        // `--` is not available here (helm takes the path positionally), so a
43        // chart directory is passed as-is; `marker_roots` only ever returns
44        // paths it walked up from a staged file, never anything user-supplied
45        // on a command line.
46        let ok_now = Command::new(&bin)
47            .arg("lint")
48            .arg(chart)
49            .current_dir(&root)
50            .stdin(Stdio::null())
51            .status()
52            .map(|s| s.success())
53            .unwrap_or(false);
54        if !ok_now {
55            bad.push(chart);
56        }
57    }
58    if !bad.is_empty() {
59        fail(&format!(
60            "helm lint found issues in {}. Please fix",
61            hl(&bad.join(", "))
62        ));
63        return Outcome::Failed;
64    }
65    ok(
66        settings,
67        &format!(
68            "helm lint passed ({} chart{})",
69            charts.len(),
70            if charts.len() == 1 { "" } else { "s" }
71        ),
72    );
73    Outcome::Passed
74}