helm-rs 0.1.1

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! `handleSchemaRefs` of helm-schema's `pkg/schema/schema.go`: `$ref`s to relative JSON files
//! are loaded and bundled into the schema. Files come from an in-memory map keyed by the path
//! relative to the chart root instead of the file system.

use std::collections::BTreeMap;

use serde_json::Value;

use super::model::Schema;
use super::schema_decode::parse_schema;

/// `filepath.Clean` for a relative slash path.
fn clean(path: &str) -> String {
    let mut parts: Vec<&str> = Vec::new();

    for part in path.split('/') {
        match part {
            "" | "." => {}
            ".." if parts.last().is_some_and(|p| *p != "..") => {
                parts.pop();
            }
            other => parts.push(other),
        }
    }

    if parts.is_empty() {
        ".".to_owned()
    } else {
        parts.join("/")
    }
}

/// RFC 6901 lookup, like `go-jsonpointer`.
fn pointer<'v>(value: &'v Value, pointer: &str) -> Result<&'v Value, String> {
    let mut current = value;

    for token in pointer.split('/').skip(1) {
        let token = token.replace("~1", "/").replace("~0", "~");

        current = match current {
            Value::Object(map) => map.get(&token),
            Value::Array(items) => token.parse::<usize>().ok().and_then(|i| items.get(i)),
            _ => None,
        }
        .ok_or_else(|| format!("path {pointer} not found"))?;
    }

    Ok(current)
}

/// Resolves the `$ref` of `schema` (and of its `patternProperties`) when it names a relative
/// file present in `files`; other references are left for the final schema to resolve.
///
/// # Errors
/// Go's message: the file does not parse, or the pointer is not found in it.
pub(super) fn handle_refs(
    schema: &mut Schema,
    files: &BTreeMap<String, String>,
) -> Result<(), String> {
    if !schema.reference.is_empty() {
        let (file_ref, rest) = match schema.reference.split_once('#') {
            Some((file, rest)) => (file.to_owned(), Some(rest.to_owned())),
            None => (schema.reference.clone(), None),
        };

        if !file_ref.is_empty()
            && !file_ref.starts_with('/')
            && let Some(content) = files.get(&clean(&file_ref))
        {
            bundle(schema, &file_ref, rest.as_deref(), content)?;
        }
    }

    for (pattern, sub) in schema.pattern_properties.iter_mut().flatten() {
        if !sub.reference.is_empty() {
            handle_refs(sub, files).map_err(|e| {
                format!("failed to resolve $ref in patternProperties[{pattern}]: {e}")
            })?;
        }
    }

    Ok(())
}

fn bundle(
    schema: &mut Schema,
    file_ref: &str,
    pointer_text: Option<&str>,
    content: &str,
) -> Result<(), String> {
    let prefix = clean(file_ref);
    let path = &prefix;
    let relative = match pointer_text.filter(|p| !p.is_empty()) {
        Some(ptr) => {
            let object: Value = serde_json::from_str(content)
                .map_err(|e| format!("failed to unmarshal JSON from {path}: {e}"))?;
            let found = pointer(&object, ptr)
                .map_err(|e| format!("failed to resolve JSON pointer {ptr} in {path}: {e}"))?;

            if ptr.starts_with("/definitions/") || ptr.starts_with("/$defs/") {
                let mut full = parse_schema(content, true)
                    .map_err(|e| format!("failed to unmarshal schema from {path}: {e}"))?;

                full.reference = format!("#{}", ptr.replacen("/$defs/", "/definitions/", 1));

                let bundled = full.with_definition_prefix(&prefix);

                schema.definitions = bundled.definitions;
                schema.reference = bundled.reference;
                schema.has_data = true;

                return Ok(());
            }

            parse_schema(&found.to_string(), true)
                .map_err(|e| format!("failed to unmarshal JSON pointer result from {path}: {e}"))?
        }
        None => parse_schema(content, true)
            .map_err(|e| format!("failed to unmarshal schema from {path}: {e}"))?,
    };

    *schema = relative.with_definition_prefix(&prefix);
    schema.has_data = true;

    Ok(())
}