helm-rs 0.1.1

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! `NewSchema` and `Schema.MarshalJSON` of helm-schema's `pkg/schema/schema.go`: how a schema is
//! written as JSON. Keys are sorted (Go marshals a map), custom annotations are inlined, and numbers
//! are normalised like Go's float64 round trip.

use serde_json::{Map, Number, Value};

use super::model::Schema;

impl Schema {
    /// `NewSchema`: an empty schema, or one of the given type with an empty `required`.
    pub(super) fn new(schema_type: &str) -> Self {
        let mut schema = Self::default();

        if !schema_type.is_empty() {
            schema.types = vec![schema_type.to_owned()];
        }

        schema
    }

    /// The boolean keyword `name`, false when unset.
    pub(super) fn bool_of(&self, name: &str) -> bool {
        self.simple
            .get(name)
            .and_then(Value::as_bool)
            .unwrap_or(false)
    }

    /// `canDropRequired`: a lone scalar or array type has no `required` in the output.
    fn can_drop_required(&self) -> bool {
        self.types.len() == 1
            && matches!(
                self.types[0].as_str(),
                "string" | "number" | "boolean" | "integer" | "null" | "array"
            )
    }

    /// `Schema.MarshalJSON`: keys are sorted (Go marshals a map), custom annotations are
    /// inlined, and numbers are normalised like Go's float64 round trip.
    pub(super) fn to_value(&self) -> Value {
        let mut map = Map::new();

        for (name, value) in [
            ("additionalProperties", &self.additional_properties),
            ("additionalItems", &self.additional_items),
            ("default", &self.default),
            ("const", &self.const_),
        ] {
            if let Some(value) = value {
                map.insert(name.to_owned(), value.clone());
            }
        }

        if self.const_was_set && self.const_.is_none() {
            map.insert("const".to_owned(), Value::Null);
        }

        for (name, schema) in [
            ("then", &self.then),
            ("if", &self.if_),
            ("else", &self.else_),
            ("not", &self.not),
            ("items", &self.items),
            ("contains", &self.contains),
            ("propertyNames", &self.property_names),
        ] {
            if let Some(schema) = schema {
                map.insert(name.to_owned(), schema.to_value());
            }
        }

        for (name, schemas) in [
            ("properties", &self.properties),
            ("patternProperties", &self.pattern_properties),
            ("definitions", &self.definitions),
        ] {
            if let Some(schemas) = schemas
                && !schemas.is_empty()
            {
                let entries = schemas
                    .iter()
                    .map(|(k, v)| (k.clone(), v.to_value()))
                    .collect();

                map.insert(name.to_owned(), Value::Object(entries));
            }
        }

        for (name, schemas) in [
            ("anyOf", &self.any_of),
            ("allOf", &self.all_of),
            ("oneOf", &self.one_of),
        ] {
            if !schemas.is_empty() {
                map.insert(
                    name.to_owned(),
                    schemas.iter().map(Self::to_value).collect(),
                );
            }
        }

        if let Some(dependencies) = &self.dependencies
            && !dependencies.is_empty()
        {
            let entries = dependencies
                .iter()
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect();

            map.insert("dependencies".to_owned(), Value::Object(entries));
        }

        for (name, text) in [
            ("$ref", &self.reference),
            ("title", &self.title),
            ("description", &self.description),
        ] {
            if !text.is_empty() {
                map.insert(name.to_owned(), Value::String(text.clone()));
            }
        }

        for (name, list) in [("examples", &self.examples), ("enum", &self.enum_)] {
            if !list.is_empty() {
                map.insert(name.to_owned(), Value::Array(list.clone()));
            }
        }

        if self.unique_items {
            map.insert("uniqueItems".to_owned(), Value::Bool(true));
        }

        for (name, value) in &self.simple {
            map.insert((*name).to_owned(), value.clone());
        }

        match self.types.len() {
            0 => {}
            1 => {
                map.insert("type".to_owned(), Value::String(self.types[0].clone()));
            }
            _ => {
                map.insert(
                    "type".to_owned(),
                    self.types.iter().cloned().map(Value::String).collect(),
                );
            }
        }

        if !self.can_drop_required() {
            map.insert(
                "required".to_owned(),
                self.required
                    .strings
                    .iter()
                    .cloned()
                    .map(Value::String)
                    .collect(),
            );
        }

        for (name, value) in &self.custom {
            map.insert(name.clone(), value.clone());
        }

        normalise(Value::Object(map))
    }
}

/// Rewrites every number as Go does after `json.Unmarshal` into `interface{}` and back: through
/// float64, so integral values below 1e21 print as integers.
pub(super) fn normalise(value: Value) -> Value {
    match value {
        Value::Number(number) => Value::Number(normalise_number(&number)),
        Value::Array(items) => Value::Array(items.into_iter().map(normalise).collect()),
        Value::Object(map) => {
            Value::Object(map.into_iter().map(|(k, v)| (k, normalise(v))).collect())
        }
        other => other,
    }
}

#[allow(
    clippy::cast_precision_loss,
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss
)]
fn normalise_number(number: &Number) -> Number {
    let Some(f) = number.as_f64() else {
        return number.clone();
    };

    if f.fract() != 0.0 || f.abs() >= 1e21 {
        return Number::from_f64(f).unwrap_or_else(|| number.clone());
    }

    if f >= i64::MIN as f64 && f < i64::MAX as f64 {
        return Number::from(f as i64);
    }

    if f >= 0.0 && f < u64::MAX as f64 {
        return Number::from(f as u64);
    }

    Number::from_f64(f).unwrap_or_else(|| number.clone())
}