Skip to main content

helm_rs/version/
constraints.rs

1//! Version constraints (`constraints.go` of Masterminds semver v3.5.0).
2
3use std::cmp::Ordering;
4
5use super::{Error, MAX_CONSTRAINT_GROUPS, MAX_CONSTRAINT_LEN, Version, is_ident, run};
6
7/// A parsed constraint such as `>= 1.2, < 2 || ^3`: `||` groups of constraints that must all hold.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct Constraints {
10    groups: Vec<Group>,
11}
12
13/// One `||` alternative.
14#[derive(Debug, Clone, PartialEq, Eq)]
15struct Group {
16    terms: Vec<Term>,
17    contains_pre: bool,
18}
19
20/// One operator and operand (`constraint`).
21#[derive(Debug, Clone, PartialEq, Eq)]
22struct Term {
23    op: Op,
24    version: Version,
25    minor_dirty: bool,
26    patch_dirty: bool,
27    dirty: bool,
28}
29
30/// The operators of `constraintOps`; `=` and the empty operator are the same.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32enum Op {
33    TildeOrEqual,
34    NotEqual,
35    Greater,
36    Less,
37    GreaterEqual,
38    LessEqual,
39    Tilde,
40    Caret,
41}
42
43/// The operand text of a term, split like the groups of `cvRegex`.
44struct Operand<'a> {
45    whole: &'a str,
46    major: &'a str,
47    minor: &'a str,
48    patch: &'a str,
49    pre: &'a str,
50}
51
52/// True for the characters of an operand number, `[0-9|xX*]`.
53fn is_num(byte: u8) -> bool {
54    byte.is_ascii_digit() || matches!(byte, b'|' | b'x' | b'X' | b'*')
55}
56
57/// True for `x`, `X` and `*` (`isX`).
58fn is_x(text: &str) -> bool {
59    matches!(text, "x" | "X" | "*")
60}
61
62/// Scans an operand (`cvRegex`) at `from`: `v?N(.N)?(.N)?(-pre)?(+meta)?` with `N = [0-9|xX*]+`.
63fn operand(text: &str, from: usize) -> Option<(Operand<'_>, usize)> {
64    let bytes = text.as_bytes();
65    let start = from + usize::from(bytes.get(from) == Some(&b'v'));
66    let major_end = run(bytes, start, is_num);
67    let mut end = major_end;
68    let mut parts = [""; 2];
69
70    if major_end == start {
71        return None;
72    }
73
74    for part in &mut parts {
75        if bytes.get(end) == Some(&b'.') && bytes.get(end + 1).is_some_and(|b| is_num(*b)) {
76            let next = run(bytes, end + 1, is_num);
77
78            *part = &text[end + 1..next];
79            end = next;
80        }
81    }
82
83    let pre_start = end;
84
85    if bytes.get(end) == Some(&b'-') && bytes.get(end + 1).is_some_and(|b| is_ident(*b)) {
86        end = run(bytes, end + 1, is_ident);
87
88        while bytes.get(end) == Some(&b'.') && bytes.get(end + 1).is_some_and(|b| is_ident(*b)) {
89            end = run(bytes, end + 1, is_ident);
90        }
91    }
92
93    let pre = &text[pre_start..end];
94
95    if bytes.get(end) == Some(&b'+') && bytes.get(end + 1).is_some_and(|b| is_ident(*b)) {
96        end = run(bytes, end + 1, is_ident);
97
98        while bytes.get(end) == Some(&b'.') && bytes.get(end + 1).is_some_and(|b| is_ident(*b)) {
99            end = run(bytes, end + 1, is_ident);
100        }
101    }
102
103    let operand = Operand {
104        whole: &text[from..end],
105        major: &text[start..major_end],
106        minor: parts[0],
107        patch: parts[1],
108        pre,
109    };
110
111    Some((operand, end))
112}
113
114/// Skips whitespace (Go's `\s`: space, tab, newline, form feed, carriage return).
115fn skip_space(bytes: &[u8], from: usize) -> usize {
116    run(bytes, from, |b| {
117        matches!(b, b' ' | b'\t' | b'\n' | 0x0c | b'\r')
118    })
119}
120
121/// `rewriteRange`: replaces each `a - b` with `>= a, <= b `.
122pub(super) fn rewrite_range(text: &str) -> String {
123    let bytes = text.as_bytes();
124    let mut rewritten = text.to_owned();
125    let mut index = 0;
126
127    while index < bytes.len() {
128        let Some((matched, low, high)) = range_at(text, index) else {
129            index += 1;
130
131            continue;
132        };
133
134        rewritten = rewritten.replacen(&text[index..matched], &format!(">= {low}, <= {high} "), 1);
135        index = matched;
136    }
137
138    rewritten
139}
140
141/// Matches `\s*cv\s+-\s+cv\s*` at `from`; returns the end and the two operands.
142fn range_at(text: &str, from: usize) -> Option<(usize, &str, &str)> {
143    let bytes = text.as_bytes();
144    let (low, end) = operand(text, skip_space(bytes, from))?;
145    let after_low = skip_space(bytes, end);
146
147    if after_low == end || bytes.get(after_low) != Some(&b'-') {
148        return None;
149    }
150
151    let start_high = skip_space(bytes, after_low + 1);
152
153    if start_high == after_low + 1 {
154        return None;
155    }
156
157    let (high, end) = operand(text, start_high)?;
158
159    Some((skip_space(bytes, end), low.whole, high.whole))
160}
161
162/// Reads the operator at `from` (the run of `=!<>~^`), returning it and the end.
163fn operator(bytes: &[u8], from: usize) -> Option<(Op, usize)> {
164    let end = run(bytes, from, |b| {
165        matches!(b, b'=' | b'!' | b'<' | b'>' | b'~' | b'^')
166    });
167    let op = match &bytes[from..end] {
168        b"" | b"=" => Op::TildeOrEqual,
169        b"!=" => Op::NotEqual,
170        b">" => Op::Greater,
171        b"<" => Op::Less,
172        b">=" | b"=>" => Op::GreaterEqual,
173        b"<=" | b"=<" => Op::LessEqual,
174        b"~" | b"~>" => Op::Tilde,
175        b"^" => Op::Caret,
176        _ => return None,
177    };
178
179    Some((op, end))
180}
181
182impl Term {
183    /// `parseConstraint`: an operand with a wildcard or missing part is "dirty" and reads as zeros.
184    fn new(op: Op, operand: &Operand<'_>) -> Result<Self, Error> {
185        let pre = operand.pre;
186        let mut term = Self {
187            op,
188            version: Version::default(),
189            minor_dirty: false,
190            patch_dirty: false,
191            dirty: false,
192        };
193        let text = if is_x(operand.major) {
194            term.dirty = true;
195
196            format!("0.0.0{pre}")
197        } else if operand.minor.is_empty() || is_x(operand.minor) {
198            term.minor_dirty = true;
199            term.dirty = true;
200
201            format!("{}.0.0{pre}", operand.major)
202        } else if operand.patch.is_empty() || is_x(operand.patch) {
203            term.patch_dirty = true;
204            term.dirty = true;
205
206            format!("{}.{}.0{pre}", operand.major, operand.minor)
207        } else {
208            operand.whole.to_owned()
209        };
210
211        term.version = Version::parse(&text).map_err(|_| Error::ConstraintParser)?;
212
213        Ok(term)
214    }
215
216    /// The `constraint.check` of this term for `v`.
217    fn check(&self, v: &Version, include_pre: bool) -> bool {
218        let c = &self.version;
219
220        if !v.pre.is_empty() && !include_pre {
221            return false;
222        }
223
224        match self.op {
225            Op::NotEqual => self.not_equal(v),
226            Op::Greater => self.greater(v),
227            Op::Less => v.compare(c) == Ordering::Less,
228            Op::GreaterEqual => v.compare(c) != Ordering::Less,
229            Op::LessEqual => self.less_equal(v),
230            Op::Tilde => self.tilde(v),
231            Op::TildeOrEqual if self.dirty => self.tilde(v),
232            Op::TildeOrEqual => v.compare(c) == Ordering::Equal,
233            Op::Caret => self.caret(v),
234        }
235    }
236
237    fn not_equal(&self, v: &Version) -> bool {
238        let c = &self.version;
239
240        if self.dirty {
241            if c.major != v.major {
242                return true;
243            }
244
245            if c.minor != v.minor && !self.minor_dirty {
246                return true;
247            } else if self.minor_dirty {
248                return false;
249            } else if c.patch != v.patch && !self.patch_dirty {
250                return true;
251            } else if self.patch_dirty {
252                if !v.pre.is_empty() || !c.pre.is_empty() {
253                    return super::compare_prerelease(&v.pre, &c.pre) != Ordering::Equal;
254                }
255
256                return false;
257            }
258        }
259
260        v.compare(c) != Ordering::Equal
261    }
262
263    fn greater(&self, v: &Version) -> bool {
264        let c = &self.version;
265
266        if !self.dirty {
267            return v.compare(c) == Ordering::Greater;
268        }
269
270        if v.major != c.major {
271            return v.major > c.major;
272        }
273
274        if self.minor_dirty {
275            return false;
276        }
277
278        if self.patch_dirty {
279            return v.minor > c.minor;
280        }
281
282        v.compare(c) == Ordering::Greater
283    }
284
285    fn less_equal(&self, v: &Version) -> bool {
286        let c = &self.version;
287
288        if !self.dirty {
289            return v.compare(c) != Ordering::Greater;
290        }
291
292        if v.major > c.major {
293            return false;
294        }
295
296        !(v.major == c.major && v.minor > c.minor && !self.minor_dirty)
297    }
298
299    fn tilde(&self, v: &Version) -> bool {
300        let c = &self.version;
301
302        if v.compare(c) == Ordering::Less {
303            return false;
304        }
305
306        if c.major == 0 && c.minor == 0 && c.patch == 0 && !self.minor_dirty && !self.patch_dirty {
307            return true;
308        }
309
310        if v.major != c.major {
311            return false;
312        }
313
314        v.minor == c.minor || self.minor_dirty
315    }
316
317    fn caret(&self, v: &Version) -> bool {
318        let c = &self.version;
319
320        if v.compare(c) == Ordering::Less {
321            return false;
322        }
323
324        if c.major > 0 || self.minor_dirty {
325            return v.major == c.major;
326        }
327
328        if v.major > 0 {
329            return false;
330        }
331
332        if c.minor > 0 || self.patch_dirty {
333            return v.minor == c.minor;
334        }
335
336        if v.minor > 0 {
337            return false;
338        }
339
340        c.patch == v.patch
341    }
342}
343
344/// Parses one `||` group (`validConstraintRegex` plus `findConstraintRegex`): operator and
345/// operand terms separated by whitespace or a comma.
346fn parse_group(text: &str) -> Result<Group, Error> {
347    let improper = || Error::ImproperConstraint(text.to_owned());
348    let bytes = text.as_bytes();
349    let mut terms = Vec::new();
350    let mut index = skip_space(bytes, 0);
351
352    loop {
353        let (op, after_op) = operator(bytes, index).ok_or_else(improper)?;
354        let (operand, end) = operand(text, skip_space(bytes, after_op)).ok_or_else(improper)?;
355        let spaced = skip_space(bytes, end);
356
357        terms.push(Term::new(op, &operand)?);
358
359        if spaced == bytes.len() {
360            break;
361        }
362
363        index = if bytes[spaced] == b',' {
364            skip_space(bytes, spaced + 1)
365        } else if spaced > end {
366            spaced
367        } else {
368            return Err(improper());
369        };
370
371        if index == bytes.len() {
372            return Err(improper());
373        }
374    }
375
376    let contains_pre = terms.iter().any(|t| !t.version.pre.is_empty());
377
378    Ok(Group {
379        terms,
380        contains_pre,
381    })
382}
383
384impl Constraints {
385    /// Parses a constraint like `NewConstraint`: `,` or whitespace is AND, `||` is OR, with the
386    /// operators `=`, `!=`, `>`, `<`, `>=`, `<=`, `~`, `^`, `x`/`X`/`*` wildcards and hyphen ranges.
387    pub fn parse(text: &str) -> Result<Self, Error> {
388        if text.len() > MAX_CONSTRAINT_LEN {
389            return Err(Error::ConstraintTooLong);
390        }
391
392        let rewritten = rewrite_range(text);
393        let groups: Vec<&str> = rewritten.split("||").collect();
394
395        if groups.len() > MAX_CONSTRAINT_GROUPS {
396            return Err(Error::TooManyConstraintGroups);
397        }
398
399        Ok(Self {
400            groups: groups
401                .into_iter()
402                .map(parse_group)
403                .collect::<Result<_, _>>()?,
404        })
405    }
406
407    /// Reports whether `version` satisfies any `||` group, like `Constraints.Check`. A
408    /// pre-release version matches only a group in which some constraint names a pre-release.
409    #[must_use]
410    pub fn matches(&self, version: &Version) -> bool {
411        self.groups
412            .iter()
413            .any(|g| g.terms.iter().all(|t| t.check(version, g.contains_pre)))
414    }
415}
416
417#[cfg(test)]
418impl Constraints {
419    /// The number of `||` groups and the number of terms in the first group.
420    pub(super) fn shape(&self) -> (usize, usize) {
421        (self.groups.len(), self.groups[0].terms.len())
422    }
423}