Skip to main content

libtea_core/
vers.rs

1//! `vers` version ranges (the version-range notation CLE and PURL use),
2//! parsed in full and evaluated for SemVer and PyPI versions.
3//!
4//! **Experimental:** may change in a 0.x minor release.
5//!
6//! [`VersRange::parse`] checks the syntax of any `vers:<type>/<constraints>`
7//! string. [`VersRange::contains_semver`] then evaluates it when its type
8//! compares versions as SemVer 2.0 ([`VersRange::is_semver_type`]): `semver`,
9//! and `npm`, whose registered `vers` type uses node-semver versions.
10//! [`VersRange::contains_pypi`] evaluates the `pypi` type with PEP 440
11//! ordering ([`crate::pep440`]). Every other type is reported as unsupported,
12//! never guessed.
13//!
14//! The rules are from the `vers` specification, release `v1.2.1` of
15//! <https://github.com/package-url/vers-spec> (`docs/specification/`):
16//! constraints are sorted by version, each version occurs once, `*` stands
17//! alone, and outside `!=` the comparators alternate between lower and upper
18//! bounds. A range that breaks these rules is an error, not corrected.
19
20use std::cmp::Ordering;
21
22use thiserror::Error;
23
24use crate::pep440::Pep440Version;
25
26/// Inputs longer than this are rejected with [`VersError::TooLong`].
27pub const MAX_VERS_BYTES: usize = 4096;
28
29/// Why a string is not a valid `vers` range, or could not be evaluated.
30///
31/// **Experimental:** may change in a 0.x minor release.
32#[derive(Debug, Clone, PartialEq, Eq, Error)]
33#[non_exhaustive]
34pub enum VersError {
35    /// Longer than [`MAX_VERS_BYTES`].
36    #[error("vers range is longer than {MAX_VERS_BYTES} bytes")]
37    TooLong,
38    /// The scheme is missing or is not lowercase `vers`.
39    #[error("vers range must start with `vers:`")]
40    Scheme,
41    /// The type is missing, not lowercase, does not start with a letter, or
42    /// has characters other than ASCII letters, digits, `.` and `-`.
43    #[error("vers type is missing or invalid")]
44    Type,
45    /// Nothing after `vers:<type>/`.
46    #[error("vers constraints are empty")]
47    Empty,
48    /// Literal ASCII whitespace anywhere in the string, or a decoded version
49    /// with whitespace other than a space.
50    #[error("vers range contains whitespace")]
51    Whitespace,
52    /// A leading, trailing or repeated `|`.
53    #[error("vers constraints have an empty segment")]
54    EmptyConstraint,
55    /// A constraint starts with `=`; equality is a bare version.
56    #[error("vers constraint starts with `=`")]
57    LeadingEquals,
58    /// A comparator with no version after it.
59    #[error("vers constraint has no version")]
60    EmptyVersion,
61    /// `*` together with other constraints, or `*` followed by a version.
62    #[error("vers `*` must stand alone")]
63    Asterisk,
64    /// A `%` not followed by two hex digits, decoded bytes that are not UTF-8,
65    /// or an unencoded character the specification reserves.
66    #[error("vers version has an invalid percent-encoding")]
67    Encoding,
68    /// The type is not one the evaluating method handles (SemVer types for
69    /// [`VersRange::contains_semver`], `pypi` for [`VersRange::contains_pypi`]).
70    #[error("vers type is not evaluated by this method")]
71    UnsupportedType,
72    /// A constraint version is not a SemVer 2.0 version.
73    #[error("vers version is not a SemVer version")]
74    NotSemver,
75    /// Constraints are not sorted by version, or a version occurs twice.
76    #[error("vers constraints are not sorted by version or repeat one")]
77    Order,
78    /// Comparators do not alternate between lower and upper bounds.
79    #[error("vers constraints have an invalid comparator sequence")]
80    Sequence,
81    /// A constraint version of a `pypi` range is not a PEP 440 version.
82    #[error("vers version is not a PEP 440 version")]
83    NotPep440,
84}
85
86/// The comparator of one constraint.
87///
88/// **Experimental:** may change in a 0.x minor release.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
90#[non_exhaustive]
91pub enum Comparator {
92    /// A bare version: equal to it.
93    Equal,
94    /// `!=`: excluded.
95    NotEqual,
96    /// `<`.
97    Less,
98    /// `<=`.
99    LessOrEqual,
100    /// `>`.
101    Greater,
102    /// `>=`.
103    GreaterOrEqual,
104}
105
106impl Comparator {
107    /// The comparator as written in a range (empty for [`Self::Equal`]).
108    #[must_use]
109    pub fn as_str(self) -> &'static str {
110        match self {
111            Self::Equal => "",
112            Self::NotEqual => "!=",
113            Self::Less => "<",
114            Self::LessOrEqual => "<=",
115            Self::Greater => ">",
116            Self::GreaterOrEqual => ">=",
117        }
118    }
119
120    fn is_upper(self) -> bool {
121        matches!(self, Self::Less | Self::LessOrEqual)
122    }
123
124    fn is_lower(self) -> bool {
125        matches!(self, Self::Greater | Self::GreaterOrEqual)
126    }
127}
128
129/// One constraint: a comparator and a percent-decoded version.
130///
131/// **Experimental:** may change in a 0.x minor release.
132#[derive(Debug, Clone, PartialEq, Eq, Hash)]
133pub struct Constraint {
134    comparator: Comparator,
135    version: String,
136}
137
138impl Constraint {
139    /// The comparator.
140    #[must_use]
141    pub fn comparator(&self) -> Comparator {
142        self.comparator
143    }
144
145    /// The version, percent-decoded once.
146    #[must_use]
147    pub fn version(&self) -> &str {
148        &self.version
149    }
150}
151
152/// A parsed `vers` range.
153///
154/// **Experimental:** may change in a 0.x minor release.
155///
156/// ```
157/// use libtea_core::vers::VersRange;
158///
159/// let range = VersRange::parse("vers:npm/>=1.0.0|!=1.2.0|<2.0.0").unwrap();
160/// let v = |s: &str| semver::Version::parse(s).unwrap();
161/// assert_eq!(range.contains_semver(&v("1.5.0")), Ok(true));
162/// assert_eq!(range.contains_semver(&v("1.2.0")), Ok(false));
163/// assert_eq!(range.contains_semver(&v("2.0.0")), Ok(false));
164/// assert_eq!(range.contains_semver(&v("2.0.0-rc.1")), Ok(true));
165/// ```
166#[derive(Debug, Clone, PartialEq, Eq, Hash)]
167pub struct VersRange {
168    version_type: String,
169    any: bool,
170    constraints: Vec<Constraint>,
171}
172
173impl VersRange {
174    /// Parse `vers:<type>/<constraints>` as the specification's
175    /// "How to parse" describes. Ordering and comparator rules depend on how
176    /// the type compares versions, so they are checked by
177    /// [`Self::contains_semver`], not here.
178    ///
179    /// # Errors
180    ///
181    /// Returns [`VersError`] for a missing or wrong scheme or type, empty
182    /// constraints or constraint segments, whitespace, a leading `=`, an empty
183    /// version, a misplaced `*`, invalid percent-encoding, or a string longer
184    /// than [`MAX_VERS_BYTES`].
185    pub fn parse(text: &str) -> Result<Self, VersError> {
186        if text.len() > MAX_VERS_BYTES {
187            return Err(VersError::TooLong);
188        }
189        if text.bytes().any(|b| b.is_ascii_whitespace()) {
190            return Err(VersError::Whitespace);
191        }
192        let (scheme, specifier) = text.split_once(':').ok_or(VersError::Scheme)?;
193        if scheme != "vers" {
194            return Err(VersError::Scheme);
195        }
196        let (version_type, constraints) = specifier.split_once('/').ok_or(VersError::Type)?;
197        if !valid_type(version_type) {
198            return Err(VersError::Type);
199        }
200        if constraints.is_empty() {
201            return Err(VersError::Empty);
202        }
203        if constraints == "*" {
204            return Ok(Self {
205                version_type: version_type.to_owned(),
206                any: true,
207                constraints: Vec::new(),
208            });
209        }
210        let mut parsed = Vec::new();
211        for segment in constraints.split('|') {
212            if segment.is_empty() {
213                return Err(VersError::EmptyConstraint);
214            }
215            if segment.contains('*') {
216                return Err(VersError::Asterisk);
217            }
218            let (comparator, rest) = split_comparator(segment)?;
219            if rest.is_empty() {
220                return Err(VersError::EmptyVersion);
221            }
222            if rest.contains(['<', '>', '=', '!']) {
223                return Err(VersError::Encoding);
224            }
225            let version = percent_decode(rest)?;
226            // Only an encoded space is allowed; `%09` is still a tab.
227            if version
228                .bytes()
229                .any(|b| b.is_ascii_whitespace() && b != b' ')
230            {
231                return Err(VersError::Whitespace);
232            }
233            parsed.push(Constraint {
234                comparator,
235                version,
236            });
237        }
238        Ok(Self {
239            version_type: version_type.to_owned(),
240            any: false,
241            constraints: parsed,
242        })
243    }
244
245    /// Parse a range as ECMA-428 (CLE, 1st edition) Annex A, clause A.4, says
246    /// to: remove every space and tab, ignore leading, trailing and repeated
247    /// `|`, then parse as [`Self::parse`]. CLE ranges follow Annex A, which is
248    /// more lenient here than the vers-spec text [`Self::parse`] follows; the
249    /// lifecycle evaluation in [`crate::lifecycle`] uses this method.
250    ///
251    /// **Experimental:** may change in a 0.x minor release.
252    ///
253    /// ```
254    /// use libtea_core::vers::{VersError, VersRange};
255    ///
256    /// let lenient = VersRange::parse_cle("vers:npm/ >= 1.0.0 || < 2.0.0 |").unwrap();
257    /// assert_eq!(lenient, VersRange::parse("vers:npm/>=1.0.0|<2.0.0").unwrap());
258    /// assert_eq!(VersRange::parse("vers:npm/>=1.0.0| <2.0.0"), Err(VersError::Whitespace));
259    /// assert_eq!(VersRange::parse_cle("vers:npm/||"), Err(VersError::Empty));
260    /// ```
261    ///
262    /// # Errors
263    ///
264    /// As [`Self::parse`], except that spaces, tabs and empty `|` segments are
265    /// not errors. Other whitespace (a line break) still is.
266    pub fn parse_cle(text: &str) -> Result<Self, VersError> {
267        if text.len() > MAX_VERS_BYTES {
268            return Err(VersError::TooLong);
269        }
270        let compact: String = text.chars().filter(|c| !matches!(c, ' ' | '\t')).collect();
271        let Some((head, constraints)) = compact.split_once('/') else {
272            return Self::parse(&compact);
273        };
274        let segments: Vec<&str> = constraints.split('|').filter(|s| !s.is_empty()).collect();
275        Self::parse(&format!("{head}/{}", segments.join("|")))
276    }
277
278    /// The `vers` type, such as `npm` or `semver`.
279    #[must_use]
280    pub fn version_type(&self) -> &str {
281        &self.version_type
282    }
283
284    /// Whether the range is `*` (every version).
285    #[must_use]
286    pub fn is_any(&self) -> bool {
287        self.any
288    }
289
290    /// The constraints in the order written. Empty for `*`.
291    #[must_use]
292    pub fn constraints(&self) -> &[Constraint] {
293        &self.constraints
294    }
295
296    /// Whether this type's versions are compared as SemVer 2.0 here:
297    /// `semver`, and `npm` (node-semver versions).
298    #[must_use]
299    pub fn is_semver_type(&self) -> bool {
300        matches!(self.version_type.as_str(), "semver" | "npm")
301    }
302
303    /// Whether `version` is in the range, comparing as SemVer 2.0 (build
304    /// metadata ignored, pre-releases ordered before their release).
305    ///
306    /// The range is validated first: constraint versions must be SemVer,
307    /// sorted, unique, and in a valid comparator sequence.
308    ///
309    /// # Errors
310    ///
311    /// [`VersError::UnsupportedType`] when [`Self::is_semver_type`] is false,
312    /// [`VersError::NotSemver`] for a constraint version that does not parse,
313    /// and [`VersError::Order`] or [`VersError::Sequence`] for a range the
314    /// specification calls invalid.
315    pub fn contains_semver(&self, version: &semver::Version) -> Result<bool, VersError> {
316        if !self.is_semver_type() {
317            return Err(VersError::UnsupportedType);
318        }
319        self.contains_with(
320            version,
321            |text| semver::Version::parse(text).map_err(|_| VersError::NotSemver),
322            precedence,
323        )
324    }
325
326    /// Whether this range's versions are compared as PEP 440 versions here:
327    /// the `pypi` type.
328    #[must_use]
329    pub fn is_pypi_type(&self) -> bool {
330        self.version_type == "pypi"
331    }
332
333    /// Whether `version` is in the range, comparing with PEP 440 ordering
334    /// ([`crate::pep440`]): `1.0 == 1.0.0`, and
335    /// `1.0.dev1 < 1.0a1 < 1.0 < 1.0.post1 < 1.0.1`.
336    ///
337    /// Only the ordering is used, as `vers` asks: PEP 440's own specifier
338    /// rules (such as `<1.0` excluding `1.0a1`) do not apply, so
339    /// `vers:pypi/<1.0` contains `1.0a1`. The range is validated first, as
340    /// for [`Self::contains_semver`].
341    ///
342    /// ```
343    /// use libtea_core::pep440::Pep440Version;
344    /// use libtea_core::vers::VersRange;
345    ///
346    /// let range = VersRange::parse("vers:pypi/>=1.0|<2.0").unwrap();
347    /// let v = |s: &str| Pep440Version::parse(s).unwrap();
348    /// assert_eq!(range.contains_pypi(&v("1.5.post1")), Ok(true));
349    /// assert_eq!(range.contains_pypi(&v("1.0.0")), Ok(true));
350    /// assert_eq!(range.contains_pypi(&v("2.0rc1")), Ok(true));
351    /// assert_eq!(range.contains_pypi(&v("2.0")), Ok(false));
352    /// ```
353    ///
354    /// # Errors
355    ///
356    /// [`VersError::UnsupportedType`] when [`Self::is_pypi_type`] is false,
357    /// [`VersError::NotPep440`] for a constraint version that does not parse,
358    /// and [`VersError::Order`] or [`VersError::Sequence`] for a range the
359    /// specification calls invalid (including `1.0|1.0.0`, which repeats a
360    /// version).
361    pub fn contains_pypi(&self, version: &Pep440Version) -> Result<bool, VersError> {
362        if !self.is_pypi_type() {
363            return Err(VersError::UnsupportedType);
364        }
365        self.contains_with(
366            version,
367            |text| Pep440Version::parse(text).map_err(|_| VersError::NotPep440),
368            Ord::cmp,
369        )
370    }
371
372    /// Validate the constraints and evaluate them for `version`, with
373    /// `parse` for constraint versions and `order` for comparing them.
374    fn contains_with<T>(
375        &self,
376        version: &T,
377        parse: impl Fn(&str) -> Result<T, VersError>,
378        order: impl Fn(&T, &T) -> Ordering,
379    ) -> Result<bool, VersError> {
380        if self.any {
381            return Ok(true);
382        }
383        let mut bounds = Vec::with_capacity(self.constraints.len());
384        for constraint in &self.constraints {
385            bounds.push((constraint.comparator, parse(&constraint.version)?));
386        }
387        validate(&bounds, &order)?;
388
389        // Equality first: an inclusive constraint on the version includes it,
390        // a `!=` on it excludes it. Versions are unique, so these never clash.
391        for (comparator, bound) in &bounds {
392            if order(version, bound) == Ordering::Equal {
393                // `!=` excludes it; `<` and `>` do not include their own version.
394                return Ok(!matches!(
395                    comparator,
396                    Comparator::NotEqual | Comparator::Less | Comparator::Greater
397                ));
398            }
399        }
400        // Then the intervals the remaining bounds describe, in version order.
401        let ranges: Vec<_> = bounds
402            .iter()
403            .filter(|(comparator, _)| comparator.is_lower() || comparator.is_upper())
404            .collect();
405        for (index, (comparator, bound)) in ranges.iter().enumerate() {
406            let below = order(version, bound) == Ordering::Less;
407            if comparator.is_upper() {
408                // An upper bound opens the range when it is the first bound,
409                // or closes the interval the previous lower bound opened.
410                let opened = match index.checked_sub(1).map(|i| ranges[i]) {
411                    None => true,
412                    Some((previous, lower)) => {
413                        previous.is_lower() && order(version, lower) == Ordering::Greater
414                    }
415                };
416                if opened && below {
417                    return Ok(true);
418                }
419            } else if index + 1 == ranges.len() && order(version, bound) == Ordering::Greater {
420                // A lower bound with nothing after it is open to the top.
421                return Ok(true);
422            }
423        }
424        Ok(false)
425    }
426}
427
428/// SemVer 2.0 precedence: build metadata does not count.
429fn precedence(a: &semver::Version, b: &semver::Version) -> Ordering {
430    (a.major, a.minor, a.patch, &a.pre).cmp(&(b.major, b.minor, b.patch, &b.pre))
431}
432
433/// Specification section 5.4: sorted and unique, then the comparator rules
434/// for contiguous constraints.
435fn validate<T>(
436    bounds: &[(Comparator, T)],
437    order: impl Fn(&T, &T) -> Ordering,
438) -> Result<(), VersError> {
439    if bounds
440        .windows(2)
441        .any(|pair| order(&pair[0].1, &pair[1].1) != Ordering::Less)
442    {
443        return Err(VersError::Order);
444    }
445    let without_unequal: Vec<_> = bounds
446        .iter()
447        .map(|(comparator, _)| *comparator)
448        .filter(|comparator| *comparator != Comparator::NotEqual)
449        .collect();
450    // A bare version is followed only by a bare version or a lower bound, and
451    // a lower bound is never followed by a bare version (it would be inside
452    // the interval already, which "How to parse" calls redundant).
453    for pair in without_unequal.windows(2) {
454        if (pair[0] == Comparator::Equal && pair[1].is_upper())
455            || (pair[0].is_lower() && pair[1] == Comparator::Equal)
456        {
457            return Err(VersError::Sequence);
458        }
459    }
460    let bounds_only: Vec<_> = without_unequal
461        .iter()
462        .filter(|comparator| **comparator != Comparator::Equal)
463        .collect();
464    for pair in bounds_only.windows(2) {
465        if pair[0].is_upper() == pair[1].is_upper() {
466            return Err(VersError::Sequence);
467        }
468    }
469    Ok(())
470}
471
472fn split_comparator(segment: &str) -> Result<(Comparator, &str), VersError> {
473    for (prefix, comparator) in [
474        (">=", Comparator::GreaterOrEqual),
475        ("<=", Comparator::LessOrEqual),
476        ("!=", Comparator::NotEqual),
477        ("<", Comparator::Less),
478        (">", Comparator::Greater),
479    ] {
480        if let Some(rest) = segment.strip_prefix(prefix) {
481            return Ok((comparator, rest));
482        }
483    }
484    if segment.starts_with('=') {
485        return Err(VersError::LeadingEquals);
486    }
487    Ok((Comparator::Equal, segment))
488}
489
490/// Section 5.3.2: lowercase ASCII letters, digits, `.` and `-`, starting with a letter.
491fn valid_type(version_type: &str) -> bool {
492    let mut chars = version_type.chars();
493    chars.next().is_some_and(|c| c.is_ascii_lowercase())
494        && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '-'))
495}
496
497fn percent_decode(text: &str) -> Result<String, VersError> {
498    let bytes = text.as_bytes();
499    let mut out = Vec::with_capacity(bytes.len());
500    let mut index = 0;
501    while index < bytes.len() {
502        if bytes[index] == b'%' {
503            let digit = |offset: usize| {
504                bytes
505                    .get(index + offset)
506                    .and_then(|b| char::from(*b).to_digit(16))
507            };
508            let (Some(high), Some(low)) = (digit(1), digit(2)) else {
509                return Err(VersError::Encoding);
510            };
511            out.push((high * 16 + low) as u8);
512            index += 3;
513        } else {
514            out.push(bytes[index]);
515            index += 1;
516        }
517    }
518    String::from_utf8(out).map_err(|_| VersError::Encoding)
519}
520
521#[cfg(test)]
522mod tests {
523    use super::*;
524
525    fn v(text: &str) -> semver::Version {
526        semver::Version::parse(text).unwrap()
527    }
528
529    fn contains(range: &str, version: &str) -> bool {
530        VersRange::parse(range)
531            .unwrap()
532            .contains_semver(&v(version))
533            .unwrap()
534    }
535
536    #[test]
537    fn single_bounds_and_equality() {
538        assert!(contains("vers:semver/>=1.0.0", "1.0.0"));
539        assert!(contains("vers:semver/>=1.0.0", "9.0.0"));
540        assert!(!contains("vers:semver/>=1.0.0", "0.9.9"));
541        assert!(!contains("vers:semver/>1.0.0", "1.0.0"));
542        assert!(contains("vers:semver/<2.0.0", "0.0.1"));
543        assert!(!contains("vers:semver/<2.0.0", "2.0.0"));
544        assert!(contains("vers:semver/<=2.0.0", "2.0.0"));
545        assert!(contains("vers:semver/1.2.3", "1.2.3"));
546        assert!(!contains("vers:semver/1.2.3", "1.2.4"));
547        assert!(contains("vers:semver/*", "0.0.0"));
548    }
549
550    #[test]
551    fn several_intervals_exclusions_and_points() {
552        let range = "vers:npm/<1.4.1|>=2.0.0|<2.17.2";
553        assert!(contains(range, "1.0.0"));
554        assert!(!contains(range, "1.4.1"));
555        assert!(!contains(range, "1.9.0"));
556        assert!(contains(range, "2.0.0"));
557        assert!(contains(range, "2.17.1"));
558        assert!(!contains(range, "2.17.2"));
559        let gaps = "vers:npm/>=2.2.6|<2.47.0|>2.51.0|<=2.67.0";
560        assert!(!contains(gaps, "2.51.0"));
561        assert!(contains(gaps, "2.60.0"));
562        assert!(contains(gaps, "2.67.0"));
563        assert!(!contains(gaps, "2.68.0"));
564        let points = "vers:semver/1.0.0|1.1.0|>=2.0.0";
565        assert!(contains(points, "1.1.0"));
566        assert!(!contains(points, "1.0.5"));
567        assert!(contains(points, "3.0.0"));
568        let excluded = "vers:semver/>=1.0.0|!=1.5.0|<2.0.0";
569        assert!(!contains(excluded, "1.5.0"));
570        assert!(contains(excluded, "1.5.1"));
571    }
572
573    #[test]
574    fn prerelease_and_build_metadata() {
575        assert!(contains("vers:semver/<1.0.0", "1.0.0-rc.1"));
576        assert!(contains("vers:semver/>=1.0.0-rc.1|<1.0.0", "1.0.0-rc.2"));
577        // Build metadata is not part of precedence.
578        assert!(contains("vers:semver/1.0.0", "1.0.0+build.7"));
579        assert!(contains("vers:semver/1.0.0+a", "1.0.0"));
580    }
581
582    #[test]
583    fn invalid_ranges_are_errors_not_corrected() {
584        let check = |range: &str| {
585            VersRange::parse(range)
586                .and_then(|r| r.contains_semver(&v("1.0.0")))
587                .unwrap_err()
588        };
589        assert_eq!(check("vers:semver/<2.0.0|>=1.0.0"), VersError::Order);
590        assert_eq!(check("vers:semver/>=1.0.0|<1.0.0"), VersError::Order);
591        assert_eq!(check("vers:semver/>=1.0.0|>=2.0.0"), VersError::Sequence);
592        assert_eq!(check("vers:semver/<1.0.0|<2.0.0"), VersError::Sequence);
593        assert_eq!(check("vers:semver/1.0.0|<2.0.0"), VersError::Sequence);
594        assert_eq!(check("vers:semver/>=1.0.0|1.5.0"), VersError::Sequence);
595        assert_eq!(
596            check("vers:semver/>=1.0.0|1.5.0|<2.0.0"),
597            VersError::Sequence
598        );
599        assert_eq!(check("vers:semver/1.0"), VersError::NotSemver);
600        assert_eq!(check("vers:pypi/>=1.0"), VersError::UnsupportedType);
601    }
602
603    fn contains_pypi(range: &str, version: &str) -> Result<bool, VersError> {
604        VersRange::parse(range)
605            .unwrap()
606            .contains_pypi(&Pep440Version::parse(version).unwrap())
607    }
608
609    #[test]
610    fn pypi_ranges_use_pep440_ordering() {
611        let range = "vers:pypi/>=1.0|!=1.5|<2.0";
612        assert_eq!(contains_pypi(range, "1.0.0"), Ok(true));
613        assert_eq!(contains_pypi(range, "1.0.dev1"), Ok(false));
614        assert_eq!(contains_pypi(range, "1.5.0"), Ok(false));
615        assert_eq!(contains_pypi(range, "1.5.post1"), Ok(true));
616        assert_eq!(contains_pypi(range, "2.0rc1"), Ok(true));
617        assert_eq!(contains_pypi(range, "2.0"), Ok(false));
618        assert_eq!(contains_pypi(range, "1!0.1"), Ok(false));
619        assert_eq!(contains_pypi("vers:pypi/1.0", "1.0.0+local"), Ok(false));
620        assert_eq!(contains_pypi("vers:pypi/*", "0"), Ok(true));
621        // Spelled differently, the same version twice.
622        assert_eq!(
623            contains_pypi("vers:pypi/1.0|1.0.0", "1"),
624            Err(VersError::Order)
625        );
626        assert_eq!(
627            contains_pypi("vers:pypi/2.0|<1.0", "1"),
628            Err(VersError::Order)
629        );
630        assert_eq!(
631            contains_pypi("vers:pypi/>=1.0|latest", "1"),
632            Err(VersError::NotPep440)
633        );
634        assert_eq!(
635            VersRange::parse("vers:npm/1.0.0")
636                .unwrap()
637                .contains_pypi(&Pep440Version::parse("1.0.0").unwrap()),
638            Err(VersError::UnsupportedType)
639        );
640        assert_eq!(
641            VersRange::parse("vers:pypi/1.0.0")
642                .unwrap()
643                .contains_semver(&v("1.0.0")),
644            Err(VersError::UnsupportedType)
645        );
646    }
647
648    #[test]
649    fn syntax_errors() {
650        let cases: &[(&str, VersError)] = &[
651            ("npm/>=1.0.0", VersError::Scheme),
652            ("VERS:npm/1.0.0", VersError::Scheme),
653            ("vers:NPM/1.0.0", VersError::Type),
654            ("vers:1npm/1.0.0", VersError::Type),
655            ("vers:npm", VersError::Type),
656            ("vers:npm/", VersError::Empty),
657            ("vers:npm/>=1.0.0| <2.0.0", VersError::Whitespace),
658            ("vers:npm/|1.0.0", VersError::EmptyConstraint),
659            ("vers:npm/1.0.0|", VersError::EmptyConstraint),
660            ("vers:npm/1.0.0||2.0.0", VersError::EmptyConstraint),
661            ("vers:npm/=1.0.0", VersError::LeadingEquals),
662            ("vers:npm/>=", VersError::EmptyVersion),
663            ("vers:npm/*|1.0.0", VersError::Asterisk),
664            ("vers:npm/>=*", VersError::Asterisk),
665            ("vers:npm/1.0%zz", VersError::Encoding),
666            ("vers:npm/>==1.0.0", VersError::Encoding),
667        ];
668        for (range, error) in cases {
669            assert_eq!(
670                VersRange::parse(range).as_ref().err(),
671                Some(error),
672                "{range}"
673            );
674        }
675    }
676
677    #[test]
678    fn parse_cle_follows_ecma_428_annex_a() {
679        let strict = VersRange::parse("vers:npm/>=1.0.0|<2.0.0|!=1.5.0").unwrap();
680        for lenient in [
681            "vers:npm/>=1.0.0|<2.0.0|!=1.5.0",
682            " vers : npm / >= 1.0.0 | < 2.0.0 | != 1.5.0 ",
683            "vers:npm/|>=1.0.0||<2.0.0|!=1.5.0|",
684            "vers:npm/>=1.0.0|\t<2.0.0|||!=1.5.0",
685        ] {
686            assert_eq!(VersRange::parse_cle(lenient).unwrap(), strict, "{lenient}");
687        }
688        assert!(VersRange::parse_cle("vers:npm/ * ").unwrap().is_any());
689        // Still errors: nothing left, a line break, an invalid range.
690        for (text, error) in [
691            ("vers:npm/||", VersError::Empty),
692            ("vers:npm/ ", VersError::Empty),
693            ("vers:npm/1.0.0|\n2.0.0", VersError::Whitespace),
694            ("vers:npm/=1.0.0", VersError::LeadingEquals),
695            ("vers:npm", VersError::Type),
696        ] {
697            assert_eq!(VersRange::parse_cle(text), Err(error), "{text:?}");
698        }
699        // An encoded space survives, as in `parse`.
700        let range = VersRange::parse_cle("vers:lexicographic/1%202").unwrap();
701        assert_eq!(range.constraints()[0].version(), "1 2");
702    }
703
704    #[test]
705    fn versions_are_decoded_once() {
706        let range = VersRange::parse("vers:generic/1.0%2520a").unwrap();
707        assert_eq!(range.constraints()[0].version(), "1.0%20a");
708        assert_eq!(range.constraints()[0].comparator().as_str(), "");
709    }
710}