helm-rs 0.1.0

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
use crate::cli::{CliCommand, Invocation, flags};
use crate::command::{Lint, LintMessage, LintReport, LintSummary, LintedChart, Severity};
use crate::error::{Error, Result};

const CHART: &str = "==> Linting ";
const SEVERITIES: [(&str, Severity); 4] = [
    ("[UNKNOWN] ", Severity::Unknown),
    ("[INFO] ", Severity::Info),
    ("[WARNING] ", Severity::Warning),
    ("[ERROR] ", Severity::Error),
];

impl CliCommand for Lint {
    fn build(&self, inv: &mut Invocation) -> Result<()> {
        if self.paths.is_empty() {
            return Err(Error::InvalidCommand(
                "helm lint needs at least one chart path".to_owned(),
            ));
        }

        inv.arg("lint");

        for path in &self.paths {
            inv.arg(path);
        }

        inv.values(&self.values)?;
        flags! { inv, self;
            option("--kube-version", kube_version);
            switch("--quiet", quiet);
            switch("--skip-schema-validation", skip_schema_validation);
            switch("--strict", strict);
            switch("--with-subcharts", with_subcharts);
        }

        Ok(())
    }

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

    /// Helm exits 1 when a chart failed but still prints every finding on stdout (the totals go
    /// to stderr then). Without a `==> Linting` section Helm failed before linting, which stays
    /// an error.
    fn parse_failure(&self, stdout: &str, stderr: &str) -> Option<Result<LintReport>> {
        stdout
            .lines()
            .any(|line| line.starts_with(CHART))
            .then(|| Ok(self.report(stdout, stderr)))
    }
}

/// One chart section under construction.
struct Section {
    chart: LintedChart,
    last: Last,
}

/// What the previous line of a section was, so a continuation line knows what it continues.
enum Last {
    Message,
    Error,
    Nothing,
}

impl Lint {
    /// Reads the sections of `stdout`; the totals come from whichever of `stdout` and `totals`
    /// has them.
    fn report(&self, stdout: &str, totals: &str) -> LintReport {
        let mut charts: Vec<LintedChart> = Vec::new();
        let mut section: Option<Section> = None;

        for line in stdout.lines() {
            if let Some(path) = line.strip_prefix(CHART) {
                charts.extend(section.take().map(|s| self.finish(s.chart)));
                section = Some(Section {
                    chart: LintedChart {
                        path: path.to_owned(),
                        messages: Vec::new(),
                        errors: Vec::new(),
                        failed: false,
                    },
                    last: Last::Nothing,
                });

                continue;
            }

            let Some(open) = section.as_mut() else {
                continue;
            };

            if line.is_empty() {
                charts.extend(section.take().map(|s| self.finish(s.chart)));

                continue;
            }

            open.read(line);
        }

        charts.extend(section.map(|s| self.finish(s.chart)));

        LintReport {
            charts,
            summary: summary(stdout).or_else(|| summary(totals)),
        }
    }

    /// Decides whether Helm counts the chart as failed: an error finding or failure, and with
    /// `--strict` a warning (`action.Lint.Run`).
    fn finish(&self, mut chart: LintedChart) -> LintedChart {
        let tolerance = if self.strict {
            Severity::Warning
        } else {
            Severity::Error
        };

        chart.failed =
            !chart.errors.is_empty() || chart.messages.iter().any(|m| m.severity >= tolerance);

        chart
    }
}

impl Section {
    /// Reads one non-blank line of the section.
    fn read(&mut self, line: &str) {
        if let Some((severity, rest)) = SEVERITIES
            .iter()
            .find_map(|(tag, severity)| line.strip_prefix(tag).map(|rest| (*severity, rest)))
        {
            let (path, message) = rest.split_once(": ").unwrap_or((rest, ""));

            self.chart.messages.push(LintMessage {
                severity,
                path: path.to_owned(),
                message: message.to_owned(),
            });
            self.last = Last::Message;
        } else if let (Last::Nothing, Some(error)) = (&self.last, line.strip_prefix("Error ")) {
            self.chart.errors.push(error.to_owned());
            self.last = Last::Error;
        } else if let Some(text) = self.continued() {
            text.push('\n');
            text.push_str(line);
        }
    }

    /// The text the next continuation line extends.
    fn continued(&mut self) -> Option<&mut String> {
        match self.last {
            Last::Message => self.chart.messages.last_mut().map(|m| &mut m.message),
            Last::Error => self.chart.errors.last_mut(),
            Last::Nothing => None,
        }
    }
}

/// Finds `N chart(s) linted, M chart(s) failed`.
fn summary(text: &str) -> Option<LintSummary> {
    text.lines().find_map(|line| {
        let line = line.strip_prefix("Error: ").unwrap_or(line);
        let (linted, failed) = line.split_once(" chart(s) linted, ")?;
        let failed = failed.strip_suffix(" chart(s) failed")?;

        Some(LintSummary {
            linted: linted.parse().ok()?,
            failed: failed.parse().ok()?,
        })
    })
}