Skip to main content

helm_rs/chart/yaml/
mod.rs

1//! YAML to JSON with the semantics Helm gets from `sigs.k8s.io/yaml` (`yaml.v2`, YAML 1.1).
2//!
3//! Helm decodes YAML into Go values and re-encodes them as JSON, so a few things differ from
4//! YAML 1.2 parsers (verified against `helm template` 4.3.0):
5//!
6//! - plain `y`, `yes`, `on` and `n`, `no`, `off` (any of the three spellings) are booleans, also
7//!   as mapping keys (the key `y` becomes `"true"`);
8//! - plain integers accept `_` separators, `0x`, `0o`, `0b` and leading-zero octal (`0777` is
9//!   511); `1e3` and `1.` are floats;
10//! - every number ends up an `f64` in Go, so integers beyond 2^53 lose precision; integral values
11//!   within 2^53 are returned as JSON integers, everything else as floats;
12//! - `.inf` and `.nan` are errors (JSON cannot hold them), `1e400` stays a string;
13//! - mapping keys are converted to strings; a later duplicate key wins;
14//! - `<<` merges mappings in document order, so a merge overrides keys written before it.
15
16use serde_json::{Map, Number, Value};
17use yaml_rust2::parser::{Event, MarkedEventReceiver, Parser, Tag};
18use yaml_rust2::scanner::{Marker, TScalarStyle};
19
20/// Largest magnitude below which `f64` represents every integer exactly.
21const MAX_EXACT: f64 = 9_007_199_254_740_992.0;
22
23/// A YAML document that Helm would refuse to turn into JSON.
24#[derive(Debug, thiserror::Error)]
25pub enum YamlError {
26    /// The text is not valid YAML.
27    #[error("{0}")]
28    Syntax(String),
29    /// A value cannot be represented in JSON (`.inf`, `.nan`) or a key is not a scalar.
30    #[error("error converting YAML to JSON: {0}")]
31    Unsupported(String),
32}
33
34/// Parses every document of `data` into JSON values.
35///
36/// # Errors
37/// Fails on a YAML syntax error or a value JSON cannot represent.
38pub fn parse_documents(data: &[u8]) -> Result<Vec<Value>, YamlError> {
39    let text = String::from_utf8_lossy(data);
40    let mut builder = Builder::default();
41
42    Parser::new_from_str(&text)
43        .load(&mut builder, true)
44        .map_err(|e| YamlError::Syntax(e.to_string()))?;
45    if let Some(error) = builder.error {
46        return Err(error);
47    }
48
49    Ok(builder.documents)
50}
51
52/// Parses the first document of `data`, the way `yaml.Unmarshal` does; empty input is `null`.
53///
54/// # Errors
55/// As [`parse_documents`].
56pub fn parse_first(data: &[u8]) -> Result<Value, YamlError> {
57    Ok(parse_documents(data)?
58        .into_iter()
59        .next()
60        .unwrap_or(Value::Null))
61}
62
63/// Event receiver that builds JSON values, resolving scalars the `yaml.v2` way.
64#[derive(Default)]
65struct Builder {
66    documents: Vec<Value>,
67    stack: Vec<Frame>,
68    anchors: Vec<(usize, Value)>,
69    error: Option<YamlError>,
70}
71
72/// A container being filled.
73enum Frame {
74    Seq(usize, Vec<Value>),
75    Map(usize, Vec<(String, Value)>, Option<MapKey>),
76}
77
78/// Pending key of a mapping: either a string key or the `<<` merge marker.
79enum MapKey {
80    Key(String),
81    Merge,
82}
83
84impl Builder {
85    /// Hands a finished node to the enclosing container, or records it as a document.
86    fn push(&mut self, value: Value, anchor: usize) {
87        if anchor != 0 {
88            self.anchors.push((anchor, value.clone()));
89        }
90        match self.stack.last_mut() {
91            None => self.documents.push(value),
92            Some(Frame::Seq(_, items)) => items.push(value),
93            Some(Frame::Map(_, entries, key)) => match key.take() {
94                None => match key_of(&value) {
95                    Ok(k) => *key = Some(MapKey::Key(k)),
96                    Err(e) => self.error = Some(e),
97                },
98                Some(MapKey::Key(k)) => entries.push((k, value)),
99                Some(MapKey::Merge) => merge_into(entries, value),
100            },
101        }
102    }
103
104    /// Handles a scalar, which may be the key of a mapping.
105    fn scalar(&mut self, text: &str, style: TScalarStyle, anchor: usize, tag: Option<&Tag>) {
106        let is_key = matches!(self.stack.last(), Some(Frame::Map(_, _, None)));
107
108        if is_key && style == TScalarStyle::Plain && text == "<<" && tag.is_none() {
109            if let Some(Frame::Map(_, _, key)) = self.stack.last_mut() {
110                *key = Some(MapKey::Merge);
111            }
112
113            return;
114        }
115
116        match resolve(text, style, tag) {
117            Ok(value) => self.push(value, anchor),
118            Err(e) => self.error = Some(e),
119        }
120    }
121}
122
123impl MarkedEventReceiver for Builder {
124    fn on_event(&mut self, event: Event, _mark: Marker) {
125        if self.error.is_some() {
126            return;
127        }
128
129        match event {
130            Event::Scalar(text, style, anchor, tag) => {
131                self.scalar(&text, style, anchor, tag.as_ref());
132            }
133            Event::SequenceStart(anchor, _) => self.stack.push(Frame::Seq(anchor, Vec::new())),
134            Event::MappingStart(anchor, _) => {
135                self.stack.push(Frame::Map(anchor, Vec::new(), None));
136            }
137            Event::SequenceEnd => {
138                if let Some(Frame::Seq(anchor, items)) = self.stack.pop() {
139                    self.push(Value::Array(items), anchor);
140                }
141            }
142            Event::MappingEnd => {
143                if let Some(Frame::Map(anchor, entries, _)) = self.stack.pop() {
144                    self.push(Value::Object(entries.into_iter().collect()), anchor);
145                }
146            }
147            Event::Alias(id) => {
148                let found = self.anchors.iter().rfind(|(a, _)| *a == id);
149
150                match found {
151                    Some((_, value)) => {
152                        let value = value.clone();
153
154                        self.push(value, 0);
155                    }
156                    None => {
157                        self.error = Some(YamlError::Syntax(format!("unknown anchor id {id}")));
158                    }
159                }
160            }
161            _ => {}
162        }
163    }
164}
165
166/// Applies a `<<` merge: a mapping, or a sequence of mappings where earlier ones win.
167fn merge_into(entries: &mut Vec<(String, Value)>, value: Value) {
168    let sources = match value {
169        Value::Object(map) => vec![map],
170        Value::Array(items) => items
171            .into_iter()
172            .rev()
173            .filter_map(|v| match v {
174                Value::Object(map) => Some(map),
175                _ => None,
176            })
177            .collect(),
178        _ => Vec::new(),
179    };
180
181    for source in sources {
182        entries.extend(source);
183    }
184}
185
186/// Converts a scalar node used as a mapping key to the string `sigs.k8s.io/yaml` would use.
187fn key_of(value: &Value) -> Result<String, YamlError> {
188    match value {
189        Value::String(s) => Ok(s.clone()),
190        Value::Number(n) => Ok(n.to_string()),
191        Value::Bool(b) => Ok(b.to_string()),
192        other => Err(YamlError::Unsupported(format!(
193            "unsupported map key: {other}"
194        ))),
195    }
196}
197
198/// Resolves a scalar to a JSON value following `yaml.v2`'s resolver.
199fn resolve(text: &str, style: TScalarStyle, tag: Option<&Tag>) -> Result<Value, YamlError> {
200    let kind = tag
201        .filter(|t| t.handle == "tag:yaml.org,2002:")
202        .map(|t| t.suffix.as_str());
203    let non_specific = tag.is_some_and(|t| t.handle.is_empty() && t.suffix == "!");
204
205    if kind == Some("str") || non_specific || (style != TScalarStyle::Plain && kind.is_none()) {
206        return Ok(Value::String(text.to_owned()));
207    }
208
209    match text {
210        "" | "~" | "null" | "Null" | "NULL" => return Ok(Value::Null),
211        "y" | "Y" | "yes" | "Yes" | "YES" | "true" | "True" | "TRUE" | "on" | "On" | "ON" => {
212            return Ok(Value::Bool(true));
213        }
214        "n" | "N" | "no" | "No" | "NO" | "false" | "False" | "FALSE" | "off" | "Off" | "OFF" => {
215            return Ok(Value::Bool(false));
216        }
217        ".inf" | "+.inf" | "-.inf" | ".Inf" | ".INF" | "+.Inf" | "+.INF" | "-.Inf" | "-.INF" => {
218            return Err(YamlError::Unsupported(format!(
219                "json: unsupported value: {text}"
220            )));
221        }
222        ".nan" | ".NaN" | ".NAN" => {
223            return Err(YamlError::Unsupported(
224                "json: unsupported value: NaN".into(),
225            ));
226        }
227        _ => {}
228    }
229
230    Ok(resolve_number(text).unwrap_or_else(|| Value::String(text.to_owned())))
231}
232
233/// Resolves plain numbers: Go `ParseInt`/`ParseUint` with base 0, then `yaml.v2`'s float shape.
234fn resolve_number(text: &str) -> Option<Value> {
235    let first = text.chars().next()?;
236
237    if !(first.is_ascii_digit() || matches!(first, '+' | '-' | '.')) {
238        return None;
239    }
240
241    let plain = text.replace('_', "");
242
243    if let Some(int) = parse_int(&plain) {
244        return Some(number(int));
245    }
246    if is_yaml_float(&plain) {
247        return plain
248            .parse::<f64>()
249            .ok()
250            .filter(|f| f.is_finite())
251            .map(number);
252    }
253
254    None
255}
256
257/// Parses an integer with Go's base-0 rules, returned as the `f64` Go would end up with.
258#[allow(clippy::cast_precision_loss)]
259fn parse_int(plain: &str) -> Option<f64> {
260    let (negative, rest) = match plain.as_bytes().first()? {
261        b'-' => (true, &plain[1..]),
262        b'+' => (false, &plain[1..]),
263        _ => (false, plain),
264    };
265    let lower = rest.to_ascii_lowercase();
266    let (radix, digits) = if let Some(d) = lower.strip_prefix("0x") {
267        (16, d)
268    } else if let Some(d) = lower.strip_prefix("0b") {
269        (2, d)
270    } else if let Some(d) = lower.strip_prefix("0o") {
271        (8, d)
272    } else if lower.len() > 1 && lower.starts_with('0') {
273        (8, &lower[1..])
274    } else {
275        (10, lower.as_str())
276    };
277
278    if digits.is_empty() || !digits.chars().all(|c| c.is_digit(radix)) {
279        return None;
280    }
281
282    let magnitude = u64::from_str_radix(digits, radix).ok()?;
283
284    if negative && magnitude > i64::MAX as u64 + 1 {
285        return None;
286    }
287
288    let value = magnitude as f64;
289
290    Some(if negative { -value } else { value })
291}
292
293/// Matches `yaml.v2`'s `yamlStyleFloat`: `^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$`.
294fn is_yaml_float(s: &str) -> bool {
295    let s = s.strip_prefix(['-', '+']).unwrap_or(s);
296    let (mantissa, exponent) = match s.find(['e', 'E']) {
297        Some(i) => (&s[..i], Some(&s[i + 1..])),
298        None => (s, None),
299    };
300    let (int, frac) = match mantissa.split_once('.') {
301        Some((i, f)) => (i, Some(f)),
302        None => (mantissa, None),
303    };
304    let digits = |t: &str| t.chars().all(|c| c.is_ascii_digit());
305    let mantissa_ok = match frac {
306        Some(f) if int.is_empty() => !f.is_empty() && digits(f),
307        Some(f) => digits(int) && digits(f),
308        None => !int.is_empty() && digits(int),
309    };
310    let exponent_ok = exponent.is_none_or(|e| {
311        let e = e.strip_prefix(['-', '+']).unwrap_or(e);
312
313        !e.is_empty() && digits(e)
314    });
315
316    mantissa_ok && exponent_ok
317}
318
319/// Builds a JSON number the way Go's float64 round trip does.
320#[allow(clippy::cast_possible_truncation)]
321fn number(value: f64) -> Value {
322    if value.fract() == 0.0 && value.abs() <= MAX_EXACT {
323        return Value::Number(Number::from(value as i64));
324    }
325
326    Number::from_f64(value).map_or(Value::Null, Value::Number)
327}
328
329/// Returns the top-level mapping of `value`, with `null` as an empty mapping.
330///
331/// # Errors
332/// Fails when the document is neither a mapping nor `null`, as Helm's `map[string]any` decode.
333pub fn into_map(value: Value) -> Result<Map<String, Value>, YamlError> {
334    match value {
335        Value::Object(map) => Ok(map),
336        Value::Null => Ok(Map::new()),
337        _ => Err(YamlError::Unsupported(
338            "error unmarshaling JSON: json: cannot unmarshal into Go value of type map[string]interface {}"
339                .into(),
340        )),
341    }
342}
343
344#[cfg(test)]
345mod tests;