helm-rs 0.1.0

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! YAML to JSON with the semantics Helm gets from `sigs.k8s.io/yaml` (`yaml.v2`, YAML 1.1).
//!
//! Helm decodes YAML into Go values and re-encodes them as JSON, so a few things differ from
//! YAML 1.2 parsers (verified against `helm template` 4.3.0):
//!
//! - plain `y`, `yes`, `on` and `n`, `no`, `off` (any of the three spellings) are booleans, also
//!   as mapping keys (the key `y` becomes `"true"`);
//! - plain integers accept `_` separators, `0x`, `0o`, `0b` and leading-zero octal (`0777` is
//!   511); `1e3` and `1.` are floats;
//! - every number ends up an `f64` in Go, so integers beyond 2^53 lose precision; integral values
//!   within 2^53 are returned as JSON integers, everything else as floats;
//! - `.inf` and `.nan` are errors (JSON cannot hold them), `1e400` stays a string;
//! - mapping keys are converted to strings; a later duplicate key wins;
//! - `<<` merges mappings in document order, so a merge overrides keys written before it.

use serde_json::{Map, Number, Value};
use yaml_rust2::parser::{Event, MarkedEventReceiver, Parser, Tag};
use yaml_rust2::scanner::{Marker, TScalarStyle};

/// Largest magnitude below which `f64` represents every integer exactly.
const MAX_EXACT: f64 = 9_007_199_254_740_992.0;

/// A YAML document that Helm would refuse to turn into JSON.
#[derive(Debug, thiserror::Error)]
pub enum YamlError {
    /// The text is not valid YAML.
    #[error("{0}")]
    Syntax(String),
    /// A value cannot be represented in JSON (`.inf`, `.nan`) or a key is not a scalar.
    #[error("error converting YAML to JSON: {0}")]
    Unsupported(String),
}

/// Parses every document of `data` into JSON values.
///
/// # Errors
/// Fails on a YAML syntax error or a value JSON cannot represent.
pub fn parse_documents(data: &[u8]) -> Result<Vec<Value>, YamlError> {
    let text = String::from_utf8_lossy(data);
    let mut builder = Builder::default();

    Parser::new_from_str(&text)
        .load(&mut builder, true)
        .map_err(|e| YamlError::Syntax(e.to_string()))?;
    if let Some(error) = builder.error {
        return Err(error);
    }

    Ok(builder.documents)
}

/// Parses the first document of `data`, the way `yaml.Unmarshal` does; empty input is `null`.
///
/// # Errors
/// As [`parse_documents`].
pub fn parse_first(data: &[u8]) -> Result<Value, YamlError> {
    Ok(parse_documents(data)?
        .into_iter()
        .next()
        .unwrap_or(Value::Null))
}

/// Event receiver that builds JSON values, resolving scalars the `yaml.v2` way.
#[derive(Default)]
struct Builder {
    documents: Vec<Value>,
    stack: Vec<Frame>,
    anchors: Vec<(usize, Value)>,
    error: Option<YamlError>,
}

/// A container being filled.
enum Frame {
    Seq(usize, Vec<Value>),
    Map(usize, Vec<(String, Value)>, Option<MapKey>),
}

/// Pending key of a mapping: either a string key or the `<<` merge marker.
enum MapKey {
    Key(String),
    Merge,
}

impl Builder {
    /// Hands a finished node to the enclosing container, or records it as a document.
    fn push(&mut self, value: Value, anchor: usize) {
        if anchor != 0 {
            self.anchors.push((anchor, value.clone()));
        }
        match self.stack.last_mut() {
            None => self.documents.push(value),
            Some(Frame::Seq(_, items)) => items.push(value),
            Some(Frame::Map(_, entries, key)) => match key.take() {
                None => match key_of(&value) {
                    Ok(k) => *key = Some(MapKey::Key(k)),
                    Err(e) => self.error = Some(e),
                },
                Some(MapKey::Key(k)) => entries.push((k, value)),
                Some(MapKey::Merge) => merge_into(entries, value),
            },
        }
    }

    /// Handles a scalar, which may be the key of a mapping.
    fn scalar(&mut self, text: &str, style: TScalarStyle, anchor: usize, tag: Option<&Tag>) {
        let is_key = matches!(self.stack.last(), Some(Frame::Map(_, _, None)));

        if is_key && style == TScalarStyle::Plain && text == "<<" && tag.is_none() {
            if let Some(Frame::Map(_, _, key)) = self.stack.last_mut() {
                *key = Some(MapKey::Merge);
            }

            return;
        }

        match resolve(text, style, tag) {
            Ok(value) => self.push(value, anchor),
            Err(e) => self.error = Some(e),
        }
    }
}

impl MarkedEventReceiver for Builder {
    fn on_event(&mut self, event: Event, _mark: Marker) {
        if self.error.is_some() {
            return;
        }

        match event {
            Event::Scalar(text, style, anchor, tag) => {
                self.scalar(&text, style, anchor, tag.as_ref());
            }
            Event::SequenceStart(anchor, _) => self.stack.push(Frame::Seq(anchor, Vec::new())),
            Event::MappingStart(anchor, _) => {
                self.stack.push(Frame::Map(anchor, Vec::new(), None));
            }
            Event::SequenceEnd => {
                if let Some(Frame::Seq(anchor, items)) = self.stack.pop() {
                    self.push(Value::Array(items), anchor);
                }
            }
            Event::MappingEnd => {
                if let Some(Frame::Map(anchor, entries, _)) = self.stack.pop() {
                    self.push(Value::Object(entries.into_iter().collect()), anchor);
                }
            }
            Event::Alias(id) => {
                let found = self.anchors.iter().rfind(|(a, _)| *a == id);

                match found {
                    Some((_, value)) => {
                        let value = value.clone();

                        self.push(value, 0);
                    }
                    None => {
                        self.error = Some(YamlError::Syntax(format!("unknown anchor id {id}")));
                    }
                }
            }
            _ => {}
        }
    }
}

/// Applies a `<<` merge: a mapping, or a sequence of mappings where earlier ones win.
fn merge_into(entries: &mut Vec<(String, Value)>, value: Value) {
    let sources = match value {
        Value::Object(map) => vec![map],
        Value::Array(items) => items
            .into_iter()
            .rev()
            .filter_map(|v| match v {
                Value::Object(map) => Some(map),
                _ => None,
            })
            .collect(),
        _ => Vec::new(),
    };

    for source in sources {
        entries.extend(source);
    }
}

/// Converts a scalar node used as a mapping key to the string `sigs.k8s.io/yaml` would use.
fn key_of(value: &Value) -> Result<String, YamlError> {
    match value {
        Value::String(s) => Ok(s.clone()),
        Value::Number(n) => Ok(n.to_string()),
        Value::Bool(b) => Ok(b.to_string()),
        other => Err(YamlError::Unsupported(format!(
            "unsupported map key: {other}"
        ))),
    }
}

/// Resolves a scalar to a JSON value following `yaml.v2`'s resolver.
fn resolve(text: &str, style: TScalarStyle, tag: Option<&Tag>) -> Result<Value, YamlError> {
    let kind = tag
        .filter(|t| t.handle == "tag:yaml.org,2002:")
        .map(|t| t.suffix.as_str());
    let non_specific = tag.is_some_and(|t| t.handle.is_empty() && t.suffix == "!");

    if kind == Some("str") || non_specific || (style != TScalarStyle::Plain && kind.is_none()) {
        return Ok(Value::String(text.to_owned()));
    }

    match text {
        "" | "~" | "null" | "Null" | "NULL" => return Ok(Value::Null),
        "y" | "Y" | "yes" | "Yes" | "YES" | "true" | "True" | "TRUE" | "on" | "On" | "ON" => {
            return Ok(Value::Bool(true));
        }
        "n" | "N" | "no" | "No" | "NO" | "false" | "False" | "FALSE" | "off" | "Off" | "OFF" => {
            return Ok(Value::Bool(false));
        }
        ".inf" | "+.inf" | "-.inf" | ".Inf" | ".INF" | "+.Inf" | "+.INF" | "-.Inf" | "-.INF" => {
            return Err(YamlError::Unsupported(format!(
                "json: unsupported value: {text}"
            )));
        }
        ".nan" | ".NaN" | ".NAN" => {
            return Err(YamlError::Unsupported(
                "json: unsupported value: NaN".into(),
            ));
        }
        _ => {}
    }

    Ok(resolve_number(text).unwrap_or_else(|| Value::String(text.to_owned())))
}

/// Resolves plain numbers: Go `ParseInt`/`ParseUint` with base 0, then `yaml.v2`'s float shape.
fn resolve_number(text: &str) -> Option<Value> {
    let first = text.chars().next()?;

    if !(first.is_ascii_digit() || matches!(first, '+' | '-' | '.')) {
        return None;
    }

    let plain = text.replace('_', "");

    if let Some(int) = parse_int(&plain) {
        return Some(number(int));
    }
    if is_yaml_float(&plain) {
        return plain
            .parse::<f64>()
            .ok()
            .filter(|f| f.is_finite())
            .map(number);
    }

    None
}

/// Parses an integer with Go's base-0 rules, returned as the `f64` Go would end up with.
#[allow(clippy::cast_precision_loss)]
fn parse_int(plain: &str) -> Option<f64> {
    let (negative, rest) = match plain.as_bytes().first()? {
        b'-' => (true, &plain[1..]),
        b'+' => (false, &plain[1..]),
        _ => (false, plain),
    };
    let lower = rest.to_ascii_lowercase();
    let (radix, digits) = if let Some(d) = lower.strip_prefix("0x") {
        (16, d)
    } else if let Some(d) = lower.strip_prefix("0b") {
        (2, d)
    } else if let Some(d) = lower.strip_prefix("0o") {
        (8, d)
    } else if lower.len() > 1 && lower.starts_with('0') {
        (8, &lower[1..])
    } else {
        (10, lower.as_str())
    };

    if digits.is_empty() || !digits.chars().all(|c| c.is_digit(radix)) {
        return None;
    }

    let magnitude = u64::from_str_radix(digits, radix).ok()?;

    if negative && magnitude > i64::MAX as u64 + 1 {
        return None;
    }

    let value = magnitude as f64;

    Some(if negative { -value } else { value })
}

/// Matches `yaml.v2`'s `yamlStyleFloat`: `^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$`.
fn is_yaml_float(s: &str) -> bool {
    let s = s.strip_prefix(['-', '+']).unwrap_or(s);
    let (mantissa, exponent) = match s.find(['e', 'E']) {
        Some(i) => (&s[..i], Some(&s[i + 1..])),
        None => (s, None),
    };
    let (int, frac) = match mantissa.split_once('.') {
        Some((i, f)) => (i, Some(f)),
        None => (mantissa, None),
    };
    let digits = |t: &str| t.chars().all(|c| c.is_ascii_digit());
    let mantissa_ok = match frac {
        Some(f) if int.is_empty() => !f.is_empty() && digits(f),
        Some(f) => digits(int) && digits(f),
        None => !int.is_empty() && digits(int),
    };
    let exponent_ok = exponent.is_none_or(|e| {
        let e = e.strip_prefix(['-', '+']).unwrap_or(e);

        !e.is_empty() && digits(e)
    });

    mantissa_ok && exponent_ok
}

/// Builds a JSON number the way Go's float64 round trip does.
#[allow(clippy::cast_possible_truncation)]
fn number(value: f64) -> Value {
    if value.fract() == 0.0 && value.abs() <= MAX_EXACT {
        return Value::Number(Number::from(value as i64));
    }

    Number::from_f64(value).map_or(Value::Null, Value::Number)
}

/// Returns the top-level mapping of `value`, with `null` as an empty mapping.
///
/// # Errors
/// Fails when the document is neither a mapping nor `null`, as Helm's `map[string]any` decode.
pub fn into_map(value: Value) -> Result<Map<String, Value>, YamlError> {
    match value {
        Value::Object(map) => Ok(map),
        Value::Null => Ok(Map::new()),
        _ => Err(YamlError::Unsupported(
            "error unmarshaling JSON: json: cannot unmarshal into Go value of type map[string]interface {}"
                .into(),
        )),
    }
}

#[cfg(test)]
mod tests;