Skip to main content

helm_rs/schema/generate/
mod.rs

1//! Generation of `values.schema.json` from an annotated `values.yaml`, a native port of
2//! [dadav/helm-schema](https://github.com/dadav/helm-schema) 0.24.0 (commit
3//! `52bc2fd182c393c0453f5fc08b7cac68c8971a68`). The output equals helm-schema's as a JSON
4//! value, with the same alphabetical key order.
5//!
6//! The Go files mirrored: `pkg/schema/schema.go` (annotations, inference, validation),
7//! `pkg/schema/definitions.go`, `pkg/schema/values_merge.go`, `pkg/schema/worker.go`,
8//! `pkg/chart/graph.go` and `cmd/helm-schema/main.go` (dependency merging), `pkg/util/file.go`
9//! (`--uncomment`) and helm-docs v1.14.2 `pkg/helm/comment.go`. The YAML layer in `yaml` is a
10//! port of `gopkg.in/yaml.v3` v3.0.1, so comment attribution matches the Go tool.
11//!
12//! The port keeps the shape of the Go code (long state functions, structs of flags), so the
13//! matching pedantic lints are allowed in this module tree.
14//!
15//! Known differences from the Go tool are listed in the crate's fixture README
16//! (`tests/fixtures/schema-gen/README.md`).
17
18#![allow(
19    clippy::assigning_clones,
20    clippy::similar_names,
21    clippy::struct_excessive_bools,
22    clippy::too_many_lines
23)]
24
25mod annotation;
26mod comments;
27mod constraint;
28mod decode;
29mod deps;
30mod error;
31mod finish;
32mod helm_docs;
33mod infer;
34mod merge_ops;
35mod model;
36mod options;
37mod refs;
38mod schema_decode;
39mod schema_value;
40mod tree_ops;
41mod types;
42mod uncomment;
43mod validate;
44mod yaml;
45
46use std::collections::BTreeMap;
47
48use jsonschema::{Draft, Retrieve, Uri};
49use serde_json::Value;
50
51use crate::chart::Chart;
52
53pub use annotation::{Annotation, annotations};
54pub use error::{GenerateError, Result};
55pub use options::{GenerateOptions, SkipField};
56
57use infer::Walker;
58use model::Schema;
59use yaml::{Kind, Node};
60
61struct StubRetriever;
62
63impl Retrieve for StubRetriever {
64    fn retrieve(
65        &self,
66        _uri: &Uri<String>,
67    ) -> std::result::Result<Value, Box<dyn std::error::Error + Send + Sync>> {
68        Ok(Value::Bool(true))
69    }
70}
71
72/// The text helm-schema reads: `\r\n` becomes `\n`, and `--uncomment` is applied.
73fn prepare(text: &str, options: &GenerateOptions) -> String {
74    let text = text.replace("\r\n", "\n");
75
76    if options.uncomment {
77        uncomment::remove_comments(&text)
78    } else {
79        text
80    }
81}
82
83/// Parses a values file; an empty or `null` document is an empty mapping, as Helm reads it.
84fn parse_values(text: &str) -> Result<yaml::Doc> {
85    let mut doc = yaml::parse(text)?;
86
87    match doc.root {
88        None => {
89            let mut mapping = Node::new(Kind::Mapping);
90            let mut document = Node::new(Kind::Document);
91
92            mapping.tag = "!!map".to_owned();
93            document.content = vec![doc.add(mapping)];
94            doc.root = Some(doc.add(document));
95        }
96        Some(root) => {
97            if let Some(&child) = doc.nodes[root].content.first()
98                && doc.nodes[child].tag == "!!null"
99                && doc.nodes[child].kind == Kind::Scalar
100            {
101                let node = &mut doc.nodes[child];
102
103                node.kind = Kind::Mapping;
104                node.tag = "!!map".to_owned();
105                node.value.clear();
106                node.style = yaml::Style::default();
107            }
108        }
109    }
110
111    Ok(doc)
112}
113
114fn values_schema(
115    text: &str,
116    options: &GenerateOptions,
117    files: &BTreeMap<String, String>,
118) -> Result<Schema> {
119    let doc = parse_values(&prepare(text, options))?;
120    let root = doc.root.expect("parse_values always sets a root");
121
122    Walker::new(doc, options, files).document(root)
123}
124
125/// Hoists definitions, serialises and checks that the result compiles as Draft 7.
126fn finish(mut schema: Schema) -> Result<Value> {
127    schema.hoist_definitions();
128
129    let value = schema.to_value();
130
131    jsonschema::options()
132        .with_draft(Draft::Draft7)
133        .with_retriever(StubRetriever)
134        .build(&value)
135        .map_err(|e| {
136            GenerateError::schema("generated schema is not valid".to_owned(), e.to_string())
137        })?;
138
139    Ok(value)
140}
141
142/// Generates the schema of one `values.yaml`, without dependencies (`helm-schema` run with
143/// `--no-dependencies` on a chart that only has this file).
144///
145/// # Errors
146/// [`GenerateError`] for invalid YAML, a malformed annotation (naming the line inside the
147/// annotation block), an unresolvable `$ref` or an invalid result.
148pub fn generate(values_yaml: &str, options: &GenerateOptions) -> Result<Value> {
149    finish(values_schema(values_yaml, options, &options.files)?)
150}
151
152fn chart_schema(
153    chart: &Chart,
154    options: &GenerateOptions,
155    patches: &[Vec<String>],
156    dependency: bool,
157) -> Result<Schema> {
158    let mut files = options.files.clone();
159
160    files.extend(chart.files.iter().map(|f| {
161        (
162            f.name.clone(),
163            String::from_utf8_lossy(&f.data).into_owned(),
164        )
165    }));
166
167    let existing = chart
168        .schema_raw
169        .as_deref()
170        .filter(|_| dependency && options.keep_existing_dep_schemas)
171        .and_then(|raw| std::str::from_utf8(raw).ok())
172        .and_then(|text| schema_decode::parse_schema(text, true).ok());
173    let mut schema = if let Some(schema) = existing {
174        schema
175    } else {
176        let text = match &chart.values_raw {
177            Some(raw) => String::from_utf8_lossy(raw).into_owned(),
178            None => chart.values.to_string(),
179        };
180
181        values_schema(&text, options, &files)?
182    };
183
184    deps::patch_conditions(&mut schema, patches);
185
186    if options.no_dependencies {
187        return Ok(schema);
188    }
189
190    let bound = deps::bind(chart, &options.dependencies_filter)?;
191    let child_patches = deps::condition_patches(&bound, &options.dependencies_filter);
192
193    for entry in &bound {
194        let Some(index) = entry.child else { continue };
195        let child = &chart.dependencies[index];
196        let patches = child_patches.get(&index).map_or(&[][..], Vec::as_slice);
197        let mut child_schema = chart_schema(child, options, patches, true)?;
198
199        child_schema.hoist_definitions();
200        deps::merge_dependency(&mut schema, entry.dep, child, child_schema);
201    }
202
203    if options.skip_dependencies_schema_validation {
204        deps::skip_validation(&mut schema, &bound, &options.dependencies_filter);
205    }
206
207    Ok(schema)
208}
209
210/// Generates the schema of a loaded chart, with the schemas of the subcharts in `charts/` merged
211/// as helm-schema does (nested under the dependency name or alias, `import-values`, library
212/// charts, conditions). Relative `$ref`s are read from the chart's files.
213///
214/// # Errors
215/// As [`generate`], plus an ambiguous or invalid dependency binding.
216pub fn generate_chart(chart: &Chart, options: &GenerateOptions) -> Result<Value> {
217    finish(chart_schema(chart, options, &[], false)?)
218}
219
220impl Chart {
221    /// The `values.schema.json` helm-schema generates for this chart; see [`generate_chart`].
222    ///
223    /// # Errors
224    /// As [`generate_chart`].
225    pub fn generate_schema(&self, options: &GenerateOptions) -> Result<Value> {
226        generate_chart(self, options)
227    }
228}
229
230#[cfg(test)]
231mod tests;