helm-rs 0.1.1

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! Merging of dependency schemas into the schema of their parent: the dependency handling of
//! helm-schema's `cmd/helm-schema/main.go` (`exec`, `processImportValues`,
//! `mergeSchemaProperties`, `parseConditionPaths`, `conditionTargets`) and the binding of
//! `pkg/chart/graph.go`, for the subcharts a loaded chart carries in `charts/`.

use std::collections::{BTreeMap, BTreeSet};

use serde_json::Value;

use super::constraint::satisfies;
use super::error::{GenerateError, Result};
use super::model::Schema;
use crate::chart::{Chart, Dependency};

/// One dependency declaration and the subchart it binds to.
pub(super) struct Bound<'a> {
    pub(super) dep: &'a Dependency,
    pub(super) child: Option<usize>,
}

fn selected(dep: &Dependency, filter: &[String]) -> bool {
    !dep.name.is_empty() && (filter.is_empty() || filter.contains(&dep.name))
}

fn key_of(dep: &Dependency) -> &str {
    if dep.alias.is_empty() {
        &dep.name
    } else {
        &dep.alias
    }
}

/// `resolveDependency` for subcharts in `charts/` (the first binding tier): the chart named like
/// the dependency whose version satisfies its constraint.
///
/// # Errors
/// An invalid constraint, or more than one matching subchart.
pub(super) fn bind<'a>(chart: &'a Chart, filter: &[String]) -> Result<Vec<Bound<'a>>> {
    let mut bound = Vec::new();

    for dep in &chart.metadata.dependencies {
        let Some(dep) = dep.as_ref() else { continue };
        let mut matches = Vec::new();

        if selected(dep, filter) {
            for (index, child) in chart.dependencies.iter().enumerate() {
                if child.metadata.name != dep.name {
                    continue;
                }

                let ok = dep.version.is_empty()
                    || satisfies(&dep.version, &child.metadata.version).map_err(|e| {
                        GenerateError::Dependency(format!(
                            "chart {} dependency {:?} (alias {:?}) has invalid version constraint {:?}: {e}",
                            chart.metadata.name, dep.name, dep.alias, dep.version
                        ))
                    })?;

                if ok {
                    matches.push(index);
                }
            }
        }

        if matches.len() > 1 {
            return Err(GenerateError::Dependency(format!(
                "ambiguous dependency {:?} (version {:?}, alias {:?}, repository {:?}) in chart {}; matching charts: {}",
                dep.name,
                dep.version,
                dep.alias,
                dep.repository,
                chart.metadata.name,
                matches
                    .iter()
                    .map(|i| format!("charts/{}", chart.dependencies[*i].metadata.name))
                    .collect::<Vec<_>>()
                    .join(", ")
            )));
        }

        bound.push(Bound {
            dep,
            child: matches.first().copied(),
        });
    }

    Ok(bound)
}

/// `parseConditionPaths`: each comma-separated condition path with at least two keys.
fn condition_paths(condition: &str) -> Vec<Vec<String>> {
    condition
        .split(',')
        .map(str::trim)
        .filter(|part| !part.is_empty())
        .map(|part| part.split('.').map(str::to_owned).collect::<Vec<_>>())
        .filter(|keys| keys.len() > 1 && !keys[0].is_empty())
        .collect()
}

/// The condition paths each subchart receives as boolean markers (`conditionTargets`), by index
/// into `chart.dependencies`.
pub(super) fn condition_patches(
    bound: &[Bound<'_>],
    filter: &[String],
) -> BTreeMap<usize, Vec<Vec<String>>> {
    let mut patches: BTreeMap<usize, Vec<Vec<String>>> = BTreeMap::new();

    for (index, entry) in bound.iter().enumerate() {
        if !selected(entry.dep, filter) || entry.dep.condition.is_empty() {
            continue;
        }

        for path in condition_paths(&entry.dep.condition) {
            let mut targets: Vec<usize> = Vec::new();

            for sibling in bound {
                if let Some(child) = sibling.child
                    && key_of(sibling.dep) == path[0]
                    && !targets.contains(&child)
                {
                    targets.push(child);
                }
            }

            if targets.is_empty()
                && path[0] == entry.dep.name
                && let Some(child) = bound[index].child
            {
                targets.push(child);
            }

            for target in targets {
                patches.entry(target).or_default().push(path[1..].to_vec());
            }
        }
    }

    patches
}

/// Adds the boolean markers for conditions (`conditionsToPatch`) to a subchart's schema.
pub(super) fn patch_conditions(schema: &mut Schema, patches: &[Vec<String>]) {
    for patch in patches {
        let mut current = &mut *schema;

        for (i, key) in patch.iter().enumerate() {
            let last = i + 1 == patch.len();
            let properties = current.properties.get_or_insert_with(BTreeMap::new);

            if !properties.contains_key(key) {
                let created = if last {
                    Schema {
                        types: vec!["boolean".to_owned()],
                        title: key.clone(),
                        description: "Conditional property used in parent chart".to_owned(),
                        ..Schema::default()
                    }
                } else {
                    Schema {
                        types: vec!["object".to_owned()],
                        title: key.clone(),
                        properties: Some(BTreeMap::new()),
                        ..Schema::default()
                    }
                };

                properties.insert(key.clone(), created);
            }

            current = properties
                .get_mut(key)
                .expect("the property was just inserted");
        }
    }
}

/// `mergeSchemaProperties`: returns the names taken from `source`. An explicit annotation in the
/// target wins; an inferred target property is replaced by an annotated source.
fn merge_properties(
    target: &mut Schema,
    source: &Schema,
    skip: &BTreeSet<String>,
) -> BTreeSet<String> {
    let mut merged = BTreeSet::new();
    let Some(properties) = &source.properties else {
        return merged;
    };
    let mine = target.properties.get_or_insert_with(BTreeMap::new);

    for (name, schema) in properties {
        if name == "global" || skip.contains(name) {
            continue;
        }

        let replace = match mine.get(name) {
            None => true,
            Some(existing) => !existing.has_data && schema.has_data,
        };

        if replace {
            mine.insert(name.clone(), schema.clone());
            merged.insert(name.clone());
        }
    }

    merged
}

/// `processImportValues`: the properties imported into `parent`, as `(parent path, name)`.
fn import_values(
    parent: &mut Schema,
    dependency: &Schema,
    dep: &Dependency,
) -> Vec<(String, String)> {
    let mut imported = Vec::new();

    for entry in &dep.import_values {
        let (child, target) = match entry {
            Value::String(name) => (format!("exports.{name}"), String::new()),
            Value::Object(map) => (
                map.get("child")
                    .and_then(Value::as_str)
                    .unwrap_or_default()
                    .to_owned(),
                map.get("parent")
                    .and_then(Value::as_str)
                    .unwrap_or_default()
                    .to_owned(),
            ),
            _ => continue,
        };

        if child.is_empty() {
            continue;
        }

        let Some(source) = dependency
            .property_at(&child)
            .filter(|s| s.properties.is_some())
        else {
            continue;
        };
        let target_schema = if target.is_empty() {
            &mut *parent
        } else {
            parent.property_at_or_create(&target)
        };

        for name in merge_properties(target_schema, source, &BTreeSet::new()) {
            imported.push((target.clone(), name));
        }
    }

    imported
}

/// Merges the schema of the subchart `child` into `parent` as `dep` declares it.
pub(super) fn merge_dependency(
    parent: &mut Schema,
    dep: &Dependency,
    child: &Chart,
    child_schema: Schema,
) {
    let key = key_of(dep).to_owned();
    let dependency = child_schema.with_definition_prefix(&key);

    if let Some(definitions) = dependency.definitions.as_ref().filter(|d| !d.is_empty()) {
        let mine = parent.definitions.get_or_insert_with(BTreeMap::new);

        for (name, definition) in definitions {
            mine.entry(name.clone())
                .or_insert_with(|| definition.clone());
        }
    }

    let imported = import_values(parent, &dependency, dep);

    if child.metadata.chart_type == "library" {
        let skip = imported.into_iter().map(|(_, name)| name).collect();

        merge_properties(parent, &dependency, &skip);

        return;
    }

    let mut wrapper = Schema {
        types: vec!["object".to_owned()],
        title: dep.name.clone(),
        description: child.metadata.description.clone(),
        properties: dependency.properties,
        ..Schema::default()
    };

    if !dep.condition.is_empty() && !dep.condition.contains('.') {
        wrapper.types.push("boolean".to_owned());
    }

    wrapper.disable_required();

    for (path, name) in imported {
        let target = if path.is_empty() {
            &mut *parent
        } else {
            parent.property_at_or_create(&path)
        };

        if let Some(property) = target.properties.as_mut().and_then(|p| p.get_mut(&name)) {
            property.disable_required();
        }
    }

    parent
        .properties
        .get_or_insert_with(BTreeMap::new)
        .insert(key, wrapper);
}

/// `skip-dependencies-schema-validation`: dependencies leave `required` and accept anything.
pub(super) fn skip_validation(schema: &mut Schema, bound: &[Bound<'_>], filter: &[String]) {
    let names: Vec<&str> = bound
        .iter()
        .filter(|b| selected(b.dep, filter))
        .map(|b| key_of(b.dep))
        .collect();

    schema
        .required
        .strings
        .retain(|n| !names.contains(&n.as_str()));

    for name in names {
        if let Some(property) = schema.properties.as_mut().and_then(|p| p.get_mut(name)) {
            property.additional_properties = Some(Value::Bool(true));
        }
    }
}