Skip to main content

helm_rs/version/
mod.rs

1//! Semantic versions and constraints the way Helm reads them.
2//!
3//! Helm resolves chart versions, dependency ranges and `kubeVersion` with
4//! `github.com/Masterminds/semver/v3` (v3.5.0, the version Helm v4.3.0 pins). This module ports
5//! `NewVersion` (with the default `CoerceNewVersion`, the loose parser), `Version.Compare`,
6//! `NewConstraint` and `Constraints.Check` from `version.go` and `constraints.go`, including the
7//! pre-release rule: a pre-release matches only an `||` group in which some constraint itself
8//! names a pre-release. The Go regular expressions are hand-written scanners with the same
9//! results. Not ported: `IncludePrerelease` (Helm never sets it), `Validate`, `Inc`, `Set*`,
10//! `StrictNewVersion` and the (de)serialisation helpers.
11
12use std::cmp::Ordering;
13use std::fmt;
14
15#[cfg(test)]
16mod tests;
17
18/// The longest version string `NewVersion` accepts (`MaxVersionLen`).
19const MAX_VERSION_LEN: usize = 256;
20/// The longest constraint string `NewConstraint` accepts (`MaxConstraintLen`).
21const MAX_CONSTRAINT_LEN: usize = 512;
22/// The most `||` groups `NewConstraint` accepts (`MaxConstraintGroups`).
23const MAX_CONSTRAINT_GROUPS: usize = 32;
24
25/// Why a version or constraint was rejected; the messages are Masterminds'.
26#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
27#[non_exhaustive]
28pub enum Error {
29    /// The version string is longer than 256 bytes.
30    #[error("version string is too long (max {MAX_VERSION_LEN} bytes)")]
31    VersionTooLong,
32
33    /// The text is not a version (`ErrInvalidSemVer`).
34    #[error("invalid semantic version")]
35    InvalidVersion,
36
37    /// A numeric pre-release segment starts with `0` (`ErrSegmentStartsZero`).
38    #[error("version segment starts with 0")]
39    SegmentStartsZero,
40
41    /// A number does not fit in 64 bits.
42    #[error("error parsing version segment: number too large")]
43    SegmentTooLarge,
44
45    /// The constraint string is longer than 512 bytes.
46    #[error("constraint string is too long (max {MAX_CONSTRAINT_LEN} bytes)")]
47    ConstraintTooLong,
48
49    /// The constraint has more than 32 `||` groups.
50    #[error("too many constraint groups (max {MAX_CONSTRAINT_GROUPS})")]
51    TooManyConstraintGroups,
52
53    /// A `||` group is not a list of constraints (`improper constraint`).
54    #[error("improper constraint: {0:?}")]
55    ImproperConstraint(String),
56
57    /// A constraint operand is not a version (`constraint parser error`).
58    #[error("constraint parser error")]
59    ConstraintParser,
60}
61
62/// A semantic version as `NewVersion` reads it: an optional `v`, one to three numbers, a
63/// pre-release and build metadata. Leading zeros and missing minor or patch are accepted.
64#[derive(Debug, Clone, PartialEq, Eq, Default)]
65pub struct Version {
66    /// The major number.
67    pub major: u64,
68    /// The minor number (0 when absent).
69    pub minor: u64,
70    /// The patch number (0 when absent).
71    pub patch: u64,
72    /// The pre-release without the leading `-`.
73    pub pre: String,
74    /// The build metadata without the leading `+`.
75    pub metadata: String,
76}
77
78/// True for the characters of a pre-release or metadata identifier, `[0-9A-Za-z-]`.
79fn is_ident(byte: u8) -> bool {
80    byte.is_ascii_alphanumeric() || byte == b'-'
81}
82
83/// The end of the run of bytes at `from` that satisfy `pred`.
84fn run(bytes: &[u8], from: usize, pred: impl Fn(u8) -> bool) -> usize {
85    from + bytes[from..].iter().take_while(|b| pred(**b)).count()
86}
87
88/// True when `bytes[at]` exists and satisfies `pred`.
89fn at(bytes: &[u8], index: usize, pred: impl Fn(u8) -> bool) -> bool {
90    bytes.get(index).is_some_and(|b| pred(*b))
91}
92
93/// Scans `prefix ident(.ident)*` at `from` (`-pre` or `+metadata`); returns the identifiers and
94/// the end, or `None` when `bytes[from]` is not `prefix` followed by an identifier character.
95fn dotted(bytes: &[u8], from: usize, prefix: u8) -> Option<(&[u8], usize)> {
96    if !(bytes.get(from) == Some(&prefix) && at(bytes, from + 1, is_ident)) {
97        return None;
98    }
99
100    let mut end = run(bytes, from + 1, is_ident);
101
102    while bytes.get(end) == Some(&b'.') && at(bytes, end + 1, is_ident) {
103        end = run(bytes, end + 1, is_ident);
104    }
105
106    Some((&bytes[from + 1..end], end))
107}
108
109/// Parses a decimal number of ASCII digits.
110fn number(digits: &[u8]) -> Result<u64, Error> {
111    std::str::from_utf8(digits)
112        .ok()
113        .and_then(|d| d.parse().ok())
114        .ok_or(Error::SegmentTooLarge)
115}
116
117impl Version {
118    /// Parses a version like Masterminds' `NewVersion`: `v?N(.N)?(.N)?(-pre)?(+meta)?` where a
119    /// numeric pre-release segment may not have a leading zero.
120    pub fn parse(text: &str) -> Result<Self, Error> {
121        if text.len() > MAX_VERSION_LEN {
122            return Err(Error::VersionTooLong);
123        }
124
125        let bytes = text.as_bytes();
126        let start = usize::from(bytes.first() == Some(&b'v'));
127        let digit = |b: u8| b.is_ascii_digit();
128        let mut numbers = [0u64; 3];
129        let mut end = run(bytes, start, digit);
130
131        if end == start {
132            return Err(Error::InvalidVersion);
133        }
134
135        numbers[0] = number(&bytes[start..end])?;
136
137        for slot in &mut numbers[1..] {
138            if bytes.get(end) == Some(&b'.') && at(bytes, end + 1, digit) {
139                let next = run(bytes, end + 1, digit);
140
141                *slot = number(&bytes[end + 1..next])?;
142                end = next;
143            }
144        }
145
146        let pre = dotted(bytes, end, b'-');
147
148        end = pre.map_or(end, |(_, next)| next);
149
150        let metadata = dotted(bytes, end, b'+');
151
152        end = metadata.map_or(end, |(_, next)| next);
153
154        if end != bytes.len() {
155            return Err(Error::InvalidVersion);
156        }
157
158        let pre = pre.map_or(&[][..], |(ident, _)| ident);
159
160        for segment in pre.split(|b| *b == b'.').filter(|s| !s.is_empty()) {
161            if segment.len() > 1 && segment[0] == b'0' && segment.iter().all(u8::is_ascii_digit) {
162                return Err(Error::SegmentStartsZero);
163            }
164        }
165
166        Ok(Self {
167            major: numbers[0],
168            minor: numbers[1],
169            patch: numbers[2],
170            pre: String::from_utf8_lossy(pre).into_owned(),
171            metadata: metadata
172                .map(|(ident, _)| String::from_utf8_lossy(ident).into_owned())
173                .unwrap_or_default(),
174        })
175    }
176
177    /// Orders two versions like `Version.Compare`; build metadata is ignored.
178    #[must_use]
179    pub fn compare(&self, other: &Self) -> Ordering {
180        let core =
181            (self.major, self.minor, self.patch).cmp(&(other.major, other.minor, other.patch));
182
183        core.then_with(|| match (self.pre.is_empty(), other.pre.is_empty()) {
184            (true, true) => Ordering::Equal,
185            (true, false) => Ordering::Greater,
186            (false, true) => Ordering::Less,
187            (false, false) => compare_prerelease(&self.pre, &other.pre),
188        })
189    }
190}
191
192impl fmt::Display for Version {
193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)?;
195
196        if !self.pre.is_empty() {
197            write!(f, "-{}", self.pre)?;
198        }
199
200        if !self.metadata.is_empty() {
201            write!(f, "+{}", self.metadata)?;
202        }
203
204        Ok(())
205    }
206}
207
208/// `comparePrerelease`: dot-separated segments, numeric ones numerically and below text ones;
209/// a missing segment sorts first; text segments sort above numeric ones.
210fn compare_prerelease(a: &str, b: &str) -> Ordering {
211    let mut left = a.split('.');
212    let mut right = b.split('.');
213
214    loop {
215        let order = match (left.next(), right.next()) {
216            (None, None) => return Ordering::Equal,
217            (l, r) => compare_segment(l.unwrap_or(""), r.unwrap_or("")),
218        };
219
220        if order != Ordering::Equal {
221            return order;
222        }
223    }
224}
225
226/// `comparePrePart`; Go's text comparison is bytewise, like `str::cmp`. Two segments that
227/// differ never compare equal, so Go's "else -1" falls out of `cmp`.
228fn compare_segment(a: &str, b: &str) -> Ordering {
229    match (a, b) {
230        _ if a == b => Ordering::Equal,
231        ("", _) => Ordering::Less,
232        (_, "") => Ordering::Greater,
233        _ => match (a.parse::<u64>(), b.parse::<u64>()) {
234            (Ok(x), Ok(y)) => x.cmp(&y),
235            (Err(_), Err(_)) => a.cmp(b),
236            (Ok(_), Err(_)) => Ordering::Less,
237            (Err(_), Ok(_)) => Ordering::Greater,
238        },
239    }
240}
241
242mod constraints;
243
244pub use constraints::Constraints;