helm-rs 0.1.2

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! Generation of `values.schema.json` from an annotated `values.yaml`, a native port of
//! [dadav/helm-schema](https://github.com/dadav/helm-schema) 0.24.0 (commit
//! `52bc2fd182c393c0453f5fc08b7cac68c8971a68`). The output equals helm-schema's as a JSON
//! value, with the same alphabetical key order.
//!
//! The Go files mirrored: `pkg/schema/schema.go` (annotations, inference, validation),
//! `pkg/schema/definitions.go`, `pkg/schema/values_merge.go`, `pkg/schema/worker.go`,
//! `pkg/chart/graph.go` and `cmd/helm-schema/main.go` (dependency merging), `pkg/util/file.go`
//! (`--uncomment`) and helm-docs v1.14.2 `pkg/helm/comment.go`. The YAML layer in `yaml` is a
//! port of `gopkg.in/yaml.v3` v3.0.1, so comment attribution matches the Go tool.
//!
//! The port keeps the shape of the Go code (long state functions, structs of flags), so the
//! matching pedantic lints are allowed in this module tree.
//!
//! Known differences from the Go tool are listed in the crate's fixture README
//! (`tests/fixtures/schema-gen/README.md`).

#![allow(
    clippy::assigning_clones,
    clippy::similar_names,
    clippy::struct_excessive_bools,
    clippy::too_many_lines
)]

mod annotation;
mod comments;
mod constraint;
mod decode;
mod deps;
mod error;
mod finish;
mod helm_docs;
mod infer;
mod merge_ops;
mod model;
mod options;
mod refs;
mod schema_decode;
mod schema_value;
mod tree_ops;
mod types;
mod uncomment;
mod validate;
mod yaml;

use std::collections::BTreeMap;

use jsonschema::{Draft, Retrieve, Uri};
use serde_json::Value;

use crate::chart::Chart;

pub use annotation::{Annotation, annotations};
pub use error::{GenerateError, Result};
pub use options::{GenerateOptions, SkipField};

use infer::Walker;
use model::Schema;
use yaml::{Kind, Node};

struct StubRetriever;

impl Retrieve for StubRetriever {
    fn retrieve(
        &self,
        _uri: &Uri<String>,
    ) -> std::result::Result<Value, Box<dyn std::error::Error + Send + Sync>> {
        Ok(Value::Bool(true))
    }
}

/// The text helm-schema reads: `\r\n` becomes `\n`, and `--uncomment` is applied.
fn prepare(text: &str, options: &GenerateOptions) -> String {
    let text = text.replace("\r\n", "\n");

    if options.uncomment {
        uncomment::remove_comments(&text)
    } else {
        text
    }
}

/// Parses a values file; an empty or `null` document is an empty mapping, as Helm reads it.
fn parse_values(text: &str) -> Result<yaml::Doc> {
    let mut doc = yaml::parse(text)?;

    match doc.root {
        None => {
            let mut mapping = Node::new(Kind::Mapping);
            let mut document = Node::new(Kind::Document);

            mapping.tag = "!!map".to_owned();
            document.content = vec![doc.add(mapping)];
            doc.root = Some(doc.add(document));
        }
        Some(root) => {
            if let Some(&child) = doc.nodes[root].content.first()
                && doc.nodes[child].tag == "!!null"
                && doc.nodes[child].kind == Kind::Scalar
            {
                let node = &mut doc.nodes[child];

                node.kind = Kind::Mapping;
                node.tag = "!!map".to_owned();
                node.value.clear();
                node.style = yaml::Style::default();
            }
        }
    }

    Ok(doc)
}

fn values_schema(
    text: &str,
    options: &GenerateOptions,
    files: &BTreeMap<String, String>,
) -> Result<Schema> {
    let doc = parse_values(&prepare(text, options))?;
    let root = doc.root.expect("parse_values always sets a root");

    Walker::new(doc, options, files).document(root)
}

/// Hoists definitions, serialises and checks that the result compiles as Draft 7.
fn finish(mut schema: Schema) -> Result<Value> {
    schema.hoist_definitions();

    let value = schema.to_value();

    jsonschema::options()
        .with_draft(Draft::Draft7)
        .with_retriever(StubRetriever)
        .build(&value)
        .map_err(|e| {
            GenerateError::schema("generated schema is not valid".to_owned(), e.to_string())
        })?;

    Ok(value)
}

/// Generates the schema of one `values.yaml`, without dependencies (`helm-schema` run with
/// `--no-dependencies` on a chart that only has this file).
///
/// # Errors
/// [`GenerateError`] for invalid YAML, a malformed annotation (naming the line inside the
/// annotation block), an unresolvable `$ref` or an invalid result.
pub fn generate(values_yaml: &str, options: &GenerateOptions) -> Result<Value> {
    finish(values_schema(values_yaml, options, &options.files)?)
}

fn chart_schema(
    chart: &Chart,
    options: &GenerateOptions,
    patches: &[Vec<String>],
    dependency: bool,
) -> Result<Schema> {
    let mut files = options.files.clone();

    files.extend(chart.files.iter().map(|f| {
        (
            f.name.clone(),
            String::from_utf8_lossy(&f.data).into_owned(),
        )
    }));

    let existing = chart
        .schema_raw
        .as_deref()
        .filter(|_| dependency && options.keep_existing_dep_schemas)
        .and_then(|raw| std::str::from_utf8(raw).ok())
        .and_then(|text| schema_decode::parse_schema(text, true).ok());
    let mut schema = if let Some(schema) = existing {
        schema
    } else {
        let text = match &chart.values_raw {
            Some(raw) => String::from_utf8_lossy(raw).into_owned(),
            None => chart.values.to_string(),
        };

        values_schema(&text, options, &files)?
    };

    deps::patch_conditions(&mut schema, patches);

    if options.no_dependencies {
        return Ok(schema);
    }

    let bound = deps::bind(chart, &options.dependencies_filter)?;
    let child_patches = deps::condition_patches(&bound, &options.dependencies_filter);

    for entry in &bound {
        let Some(index) = entry.child else { continue };
        let child = &chart.dependencies[index];
        let patches = child_patches.get(&index).map_or(&[][..], Vec::as_slice);
        let mut child_schema = chart_schema(child, options, patches, true)?;

        child_schema.hoist_definitions();
        deps::merge_dependency(&mut schema, entry.dep, child, child_schema);
    }

    if options.skip_dependencies_schema_validation {
        deps::skip_validation(&mut schema, &bound, &options.dependencies_filter);
    }

    Ok(schema)
}

/// Generates the schema of a loaded chart, with the schemas of the subcharts in `charts/` merged
/// as helm-schema does (nested under the dependency name or alias, `import-values`, library
/// charts, conditions). Relative `$ref`s are read from the chart's files.
///
/// # Errors
/// As [`generate`], plus an ambiguous or invalid dependency binding.
pub fn generate_chart(chart: &Chart, options: &GenerateOptions) -> Result<Value> {
    finish(chart_schema(chart, options, &[], false)?)
}

impl Chart {
    /// The `values.schema.json` helm-schema generates for this chart; see [`generate_chart`].
    ///
    /// # Errors
    /// As [`generate_chart`].
    pub fn generate_schema(&self, options: &GenerateOptions) -> Result<Value> {
        generate_chart(self, options)
    }
}

#[cfg(test)]
mod tests;