helm-rs 0.1.0

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! Reading annotations out of comments: `GetSchemaFromComment` and `GetRootSchemaFromComment` of
//! helm-schema's `pkg/schema/schema.go`, and the comment cleaners.

use std::collections::BTreeMap;
use std::sync::LazyLock;

use regex::Regex;
use serde_json::Value;

use super::decode::Decoder;
use super::model::Schema;
use super::schema_decode::parse_schema;
use super::yaml;

const SCHEMA_PREFIX: &str = "# @schema";
const ROOT_PREFIX: &str = "# @schema.root";
pub(super) const WS: &str = r"[\t\n\f\r ]";

static TAGS: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(
        r"(?ms)(\r\n|\r|\n)?{WS}*@[0-9A-Za-z_]+({WS}+--{WS})?[^\n\r]*"
    ))
    .expect("static regex")
});
static PREFIX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(&format!(r"(?m)^--{WS}?")).expect("static regex"));

/// `bufio.ScanLines` over a string.
fn scan_lines(text: &str) -> Vec<&str> {
    let mut lines: Vec<&str> = text.split('\n').collect();

    if lines.last() == Some(&"") {
        lines.pop();
    }

    lines
        .into_iter()
        .map(|l| l.strip_suffix('\r').unwrap_or(l))
        .collect()
}

fn strip_comment_marker(line: &str) -> &str {
    let content = line.strip_prefix('#').unwrap_or(line);
    let content = content.strip_prefix('#').unwrap_or(content);

    content.strip_prefix(' ').unwrap_or(content)
}

/// `leadingCommentsRemover`: keeps what follows the last blank line.
pub(super) fn remove_leading(comment: &str) -> &str {
    match comment.rfind("\n\n") {
        Some(i) => comment[i + 2..].trim_start_matches('\n'),
        None => comment,
    }
}

/// The `helmDocsTagsRemover` and `helmDocsPrefixRemover` replacements.
pub(super) fn strip_helm_docs(description: &str) -> String {
    let without_tags = TAGS.replace_all(description, "");

    PREFIX.replace_all(&without_tags, "").into_owned()
}

/// Splits `comment` at `prefix` toggles; the lines inside blocks are decoded as one schema.
/// Returns the block schema (with `has_data`), the text outside the blocks and whether a block
/// was seen.
fn read_blocks(
    comment: &str,
    prefix: &str,
    root: bool,
) -> Result<(Schema, Vec<String>, Vec<String>), String> {
    let mut block = Vec::new();
    let mut outside = Vec::new();
    let mut inside = false;
    let mut found = false;

    for line in scan_lines(comment) {
        if line.starts_with(prefix) {
            inside = !inside;
            found = true;

            continue;
        }

        if inside {
            block.push(strip_comment_marker(line).to_owned());
        } else if root {
            outside.push(line.to_owned());
        } else {
            let stripped = line.strip_prefix('#').unwrap_or(line);

            outside.push(stripped.strip_prefix(' ').unwrap_or(stripped).to_owned());
        }
    }

    if inside {
        let kind = if root { "root schema" } else { "schema" };

        return Err(format!("unclosed {kind} block found in comment: {comment}"));
    }

    let mut schema = if found || !root {
        parse_schema(&block.join("\n"), false)?
    } else {
        Schema::default()
    };

    schema.has_data = !block.is_empty();

    Ok((schema, outside, block))
}

/// `GetSchemaFromComment`: the schema of the `# @schema` blocks and the remaining description.
///
/// # Errors
/// Go's message: an unclosed block, or the YAML decode error of the block text.
pub(super) fn schema_from_comment(comment: &str) -> Result<(Schema, String), String> {
    let (schema, outside, _) = read_blocks(comment, SCHEMA_PREFIX, false)?;

    Ok((schema, outside.join("\n")))
}

/// `GetRootSchemaFromComment`: the schema of the `# @schema.root` blocks and the remaining comment.
///
/// # Errors
/// Go's message: an unclosed block, or the YAML decode error of the block text.
pub(super) fn root_schema_from_comment(comment: &str) -> Result<(Schema, String), String> {
    let (schema, outside, _) = read_blocks(comment, ROOT_PREFIX, true)?;

    Ok((schema, outside.join("\n")))
}

/// The keywords of the blocks of a comment, with its description.
pub(super) type Keywords = (BTreeMap<String, Value>, String);

/// The keywords of the blocks of `comment` as written, with the description, or `None` when the
/// comment has no block.
pub(super) fn keywords(comment: &str, root: bool) -> Result<Option<Keywords>, String> {
    let prefix = if root { ROOT_PREFIX } else { SCHEMA_PREFIX };
    let (_, outside, block) = read_blocks(comment, prefix, root)?;

    if block.is_empty() {
        return Ok(None);
    }

    let doc = yaml::parse(&block.join("\n")).map_err(|e| e.to_string())?;
    let mut decoder = Decoder::new(&doc);
    let value = match doc.root.and_then(|r| doc.nodes[r].content.first().copied()) {
        Some(id) => decoder.any(id).map_err(|e| e.to_string())?,
        None => Value::Null,
    };
    let keywords = match value {
        Value::Object(map) => map.into_iter().collect(),
        _ => BTreeMap::new(),
    };

    Ok(Some((keywords, outside.join("\n"))))
}