helm-rs 0.1.0

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! Type helpers of the walker: the JSON types of a YAML tag, casting of defaults and helm-docs
//! type names.

use serde_json::{Number, Value};

use super::yaml::go_parse_float;

/// `typeFromTag`.
pub(super) fn type_from_tag(tag: &str) -> std::result::Result<Vec<String>, String> {
    let name = match tag {
        "!!null" => "null",
        "!!bool" => "boolean",
        "!!str" | "!!timestamp" => "string",
        "!!int" => "integer",
        "!!float" => "number",
        "!!seq" => "array",
        "!!map" => "object",
        _ => return Err(format!("unsupported yaml tag found: {tag}")),
    };

    Ok(vec![name.to_owned()])
}

/// `castNodeValueByType`: the raw scalar as the first matching type, else the raw string.
pub(super) fn cast_by_type(raw: &str, types: &[String]) -> Value {
    for t in types {
        match t.as_str() {
            "boolean" if raw == "true" => return Value::Bool(true),
            "boolean" if raw == "false" => return Value::Bool(false),
            "integer" => {
                if let Some(i) = go_atoi(raw) {
                    return Value::from(i);
                }
            }
            "number" => {
                if let Some(n) = go_parse_float(raw).and_then(Number::from_f64) {
                    return Value::Number(n);
                }
            }
            _ => {}
        }
    }

    Value::String(raw.to_owned())
}

/// `strconv.ParseInt(s, 10, 64)` as `strconv.Atoi` does it: an optional sign and decimal digits.
fn go_atoi(s: &str) -> Option<i64> {
    let digits = s.strip_prefix(['+', '-']).unwrap_or(s);

    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }

    s.strip_prefix('+').unwrap_or(s).parse().ok()
}