helm-rs 0.1.0

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! Decoding of annotation YAML (and JSON) into [`Schema`]: `Schema.UnmarshalYAML`,
//! `BoolOrArrayOfString.UnmarshalYAML`, `StringOrArrayOfString.UnmarshalYAML` and
//! `Schema.UnmarshalJSON` of helm-schema's `pkg/schema/schema.go`.

use std::collections::BTreeMap;

use serde_json::Value;

use super::decode::{Decoder, Hard, Target, Typed, type_error_text};
use super::model::{SIMPLE, Schema, Simple};
use super::yaml::{self, Doc, Kind, YamlError};

const SCHEMA_TYPE: &str = "schema.schemaAlias";

impl Decoder<'_> {
    fn is_null(&self, id: usize) -> bool {
        let node = self.node(self.deref(id));

        node.kind == Kind::Scalar && node.tag == "!!null"
    }

    fn string_list(&mut self, id: usize) -> Hard<Vec<String>> {
        let id = self.deref(id);
        let node = self.node(id);
        let mut out = Vec::new();

        if node.kind != Kind::Sequence {
            let single = self.typed(id, Target::String)?;

            return Ok(vec![match single {
                Typed::Str(s) => s,
                _ => String::new(),
            }]);
        }

        for &child in &node.content {
            if self.is_null(child) {
                out.push("null".to_owned());

                continue;
            }

            if let Typed::Str(s) = self.typed(child, Target::String)? {
                out.push(s);
            }
        }

        Ok(out)
    }

    fn schema_list(&mut self, id: usize, json: bool) -> Hard<Vec<Schema>> {
        let id = self.deref(id);
        let node = self.node(id);
        let mut out = Vec::new();

        if self.is_null(id) {
            return Ok(out);
        }

        if node.kind != Kind::Sequence {
            self.type_problem(id, "!!map", "[]*schema.Schema");

            return Ok(out);
        }

        for &child in &node.content {
            out.push(self.schema(child, json)?);
        }

        Ok(out)
    }

    fn schema_map(&mut self, id: usize, json: bool) -> Hard<Option<BTreeMap<String, Schema>>> {
        let id = self.deref(id);
        let node = self.node(id);

        if self.is_null(id) {
            return Ok(None);
        }

        if node.kind != Kind::Mapping {
            self.type_problem(id, "!!seq", "map[string]*schema.Schema");

            return Ok(Some(BTreeMap::new()));
        }

        let mut out = BTreeMap::new();

        self.unique_keys(id);

        for (key, value) in self.pairs(id)? {
            let key = self.node(key).value.clone();

            out.insert(key, self.schema(value, json)?);
        }

        Ok(Some(out))
    }

    fn any_list(&mut self, id: usize) -> Hard<Vec<Value>> {
        let id = self.deref(id);
        let node = self.node(id);
        let mut out = Vec::new();

        if self.is_null(id) {
            return Ok(out);
        }

        if node.kind != Kind::Sequence {
            self.type_problem(id, "!!map", "[]interface {}");

            return Ok(out);
        }

        for &child in &node.content {
            out.push(self.any(child)?);
        }

        Ok(out)
    }

    fn required(&mut self, id: usize, schema: &mut Schema) -> Hard<()> {
        let id = self.deref(id);
        let node = self.node(id);

        if node.kind == Kind::Sequence {
            let mut strings = Vec::new();

            for &child in &node.content {
                if let Typed::Str(s) = self.typed(child, Target::String)? {
                    strings.push(s);
                }
            }

            schema.required.strings = strings;

            return Ok(());
        }

        if node.kind == Kind::Scalar && node.tag == "!!bool" {
            if let Typed::Bool(b) = self.typed(id, Target::Bool)? {
                schema.required.flag = b;
            }

            return Ok(());
        }

        Err(YamlError::plain_raw(
            "could not unmarshal [] to slice of string or bool",
        ))
    }

    fn simple(
        &mut self,
        id: usize,
        name: &'static str,
        kind: Simple,
        schema: &mut Schema,
    ) -> Hard<()> {
        let target = match kind {
            Simple::Str => Target::String,
            Simple::Float => Target::Float,
            Simple::Int => Target::Int,
            Simple::Bool => Target::Bool,
        };
        let value = match self.typed(id, target)? {
            Typed::Str(s) if !s.is_empty() => Some(Value::String(s)),
            Typed::Float(f) => serde_json::Number::from_f64(f).map(Value::Number),
            Typed::Int(i) => Some(Value::from(i)),
            Typed::Bool(true) => Some(Value::Bool(true)),
            _ => None,
        };

        if let Some(value) = value {
            schema.simple.insert(name, value);
        }

        Ok(())
    }

    /// Decodes a node into a schema (`Schema.UnmarshalYAML`; `json` adds the `$defs` merge of
    /// `Schema.UnmarshalJSON`).
    pub(super) fn schema(&mut self, id: usize, json: bool) -> Hard<Schema> {
        let (id, entered) = self.enter(id)?;
        let schema = self.schema_node(id, json);

        self.leave(entered);

        schema
    }

    fn schema_node(&mut self, id: usize, json: bool) -> Hard<Schema> {
        let node = self.node(id);
        let mut schema = Schema::default();

        if self.is_null(id) {
            return Ok(schema);
        }

        if node.kind != Kind::Mapping {
            let tag = if node.kind == Kind::Sequence {
                "!!seq"
            } else {
                "!!map"
            };

            self.type_problem(id, tag, SCHEMA_TYPE);

            return Ok(schema);
        }

        self.unique_keys(id);

        let mut defs = None;
        let own: Vec<usize> = node.content.chunks(2).map(|pair| pair[0]).collect();

        for (key_id, value) in self.pairs(id)? {
            let key = self.node(key_id).value.clone();

            if let Some((name, kind)) = SIMPLE.iter().find(|(name, _)| *name == key) {
                self.simple(value, name, *kind, &mut schema)?;

                continue;
            }

            match key.as_str() {
                "type" => schema.types = self.string_list(value)?,
                "required" => self.required(value, &mut schema)?,
                "properties" => schema.properties = self.schema_map(value, json)?,
                "patternProperties" => {
                    schema.pattern_properties = self.schema_map(value, json)?;
                }
                "definitions" => schema.definitions = self.schema_map(value, json)?,
                "$defs" if json => defs = self.schema_map(value, json)?,
                "anyOf" => schema.any_of = self.schema_list(value, json)?,
                "allOf" => schema.all_of = self.schema_list(value, json)?,
                "oneOf" => schema.one_of = self.schema_list(value, json)?,
                "items" | "not" | "if" | "then" | "else" | "contains" | "propertyNames" => {
                    let child = self.optional_schema(value, json)?;

                    match key.as_str() {
                        "items" => schema.items = child,
                        "not" => schema.not = child,
                        "if" => schema.if_ = child,
                        "then" => schema.then = child,
                        "else" => schema.else_ = child,
                        "contains" => schema.contains = child,
                        _ => schema.property_names = child,
                    }
                }
                "additionalProperties" => schema.additional_properties = non_null(self.any(value)?),
                "additionalItems" => schema.additional_items = non_null(self.any(value)?),
                "default" => schema.default = non_null(self.any(value)?),
                "const" => {
                    schema.const_ = non_null(self.any(value)?);
                    schema.const_was_set = true;
                }
                "const-from-value" => {
                    if let Typed::Bool(b) = self.typed(value, Target::Bool)? {
                        schema.const_from_value = b;
                    }
                }
                "uniqueItems" => {
                    if let Typed::Bool(b) = self.typed(value, Target::Bool)? {
                        schema.unique_items = b;
                    }
                }
                "$ref" => schema.reference = self.text(value)?,
                "title" => schema.title = self.text(value)?,
                "description" => schema.description = self.text(value)?,
                "examples" => schema.examples = self.any_list(value)?,
                "enum" => schema.enum_ = self.any_list(value)?,
                "dependencies" => schema.dependencies = Some(self.any_map(value)?),
                _ if key.starts_with("x-") && own.contains(&key_id) => {
                    schema.custom.insert(key, self.any(value)?);
                }
                _ => {}
            }
        }

        if let Some(defs) = defs {
            let target = schema.definitions.get_or_insert_with(BTreeMap::new);

            for (name, def) in defs {
                target.entry(name).or_insert(def);
            }
        }

        Ok(schema)
    }

    fn optional_schema(&mut self, id: usize, json: bool) -> Hard<Option<Box<Schema>>> {
        if self.is_null(id) {
            return Ok(None);
        }

        Ok(Some(Box::new(self.schema(id, json)?)))
    }

    fn text(&mut self, id: usize) -> Hard<String> {
        Ok(match self.typed(id, Target::String)? {
            Typed::Str(s) => s,
            _ => String::new(),
        })
    }

    fn any_map(&mut self, id: usize) -> Hard<BTreeMap<String, Value>> {
        let id = self.deref(id);
        let node = self.node(id);
        let mut out = BTreeMap::new();

        if self.is_null(id) {
            return Ok(out);
        }

        if node.kind != Kind::Mapping {
            self.type_problem(id, "!!seq", "map[string]interface {}");

            return Ok(out);
        }

        self.unique_keys(id);

        for (key, value) in self.pairs(id)? {
            let key = self.node(key).value.clone();

            out.insert(key, self.any(value)?);
        }

        Ok(out)
    }
}

fn non_null(value: Value) -> Option<Value> {
    if value.is_null() { None } else { Some(value) }
}

/// Decodes `text` as a schema the way `yaml.Unmarshal(text, &schema)` (or `json.Unmarshal` when
/// `json` is set) does. An empty text gives an empty schema. Errors carry Go's message text.
pub(super) fn parse_schema(text: &str, json: bool) -> Result<Schema, String> {
    if json {
        check_json(text)?;
    }

    let doc: Doc = yaml::parse(text).map_err(|e| e.to_string())?;
    let mut decoder = Decoder::new(&doc);
    let Some(root) = doc.root else {
        return Ok(Schema::default());
    };
    let content = doc.nodes[root].content.first().copied();
    let result = match content {
        Some(id) => decoder.schema(id, json),
        None => Ok(Schema::default()),
    };

    match result {
        Err(e) => Err(e.to_string()),
        Ok(_) if !decoder.errors.is_empty() => Err(type_error_text(&decoder.errors)),
        Ok(schema) => Ok(if json {
            schema.with_defs_rewritten()
        } else {
            schema
        }),
    }
}

/// The syntax check `json.Unmarshal` does before it decodes anything: YAML would accept texts
/// that are not JSON. The wording of the error follows Go for empty and truncated input; for other
/// problems it names the offending character, without Go's description of the context.
fn check_json(text: &str) -> Result<(), String> {
    let Err(error) = serde_json::from_str::<serde::de::IgnoredAny>(text) else {
        return Ok(());
    };

    if error.is_eof() {
        return Err("unexpected end of JSON input".to_owned());
    }

    let found = text
        .lines()
        .nth(error.line().saturating_sub(1))
        .and_then(|line| line.get(error.column().saturating_sub(1)..))
        .and_then(|rest| rest.chars().next())
        .unwrap_or(' ');

    Err(format!(
        "invalid character {found:?} looking for beginning of value"
    ))
}

#[cfg(test)]
mod tests;