helm-rs 0.1.2

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! Semantic versions and constraints the way Helm reads them.
//!
//! Helm resolves chart versions, dependency ranges and `kubeVersion` with
//! `github.com/Masterminds/semver/v3` (v3.5.0, the version Helm v4.3.0 pins). This module ports
//! `NewVersion` (with the default `CoerceNewVersion`, the loose parser), `Version.Compare`,
//! `NewConstraint` and `Constraints.Check` from `version.go` and `constraints.go`, including the
//! pre-release rule: a pre-release matches only an `||` group in which some constraint itself
//! names a pre-release. The Go regular expressions are hand-written scanners with the same
//! results. Not ported: `IncludePrerelease` (Helm never sets it), `Validate`, `Inc`, `Set*`,
//! `StrictNewVersion` and the (de)serialisation helpers.

use std::cmp::Ordering;
use std::fmt;

#[cfg(test)]
mod tests;

/// The longest version string `NewVersion` accepts (`MaxVersionLen`).
const MAX_VERSION_LEN: usize = 256;
/// The longest constraint string `NewConstraint` accepts (`MaxConstraintLen`).
const MAX_CONSTRAINT_LEN: usize = 512;
/// The most `||` groups `NewConstraint` accepts (`MaxConstraintGroups`).
const MAX_CONSTRAINT_GROUPS: usize = 32;

/// Why a version or constraint was rejected; the messages are Masterminds'.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The version string is longer than 256 bytes.
    #[error("version string is too long (max {MAX_VERSION_LEN} bytes)")]
    VersionTooLong,

    /// The text is not a version (`ErrInvalidSemVer`).
    #[error("invalid semantic version")]
    InvalidVersion,

    /// A numeric pre-release segment starts with `0` (`ErrSegmentStartsZero`).
    #[error("version segment starts with 0")]
    SegmentStartsZero,

    /// A number does not fit in 64 bits.
    #[error("error parsing version segment: number too large")]
    SegmentTooLarge,

    /// The constraint string is longer than 512 bytes.
    #[error("constraint string is too long (max {MAX_CONSTRAINT_LEN} bytes)")]
    ConstraintTooLong,

    /// The constraint has more than 32 `||` groups.
    #[error("too many constraint groups (max {MAX_CONSTRAINT_GROUPS})")]
    TooManyConstraintGroups,

    /// A `||` group is not a list of constraints (`improper constraint`).
    #[error("improper constraint: {0:?}")]
    ImproperConstraint(String),

    /// A constraint operand is not a version (`constraint parser error`).
    #[error("constraint parser error")]
    ConstraintParser,
}

/// A semantic version as `NewVersion` reads it: an optional `v`, one to three numbers, a
/// pre-release and build metadata. Leading zeros and missing minor or patch are accepted.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Version {
    /// The major number.
    pub major: u64,
    /// The minor number (0 when absent).
    pub minor: u64,
    /// The patch number (0 when absent).
    pub patch: u64,
    /// The pre-release without the leading `-`.
    pub pre: String,
    /// The build metadata without the leading `+`.
    pub metadata: String,
}

/// True for the characters of a pre-release or metadata identifier, `[0-9A-Za-z-]`.
fn is_ident(byte: u8) -> bool {
    byte.is_ascii_alphanumeric() || byte == b'-'
}

/// The end of the run of bytes at `from` that satisfy `pred`.
fn run(bytes: &[u8], from: usize, pred: impl Fn(u8) -> bool) -> usize {
    from + bytes[from..].iter().take_while(|b| pred(**b)).count()
}

/// True when `bytes[at]` exists and satisfies `pred`.
fn at(bytes: &[u8], index: usize, pred: impl Fn(u8) -> bool) -> bool {
    bytes.get(index).is_some_and(|b| pred(*b))
}

/// Scans `prefix ident(.ident)*` at `from` (`-pre` or `+metadata`); returns the identifiers and
/// the end, or `None` when `bytes[from]` is not `prefix` followed by an identifier character.
fn dotted(bytes: &[u8], from: usize, prefix: u8) -> Option<(&[u8], usize)> {
    if !(bytes.get(from) == Some(&prefix) && at(bytes, from + 1, is_ident)) {
        return None;
    }

    let mut end = run(bytes, from + 1, is_ident);

    while bytes.get(end) == Some(&b'.') && at(bytes, end + 1, is_ident) {
        end = run(bytes, end + 1, is_ident);
    }

    Some((&bytes[from + 1..end], end))
}

/// Parses a decimal number of ASCII digits.
fn number(digits: &[u8]) -> Result<u64, Error> {
    std::str::from_utf8(digits)
        .ok()
        .and_then(|d| d.parse().ok())
        .ok_or(Error::SegmentTooLarge)
}

impl Version {
    /// Parses a version like Masterminds' `NewVersion`: `v?N(.N)?(.N)?(-pre)?(+meta)?` where a
    /// numeric pre-release segment may not have a leading zero.
    pub fn parse(text: &str) -> Result<Self, Error> {
        if text.len() > MAX_VERSION_LEN {
            return Err(Error::VersionTooLong);
        }

        let bytes = text.as_bytes();
        let start = usize::from(bytes.first() == Some(&b'v'));
        let digit = |b: u8| b.is_ascii_digit();
        let mut numbers = [0u64; 3];
        let mut end = run(bytes, start, digit);

        if end == start {
            return Err(Error::InvalidVersion);
        }

        numbers[0] = number(&bytes[start..end])?;

        for slot in &mut numbers[1..] {
            if bytes.get(end) == Some(&b'.') && at(bytes, end + 1, digit) {
                let next = run(bytes, end + 1, digit);

                *slot = number(&bytes[end + 1..next])?;
                end = next;
            }
        }

        let pre = dotted(bytes, end, b'-');

        end = pre.map_or(end, |(_, next)| next);

        let metadata = dotted(bytes, end, b'+');

        end = metadata.map_or(end, |(_, next)| next);

        if end != bytes.len() {
            return Err(Error::InvalidVersion);
        }

        let pre = pre.map_or(&[][..], |(ident, _)| ident);

        for segment in pre.split(|b| *b == b'.').filter(|s| !s.is_empty()) {
            if segment.len() > 1 && segment[0] == b'0' && segment.iter().all(u8::is_ascii_digit) {
                return Err(Error::SegmentStartsZero);
            }
        }

        Ok(Self {
            major: numbers[0],
            minor: numbers[1],
            patch: numbers[2],
            pre: String::from_utf8_lossy(pre).into_owned(),
            metadata: metadata
                .map(|(ident, _)| String::from_utf8_lossy(ident).into_owned())
                .unwrap_or_default(),
        })
    }

    /// Orders two versions like `Version.Compare`; build metadata is ignored.
    #[must_use]
    pub fn compare(&self, other: &Self) -> Ordering {
        let core =
            (self.major, self.minor, self.patch).cmp(&(other.major, other.minor, other.patch));

        core.then_with(|| match (self.pre.is_empty(), other.pre.is_empty()) {
            (true, true) => Ordering::Equal,
            (true, false) => Ordering::Greater,
            (false, true) => Ordering::Less,
            (false, false) => compare_prerelease(&self.pre, &other.pre),
        })
    }
}

impl fmt::Display for Version {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)?;

        if !self.pre.is_empty() {
            write!(f, "-{}", self.pre)?;
        }

        if !self.metadata.is_empty() {
            write!(f, "+{}", self.metadata)?;
        }

        Ok(())
    }
}

/// `comparePrerelease`: dot-separated segments, numeric ones numerically and below text ones;
/// a missing segment sorts first; text segments sort above numeric ones.
fn compare_prerelease(a: &str, b: &str) -> Ordering {
    let mut left = a.split('.');
    let mut right = b.split('.');

    loop {
        let order = match (left.next(), right.next()) {
            (None, None) => return Ordering::Equal,
            (l, r) => compare_segment(l.unwrap_or(""), r.unwrap_or("")),
        };

        if order != Ordering::Equal {
            return order;
        }
    }
}

/// `comparePrePart`; Go's text comparison is bytewise, like `str::cmp`. Two segments that
/// differ never compare equal, so Go's "else -1" falls out of `cmp`.
fn compare_segment(a: &str, b: &str) -> Ordering {
    match (a, b) {
        _ if a == b => Ordering::Equal,
        ("", _) => Ordering::Less,
        (_, "") => Ordering::Greater,
        _ => match (a.parse::<u64>(), b.parse::<u64>()) {
            (Ok(x), Ok(y)) => x.cmp(&y),
            (Err(_), Err(_)) => a.cmp(b),
            (Ok(_), Err(_)) => Ordering::Less,
            (Err(_), Ok(_)) => Ordering::Greater,
        },
    }
}

mod constraints;

pub use constraints::Constraints;