helm-rs 0.1.1

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! The annotation model: the `# @schema` keywords of a values file per values path.

use std::collections::BTreeMap;

use serde_json::Value;

use super::decode::AliasBudget;
use super::error::{GenerateError, Result};
use super::yaml::{self, Kind, YamlError};
use super::{comments, parse_values};

/// The annotation block of one key of a values file: the keywords as written.
#[derive(Debug, Clone, PartialEq)]
pub struct Annotation {
    /// The values path of the key; empty for the `# @schema.root` of the whole file.
    pub path: Vec<String>,
    /// The keywords of the block with their values, as written (custom `x-` ones included).
    pub keywords: BTreeMap<String, Value>,
    /// The comment text outside the blocks that becomes the description.
    pub description: String,
    /// Whether the block is a `# @schema.root` block.
    pub root: bool,
}

/// The walk over a values mapping: where it is, and what it has already collected.
struct Walk<'a> {
    doc: &'a yaml::Doc,
    keep_full_comment: bool,
    path: Vec<String>,
    active: Vec<usize>,
    budget: AliasBudget,
    out: Vec<Annotation>,
}

impl Walk<'_> {
    /// Collects the annotations of the keys of mapping `id`. `first_comment` replaces the head
    /// comment of its first key (the comment left once the root block is taken out of it).
    fn collect(&mut self, id: usize, first_comment: Option<&str>) -> Result<()> {
        let doc = self.doc;
        let node = &doc.nodes[id];

        if node.kind != Kind::Mapping {
            return Ok(());
        }

        self.active.push(id);

        for (index, pair) in node.content.chunks(2).enumerate() {
            self.budget.tick()?;

            let key = &doc.nodes[pair[0]];
            let head = match first_comment {
                Some(text) if index == 0 => text,
                _ => key.head_comment.as_str(),
            };
            let comment = if self.keep_full_comment {
                head
            } else {
                comments::remove_leading(head)
            };

            self.path.push(key.value.clone());

            if let Some((keywords, description)) =
                comments::keywords(comment, false).map_err(|m| {
                    GenerateError::annotation(
                        format!("error parsing comment of key {}", key.value),
                        m,
                    )
                })?
            {
                self.out.push(Annotation {
                    path: self.path.clone(),
                    keywords,
                    description,
                    root: false,
                });
            }

            let value = &doc.nodes[pair[1]];
            let target = if value.kind == Kind::Alias {
                value.alias.unwrap_or(pair[1])
            } else {
                pair[1]
            };

            if self.active.contains(&target) {
                return Err(YamlError::plain(&format!(
                    "anchor '{}' value contains itself",
                    value.value
                ))
                .into());
            }

            if target != pair[1] {
                self.budget.enter_alias();
            }

            self.collect(target, None)?;

            if target != pair[1] {
                self.budget.leave_alias();
            }

            self.path.pop();
        }

        self.active.pop();

        Ok(())
    }
}

/// Reads the annotation blocks of a values file: the keywords per values path, including the
/// `# @schema.root` blocks (path empty) of the document and of the first key of every mapping.
///
/// # Errors
/// [`GenerateError`] for invalid YAML or a malformed block.
pub fn annotations(values_yaml: &str, keep_full_comment: bool) -> Result<Vec<Annotation>> {
    let doc = parse_values(&values_yaml.replace("\r\n", "\n"))?;
    let root = doc.root.unwrap_or_default();
    let mut out = Vec::new();
    let mut heads = vec![doc.nodes[root].head_comment.as_str()];
    let mut first_comment = None;

    if let Some(&first) = doc.nodes[root].content.first()
        && let Some(&key) = doc.nodes[first].content.first()
    {
        heads.push(&doc.nodes[key].head_comment);
    }

    for (index, head) in heads.into_iter().enumerate() {
        if let Some((keywords, description)) = comments::keywords(head, true).map_err(|m| {
            GenerateError::annotation("error parsing root schema comment".to_owned(), m)
        })? {
            if index == 1 {
                first_comment = Some(description.clone());
            }

            out.push(Annotation {
                path: Vec::new(),
                keywords,
                description,
                root: true,
            });
        }
    }

    let mut walk = Walk {
        doc: &doc,
        keep_full_comment,
        path: Vec::new(),
        active: Vec::new(),
        budget: AliasBudget::default(),
        out,
    };

    if let Some(&child) = doc.nodes[root].content.first() {
        walk.collect(child, first_comment.as_deref())?;
    }

    Ok(walk.out)
}

#[cfg(test)]
mod tests;