mod coalesce;
pub mod generate;
mod resolver;
pub use generate::{
Annotation, GenerateError, GenerateOptions, SkipField, annotations, generate, generate_chart,
};
use std::fmt;
use serde_json::Value;
use crate::chart::Chart;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Violation {
pub path: String,
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChartViolations {
pub chart: String,
pub violations: Vec<Violation>,
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("{}", Report(.0))]
Invalid(Vec<ChartViolations>),
#[error(
"values.schema.json of chart {chart} refers to {uri}; resolving remote references needs the `schema-remote-refs` feature"
)]
RemoteRef {
chart: String,
uri: String,
},
#[error("{0}")]
Unsupported(&'static str),
}
struct Report<'a>(&'a [ChartViolations]);
impl fmt::Display for Report<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(
f,
"values don't meet the specifications of the schema(s) in the following chart(s):"
)?;
for chart in self.0 {
writeln!(f, "{}:", chart.chart)?;
for v in &chart.violations {
if v.path.is_empty() && !v.message.starts_with("missing") {
writeln!(f, "{}", v.message)?;
} else {
writeln!(f, "- at '{}': {}", v.path, v.message)?;
}
}
}
Ok(())
}
}
pub fn validate(chart: &Chart, values: &Value) -> Result<(), Error> {
let mut failures = Vec::new();
collect(chart, chart.name(), values, &mut failures)?;
if failures.is_empty() {
return Ok(());
}
Err(Error::Invalid(failures))
}
pub fn final_values(chart: &Chart, user_values: &Value) -> Result<Value, Error> {
if !chart.dependencies.is_empty() {
return Err(Error::Unsupported(
"final values of a chart with subcharts need Helm's coalescing; use the backend",
));
}
coalesce::coalesce(chart, user_values)
}
fn collect(
chart: &Chart,
label: &str,
values: &Value,
out: &mut Vec<ChartViolations>,
) -> Result<(), Error> {
let violations = check_one(chart, label, values)?;
if !violations.is_empty() {
out.push(ChartViolations {
chart: label.to_owned(),
violations,
});
}
for sub in &chart.dependencies {
for key in keys_of(chart, sub) {
match values.get(&key) {
None | Some(Value::Null) => {}
Some(inner @ Value::Object(_)) => collect(sub, &key, inner, out)?,
Some(other) => out.push(ChartViolations {
chart: key,
violations: vec![Violation {
path: String::new(),
message: format!(
"invalid type for values: expected object (map), got {}",
go_type(other)
),
}],
}),
}
}
}
Ok(())
}
fn keys_of(parent: &Chart, sub: &Chart) -> Vec<String> {
let declared: Vec<String> = parent
.metadata
.dependencies
.iter()
.flatten()
.filter(|d| d.name == sub.name())
.map(|d| {
if d.alias.is_empty() {
d.name.clone()
} else {
d.alias.clone()
}
})
.collect();
if declared.is_empty() {
vec![sub.name().to_owned()]
} else {
declared
}
}
fn go_type(value: &Value) -> &'static str {
match value {
Value::Bool(_) => "bool",
Value::Number(_) => "float64",
Value::String(_) => "string",
Value::Array(_) => "[]interface {}",
_ => "map[string]interface {}",
}
}
fn check_one(chart: &Chart, label: &str, values: &Value) -> Result<Vec<Violation>, Error> {
let Some(raw) = &chart.schema_raw else {
return Ok(Vec::new());
};
let whole = |message: String| {
vec![Violation {
path: String::new(),
message,
}]
};
let schema: Value = match serde_json::from_slice(raw) {
Ok(schema) => schema,
Err(e) => return Ok(whole(e.to_string())),
};
let (resolver, refused) = resolver::Resolver::new();
let validator = jsonschema::options()
.with_base_uri("file:///values.schema.json")
.with_retriever(resolver)
.build(&schema);
let validator = match validator {
Ok(validator) => validator,
Err(e) => {
let uri = refused.lock().expect("lock is not poisoned").take();
return match uri {
Some(uri) => Err(Error::RemoteRef {
chart: label.to_owned(),
uri,
}),
None => Ok(whole(e.to_string())),
};
}
};
let mut violations: Vec<Violation> = validator
.iter_errors(values)
.map(|e| Violation {
path: e.instance_path().to_string(),
message: e.to_string(),
})
.collect();
violations.sort_by(|a, b| a.path.cmp(&b.path));
Ok(violations)
}
#[cfg(test)]
mod tests;