helm-rs 0.1.0

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! Version constraints in the syntax of `Masterminds/semver` v3 (used by helm-schema to bind a
//! dependency declaration to a chart): `||` alternatives, comma or space separated `AND`s, the
//! operators `= != > < >= <= ~ ~> ^`, `x`/`X`/`*` wildcards, partial versions and hyphen ranges.

use semver::Version;

/// A version with optional minor and patch (partial or wildcard parts are `None`).
struct Partial {
    major: u64,
    minor: Option<u64>,
    patch: Option<u64>,
    pre: String,
}

impl Partial {
    fn parse(text: &str) -> Option<Self> {
        let text = text.strip_prefix(['v', 'V']).unwrap_or(text);
        let text = text.split('+').next().unwrap_or(text);
        let (numbers, pre) = match text.split_once('-') {
            Some((n, p)) => (n, p.to_owned()),
            None => (text, String::new()),
        };
        let mut parts = numbers.split('.');
        let number = |p: Option<&str>| match p {
            None | Some("x" | "X" | "*" | "") => Some(None),
            Some(p) => p.parse::<u64>().ok().map(Some),
        };
        let major = number(parts.next())??;
        let minor = number(parts.next())?;
        let patch = number(parts.next())?;

        if parts.next().is_some() {
            return None;
        }

        Some(Self {
            major,
            minor,
            patch: if minor.is_some() { patch } else { None },
            pre,
        })
    }

    fn lower(&self) -> Version {
        build(
            self.major,
            self.minor.unwrap_or(0),
            self.patch.unwrap_or(0),
            &self.pre,
        )
    }

    fn next(&self) -> Version {
        match (self.minor, self.patch) {
            (None, _) => build(self.major + 1, 0, 0, ""),
            (Some(minor), None) => build(self.major, minor + 1, 0, ""),
            (Some(minor), Some(patch)) => build(self.major, minor, patch + 1, ""),
        }
    }

    fn exact(&self) -> bool {
        self.minor.is_some() && self.patch.is_some()
    }
}

fn build(major: u64, minor: u64, patch: u64, pre: &str) -> Version {
    let mut v = Version::new(major, minor, patch);

    if !pre.is_empty() {
        v.pre = semver::Prerelease::new(pre).unwrap_or_default();
    }

    v
}

/// Whether `version` (leniently parsed, as `semver.NewVersion` does) satisfies `constraint`.
///
/// # Errors
/// The constraint is not valid; helm-schema reports its text.
pub(super) fn satisfies(constraint: &str, version: &str) -> Result<bool, String> {
    let Some(v) = Partial::parse(version) else {
        return Ok(false);
    };
    let v = build(v.major, v.minor.unwrap_or(0), v.patch.unwrap_or(0), &v.pre);

    for group in constraint.split("||") {
        if group_matches(group, &v)? {
            return Ok(true);
        }
    }

    Ok(false)
}

fn group_matches(group: &str, v: &Version) -> Result<bool, String> {
    let text = group.trim();
    let tokens: Vec<&str> = text.split([',', ' ']).filter(|t| !t.is_empty()).collect();
    let mut constraints = Vec::new();
    let mut i = 0;

    while i < tokens.len() {
        let token = tokens[i];

        if tokens.get(i + 1) == Some(&"-") && tokens.len() > i + 2 {
            constraints.push((">=".to_owned(), tokens[i].to_owned()));
            constraints.push(("<=".to_owned(), tokens[i + 2].to_owned()));
            i += 3;

            continue;
        }

        let split = token
            .find(|c: char| !"=!<>~^".contains(c))
            .unwrap_or(token.len());
        let (op, rest) = token.split_at(split);

        if matches!(rest, "*" | "x" | "X") {
            constraints.push((">=".to_owned(), "0.0.0".to_owned()));
            i += 1;

            continue;
        }

        if rest.is_empty() {
            let Some(next) = tokens.get(i + 1) else {
                return Err(format!(
                    "improper constraint: {constraint}",
                    constraint = group.trim()
                ));
            };

            constraints.push((op.to_owned(), (*next).to_owned()));
            i += 2;
        } else {
            constraints.push((op.to_owned(), rest.to_owned()));
            i += 1;
        }
    }

    if constraints.is_empty() {
        return Err(format!("improper constraint: {}", group.trim()));
    }

    for (op, text) in &constraints {
        let partial = Partial::parse(text).ok_or_else(|| format!("improper constraint: {text}"))?;

        if !check(op, &partial, v)? {
            return Ok(false);
        }
    }

    Ok(true)
}

fn check(op: &str, c: &Partial, v: &Version) -> Result<bool, String> {
    if !v.pre.is_empty() && c.pre.is_empty() {
        return Ok(false);
    }

    let (low, next) = (c.lower(), c.next());

    Ok(match op {
        "" | "=" => v >= &low && (c.exact() && v == &low || !c.exact() && v < &next),
        "!=" => !(v >= &low && (c.exact() && v == &low || !c.exact() && v < &next)),
        ">" => {
            if c.exact() {
                v > &low
            } else {
                v >= &next
            }
        }
        "<" => v < &low,
        ">=" | "=>" => v >= &low,
        "<=" | "=<" => {
            if c.exact() {
                v <= &low
            } else {
                v < &next
            }
        }
        "~" | "~>" => v >= &low && v < &tilde_upper(c),
        "^" => v >= &low && v < &caret_upper(c),
        other => return Err(format!("improper constraint operator: {other}")),
    })
}

fn tilde_upper(c: &Partial) -> Version {
    match c.minor {
        None => build(c.major + 1, 0, 0, ""),
        Some(minor) => build(c.major, minor + 1, 0, ""),
    }
}

fn caret_upper(c: &Partial) -> Version {
    match (c.major, c.minor, c.patch) {
        (0, Some(0), Some(patch)) => build(0, 0, patch + 1, ""),
        (0, Some(minor), _) => build(0, minor + 1, 0, ""),
        (major, _, _) => build(major + 1, 0, 0, ""),
    }
}