1mod coalesce;
19pub mod generate;
20mod resolver;
21
22pub use generate::{
23 Annotation, GenerateError, GenerateOptions, SkipField, annotations, generate, generate_chart,
24};
25
26use std::fmt;
27
28use serde_json::Value;
29
30use crate::chart::Chart;
31
32#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct Violation {
35 pub path: String,
37 pub message: String,
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct ChartViolations {
44 pub chart: String,
46 pub violations: Vec<Violation>,
48}
49
50#[derive(Debug, thiserror::Error)]
52pub enum Error {
53 #[error("{}", Report(.0))]
55 Invalid(Vec<ChartViolations>),
56 #[error(
59 "values.schema.json of chart {chart} refers to {uri}; resolving remote references needs the `schema-remote-refs` feature"
60 )]
61 RemoteRef {
62 chart: String,
64 uri: String,
66 },
67 #[error("{0}")]
69 Unsupported(&'static str),
70}
71
72struct Report<'a>(&'a [ChartViolations]);
74
75impl fmt::Display for Report<'_> {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 writeln!(
78 f,
79 "values don't meet the specifications of the schema(s) in the following chart(s):"
80 )?;
81
82 for chart in self.0 {
83 writeln!(f, "{}:", chart.chart)?;
84
85 for v in &chart.violations {
86 if v.path.is_empty() && !v.message.starts_with("missing") {
87 writeln!(f, "{}", v.message)?;
88 } else {
89 writeln!(f, "- at '{}': {}", v.path, v.message)?;
90 }
91 }
92 }
93
94 Ok(())
95 }
96}
97
98pub fn validate(chart: &Chart, values: &Value) -> Result<(), Error> {
104 let mut failures = Vec::new();
105
106 collect(chart, chart.name(), values, &mut failures)?;
107
108 if failures.is_empty() {
109 return Ok(());
110 }
111
112 Err(Error::Invalid(failures))
113}
114
115pub fn final_values(chart: &Chart, user_values: &Value) -> Result<Value, Error> {
124 if !chart.dependencies.is_empty() {
125 return Err(Error::Unsupported(
126 "final values of a chart with subcharts need Helm's coalescing; use the backend",
127 ));
128 }
129
130 coalesce::coalesce(chart, user_values)
131}
132
133fn collect(
135 chart: &Chart,
136 label: &str,
137 values: &Value,
138 out: &mut Vec<ChartViolations>,
139) -> Result<(), Error> {
140 let violations = check_one(chart, label, values)?;
141
142 if !violations.is_empty() {
143 out.push(ChartViolations {
144 chart: label.to_owned(),
145 violations,
146 });
147 }
148
149 for sub in &chart.dependencies {
150 for key in keys_of(chart, sub) {
151 match values.get(&key) {
152 None | Some(Value::Null) => {}
153 Some(inner @ Value::Object(_)) => collect(sub, &key, inner, out)?,
154 Some(other) => out.push(ChartViolations {
155 chart: key,
156 violations: vec![Violation {
157 path: String::new(),
158 message: format!(
159 "invalid type for values: expected object (map), got {}",
160 go_type(other)
161 ),
162 }],
163 }),
164 }
165 }
166 }
167
168 Ok(())
169}
170
171fn keys_of(parent: &Chart, sub: &Chart) -> Vec<String> {
173 let declared: Vec<String> = parent
174 .metadata
175 .dependencies
176 .iter()
177 .flatten()
178 .filter(|d| d.name == sub.name())
179 .map(|d| {
180 if d.alias.is_empty() {
181 d.name.clone()
182 } else {
183 d.alias.clone()
184 }
185 })
186 .collect();
187
188 if declared.is_empty() {
189 vec![sub.name().to_owned()]
190 } else {
191 declared
192 }
193}
194
195fn go_type(value: &Value) -> &'static str {
197 match value {
198 Value::Bool(_) => "bool",
199 Value::Number(_) => "float64",
200 Value::String(_) => "string",
201 Value::Array(_) => "[]interface {}",
202 _ => "map[string]interface {}",
203 }
204}
205
206fn check_one(chart: &Chart, label: &str, values: &Value) -> Result<Vec<Violation>, Error> {
208 let Some(raw) = &chart.schema_raw else {
209 return Ok(Vec::new());
210 };
211 let whole = |message: String| {
212 vec![Violation {
213 path: String::new(),
214 message,
215 }]
216 };
217 let schema: Value = match serde_json::from_slice(raw) {
218 Ok(schema) => schema,
219 Err(e) => return Ok(whole(e.to_string())),
220 };
221 let (resolver, refused) = resolver::Resolver::new();
222 let validator = jsonschema::options()
223 .with_base_uri("file:///values.schema.json")
224 .with_retriever(resolver)
225 .build(&schema);
226 let validator = match validator {
227 Ok(validator) => validator,
228 Err(e) => {
229 let uri = refused.lock().expect("lock is not poisoned").take();
230
231 return match uri {
232 Some(uri) => Err(Error::RemoteRef {
233 chart: label.to_owned(),
234 uri,
235 }),
236 None => Ok(whole(e.to_string())),
237 };
238 }
239 };
240 let mut violations: Vec<Violation> = validator
241 .iter_errors(values)
242 .map(|e| Violation {
243 path: e.instance_path().to_string(),
244 message: e.to_string(),
245 })
246 .collect();
247
248 violations.sort_by(|a, b| a.path.cmp(&b.path));
249
250 Ok(violations)
251}
252
253#[cfg(test)]
254mod tests;