helm-rs 0.1.1

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! The final passes over a generated schema: `HoistDefinitions` and `FixRequiredProperties` of
//! helm-schema's `pkg/schema/schema.go` and `definitions.go`.

use std::collections::BTreeMap;

use super::model::Schema;
use super::tree_ops::Slot;

impl Schema {
    /// `HoistDefinitions`: nested `definitions` move to the root; the first one of a name wins.
    pub(super) fn hoist_definitions(&mut self) {
        let mut root = self.definitions.take().unwrap_or_default();

        self.collect_definitions(&mut root);
        self.definitions = Some(root);
    }

    fn collect_definitions(&mut self, root: &mut BTreeMap<String, Schema>) {
        let own = [
            &mut self.items,
            &mut self.if_,
            &mut self.then,
            &mut self.else_,
            &mut self.not,
        ];
        let mut children: Vec<&mut Schema> = Vec::new();

        if let Some(map) = &mut self.properties {
            children.extend(map.values_mut());
        }

        if let Some(map) = &mut self.pattern_properties {
            children.extend(map.values_mut());
        }

        children.extend(own.into_iter().flatten().map(|b| &mut **b));
        children.extend(self.all_of.iter_mut());
        children.extend(self.any_of.iter_mut());
        children.extend(self.one_of.iter_mut());

        for child in children {
            child.collect_definitions(root);

            if let Some(defs) = child.definitions.take() {
                for (name, def) in defs {
                    root.entry(name).or_insert(def);
                }
            }
        }
    }

    /// `FixRequiredProperties`: a child's `required: true` becomes a name in this `required`;
    /// a schema with `properties` gets the `object` type. Go iterates a map here, so the order
    /// of the names added is random there and sorted here.
    pub(super) fn fix_required(&mut self) {
        let mut added = Vec::new();

        if let Some(properties) = &mut self.properties {
            for (name, child) in properties.iter_mut() {
                child.fix_required();

                if child.required.flag && !self.required.strings.contains(name) {
                    added.push(name.clone());
                }
            }
        }

        self.required.strings.extend(added);

        if self.properties.is_some() && !self.types.iter().any(|t| t == "object") {
            self.types.push("object".to_owned());
        }

        for (slot, child) in self.children_mut() {
            if slot != Slot::Property {
                child.fix_required();
            }
        }
    }
}