Skip to main content

sbom_model/
versions.rs

1//! version parsing and comparison utilities.
2//!
3//! provides lenient version parsing for SBOM component versions, supporting
4//! semver, dot-separated numeric strings, PEP 440 (Python) versions,
5//! Debian and RPM epoch/revision versions, Maven (Java) versions, NuGet
6//! (.NET) versions, Alpine `apk` versions, and opaque version strings.
7//!
8//! two entry points parse a version string: [`Version::parse_lenient`] infers
9//! the format from the string alone, and [`Version::parse_for_ecosystem`]
10//! applies the rules of the component's ecosystem. inference cannot separate a
11//! Debian revision from a semver pre-release — `1.2.3-1ubuntu2` and
12//! `1.0.0-alpha.1` are the same shape, ordered in opposite directions — so
13//! callers that know the ecosystem should pass it. the same holds for PEP 440:
14//! `1.0.2a` is a Python pre-release and a Debian upstream version, ordered on
15//! opposite sides of `1.0.2`. and for Alpine: `1.2.3-r4` is a rebuild of
16//! `1.2.3` that sits above it, where semver reads `-r4` as a pre-release below
17//! it.
18
19use std::cmp::Ordering;
20
21/// parsed version representation for lenient comparison.
22///
23/// covers the common version formats found in SBOMs:
24/// - standard semver (possibly with `v` prefix or fewer than three parts)
25/// - dot-separated numeric (e.g., date-based `2024.01.15` or four-part `1.2.3.4`)
26/// - PEP 440 pre/post/dev releases and epochs (dominant in Python SBOMs)
27/// - Debian `epoch:upstream-revision` and RPM `epoch:version-release` (dominant
28///   in OS/container SBOMs)
29/// - Maven versions, whose qualifiers (`1.0-SNAPSHOT`, `2.0-rc1`) look like
30///   semver pre-releases but are ranked by a named order
31/// - NuGet versions, which carry a fourth numeric field and compare their
32///   release labels case-insensitively
33/// - Alpine `apk` versions, whose `-rN` package revision looks like a semver
34///   pre-release but ranks above the bare version
35/// - opaque strings that cannot be compared
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub enum Version {
38    /// parseable as semver (with lenient parsing: `v`/`V` prefix stripped,
39    /// one- or two-part versions padded to three parts).
40    Semver(semver::Version),
41    /// dot-separated numeric segments that don't qualify as semver
42    /// (e.g., four-part versions or versions with leading zeros).
43    Numeric(Vec<u64>),
44    /// PEP 440 (Python) version, ordered per the PEP. inference produces this
45    /// variant only for a version carrying an epoch, pre-release, post-release
46    /// or dev-release segment;
47    /// [`parse_for_ecosystem`](Version::parse_for_ecosystem) produces it for
48    /// every `pypi` version, including a plain release and the spellings a
49    /// Debian version shares (`1.0.2a`, `1.0-1`).
50    Pep440(Pep440),
51    /// Debian-style `epoch:upstream-revision` version, compared with the Debian
52    /// `dpkg` algorithm. a `N!` epoch prefix is accepted too, for strings
53    /// [`Pep440`](Version::Pep440) declines. an absent epoch is `0` and an
54    /// absent revision is the empty string.
55    Deb {
56        epoch: u64,
57        upstream: String,
58        revision: String,
59    },
60    /// RPM `epoch:version-release`, compared with rpm's own `rpmvercmp`
61    /// algorithm, which disagrees with the Debian one on ordinary inputs. an
62    /// absent epoch is `0`; an absent release is the empty string and sorts
63    /// below every release, including `0`. only
64    /// [`parse_for_ecosystem`](Version::parse_for_ecosystem) produces this
65    /// variant — the shape alone does not distinguish an RPM version from a
66    /// Debian one.
67    Rpm {
68        epoch: u64,
69        version: String,
70        release: String,
71    },
72    /// Maven (Java) version, compared with Maven's own version-order algorithm,
73    /// under which `1.0-SNAPSHOT` sorts below `1.0` but `1.0-sp` above it. only
74    /// [`parse_for_ecosystem`](Version::parse_for_ecosystem) produces this
75    /// variant — the shape alone does not distinguish a Maven qualifier from a
76    /// semver pre-release or a Debian revision.
77    Maven(String),
78    /// NuGet (.NET) version `major.minor.patch[.revision][-release][+metadata]`,
79    /// compared with NuGet.Versioning's rules: four numeric fields, an absent
80    /// one being `0`, then dot-separated release labels compared
81    /// case-insensitively. build metadata is not kept: NuGet ignores it for
82    /// both ordering and equality. only
83    /// [`parse_for_ecosystem`](Version::parse_for_ecosystem) produces this
84    /// variant — the shape alone does not distinguish a NuGet release label
85    /// from a semver pre-release.
86    Nuget {
87        version: [u64; 4],
88        release: Vec<String>,
89    },
90    /// Alpine `apk` version `digits{.digits}[letter]{_suffix[number]}[~hash][-rN]`,
91    /// compared with apk-tools' own algorithm: the `-rN` package revision ranks
92    /// above the bare version rather than below it as a semver pre-release
93    /// would, a dot-separated part written with a leading zero compares as a
94    /// string, and a missing part is absent rather than zero, so `1.0` sits
95    /// below `1.0.0`. only
96    /// [`parse_for_ecosystem`](Version::parse_for_ecosystem) produces this
97    /// variant — the shape alone does not distinguish `1.2.3-r4` from a semver
98    /// pre-release.
99    Apk(String),
100    /// non-parseable version string where ordering cannot be determined.
101    Opaque(String),
102}
103
104/// a normalized PEP 440 version: `[N!]N(.N)*[{a|b|rc}N][.postN][.devN][+local]`.
105///
106/// spelling aliases are folded to the canonical form during parsing
107/// (`alpha` → `a`, `beta` → `b`, `c`/`pre`/`preview` → `rc`, `rev`/`r` →
108/// `post`), and `-`/`_`/`.` separators are equivalent.
109#[derive(Debug, Clone, PartialEq, Eq)]
110pub struct Pep440 {
111    pub epoch: u64,
112    pub release: Vec<u64>,
113    pub pre: Option<(PreRelease, u64)>,
114    pub post: Option<u64>,
115    pub dev: Option<u64>,
116    pub local: Vec<LocalSegment>,
117}
118
119/// a PEP 440 pre-release kind, in ascending order.
120#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
121pub enum PreRelease {
122    Alpha,
123    Beta,
124    Rc,
125}
126
127/// one dot-separated part of a PEP 440 local version label. the variant order
128/// is the PEP 440 rule: a lexical part sorts before any numeric one.
129#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
130pub enum LocalSegment {
131    Str(String),
132    Num(u64),
133}
134
135impl Version {
136    /// parses a version string leniently.
137    ///
138    /// tries semver first (stripping `v`/`V` prefix and padding one- or
139    /// two-part versions), then dot-separated numeric, then PEP 440, then
140    /// Debian-style epoch/revision versions, then falls back to
141    /// [`Opaque`](Version::Opaque).
142    ///
143    /// the shape alone does not always identify the format; when the
144    /// component's ecosystem is known, prefer
145    /// [`parse_for_ecosystem`](Self::parse_for_ecosystem).
146    ///
147    /// # Examples
148    ///
149    /// ```
150    /// use sbom_model::versions::Version;
151    ///
152    /// assert!(matches!(Version::parse_lenient("1.2.3"), Version::Semver(_)));
153    /// assert!(matches!(Version::parse_lenient("v1.2"), Version::Semver(_)));
154    /// assert!(matches!(Version::parse_lenient("2024.01.15"), Version::Numeric(_)));
155    /// assert!(matches!(Version::parse_lenient("4.2.0rc1"), Version::Pep440(_)));
156    /// assert!(matches!(Version::parse_lenient("2:1.0-3"), Version::Deb { .. }));
157    /// assert!(matches!(Version::parse_lenient("abc"), Version::Opaque(_)));
158    /// ```
159    pub fn parse_lenient(s: &str) -> Self {
160        let stripped = strip_v_prefix(s);
161
162        if let Ok(v) = semver::Version::parse(stripped) {
163            return Version::Semver(v);
164        }
165
166        // try padding: "1.0" -> "1.0.0", "1" -> "1.0.0"
167        let parts: Vec<&str> = stripped.splitn(3, '.').collect();
168        let padded = match parts.len() {
169            1 => Some(format!("{}.0.0", parts[0])),
170            2 => Some(format!("{}.{}.0", parts[0], parts[1])),
171            _ => None,
172        };
173        if let Some(ref padded) = padded {
174            if let Ok(v) = semver::Version::parse(padded) {
175                return Version::Semver(v);
176            }
177        }
178
179        if let Some(segments) = parse_numeric(stripped) {
180            return Version::Numeric(segments);
181        }
182
183        if let Some(pep) = parse_pep440(stripped, Pep440Grammar::Unambiguous) {
184            // a plain release has no PEP 440-specific segment; leave its classification alone
185            if pep.epoch > 0 || pep.pre.is_some() || pep.post.is_some() || pep.dev.is_some() {
186                return Version::Pep440(pep);
187            }
188        }
189
190        if let Some(deb) = parse_deb(stripped) {
191            return deb;
192        }
193
194        Version::Opaque(s.to_string())
195    }
196
197    /// parses a version string with the rules of the ecosystem it came from.
198    ///
199    /// `ecosystem` is a purl package type (the value of
200    /// [`Component::ecosystem`](crate::Component::ecosystem)). `None`, or a type
201    /// with no dedicated ruleset, is exactly [`parse_lenient`](Self::parse_lenient).
202    ///
203    /// `deb` versions are read as [`Deb`](Version::Deb) and ordered by the
204    /// `dpkg` algorithm, `rpm` versions as [`Rpm`](Version::Rpm) and ordered by
205    /// rpm's `rpmvercmp`, `maven` versions as [`Maven`](Version::Maven) and
206    /// ordered by Maven's version-order algorithm, `nuget` versions as
207    /// [`Nuget`](Version::Nuget) and ordered by NuGet.Versioning's rules,
208    /// `pypi` versions as [`Pep440`](Version::Pep440) and ordered by PEP 440,
209    /// and `apk` versions as [`Apk`](Version::Apk) and ordered by apk-tools'
210    /// own algorithm. a leading `v`/`V` is stripped, as [`parse_lenient`](Self::parse_lenient)
211    /// does; a string that is still not a valid version for that ecosystem is
212    /// [`Opaque`](Version::Opaque) rather than being retried as semver.
213    ///
214    /// # Examples
215    ///
216    /// ```
217    /// use std::cmp::Ordering;
218    /// use sbom_model::versions::Version;
219    ///
220    /// // `1ubuntu2` is a Debian revision, not a semver pre-release
221    /// let old = Version::parse_for_ecosystem(Some("deb"), "1.2.3-1ubuntu2");
222    /// let new = Version::parse_for_ecosystem(Some("deb"), "1.2.3-2");
223    /// assert_eq!(old.partial_cmp_lenient(&new), Some(Ordering::Less));
224    ///
225    /// // rpm ranks a numeric segment above an alpha one, dpkg the other way
226    /// let old = Version::parse_for_ecosystem(Some("rpm"), "1.a");
227    /// let new = Version::parse_for_ecosystem(Some("rpm"), "1.1");
228    /// assert_eq!(old.partial_cmp_lenient(&new), Some(Ordering::Less));
229    ///
230    /// // a Maven snapshot precedes its release, and `sp` follows it
231    /// let snapshot = Version::parse_for_ecosystem(Some("maven"), "1.0-SNAPSHOT");
232    /// let release = Version::parse_for_ecosystem(Some("maven"), "1.0");
233    /// let patched = Version::parse_for_ecosystem(Some("maven"), "1.0-sp1");
234    /// assert_eq!(snapshot.partial_cmp_lenient(&release), Some(Ordering::Less));
235    /// assert_eq!(patched.partial_cmp_lenient(&release), Some(Ordering::Greater));
236    ///
237    /// // NuGet compares release labels case-insensitively, and the fourth
238    /// // field outranks the release
239    /// let preview = Version::parse_for_ecosystem(Some("nuget"), "5.0.0-preview.1");
240    /// let rc = Version::parse_for_ecosystem(Some("nuget"), "5.0.0-RC.1");
241    /// let revision = Version::parse_for_ecosystem(Some("nuget"), "5.0.0.1");
242    /// assert_eq!(preview.partial_cmp_lenient(&rc), Some(Ordering::Less));
243    /// assert_eq!(rc.partial_cmp_lenient(&revision), Some(Ordering::Less));
244    ///
245    /// // `1.0.2a` is PEP 440's `1.0.2a0`, a pre-release below its release
246    /// let pre = Version::parse_for_ecosystem(Some("pypi"), "1.0.2a");
247    /// let release = Version::parse_for_ecosystem(Some("pypi"), "1.0.2");
248    /// assert_eq!(pre.partial_cmp_lenient(&release), Some(Ordering::Less));
249    ///
250    /// // `-r4` is an Alpine package revision, above the version it rebuilds
251    /// let rebuild = Version::parse_for_ecosystem(Some("apk"), "1.2.3-r4");
252    /// let base = Version::parse_for_ecosystem(Some("apk"), "1.2.3");
253    /// assert_eq!(rebuild.partial_cmp_lenient(&base), Some(Ordering::Greater));
254    ///
255    /// let guessed = Version::parse_for_ecosystem(None, "1.2.3-1ubuntu2");
256    /// assert_eq!(guessed, Version::parse_lenient("1.2.3-1ubuntu2"));
257    /// ```
258    pub fn parse_for_ecosystem(ecosystem: Option<&str>, s: &str) -> Self {
259        match Scheme::for_ecosystem(ecosystem) {
260            Scheme::Infer => Version::parse_lenient(s),
261            Scheme::Deb => parse_deb(s)
262                .or_else(|| parse_deb(strip_v_prefix(s)))
263                .unwrap_or_else(|| Version::Opaque(s.to_string())),
264            Scheme::Rpm => parse_rpm(s)
265                .or_else(|| parse_rpm(strip_v_prefix(s)))
266                .unwrap_or_else(|| Version::Opaque(s.to_string())),
267            Scheme::Maven => parse_maven(s)
268                .or_else(|| parse_maven(strip_v_prefix(s)))
269                .unwrap_or_else(|| Version::Opaque(s.to_string())),
270            Scheme::Nuget => parse_nuget(s)
271                .or_else(|| parse_nuget(strip_v_prefix(s)))
272                .unwrap_or_else(|| Version::Opaque(s.to_string())),
273            Scheme::Pypi => parse_pep440(s, Pep440Grammar::Full)
274                .or_else(|| parse_pep440(strip_v_prefix(s), Pep440Grammar::Full))
275                .map(Version::Pep440)
276                .unwrap_or_else(|| Version::Opaque(s.to_string())),
277            Scheme::Apk => parse_apk(s)
278                .or_else(|| parse_apk(strip_v_prefix(s)))
279                .unwrap_or_else(|| Version::Opaque(s.to_string())),
280        }
281    }
282
283    /// orders two versions, returning `None` when the ordering is unknown.
284    ///
285    /// comparison strategy depends on the variant pair:
286    /// - **Semver vs Semver**: semver *precedence* ordering (including
287    ///   pre-release; build metadata is ignored per SemVer §10)
288    /// - **Numeric vs Numeric**: segment-by-segment with implicit zero padding
289    /// - **Semver vs Numeric** (either direction): `[major, minor, patch]` from
290    ///   the semver side against the numeric segments; on a tie, a semver
291    ///   pre-release is the lesser (build metadata is ignored)
292    /// - **Deb vs Deb**: epoch (numeric), then upstream, then revision, via the
293    ///   Debian `dpkg` version-comparison algorithm
294    /// - **Rpm vs Rpm**: epoch (numeric), then version, then release, via rpm's
295    ///   `rpmvercmp` algorithm
296    /// - **Maven vs Maven**: item by item, via Maven's version-order algorithm.
297    ///   a version nesting past the parser's depth cap is declined
298    /// - **Nuget vs Nuget**: the four numeric fields, then a version carrying
299    ///   release labels below one that carries none, then the labels
300    /// - **Apk vs Apk**: token by token, via apk-tools' own algorithm. a
301    ///   version apk's tokenizer rejects is declined
302    /// - **Pep440 against Pep440, Semver or Numeric** (either direction): the
303    ///   other side is read as a PEP 440 version and both are ordered per PEP
304    ///   440. a semver pre-release that isn't a PEP 440 suffix (say
305    ///   `1.0.0-foo.bar`) has no PEP 440 reading, so that pair stays `None`
306    /// - **Any other pair** (including any Opaque, any two of Deb, Rpm, Maven,
307    ///   Nuget and Apk, or any of them against a semver/numeric/PEP 440
308    ///   version): `None`
309    ///
310    /// deliberately weaker than [`PartialOrd`]: even two identical
311    /// [`Opaque`](Version::Opaque) versions compare `None`.
312    ///
313    /// which arm applies depends on how each side was parsed:
314    /// [`parse_for_ecosystem`](Self::parse_for_ecosystem) puts both sides of a
315    /// known ecosystem in the same variant, where
316    /// [`parse_lenient`](Self::parse_lenient) can infer different ones.
317    ///
318    /// # Examples
319    ///
320    /// ```
321    /// use std::cmp::Ordering;
322    /// use sbom_model::versions::Version;
323    ///
324    /// let a = Version::parse_lenient("2.0.0");
325    /// let b = Version::parse_lenient("1.5.0");
326    /// assert_eq!(a.partial_cmp_lenient(&b), Some(Ordering::Greater));
327    ///
328    /// let opaque = Version::parse_lenient("deadbeef");
329    /// assert_eq!(a.partial_cmp_lenient(&opaque), None);
330    /// ```
331    pub fn partial_cmp_lenient(&self, other: &Self) -> Option<Ordering> {
332        match (self, other) {
333            (Version::Semver(a), Version::Semver(b)) => Some(a.cmp_precedence(b)),
334            (Version::Numeric(a), Version::Numeric(b)) => Some(numeric_cmp(a, b)),
335            (Version::Semver(a), Version::Numeric(b)) => Some(semver_numeric_cmp(a, b)),
336            (Version::Numeric(a), Version::Semver(b)) => Some(semver_numeric_cmp(b, a).reverse()),
337            (
338                Version::Deb {
339                    epoch: ae,
340                    upstream: au,
341                    revision: arev,
342                },
343                Version::Deb {
344                    epoch: be,
345                    upstream: bu,
346                    revision: brev,
347                },
348            ) => Some(deb_cmp((*ae, au, arev), (*be, bu, brev))),
349            (
350                Version::Rpm {
351                    epoch: ae,
352                    version: av,
353                    release: arel,
354                },
355                Version::Rpm {
356                    epoch: be,
357                    version: bv,
358                    release: brel,
359                },
360            ) => Some(rpm_cmp((*ae, av, arel), (*be, bv, brel))),
361            (Version::Maven(a), Version::Maven(b)) => maven_cmp(a, b),
362            (
363                Version::Nuget {
364                    version: av,
365                    release: arel,
366                },
367                Version::Nuget {
368                    version: bv,
369                    release: brel,
370                },
371            ) => Some(nuget_cmp((av, arel), (bv, brel))),
372            (Version::Apk(a), Version::Apk(b)) => apk_cmp(a, b),
373            (Version::Pep440(_), _) | (_, Version::Pep440(_)) => {
374                Some(pep440_cmp(&as_pep440(self)?, &as_pep440(other)?))
375            }
376            _ => None,
377        }
378    }
379
380    /// returns `true` if `new` is a downgrade from `self`.
381    ///
382    /// a pair whose ordering is unknown is not a downgrade; see
383    /// [`partial_cmp_lenient`](Self::partial_cmp_lenient) for the per-variant
384    /// comparison rules.
385    ///
386    /// # Examples
387    ///
388    /// ```
389    /// use sbom_model::versions::Version;
390    ///
391    /// let old = Version::parse_lenient("2.0.0");
392    /// let new = Version::parse_lenient("1.5.0");
393    /// assert!(old.is_downgrade(&new));
394    ///
395    /// let old = Version::parse_lenient("1.0.0");
396    /// let new = Version::parse_lenient("2.0.0");
397    /// assert!(!old.is_downgrade(&new));
398    /// ```
399    pub fn is_downgrade(&self, new: &Self) -> bool {
400        self.partial_cmp_lenient(new) == Some(Ordering::Greater)
401    }
402}
403
404/// the ruleset [`Version::parse_for_ecosystem`] reads a string with.
405#[derive(Debug, Clone, Copy, PartialEq, Eq)]
406enum Scheme {
407    Infer,
408    Deb,
409    Rpm,
410    Maven,
411    Nuget,
412    Pypi,
413    Apk,
414}
415
416impl Scheme {
417    fn for_ecosystem(ecosystem: Option<&str>) -> Self {
418        match ecosystem {
419            Some(e) if e.eq_ignore_ascii_case("deb") => Scheme::Deb,
420            Some(e) if e.eq_ignore_ascii_case("rpm") => Scheme::Rpm,
421            Some(e) if e.eq_ignore_ascii_case("maven") => Scheme::Maven,
422            Some(e) if e.eq_ignore_ascii_case("nuget") => Scheme::Nuget,
423            Some(e) if e.eq_ignore_ascii_case("pypi") => Scheme::Pypi,
424            Some(e) if e.eq_ignore_ascii_case("apk") => Scheme::Apk,
425            _ => Scheme::Infer,
426        }
427    }
428}
429
430/// segment-by-segment numeric comparison with implicit zero padding.
431fn numeric_cmp(a: &[u64], b: &[u64]) -> Ordering {
432    let max_len = a.len().max(b.len());
433    for i in 0..max_len {
434        let x = a.get(i).copied().unwrap_or(0);
435        let y = b.get(i).copied().unwrap_or(0);
436        if x != y {
437            return x.cmp(&y);
438        }
439    }
440    Ordering::Equal
441}
442
443/// orders a semver version against numeric segments: `[major, minor, patch]`
444/// as segments, then a pre-release below the release it precedes.
445fn semver_numeric_cmp(a: &semver::Version, b: &[u64]) -> Ordering {
446    let release = numeric_cmp(&[a.major, a.minor, a.patch], b);
447    if a.pre.is_empty() {
448        release
449    } else {
450        release.then(Ordering::Less)
451    }
452}
453
454/// parses dot-separated numeric segments (e.g. four-part or leading-zero
455/// versions). returns `None` when any segment is non-numeric or the string is
456/// empty, so the caller can fall through to the next parsing strategy.
457fn parse_numeric(stripped: &str) -> Option<Vec<u64>> {
458    let mut segments = Vec::new();
459    for part in stripped.split('.') {
460        segments.push(part.parse::<u64>().ok()?);
461    }
462    if segments.is_empty() {
463        None
464    } else {
465        Some(segments)
466    }
467}
468
469/// pre-release spellings PEP 440 normalizes, longest first so `alpha` is not
470/// read as `a` with a trailing `lpha`.
471const PRE_ALIASES: [(&str, PreRelease); 8] = [
472    ("alpha", PreRelease::Alpha),
473    ("beta", PreRelease::Beta),
474    ("preview", PreRelease::Rc),
475    ("pre", PreRelease::Rc),
476    ("rc", PreRelease::Rc),
477    ("a", PreRelease::Alpha),
478    ("b", PreRelease::Beta),
479    ("c", PreRelease::Rc),
480];
481
482/// post-release spellings PEP 440 normalizes, longest first.
483const POST_ALIASES: [(&str, ()); 3] = [("post", ()), ("rev", ()), ("r", ())];
484
485const DEV_ALIASES: [(&str, ()); 1] = [("dev", ())];
486
487/// how much of PEP 440's grammar to accept.
488#[derive(Debug, Clone, Copy, PartialEq, Eq)]
489enum Pep440Grammar {
490    /// the whole PEP, for a version already known to be Python.
491    Full,
492    /// only the spellings no other ecosystem writes the same way. the implicit
493    /// post-release form (`1.0-1`) and the bare single-letter suffix
494    /// (`1.0.2a`, `2024h`, `1.1.1a-r0`) are declined: both are
495    /// indistinguishable from a Debian upstream version.
496    Unambiguous,
497}
498
499/// parses a PEP 440 version, returning `None` for anything the `grammar` does
500/// not accept, so Debian and opaque strings fall through to the next strategy.
501fn parse_pep440(s: &str, grammar: Pep440Grammar) -> Option<Pep440> {
502    let lower = s.to_ascii_lowercase();
503
504    let (head, local) = match lower.split_once('+') {
505        Some((head, tail)) => (head, parse_local(tail)?),
506        None => (lower.as_str(), Vec::new()),
507    };
508    let (epoch, mut rest) = match head.split_once('!') {
509        Some((epoch, tail)) => (epoch.parse::<u64>().ok()?, tail),
510        None => (0, head),
511    };
512
513    let mut release = Vec::new();
514    loop {
515        let end = rest
516            .find(|c: char| !c.is_ascii_digit())
517            .unwrap_or(rest.len());
518        if end == 0 {
519            return None;
520        }
521        release.push(rest[..end].parse::<u64>().ok()?);
522        rest = &rest[end..];
523        match rest.strip_prefix('.') {
524            // a dot continues the release only when a digit follows it
525            Some(next) if next.starts_with(|c: char| c.is_ascii_digit()) => rest = next,
526            _ => break,
527        }
528    }
529
530    let (pre, rest) = match take_segment(rest, &PRE_ALIASES, grammar) {
531        Some((kind, n, rest)) => (Some((kind, n)), rest),
532        None => (None, rest),
533    };
534    let (post, rest) = match take_segment(rest, &POST_ALIASES, grammar) {
535        Some((_, n, rest)) => (Some(n), rest),
536        None => take_implicit_post(rest, grammar),
537    };
538    let (dev, rest) = match take_segment(rest, &DEV_ALIASES, grammar) {
539        Some((_, n, rest)) => (Some(n), rest),
540        None => (None, rest),
541    };
542    if !rest.is_empty() {
543        return None;
544    }
545
546    Some(Pep440 {
547        epoch,
548        release,
549        pre,
550        post,
551        dev,
552        local,
553    })
554}
555
556/// consumes a `[-_.]?<keyword>[-_.]?<number>?` suffix, returning the matched
557/// keyword's tag, its number (an absent one is `0`, per PEP 440) and the rest.
558fn take_segment<'a, T: Copy>(
559    s: &'a str,
560    aliases: &[(&str, T)],
561    grammar: Pep440Grammar,
562) -> Option<(T, u64, &'a str)> {
563    let body = s.strip_prefix(['-', '_', '.']).unwrap_or(s);
564    let (name, tag, rest) = aliases
565        .iter()
566        .find_map(|(name, tag)| Some((*name, *tag, body.strip_prefix(*name)?)))?;
567    let digits = rest.strip_prefix(['-', '_', '.']).unwrap_or(rest);
568    let end = digits
569        .find(|c: char| !c.is_ascii_digit())
570        .unwrap_or(digits.len());
571    let n = match end {
572        0 if name.len() == 1 && grammar == Pep440Grammar::Unambiguous => return None,
573        0 => 0,
574        _ => digits[..end].parse::<u64>().ok()?,
575    };
576    Some((tag, n, &digits[end..]))
577}
578
579/// consumes PEP 440's implicit post-release suffix, a bare `-<number>`.
580fn take_implicit_post(s: &str, grammar: Pep440Grammar) -> (Option<u64>, &str) {
581    if grammar == Pep440Grammar::Unambiguous {
582        return (None, s);
583    }
584    let Some(digits) = s.strip_prefix('-') else {
585        return (None, s);
586    };
587    let end = digits
588        .find(|c: char| !c.is_ascii_digit())
589        .unwrap_or(digits.len());
590    match digits[..end].parse::<u64>() {
591        Ok(n) => (Some(n), &digits[end..]),
592        Err(_) => (None, s),
593    }
594}
595
596/// parses a PEP 440 local version label (the part after `+`).
597fn parse_local(s: &str) -> Option<Vec<LocalSegment>> {
598    let mut segments = Vec::new();
599    for part in s.split(['-', '_', '.']) {
600        if part.is_empty() || !part.chars().all(|c| c.is_ascii_alphanumeric()) {
601            return None;
602        }
603        segments.push(match part.parse::<u64>() {
604            Ok(n) => LocalSegment::Num(n),
605            Err(_) => LocalSegment::Str(part.to_string()),
606        });
607    }
608    Some(segments)
609}
610
611/// reads a version as a PEP 440 version, so a `Pep440` can be compared against
612/// the semver and numeric spellings of the same release. returns `None` when
613/// there is no PEP 440 reading.
614fn as_pep440(v: &Version) -> Option<Pep440> {
615    let plain = |release| Pep440 {
616        epoch: 0,
617        release,
618        pre: None,
619        post: None,
620        dev: None,
621        local: Vec::new(),
622    };
623    match v {
624        Version::Pep440(p) => Some(p.clone()),
625        Version::Numeric(segments) => Some(plain(segments.clone())),
626        Version::Semver(s) if s.pre.is_empty() => Some(plain(vec![s.major, s.minor, s.patch])),
627        Version::Semver(s) => parse_pep440(
628            &format!("{}.{}.{}-{}", s.major, s.minor, s.patch, s.pre),
629            Pep440Grammar::Unambiguous,
630        ),
631        Version::Deb { .. }
632        | Version::Rpm { .. }
633        | Version::Maven(_)
634        | Version::Nuget { .. }
635        | Version::Apk(_)
636        | Version::Opaque(_) => None,
637    }
638}
639
640/// orders two PEP 440 versions: epoch, release (zero-padded), then the
641/// pre/post/dev segments, then the local label.
642fn pep440_cmp(a: &Pep440, b: &Pep440) -> Ordering {
643    a.epoch
644        .cmp(&b.epoch)
645        .then_with(|| numeric_cmp(&a.release, &b.release))
646        .then_with(|| pre_key(a).cmp(&pre_key(b)))
647        .then_with(|| a.post.cmp(&b.post))
648        .then_with(|| dev_key(a).cmp(&dev_key(b)))
649        .then_with(|| a.local.cmp(&b.local))
650}
651
652/// the pre-release sort key: a bare dev release precedes every pre-release of
653/// the same version, and a release with no pre-release segment follows them.
654#[derive(PartialEq, Eq, PartialOrd, Ord)]
655enum PreKey {
656    BeforeAll,
657    Pre(PreRelease, u64),
658    AfterAll,
659}
660
661fn pre_key(v: &Pep440) -> PreKey {
662    match v.pre {
663        Some((kind, n)) => PreKey::Pre(kind, n),
664        None if v.post.is_none() && v.dev.is_some() => PreKey::BeforeAll,
665        None => PreKey::AfterAll,
666    }
667}
668
669/// an absent dev segment sorts *after* any dev release, the reverse of `Option`.
670fn dev_key(v: &Pep440) -> (bool, u64) {
671    (v.dev.is_none(), v.dev.unwrap_or(0))
672}
673
674/// strips a leading `v`/`V` version prefix.
675fn strip_v_prefix(s: &str) -> &str {
676    s.strip_prefix('v')
677        .or_else(|| s.strip_prefix('V'))
678        .unwrap_or(s)
679}
680
681/// parses a Debian-style `epoch:upstream-revision` version.
682///
683/// returns `None` for strings that don't look like a comparable package
684/// version — the upstream part must start with a digit (the Debian convention)
685/// and every character must be in the Debian version alphabet — so that
686/// codenames, git hashes, and other genuinely opaque strings stay
687/// [`Opaque`](Version::Opaque) rather than being force-ordered.
688fn parse_deb(s: &str) -> Option<Version> {
689    let (epoch, rest) = split_epoch(s, &[':', '!']);
690
691    if !rest.starts_with(|c: char| c.is_ascii_digit()) {
692        return None;
693    }
694    if !rest.chars().all(is_deb_char) {
695        return None;
696    }
697
698    // the revision is everything after the last hyphen (dpkg splits there);
699    // an absent revision compares equal to "0".
700    let (upstream, revision) = match rest.rfind('-') {
701        Some(idx) => (rest[..idx].to_string(), rest[idx + 1..].to_string()),
702        None => (rest.to_string(), String::new()),
703    };
704
705    Some(Version::Deb {
706        epoch,
707        upstream,
708        revision,
709    })
710}
711
712/// splits a leading numeric epoch, delimited by any of `seps` (`:` for Debian
713/// and RPM, `!` for PEP 440), off a version string. returns `(0, s)` when there
714/// is no numeric epoch prefix.
715fn split_epoch<'a>(s: &'a str, seps: &[char]) -> (u64, &'a str) {
716    if let Some(idx) = s.find(seps) {
717        let (head, tail) = s.split_at(idx);
718        if !head.is_empty() && head.bytes().all(|b| b.is_ascii_digit()) {
719            if let Ok(epoch) = head.parse::<u64>() {
720                return (epoch, &tail[1..]);
721            }
722        }
723    }
724    (0, s)
725}
726
727/// characters permitted in a Debian upstream version or revision.
728fn is_deb_char(c: char) -> bool {
729    c.is_ascii_alphanumeric() || matches!(c, '.' | '+' | '-' | '~' | ':')
730}
731
732/// orders two Debian-style versions given as `(epoch, upstream, revision)`:
733/// a higher epoch always wins; ties fall through to the upstream version and
734/// then the revision, both compared with [`verrevcmp`].
735fn deb_cmp(a: (u64, &str, &str), b: (u64, &str, &str)) -> Ordering {
736    a.0.cmp(&b.0)
737        .then_with(|| verrevcmp(a.1, b.1))
738        .then_with(|| verrevcmp(a.2, b.2))
739}
740
741/// the Debian `dpkg` version-component comparison (`verrevcmp`).
742///
743/// the two strings are scanned in lockstep, alternating between runs of
744/// non-digits and runs of digits. non-digit runs are compared lexically in the
745/// modified ordering of [`deb_order`]; digit runs are compared
746/// numerically (leading zeros stripped, longer run wins). this is the standard
747/// algorithm used for Debian upstream versions and revisions; RPM versions are
748/// ordered by [`rpmvercmp`] instead, which disagrees with it.
749fn verrevcmp(a: &str, b: &str) -> Ordering {
750    let a = a.as_bytes();
751    let b = b.as_bytes();
752    let mut i = 0;
753    let mut j = 0;
754
755    while i < a.len() || j < b.len() {
756        while (i < a.len() && !a[i].is_ascii_digit()) || (j < b.len() && !b[j].is_ascii_digit()) {
757            let ac = a.get(i).map_or(0, |&c| deb_order(c));
758            let bc = b.get(j).map_or(0, |&c| deb_order(c));
759            if ac != bc {
760                return ac.cmp(&bc);
761            }
762            i += 1;
763            j += 1;
764        }
765
766        while i < a.len() && a[i] == b'0' {
767            i += 1;
768        }
769        while j < b.len() && b[j] == b'0' {
770            j += 1;
771        }
772
773        let mut first_diff = 0i32;
774        while i < a.len() && a[i].is_ascii_digit() && j < b.len() && b[j].is_ascii_digit() {
775            if first_diff == 0 {
776                first_diff = i32::from(a[i]) - i32::from(b[j]);
777            }
778            i += 1;
779            j += 1;
780        }
781        // a longer remaining digit run means a larger number (no leading zeros
782        // remain), which takes precedence over any earlier per-digit difference.
783        if i < a.len() && a[i].is_ascii_digit() {
784            return Ordering::Greater;
785        }
786        if j < b.len() && b[j].is_ascii_digit() {
787            return Ordering::Less;
788        }
789        if first_diff != 0 {
790            return first_diff.cmp(&0);
791        }
792    }
793
794    Ordering::Equal
795}
796
797/// the per-character sort key used by [`verrevcmp`] for non-digit runs: a tilde
798/// sorts before everything (even the end of a string), letters keep their ASCII
799/// order, and all other characters sort after letters. digits and the end of a
800/// string both sort as `0`, so a digit encountered mid-scan behaves like a
801/// boundary (matching dpkg's `order()`).
802fn deb_order(c: u8) -> i32 {
803    if c.is_ascii_digit() {
804        0
805    } else if c.is_ascii_alphabetic() {
806        i32::from(c)
807    } else if c == b'~' {
808        -1
809    } else {
810        i32::from(c) + 256
811    }
812}
813
814/// parses an RPM `epoch:version-release` version.
815///
816/// returns `None` on the same grounds as [`parse_deb`]: the version must start
817/// with a digit and every character must be in the RPM version alphabet, so
818/// codenames, git hashes and other genuinely opaque strings stay
819/// [`Opaque`](Version::Opaque) rather than being force-ordered.
820fn parse_rpm(s: &str) -> Option<Version> {
821    let (epoch, rest) = split_epoch(s, &[':']);
822
823    if !rest.starts_with(|c: char| c.is_ascii_digit()) {
824        return None;
825    }
826    if !rest.chars().all(is_rpm_char) {
827        return None;
828    }
829
830    // rpm's `parseEVR` splits the release at the last hyphen, as dpkg does
831    let (version, release) = match rest.rfind('-') {
832        Some(idx) => (rest[..idx].to_string(), rest[idx + 1..].to_string()),
833        None => (rest.to_string(), String::new()),
834    };
835
836    Some(Version::Rpm {
837        epoch,
838        version,
839        release,
840    })
841}
842
843/// characters permitted in an RPM version or release. wider than
844/// [`is_deb_char`]: `_` is an ordinary separator in RPM versions and `^` marks a
845/// post-release snapshot.
846fn is_rpm_char(c: char) -> bool {
847    c.is_ascii_alphanumeric() || matches!(c, '.' | '+' | '-' | '~' | ':' | '_' | '^')
848}
849
850/// orders two RPM versions given as `(epoch, version, release)`: a higher epoch
851/// always wins; ties fall through to the version and then the release, both
852/// compared with [`rpmvercmp`].
853fn rpm_cmp(a: (u64, &str, &str), b: (u64, &str, &str)) -> Ordering {
854    a.0.cmp(&b.0)
855        .then_with(|| rpmvercmp(a.1, b.1))
856        .then_with(|| rpmvercmp(a.2, b.2))
857}
858
859/// rpm's own version-component comparison (`rpmvercmp`).
860///
861/// the two strings are scanned in lockstep, skipping separators on each side
862/// independently, so `1.0` and `1_0` are equal. `~` sorts before everything,
863/// including the end of a string; `^` sorts after the end of a string but
864/// before any longer continuation, so `1.0 < 1.0^ < 1.0.1`. otherwise each side
865/// yields its leading run of digits or of letters: a digit run outranks a letter
866/// run, two digit runs compare with leading zeros stripped and the longer run
867/// winning, and two letter runs compare bytewise. running out of string first
868/// loses.
869fn rpmvercmp(a: &str, b: &str) -> Ordering {
870    let a = a.as_bytes();
871    let b = b.as_bytes();
872    let mut i = 0;
873    let mut j = 0;
874
875    while i < a.len() || j < b.len() {
876        while i < a.len() && is_rpm_separator(a[i]) {
877            i += 1;
878        }
879        while j < b.len() && is_rpm_separator(b[j]) {
880            j += 1;
881        }
882
883        if a.get(i) == Some(&b'~') || b.get(j) == Some(&b'~') {
884            if a.get(i) != Some(&b'~') {
885                return Ordering::Greater;
886            }
887            if b.get(j) != Some(&b'~') {
888                return Ordering::Less;
889            }
890            i += 1;
891            j += 1;
892            continue;
893        }
894
895        if a.get(i) == Some(&b'^') || b.get(j) == Some(&b'^') {
896            if i == a.len() {
897                return Ordering::Less;
898            }
899            if j == b.len() {
900                return Ordering::Greater;
901            }
902            if a.get(i) != Some(&b'^') {
903                return Ordering::Greater;
904            }
905            if b.get(j) != Some(&b'^') {
906                return Ordering::Less;
907            }
908            i += 1;
909            j += 1;
910            continue;
911        }
912
913        if i == a.len() || j == b.len() {
914            break;
915        }
916
917        let numeric = a[i].is_ascii_digit();
918        let a_end = run_end(a, i, numeric);
919        let b_end = run_end(b, j, numeric);
920        // an empty run on the other side means different kinds; the digit wins
921        if b_end == j {
922            return if numeric {
923                Ordering::Greater
924            } else {
925                Ordering::Less
926            };
927        }
928
929        let mut x = &a[i..a_end];
930        let mut y = &b[j..b_end];
931        if numeric {
932            x = strip_leading_zeros(x);
933            y = strip_leading_zeros(y);
934            if x.len() != y.len() {
935                return x.len().cmp(&y.len());
936            }
937        }
938        match x.cmp(y) {
939            Ordering::Equal => {}
940            ord => return ord,
941        }
942
943        i = a_end;
944        j = b_end;
945    }
946
947    match (i == a.len(), j == b.len()) {
948        (true, true) => Ordering::Equal,
949        (true, false) => Ordering::Less,
950        _ => Ordering::Greater,
951    }
952}
953
954/// bytes [`rpmvercmp`] skips: anything that is not alphanumeric, `~` or `^`.
955fn is_rpm_separator(c: u8) -> bool {
956    !(c.is_ascii_alphanumeric() || matches!(c, b'~' | b'^'))
957}
958
959/// the end of the run of digits (or, when `numeric` is false, of letters)
960/// starting at `from`.
961fn run_end(s: &[u8], from: usize, numeric: bool) -> usize {
962    let in_run = |c: &&u8| {
963        if numeric {
964            c.is_ascii_digit()
965        } else {
966            c.is_ascii_alphabetic()
967        }
968    };
969    from + s[from..].iter().take_while(in_run).count()
970}
971
972/// drops a digit run's leading zeros, leaving an all-zero run empty.
973fn strip_leading_zeros(s: &[u8]) -> &[u8] {
974    let zeros = s.iter().take_while(|&&c| c == b'0').count();
975    &s[zeros..]
976}
977
978/// parses a Maven version.
979///
980/// returns `None` on the same grounds as [`parse_deb`]: the version must start
981/// with a digit and every character must be in the Maven version alphabet, so
982/// codenames like `RELEASE`, git hashes and other genuinely opaque strings stay
983/// [`Opaque`](Version::Opaque) rather than being force-ordered. a version whose
984/// item tree nests past [`MAVEN_MAX_DEPTH`] is declined the same way.
985fn parse_maven(s: &str) -> Option<Version> {
986    if !s.starts_with(|c: char| c.is_ascii_digit()) {
987        return None;
988    }
989    if !s.chars().all(is_maven_char) {
990        return None;
991    }
992    maven_parse(s)?;
993
994    Some(Version::Maven(s.to_string()))
995}
996
997/// characters permitted in a Maven version. wider than [`is_deb_char`]: `_` is
998/// a Maven separator, and non-ASCII letters and digits are ordinary qualifier
999/// characters.
1000fn is_maven_char(c: char) -> bool {
1001    c.is_alphanumeric() || matches!(c, '.' | '-' | '_' | '+')
1002}
1003
1004/// one node of a parsed Maven version: a run of ASCII digits with its leading
1005/// zeros stripped, a qualifier folded to the spelling the ranking is defined
1006/// on, or the sub-list a separator opens. each is null when empty.
1007#[derive(Debug, Clone, PartialEq, Eq)]
1008enum MavenItem {
1009    Num(String),
1010    Qual(String),
1011    List(Vec<MavenItem>),
1012}
1013
1014impl MavenItem {
1015    fn is_null(&self) -> bool {
1016        match self {
1017            MavenItem::Num(digits) => digits.is_empty(),
1018            MavenItem::Qual(value) => value.is_empty(),
1019            MavenItem::List(items) => items.is_empty(),
1020        }
1021    }
1022}
1023
1024/// the deepest item tree [`maven_parse`] will build. every level costs a frame
1025/// in [`maven_list_cmp`], and real Maven versions nest a handful.
1026const MAVEN_MAX_DEPTH: usize = 64;
1027
1028/// orders two Maven versions with Maven's version-order algorithm, or `None`
1029/// when either nests past [`MAVEN_MAX_DEPTH`].
1030fn maven_cmp(a: &str, b: &str) -> Option<Ordering> {
1031    Some(maven_list_cmp(&maven_parse(a)?, &maven_parse(b)?))
1032}
1033
1034/// parses a Maven version into its normalized item tree, or `None` when it
1035/// nests past [`MAVEN_MAX_DEPTH`].
1036///
1037/// items are separated by `.`, `-`, `_` and by any transition between ASCII
1038/// digits and other characters; every separator but `.` opens a sub-list, as
1039/// does a qualifier reached from a digit or introduced by a `.` after an
1040/// item. an empty item is Maven's `0`, so `1-.1` is `1-0.1`.
1041fn maven_parse(s: &str) -> Option<Vec<MavenItem>> {
1042    let s = s.to_lowercase();
1043    let mut stack: Vec<Vec<MavenItem>> = vec![Vec::new()];
1044    let mut digits = false;
1045    let mut start = 0;
1046
1047    for (i, c) in s.char_indices() {
1048        if matches!(c, '.' | '-' | '_') {
1049            let item = if i == start {
1050                MavenItem::Num(String::new())
1051            } else {
1052                maven_item(digits, &s[start..i])
1053            };
1054            stack.last_mut().expect("stack is never emptied").push(item);
1055            start = i + c.len_utf8();
1056            if c != '.' {
1057                maven_open(&mut stack)?;
1058            }
1059            continue;
1060        }
1061
1062        let is_digit = c.is_ascii_digit();
1063        if i > start && is_digit && !digits {
1064            if !stack.last().expect("stack is never emptied").is_empty() {
1065                maven_open(&mut stack)?;
1066            }
1067            let qualifier = MavenItem::Qual(maven_qualifier(&s[start..i], true));
1068            stack
1069                .last_mut()
1070                .expect("stack is never emptied")
1071                .push(qualifier);
1072            start = i;
1073            maven_open(&mut stack)?;
1074        } else if i > start && !is_digit && digits {
1075            let number = maven_item(true, &s[start..i]);
1076            stack
1077                .last_mut()
1078                .expect("stack is never emptied")
1079                .push(number);
1080            start = i;
1081            maven_open(&mut stack)?;
1082        }
1083        digits = is_digit;
1084    }
1085
1086    if s.len() > start {
1087        if !digits && !stack.last().expect("stack is never emptied").is_empty() {
1088            maven_open(&mut stack)?;
1089        }
1090        let item = maven_item(digits, &s[start..]);
1091        stack.last_mut().expect("stack is never emptied").push(item);
1092    }
1093
1094    while stack.len() > 1 {
1095        let mut child = stack.pop().expect("length is above one");
1096        maven_normalize(&mut child);
1097        stack
1098            .last_mut()
1099            .expect("stack is never emptied")
1100            .push(MavenItem::List(child));
1101    }
1102
1103    let mut items = stack.pop().expect("stack is never emptied");
1104    maven_normalize(&mut items);
1105    Some(items)
1106}
1107
1108/// opens a sub-list, or `None` at [`MAVEN_MAX_DEPTH`].
1109fn maven_open(stack: &mut Vec<Vec<MavenItem>>) -> Option<()> {
1110    if stack.len() >= MAVEN_MAX_DEPTH {
1111        return None;
1112    }
1113    stack.push(Vec::new());
1114    Some(())
1115}
1116
1117/// classifies one item's text. `followed_by_digit` only matters for the
1118/// `a`/`b`/`m` shorthands.
1119fn maven_item(digits: bool, text: &str) -> MavenItem {
1120    if digits {
1121        MavenItem::Num(text.trim_start_matches('0').to_string())
1122    } else {
1123        MavenItem::Qual(maven_qualifier(text, false))
1124    }
1125}
1126
1127/// folds a qualifier to the spelling the ranking is defined on: lower case,
1128/// `ga`/`final`/`release` to the empty release qualifier, `cr` to `rc`, and a
1129/// lone `a`/`b`/`m` directly followed by a digit to its long form.
1130fn maven_qualifier(text: &str, followed_by_digit: bool) -> String {
1131    let lower = text.to_lowercase();
1132
1133    if followed_by_digit {
1134        match lower.as_str() {
1135            "a" => return "alpha".to_string(),
1136            "b" => return "beta".to_string(),
1137            "m" => return "milestone".to_string(),
1138            _ => {}
1139        }
1140    }
1141
1142    match lower.as_str() {
1143        "ga" | "final" | "release" => String::new(),
1144        "cr" => "rc".to_string(),
1145        _ => lower,
1146    }
1147}
1148
1149/// drops a list's trailing null items, so that `1.0.0`, `1.ga` and `1-0` all
1150/// reduce to `1`. a sub-list is stepped over rather than ending the scan.
1151fn maven_normalize(items: &mut Vec<MavenItem>) {
1152    let mut i = items.len();
1153    while i > 0 {
1154        i -= 1;
1155        if items[i].is_null() {
1156            items.remove(i);
1157        } else if !matches!(items[i], MavenItem::List(_)) {
1158            break;
1159        }
1160    }
1161}
1162
1163/// orders two item lists, padding the shorter with the null each unmatched item
1164/// is measured against.
1165fn maven_list_cmp(a: &[MavenItem], b: &[MavenItem]) -> Ordering {
1166    for i in 0..a.len().max(b.len()) {
1167        let ord = match (a.get(i), b.get(i)) {
1168            (Some(x), Some(y)) => maven_item_cmp(x, y),
1169            (Some(x), None) => maven_null_cmp(x),
1170            (None, Some(y)) => maven_null_cmp(y).reverse(),
1171            (None, None) => Ordering::Equal,
1172        };
1173
1174        if ord != Ordering::Equal {
1175            return ord;
1176        }
1177    }
1178
1179    Ordering::Equal
1180}
1181
1182/// orders two items on the ranking `qualifier < sub-list < number`.
1183fn maven_item_cmp(a: &MavenItem, b: &MavenItem) -> Ordering {
1184    match (a, b) {
1185        (MavenItem::Num(x), MavenItem::Num(y)) => x.len().cmp(&y.len()).then_with(|| x.cmp(y)),
1186        (MavenItem::Qual(x), MavenItem::Qual(y)) => {
1187            maven_qualifier_rank(x).cmp(&maven_qualifier_rank(y))
1188        }
1189        (MavenItem::List(x), MavenItem::List(y)) => maven_list_cmp(x, y),
1190        (MavenItem::Num(_), _) => Ordering::Greater,
1191        (_, MavenItem::Num(_)) => Ordering::Less,
1192        (MavenItem::List(_), MavenItem::Qual(_)) => Ordering::Greater,
1193        (MavenItem::Qual(_), MavenItem::List(_)) => Ordering::Less,
1194    }
1195}
1196
1197/// orders an item against the absent one facing it: a number against `0`, a
1198/// qualifier against the release qualifier, a list against its own contents.
1199fn maven_null_cmp(item: &MavenItem) -> Ordering {
1200    match item {
1201        MavenItem::Num(digits) => {
1202            if digits.is_empty() {
1203                Ordering::Equal
1204            } else {
1205                Ordering::Greater
1206            }
1207        }
1208        MavenItem::Qual(value) => maven_qualifier_rank(value).cmp(&maven_qualifier_rank("")),
1209        MavenItem::List(items) => items
1210            .iter()
1211            .map(maven_null_cmp)
1212            .find(|ord| *ord != Ordering::Equal)
1213            .unwrap_or(Ordering::Equal),
1214    }
1215}
1216
1217/// the qualifier ranking: the named qualifiers in their documented order, then
1218/// every other one, lexically, above them all.
1219fn maven_qualifier_rank(q: &str) -> (usize, &str) {
1220    const KNOWN: [&str; 7] = ["alpha", "beta", "milestone", "rc", "snapshot", "", "sp"];
1221
1222    match KNOWN.iter().position(|known| *known == q) {
1223        Some(i) => (i, ""),
1224        None => (KNOWN.len(), q),
1225    }
1226}
1227
1228/// parses a NuGet version.
1229///
1230/// returns `None` on the same grounds as [`parse_deb`]: the string must be one
1231/// to four dot-separated numeric fields, optionally followed by a `-` release
1232/// label list and a `+` build metadata suffix, so codenames, git hashes and
1233/// other genuinely opaque strings stay [`Opaque`](Version::Opaque).
1234fn parse_nuget(s: &str) -> Option<Version> {
1235    let (core, rest) = match s.find(['-', '+']) {
1236        Some(idx) => (&s[..idx], &s[idx..]),
1237        None => (s, ""),
1238    };
1239
1240    let mut version = [0u64; 4];
1241    for (i, field) in core.split('.').enumerate() {
1242        if i == version.len() || field.is_empty() || !field.bytes().all(|b| b.is_ascii_digit()) {
1243            return None;
1244        }
1245        version[i] = field.parse().ok()?;
1246    }
1247
1248    // a `+` ahead of any `-` opens the metadata, so the rest is never a label
1249    let (labels, metadata) = match rest.strip_prefix('-') {
1250        Some(tail) => match tail.split_once('+') {
1251            Some((labels, metadata)) => (labels, Some(metadata)),
1252            None => (tail, None),
1253        },
1254        None => ("", rest.strip_prefix('+')),
1255    };
1256
1257    if let Some(metadata) = metadata {
1258        if metadata.is_empty()
1259            || !metadata
1260                .bytes()
1261                .all(|b| is_nuget_label_byte(b) || b == b'.')
1262        {
1263            return None;
1264        }
1265    }
1266
1267    let release: Vec<String> = if labels.is_empty() {
1268        Vec::new()
1269    } else {
1270        labels.split('.').map(str::to_string).collect()
1271    };
1272    if release
1273        .iter()
1274        .any(|label| label.is_empty() || !label.bytes().all(is_nuget_label_byte))
1275    {
1276        return None;
1277    }
1278
1279    Some(Version::Nuget { version, release })
1280}
1281
1282/// characters permitted in a NuGet release label or metadata part.
1283fn is_nuget_label_byte(b: u8) -> bool {
1284    b.is_ascii_alphanumeric() || b == b'-'
1285}
1286
1287/// orders two NuGet versions given as `(numeric fields, release labels)`: the
1288/// four fields in order, then a version carrying release labels below one that
1289/// carries none, then the labels themselves.
1290fn nuget_cmp(a: (&[u64; 4], &[String]), b: (&[u64; 4], &[String])) -> Ordering {
1291    a.0.cmp(b.0)
1292        .then_with(|| a.1.is_empty().cmp(&b.1.is_empty()))
1293        .then_with(|| nuget_release_cmp(a.1, b.1))
1294}
1295
1296/// orders two release-label lists label by label, a list that runs out first
1297/// sorting below the one that continues.
1298fn nuget_release_cmp(a: &[String], b: &[String]) -> Ordering {
1299    for i in 0..a.len().max(b.len()) {
1300        let ord = match (a.get(i), b.get(i)) {
1301            (Some(x), Some(y)) => nuget_label_cmp(x, y),
1302            (Some(_), None) => Ordering::Greater,
1303            (None, Some(_)) => Ordering::Less,
1304            (None, None) => Ordering::Equal,
1305        };
1306
1307        if ord != Ordering::Equal {
1308            return ord;
1309        }
1310    }
1311
1312    Ordering::Equal
1313}
1314
1315/// orders two release labels: two labels NuGet reads as numbers compare
1316/// numerically, a number sorts below a label that is not one, and any other
1317/// pair compares case-insensitively. the `i32` is NuGet's `int.TryParse`: a
1318/// digit run too long for one is an ordinary string.
1319fn nuget_label_cmp(a: &str, b: &str) -> Ordering {
1320    match (a.parse::<i32>().ok(), b.parse::<i32>().ok()) {
1321        (Some(x), Some(y)) => x.cmp(&y),
1322        (Some(_), None) => Ordering::Less,
1323        (None, Some(_)) => Ordering::Greater,
1324        (None, None) => a
1325            .bytes()
1326            .map(|b| b.to_ascii_uppercase())
1327            .cmp(b.bytes().map(|b| b.to_ascii_uppercase())),
1328    }
1329}
1330
1331/// parses an Alpine `apk` version, declining any string apk's own tokenizer
1332/// does not run to the end of.
1333fn parse_apk(s: &str) -> Option<Version> {
1334    apk_parse(s)?;
1335    Some(Version::Apk(s.to_string()))
1336}
1337
1338/// apk's version token kinds, in its own order: where two versions first
1339/// differ, the side whose next token comes later here is the lesser. `End` is
1340/// the token a version that has run out of them gets.
1341#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1342enum ApkToken {
1343    InitialDigit,
1344    Digit,
1345    Letter,
1346    Suffix,
1347    SuffixNo,
1348    CommitHash,
1349    RevisionNo,
1350    End,
1351}
1352
1353/// an apk `_suffix`, in ascending order. `alpha` through `rc` rank below a
1354/// version carrying no suffix at all; `cvs` through `p` rank above it.
1355#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1356enum ApkSuffix {
1357    Alpha,
1358    Beta,
1359    Pre,
1360    Rc,
1361    Cvs,
1362    Svn,
1363    Git,
1364    Hg,
1365    P,
1366}
1367
1368impl ApkSuffix {
1369    fn is_pre_release(self) -> bool {
1370        self <= ApkSuffix::Rc
1371    }
1372}
1373
1374/// one token of a parsed apk version. `Digit` keeps the digits as written
1375/// because a leading zero makes the token compare as a string.
1376#[derive(Debug, Clone, PartialEq, Eq)]
1377enum ApkPart<'a> {
1378    InitialDigit(u64),
1379    Digit { number: u64, digits: &'a str },
1380    Letter(u8),
1381    Suffix(ApkSuffix),
1382    SuffixNo(u64),
1383    CommitHash(&'a str),
1384    RevisionNo(u64),
1385}
1386
1387impl ApkPart<'_> {
1388    fn token(&self) -> ApkToken {
1389        match self {
1390            ApkPart::InitialDigit(_) => ApkToken::InitialDigit,
1391            ApkPart::Digit { .. } => ApkToken::Digit,
1392            ApkPart::Letter(_) => ApkToken::Letter,
1393            ApkPart::Suffix(_) => ApkToken::Suffix,
1394            ApkPart::SuffixNo(_) => ApkToken::SuffixNo,
1395            ApkPart::CommitHash(_) => ApkToken::CommitHash,
1396            ApkPart::RevisionNo(_) => ApkToken::RevisionNo,
1397        }
1398    }
1399}
1400
1401/// the `_suffix` spellings apk knows; any other makes the version unparseable.
1402fn apk_suffix(s: &str) -> Option<ApkSuffix> {
1403    match s {
1404        "alpha" => Some(ApkSuffix::Alpha),
1405        "beta" => Some(ApkSuffix::Beta),
1406        "pre" => Some(ApkSuffix::Pre),
1407        "rc" => Some(ApkSuffix::Rc),
1408        "cvs" => Some(ApkSuffix::Cvs),
1409        "svn" => Some(ApkSuffix::Svn),
1410        "git" => Some(ApkSuffix::Git),
1411        "hg" => Some(ApkSuffix::Hg),
1412        "p" => Some(ApkSuffix::P),
1413        _ => None,
1414    }
1415}
1416
1417/// tokenizes an apk version. it opens with a digit run, and each token limits
1418/// which tokens may follow it: a letter or a further dot-part only after a
1419/// digit run, a `_suffix` number only after the suffix it belongs to, a
1420/// `~commithash` only before the `-rN` revision, and one `-rN` last.
1421fn apk_parse(s: &str) -> Option<Vec<ApkPart<'_>>> {
1422    let bytes = s.as_bytes();
1423    let mut pos = 0;
1424    let mut parts = vec![ApkPart::InitialDigit(apk_digits(s, &mut pos)?.0)];
1425
1426    while pos < bytes.len() {
1427        let prev = parts[parts.len() - 1].token();
1428        let part = match bytes[pos] {
1429            b'a'..=b'z' if prev <= ApkToken::Digit => {
1430                pos += 1;
1431                ApkPart::Letter(bytes[pos - 1])
1432            }
1433            b'.' if prev <= ApkToken::Digit => {
1434                pos += 1;
1435                let (number, digits) = apk_digits(s, &mut pos)?;
1436                ApkPart::Digit { number, digits }
1437            }
1438            b'0'..=b'9' if prev == ApkToken::Suffix => {
1439                ApkPart::SuffixNo(apk_digits(s, &mut pos)?.0)
1440            }
1441            b'_' if prev <= ApkToken::SuffixNo => {
1442                pos += 1;
1443                ApkPart::Suffix(apk_suffix(apk_span(s, &mut pos, |b| {
1444                    b.is_ascii_lowercase()
1445                }))?)
1446            }
1447            b'~' if prev < ApkToken::CommitHash => {
1448                pos += 1;
1449                let hash = apk_span(s, &mut pos, |b| {
1450                    b.is_ascii_digit() || (b'a'..=b'f').contains(&b)
1451                });
1452                if hash.is_empty() {
1453                    return None;
1454                }
1455                ApkPart::CommitHash(hash)
1456            }
1457            b'-' if prev < ApkToken::RevisionNo => {
1458                if !s[pos..].starts_with("-r") {
1459                    return None;
1460                }
1461                pos += 2;
1462                ApkPart::RevisionNo(apk_digits(s, &mut pos)?.0)
1463            }
1464            _ => return None,
1465        };
1466        parts.push(part);
1467    }
1468
1469    Some(parts)
1470}
1471
1472/// the run of ASCII digits at `pos`, as a number and as written. declines an
1473/// empty run, or one too long for a `u64`.
1474fn apk_digits<'a>(s: &'a str, pos: &mut usize) -> Option<(u64, &'a str)> {
1475    let digits = apk_span(s, pos, |b| b.is_ascii_digit());
1476    Some((digits.parse().ok()?, digits))
1477}
1478
1479/// the run of bytes at `pos` satisfying `pred`, advancing past it.
1480fn apk_span<'a>(s: &'a str, pos: &mut usize, pred: fn(u8) -> bool) -> &'a str {
1481    let start = *pos;
1482    while s.as_bytes().get(*pos).is_some_and(|b| pred(*b)) {
1483        *pos += 1;
1484    }
1485    &s[start..*pos]
1486}
1487
1488/// orders two apk version strings, declining a string apk would reject.
1489fn apk_cmp(a: &str, b: &str) -> Option<Ordering> {
1490    let (a, b) = (apk_parse(a)?, apk_parse(b)?);
1491
1492    for i in 0..a.len().max(b.len()) {
1493        match (a.get(i), b.get(i)) {
1494            (Some(x), Some(y)) if x.token() == y.token() => {
1495                let ord = apk_part_cmp(x, y);
1496                if ord != Ordering::Equal {
1497                    return Some(ord);
1498                }
1499            }
1500            (x, y) => return Some(apk_tail_cmp(x, y)),
1501        }
1502    }
1503
1504    Some(Ordering::Equal)
1505}
1506
1507/// orders two tokens of the same kind. a dot-part with a leading zero on
1508/// either side compares as a string, as does a commit hash; every other
1509/// numeric token compares as a number.
1510fn apk_part_cmp(a: &ApkPart, b: &ApkPart) -> Ordering {
1511    match (a, b) {
1512        (ApkPart::InitialDigit(x), ApkPart::InitialDigit(y))
1513        | (ApkPart::SuffixNo(x), ApkPart::SuffixNo(y))
1514        | (ApkPart::RevisionNo(x), ApkPart::RevisionNo(y)) => x.cmp(y),
1515        (
1516            ApkPart::Digit {
1517                number: x,
1518                digits: xs,
1519            },
1520            ApkPart::Digit {
1521                number: y,
1522                digits: ys,
1523            },
1524        ) => {
1525            if xs.starts_with('0') || ys.starts_with('0') {
1526                xs.cmp(ys)
1527            } else {
1528                x.cmp(y)
1529            }
1530        }
1531        (ApkPart::Letter(x), ApkPart::Letter(y)) => x.cmp(y),
1532        (ApkPart::Suffix(x), ApkPart::Suffix(y)) => x.cmp(y),
1533        (ApkPart::CommitHash(x), ApkPart::CommitHash(y)) => x.cmp(y),
1534        _ => Ordering::Equal,
1535    }
1536}
1537
1538/// orders two versions at the token where their kinds diverge, `None` being a
1539/// version that has run out of tokens. the side that continues is the greater,
1540/// unless it continues with a pre-release suffix.
1541fn apk_tail_cmp(a: Option<&ApkPart>, b: Option<&ApkPart>) -> Ordering {
1542    if matches!(a, Some(ApkPart::Suffix(s)) if s.is_pre_release()) {
1543        return Ordering::Less;
1544    }
1545    if matches!(b, Some(ApkPart::Suffix(s)) if s.is_pre_release()) {
1546        return Ordering::Greater;
1547    }
1548
1549    let token = |p: Option<&ApkPart>| p.map_or(ApkToken::End, ApkPart::token);
1550    token(b).cmp(&token(a))
1551}
1552
1553/// convenience function: returns `true` if `new_ver` is a downgrade from `old_ver`.
1554///
1555/// parses both strings with [`Version::parse_lenient`] and delegates to
1556/// [`Version::is_downgrade`].
1557pub fn is_version_downgrade(old_ver: &str, new_ver: &str) -> bool {
1558    Version::parse_lenient(old_ver).is_downgrade(&Version::parse_lenient(new_ver))
1559}
1560
1561/// convenience function: orders two version strings, returning `None` when the
1562/// ordering is unknown.
1563///
1564/// parses both strings with [`Version::parse_lenient`] and delegates to
1565/// [`Version::partial_cmp_lenient`].
1566pub fn compare_versions(a: &str, b: &str) -> Option<Ordering> {
1567    Version::parse_lenient(a).partial_cmp_lenient(&Version::parse_lenient(b))
1568}
1569
1570/// convenience function: returns `true` if `new_ver` is a downgrade from
1571/// `old_ver` under `ecosystem`'s version rules.
1572///
1573/// parses both strings with [`Version::parse_for_ecosystem`] and delegates to
1574/// [`Version::is_downgrade`]. a `None` ecosystem is exactly
1575/// [`is_version_downgrade`].
1576///
1577/// # Examples
1578///
1579/// ```
1580/// use sbom_model::versions::is_version_downgrade_for_ecosystem;
1581///
1582/// // a routine Ubuntu security update, not a downgrade
1583/// assert!(!is_version_downgrade_for_ecosystem(
1584///     Some("deb"),
1585///     "1.2.3-1ubuntu2",
1586///     "1.2.3-2"
1587/// ));
1588/// assert!(is_version_downgrade_for_ecosystem(Some("deb"), "1.2.3-2", "1.2.3-1ubuntu2"));
1589///
1590/// // an Alpine rebuild, whose revision semver would read as a pre-release
1591/// assert!(!is_version_downgrade_for_ecosystem(Some("apk"), "1.2.3-r4", "1.2.3-r10"));
1592/// assert!(is_version_downgrade_for_ecosystem(Some("apk"), "1.2.3-r10", "1.2.3-r4"));
1593/// ```
1594pub fn is_version_downgrade_for_ecosystem(
1595    ecosystem: Option<&str>,
1596    old_ver: &str,
1597    new_ver: &str,
1598) -> bool {
1599    Version::parse_for_ecosystem(ecosystem, old_ver)
1600        .is_downgrade(&Version::parse_for_ecosystem(ecosystem, new_ver))
1601}
1602
1603/// convenience function: orders two version strings under `ecosystem`'s version
1604/// rules, returning `None` when the ordering is unknown.
1605///
1606/// parses both strings with [`Version::parse_for_ecosystem`] and delegates to
1607/// [`Version::partial_cmp_lenient`]. a `None` ecosystem is exactly
1608/// [`compare_versions`].
1609///
1610/// # Examples
1611///
1612/// ```
1613/// use std::cmp::Ordering;
1614/// use sbom_model::versions::compare_versions_for_ecosystem;
1615///
1616/// assert_eq!(
1617///     compare_versions_for_ecosystem(Some("deb"), "1.0~rc1", "1.0"),
1618///     Some(Ordering::Less)
1619/// );
1620///
1621/// // a `^` post-release snapshot, which the Debian alphabet has no reading for
1622/// assert_eq!(
1623///     compare_versions_for_ecosystem(Some("rpm"), "1.0^20200101git", "1.0"),
1624///     Some(Ordering::Greater)
1625/// );
1626///
1627/// // apk pads nothing: a missing part is absent, not zero
1628/// assert_eq!(
1629///     compare_versions_for_ecosystem(Some("apk"), "1.0", "1.0.0"),
1630///     Some(Ordering::Less)
1631/// );
1632/// ```
1633pub fn compare_versions_for_ecosystem(
1634    ecosystem: Option<&str>,
1635    a: &str,
1636    b: &str,
1637) -> Option<Ordering> {
1638    Version::parse_for_ecosystem(ecosystem, a)
1639        .partial_cmp_lenient(&Version::parse_for_ecosystem(ecosystem, b))
1640}
1641
1642#[cfg(test)]
1643mod tests {
1644    use super::*;
1645
1646    fn maven_cmp(a: &str, b: &str) -> Ordering {
1647        super::maven_cmp(a, b).unwrap_or_else(|| panic!("{a} vs {b} exceeds the depth cap"))
1648    }
1649
1650    #[test]
1651    fn parse_semver_shapes_pad_to_three_parts() {
1652        for (s, (major, minor, patch)) in [
1653            ("1.2.3", (1, 2, 3)),
1654            ("1.2", (1, 2, 0)),
1655            ("42", (42, 0, 0)),
1656            ("v1.2", (1, 2, 0)),
1657            ("v5", (5, 0, 0)),
1658        ] {
1659            assert_eq!(
1660                Version::parse_lenient(s),
1661                Version::Semver(semver::Version::new(major, minor, patch)),
1662                "{s}"
1663            );
1664        }
1665    }
1666
1667    #[test]
1668    fn parse_v_prefix() {
1669        assert_eq!(
1670            Version::parse_lenient("v1.2.3"),
1671            Version::Semver(semver::Version::new(1, 2, 3))
1672        );
1673        assert_eq!(
1674            Version::parse_lenient("V1.2.3"),
1675            Version::Semver(semver::Version::new(1, 2, 3))
1676        );
1677    }
1678
1679    #[test]
1680    fn parse_prerelease_and_build_metadata() {
1681        for (s, (major, minor, patch), pre, build) in [
1682            ("1.2.3-beta.1", (1, 2, 3), "beta.1", ""),
1683            ("1.2.3+build.456", (1, 2, 3), "", "build.456"),
1684            ("v2.0.0-rc.1", (2, 0, 0), "rc.1", ""),
1685        ] {
1686            assert_eq!(
1687                Version::parse_lenient(s),
1688                Version::Semver(semver::Version {
1689                    major,
1690                    minor,
1691                    patch,
1692                    pre: semver::Prerelease::new(pre).unwrap(),
1693                    build: semver::BuildMetadata::new(build).unwrap(),
1694                }),
1695                "{s}"
1696            );
1697        }
1698    }
1699
1700    #[test]
1701    fn parse_four_part_is_numeric() {
1702        assert_eq!(
1703            Version::parse_lenient("1.2.3.4"),
1704            Version::Numeric(vec![1, 2, 3, 4])
1705        );
1706    }
1707
1708    #[test]
1709    fn parse_date_based_is_numeric() {
1710        // leading zeros are rejected by semver but u64 parses them fine
1711        assert_eq!(
1712            Version::parse_lenient("2024.01.15"),
1713            Version::Numeric(vec![2024, 1, 15])
1714        );
1715    }
1716
1717    #[test]
1718    fn parse_v_prefix_four_part_is_numeric() {
1719        // the v-prefix must be stripped before the numeric fallback splits
1720        assert_eq!(
1721            Version::parse_lenient("v1.2.3.4"),
1722            Version::Numeric(vec![1, 2, 3, 4])
1723        );
1724        assert_eq!(
1725            Version::parse_lenient("V1.2.3.4"),
1726            Version::Numeric(vec![1, 2, 3, 4])
1727        );
1728    }
1729
1730    #[test]
1731    fn parse_v_prefix_date_based_is_numeric() {
1732        assert_eq!(
1733            Version::parse_lenient("v2024.01.15"),
1734            Version::Numeric(vec![2024, 1, 15])
1735        );
1736    }
1737
1738    #[test]
1739    fn parse_leading_zeros_is_numeric() {
1740        assert_eq!(
1741            Version::parse_lenient("01.02.03"),
1742            Version::Numeric(vec![1, 2, 3])
1743        );
1744    }
1745
1746    #[test]
1747    fn parse_whitespace_is_opaque() {
1748        assert!(matches!(
1749            Version::parse_lenient(" 1.2.3"),
1750            Version::Opaque(_)
1751        ));
1752        assert!(matches!(
1753            Version::parse_lenient("1.2.3 "),
1754            Version::Opaque(_)
1755        ));
1756    }
1757
1758    #[test]
1759    fn downgrade_semver_shapes() {
1760        for (old, new, expected) in [
1761            ("2.0.0", "1.5.0", true),
1762            ("1.1.0", "1.0.0", true),
1763            ("1.0.1", "1.0.0", true),
1764            ("1.0.0", "1.1.0", false),
1765            ("1.0.0", "2.0.0", false),
1766            ("1.0.0", "1.0.1", false),
1767            ("1.0.0", "1.0.0", false),
1768            // v-prefix on both sides, on one side, or equal
1769            ("v2.0.0", "v1.0.0", true),
1770            ("v1.0.0", "v2.0.0", false),
1771            ("v2.0.0", "1.0.0", true),
1772            ("2.0.0", "v1.0.0", true),
1773            ("v1.0.0", "2.0.0", false),
1774            ("1.0.0", "v2.0.0", false),
1775            ("v1.0.0", "v1.0.0", false),
1776            // short versions pad to three parts
1777            ("1.2", "1.1", true),
1778            ("1.1", "1.2", false),
1779            ("1.2", "1.2", false),
1780            ("2", "1", true),
1781            ("1", "2", false),
1782            ("5", "5", false),
1783            ("2.0", "1.9.9", true),
1784            ("1.9.9", "2.0", false),
1785            ("v2.0", "v1.0", true),
1786            ("v1.0", "v2.0", false),
1787        ] {
1788            assert_eq!(is_version_downgrade(old, new), expected, "{old} -> {new}");
1789        }
1790    }
1791
1792    #[test]
1793    fn downgrade_prerelease() {
1794        assert!(is_version_downgrade("1.0.0", "1.0.0-rc1"));
1795        assert!(!is_version_downgrade("1.0.0-rc1", "1.0.0"));
1796    }
1797
1798    #[test]
1799    fn downgrade_build_metadata() {
1800        // SemVer §10: build metadata MUST be ignored when determining
1801        // precedence, so a build-metadata-only change is never a downgrade in
1802        // either direction.
1803        assert!(!is_version_downgrade("1.0.0+build.1", "1.0.0+build.2"));
1804        assert!(!is_version_downgrade("1.0.0+build.2", "1.0.0+build.1"));
1805        assert!(!is_version_downgrade("1.0.0+build.1", "1.0.0+build.1"));
1806        // commit-hash build metadata (common in generated SBOMs) must not trip
1807        // the gate regardless of lexical ordering of the hashes.
1808        assert!(!is_version_downgrade("1.0.0+c144a98", "1.0.0+bc17664"));
1809        assert!(!is_version_downgrade("1.0.0+build.10", "1.0.0+build.9"));
1810    }
1811
1812    #[test]
1813    fn downgrade_prerelease_ordering() {
1814        assert!(is_version_downgrade("1.0.0-beta.1", "1.0.0-alpha.1"));
1815        assert!(is_version_downgrade("1.0.0-rc.1", "1.0.0-beta.1"));
1816        assert!(!is_version_downgrade("1.0.0-alpha.1", "1.0.0-beta.1"));
1817        assert!(!is_version_downgrade("1.0.0-beta.1", "1.0.0-rc.1"));
1818    }
1819
1820    #[test]
1821    fn downgrade_prerelease_numeric_ordering() {
1822        assert!(is_version_downgrade("1.0.0-rc.2", "1.0.0-rc.1"));
1823        assert!(!is_version_downgrade("1.0.0-rc.1", "1.0.0-rc.2"));
1824    }
1825
1826    #[test]
1827    fn downgrade_four_part() {
1828        assert!(is_version_downgrade("1.2.3.4", "1.2.3.3"));
1829        assert!(!is_version_downgrade("1.2.3.3", "1.2.3.4"));
1830        assert!(!is_version_downgrade("1.2.3.4", "1.2.3.4"));
1831    }
1832
1833    #[test]
1834    fn downgrade_date_based() {
1835        assert!(is_version_downgrade("2024.01.15", "2023.12.01"));
1836        assert!(!is_version_downgrade("2023.12.01", "2024.01.15"));
1837    }
1838
1839    #[test]
1840    fn downgrade_v_prefix_four_part() {
1841        // v-prefixed four-part versions parse to Numeric, so the downgrade
1842        // gate sees them instead of silently treating them as Opaque
1843        assert!(is_version_downgrade("v1.2.3.4", "v1.2.3.3"));
1844        assert!(!is_version_downgrade("v1.2.3.3", "v1.2.3.4"));
1845        assert!(!is_version_downgrade("v1.2.3.4", "v1.2.3.4"));
1846    }
1847
1848    #[test]
1849    fn downgrade_v_prefix_date_based() {
1850        assert!(is_version_downgrade("v2024.01.15", "v2023.12.01"));
1851        assert!(!is_version_downgrade("v2023.12.01", "v2024.01.15"));
1852    }
1853
1854    #[test]
1855    fn downgrade_non_numeric_not_flagged() {
1856        assert!(!is_version_downgrade("abc", "def"));
1857        assert!(!is_version_downgrade("foo.bar", "foo.baz"));
1858    }
1859
1860    #[test]
1861    fn downgrade_semver_vs_four_part() {
1862        // "1.2.3" → Semver, "1.2.3.4" → Numeric; cross-comparison extracts
1863        // [major,minor,patch] from the semver side
1864        assert!(!is_version_downgrade("1.2.3", "1.2.3.4"));
1865        assert!(is_version_downgrade("1.2.3.4", "1.2.3"));
1866    }
1867
1868    #[test]
1869    fn downgrade_v_prefix_vs_four_part() {
1870        // cross-variant comparison works after stripping the v-prefix during parse.
1871        assert!(!is_version_downgrade("v1.2.3", "1.2.3.4"));
1872        assert!(is_version_downgrade("1.2.3.4", "v1.2.3"));
1873    }
1874
1875    #[test]
1876    fn semver_prerelease_against_numeric() {
1877        use Ordering::{Equal, Greater, Less};
1878
1879        for (a, b, expected) in [
1880            ("1.2.3-rc.1", "1.2.3.0", Less),
1881            ("1.2.3-rc.1", "1.2.3.0.0", Less),
1882            ("1.2.3-rc.1", "1.2.3.1", Less),
1883            ("1.2.3-rc.1+build.5", "1.2.3.0", Less),
1884            ("1.2.4-rc.1", "1.2.3.9", Greater),
1885            ("1.2.3", "1.2.3.0.0", Equal),
1886            ("1.2.3+build.5", "1.2.3.0", Equal),
1887        ] {
1888            assert_eq!(compare_versions(a, b), Some(expected), "{a} vs {b}");
1889            assert_eq!(
1890                compare_versions(b, a),
1891                Some(expected.reverse()),
1892                "{b} vs {a}"
1893            );
1894        }
1895    }
1896
1897    #[test]
1898    fn semver_and_numeric_order_transitively() {
1899        let (pre, release, numeric) = ("1.2.3-rc.1", "1.2.3", "1.2.3.0");
1900        assert_eq!(compare_versions(pre, release), Some(Ordering::Less));
1901        assert_eq!(compare_versions(release, numeric), Some(Ordering::Equal));
1902        assert_eq!(compare_versions(pre, numeric), Some(Ordering::Less));
1903    }
1904
1905    #[test]
1906    fn downgrade_four_part_to_prerelease() {
1907        assert!(is_version_downgrade("1.2.3.0", "1.2.3-rc.1"));
1908        assert!(!is_version_downgrade("1.2.3-rc.1", "1.2.3.0"));
1909    }
1910
1911    #[test]
1912    fn downgrade_empty_strings() {
1913        assert!(!is_version_downgrade("", "1.0.0"));
1914        assert!(!is_version_downgrade("1.0.0", ""));
1915        assert!(!is_version_downgrade("", ""));
1916    }
1917
1918    // --- Debian/RPM epoch/upstream/revision parsing ---
1919
1920    #[test]
1921    fn parse_deb_fields() {
1922        match Version::parse_lenient("2:1.2.3-4") {
1923            Version::Deb {
1924                epoch,
1925                upstream,
1926                revision,
1927            } => {
1928                assert_eq!(epoch, 2);
1929                assert_eq!(upstream, "1.2.3");
1930                assert_eq!(revision, "4");
1931            }
1932            other => panic!("expected Deb, got {:?}", other),
1933        }
1934    }
1935
1936    #[test]
1937    fn parse_deb_revision_splits_at_last_hyphen() {
1938        // "1.2.3-2-1" is valid semver (pre-release "2-1"), so use a two-part
1939        // base that semver rejects to exercise the last-hyphen revision split
1940        match Version::parse_lenient("1.2-2-1") {
1941            Version::Deb {
1942                epoch,
1943                upstream,
1944                revision,
1945            } => {
1946                assert_eq!(epoch, 0);
1947                assert_eq!(upstream, "1.2-2");
1948                assert_eq!(revision, "1");
1949            }
1950            other => panic!("expected Deb, got {:?}", other),
1951        }
1952    }
1953
1954    #[test]
1955    fn parse_pep440_epoch_is_pep440() {
1956        match Version::parse_lenient("1!2.0") {
1957            Version::Pep440(p) => {
1958                assert_eq!(p.epoch, 1);
1959                assert_eq!(p.release, vec![2, 0]);
1960                assert_eq!(p.pre, None);
1961            }
1962            other => panic!("expected Pep440, got {:?}", other),
1963        }
1964    }
1965
1966    #[test]
1967    fn parse_deb_keeps_epoch_bang_forms_it_declines() {
1968        // a Debian revision after a PEP 440 epoch is not a PEP 440 version
1969        match Version::parse_lenient("1!2.0-3") {
1970            Version::Deb {
1971                epoch,
1972                upstream,
1973                revision,
1974            } => {
1975                assert_eq!(epoch, 1);
1976                assert_eq!(upstream, "2.0");
1977                assert_eq!(revision, "3");
1978            }
1979            other => panic!("expected Deb, got {:?}", other),
1980        }
1981    }
1982
1983    // --- Debian/RPM downgrade detection ---
1984
1985    #[test]
1986    fn downgrade_epoch() {
1987        // a higher epoch always wins, regardless of the upstream version
1988        assert!(is_version_downgrade("2:1.0", "1:9.0"));
1989        assert!(!is_version_downgrade("1:9.0", "2:1.0"));
1990        // epoch dominates: epoch up beats a lower upstream, epoch down beats a higher one
1991        assert!(!is_version_downgrade("1:1.0", "2:0.1"));
1992        assert!(is_version_downgrade("2:0.1", "1:1.0"));
1993    }
1994
1995    #[test]
1996    fn downgrade_epoch_equal_upstream() {
1997        assert!(is_version_downgrade("1:2.0", "1:1.0"));
1998        assert!(!is_version_downgrade("1:1.0", "1:2.0"));
1999        assert!(!is_version_downgrade("1:1.0", "1:1.0"));
2000    }
2001
2002    #[test]
2003    fn downgrade_implicit_epoch_zero() {
2004        // an absent epoch is 0, so adding an epoch is an upgrade, dropping to
2005        // an explicit 0 is neutral
2006        assert!(!is_version_downgrade("5.1-1", "1:0.1-1"));
2007        assert!(is_version_downgrade("1:0.1-1", "0:0.1-1"));
2008    }
2009
2010    #[test]
2011    fn downgrade_revision() {
2012        assert!(is_version_downgrade("5.1-3", "5.1-2"));
2013        assert!(!is_version_downgrade("5.1-2", "5.1-3"));
2014        assert!(!is_version_downgrade("5.1-2", "5.1-2"));
2015    }
2016
2017    #[test]
2018    fn downgrade_absent_revision_equals_zero() {
2019        // an absent revision compares as "0"; "1.0" is semver so pin the epoch
2020        // to force Debian parsing on both sides
2021        assert!(is_version_downgrade("1:2.0-1", "1:2.0"));
2022        assert!(!is_version_downgrade("1:2.0", "1:2.0-1"));
2023    }
2024
2025    #[test]
2026    fn downgrade_rpm_release_with_epoch() {
2027        // an epoch forces Debian parsing even though the tail resembles a
2028        // semver pre-release; RPM `.elN` release tails order numerically
2029        assert!(is_version_downgrade("1:1.2.3-2.el8", "1:1.2.3-1.el8"));
2030        assert!(!is_version_downgrade("1:1.2.3-1.el8", "1:1.2.3-2.el8"));
2031        // el8 is newer than el7
2032        assert!(is_version_downgrade("1:1.2.3-1.el8", "1:1.2.3-1.el7"));
2033        assert!(!is_version_downgrade("1:1.2.3-1.el7", "1:1.2.3-1.el8"));
2034    }
2035
2036    #[test]
2037    fn downgrade_deb_numeric_not_lexical() {
2038        // 10 > 9 numerically even though "9" > "1" lexically
2039        assert!(is_version_downgrade("1.10-1", "1.9-1"));
2040        assert!(!is_version_downgrade("1.9-1", "1.10-1"));
2041    }
2042
2043    #[test]
2044    fn downgrade_deb_tilde_prerelease() {
2045        // a tilde sorts before everything, so ~rc2 > ~rc1 and ~rc1 < the release
2046        assert!(is_version_downgrade("1.0.0~rc2", "1.0.0~rc1"));
2047        assert!(!is_version_downgrade("1.0.0~rc1", "1.0.0~rc2"));
2048        assert!(is_version_downgrade("1:1.0~rc1", "1:1.0~beta1"));
2049    }
2050
2051    #[test]
2052    fn downgrade_real_world_deb() {
2053        // openssl with epoch and an Ubuntu security revision
2054        assert!(is_version_downgrade(
2055            "1:1.1.1f-1ubuntu2.16",
2056            "1:1.1.1f-1ubuntu2.15"
2057        ));
2058        assert!(!is_version_downgrade(
2059            "1:1.1.1f-1ubuntu2.15",
2060            "1:1.1.1f-1ubuntu2.16"
2061        ));
2062    }
2063
2064    #[test]
2065    fn downgrade_deb_opaque_not_flagged() {
2066        // codenames and other non-version strings remain uncomparable
2067        assert!(!is_version_downgrade("focal", "bionic"));
2068        assert!(!is_version_downgrade("1:stable", "1:oldstable"));
2069    }
2070
2071    #[test]
2072    fn downgrade_deb_vs_semver_not_flagged() {
2073        // cross-format comparison stays conservative (returns false)
2074        assert!(!is_version_downgrade("2:1.0", "1.0.0"));
2075        assert!(!is_version_downgrade("1.0.0", "2:1.0"));
2076    }
2077
2078    #[test]
2079    fn deb_canonical_ordering_vectors() {
2080        use Ordering::{Equal, Greater, Less};
2081
2082        // canonical dpkg (`verrevcmp`) orderings for the edge cases the other
2083        // tests don't fully pin, each `expected` derived by hand from the
2084        // `deb_order`/`verrevcmp` rules documented above. every string pins an
2085        // epoch so it forces `Deb` parsing — a bare `1.0`/`1.0~rc1` would parse
2086        // as Semver/Numeric and exercise the wrong comparator (see
2087        // `downgrade_absent_revision_equals_zero`). `expected` is how `a` orders
2088        // relative to `b`; the harness drives each vector through the public
2089        // `is_version_downgrade` in both directions.
2090        let cases = [
2091            // tilde chain: `~` < end-of-string < letters < other punctuation,
2092            // so 1.0~~ < 1.0~~a < 1.0~ < 1.0 < 1.0a
2093            ("1:1.0~~", "1:1.0~~a", Less),
2094            ("1:1.0~~a", "1:1.0~", Less),
2095            ("1:1.0~", "1:1.0", Less),
2096            ("1:1.0", "1:1.0a", Less),
2097            // tilde marks a pre-release: it sorts before the release, and
2098            // pre-releases order among themselves
2099            ("1:1.0~rc1", "1:1.0", Less),
2100            ("1:1.0~rc1", "1:1.0~rc2", Less),
2101            // digit runs compare numerically, not lexically: 10 > 9
2102            ("1:1.10", "1:1.9", Greater),
2103            // leading zeros don't change a digit run's value
2104            ("1:1.0", "1:1.00", Equal),
2105            ("1:1.01", "1:1.1", Equal),
2106            // a letter outranks a digit at a component boundary...
2107            ("1:1.a", "1:1.1", Greater),
2108            // ...but a continuing digit run still outranks a letter suffix
2109            ("1:1.0a", "1:1.01", Less),
2110            // epoch dominates the upstream comparison
2111            ("2:0.1", "1:9.9", Greater),
2112            // upstream is compared before the revision
2113            ("1:5.2-1", "1:5.1-9", Greater),
2114            // an absent revision compares equal to an explicit "0"
2115            ("1:2.0", "1:2.0-0", Equal),
2116            // revision digit runs are numeric too: 10 > 9
2117            ("1:2.0-10", "1:2.0-9", Greater),
2118        ];
2119
2120        for (a, b, expected) in cases {
2121            // guard the vector: if either side stops parsing as Deb, it would
2122            // silently test a different comparator and prove nothing.
2123            assert!(
2124                matches!(Version::parse_lenient(a), Version::Deb { .. }),
2125                "{a} no longer parses as Deb"
2126            );
2127            assert!(
2128                matches!(Version::parse_lenient(b), Version::Deb { .. }),
2129                "{b} no longer parses as Deb"
2130            );
2131            match expected {
2132                // a < b: going b -> a is a downgrade, a -> b is not
2133                Less => {
2134                    assert!(is_version_downgrade(b, a), "expected {a} < {b}");
2135                    assert!(!is_version_downgrade(a, b), "expected {a} < {b}");
2136                }
2137                // a > b: going a -> b is a downgrade, b -> a is not
2138                Greater => {
2139                    assert!(is_version_downgrade(a, b), "expected {a} > {b}");
2140                    assert!(!is_version_downgrade(b, a), "expected {a} > {b}");
2141                }
2142                // a == b: neither direction is a downgrade
2143                Equal => {
2144                    assert!(!is_version_downgrade(a, b), "expected {a} == {b}");
2145                    assert!(!is_version_downgrade(b, a), "expected {a} == {b}");
2146                }
2147            }
2148        }
2149    }
2150
2151    #[test]
2152    fn compare_orders_comparable_variant_pairs() {
2153        use Ordering::{Equal, Greater, Less};
2154
2155        for (a, b, expected) in [
2156            ("2.0.0", "1.5.0", Greater),
2157            ("1.0.0", "1.0.0", Equal),
2158            ("1.2.3.4", "1.2.3.3", Greater),
2159            ("1.2.3", "1.2.3.4", Less),
2160            ("2:1.0-3", "1:9.0-1", Greater),
2161            ("5.1-3", "5.1-3", Equal),
2162        ] {
2163            assert_eq!(compare_versions(a, b), Some(expected), "{a} vs {b}");
2164            assert_eq!(
2165                compare_versions(b, a),
2166                Some(expected.reverse()),
2167                "{b} vs {a}"
2168            );
2169        }
2170    }
2171
2172    #[test]
2173    fn compare_leaves_opaque_and_mixed_variants_unordered() {
2174        for (a, b) in [
2175            ("deadbeef", "1.0.0"),
2176            ("deadbeef", "cafebabe"),
2177            ("deadbeef", "deadbeef"),
2178            ("2:1.0-3", "1.0.0"),
2179            ("5.1-3", "5.1.0.0"),
2180        ] {
2181            assert_eq!(compare_versions(a, b), None, "{a} vs {b}");
2182            assert_eq!(compare_versions(b, a), None, "{b} vs {a}");
2183        }
2184    }
2185
2186    // --- PEP 440 (Python) parsing and ordering ---
2187
2188    #[test]
2189    fn parse_pep440_suffixes() {
2190        for s in [
2191            "1.0rc1",
2192            "1.0a1",
2193            "1.0b1",
2194            "1.0.dev1",
2195            "1.0.post1",
2196            "4.2.0rc1",
2197            "1!1.0",
2198            "1.0alpha1",
2199            "1.0-rc-1",
2200            "1.0_beta_2",
2201            "1.0.RC1",
2202            "2.0.post2.dev3",
2203            "1.0rc1+ubuntu.1",
2204        ] {
2205            assert!(
2206                matches!(Version::parse_lenient(s), Version::Pep440(_)),
2207                "{s} should parse as Pep440"
2208            );
2209        }
2210    }
2211
2212    #[test]
2213    fn parse_pep440_fields() {
2214        match Version::parse_lenient("2!4.2.0.post3.dev7") {
2215            Version::Pep440(p) => {
2216                assert_eq!(p.epoch, 2);
2217                assert_eq!(p.release, vec![4, 2, 0]);
2218                assert_eq!(p.pre, None);
2219                assert_eq!(p.post, Some(3));
2220                assert_eq!(p.dev, Some(7));
2221                assert!(p.local.is_empty());
2222            }
2223            other => panic!("expected Pep440, got {:?}", other),
2224        }
2225    }
2226
2227    #[test]
2228    fn parse_pep440_leaves_other_formats_alone() {
2229        for s in [
2230            "1.2.3",
2231            "v1.2",
2232            "42",
2233            "1.2.3-beta.1",
2234            "1.0.0-alpha.1+build.789",
2235            "0.0.0",
2236        ] {
2237            assert!(
2238                matches!(Version::parse_lenient(s), Version::Semver(_)),
2239                "{s} should still be Semver"
2240            );
2241        }
2242        for s in ["1.2.3.4", "2024.01.15", "01.02.03", "v1.2.3.4"] {
2243            assert!(
2244                matches!(Version::parse_lenient(s), Version::Numeric(_)),
2245                "{s} should still be Numeric"
2246            );
2247        }
2248        for s in [
2249            "2:1.0",
2250            "5.1-3",
2251            "2:1.2.3-4",
2252            "1.2-2-1",
2253            "1.0.0~rc1",
2254            "1:1.1.1f-1ubuntu2.16",
2255            "1.0+ubuntu.1",
2256        ] {
2257            assert!(
2258                matches!(Version::parse_lenient(s), Version::Deb { .. }),
2259                "{s} should still be Deb"
2260            );
2261        }
2262        for s in ["abc", "foo.bar.baz", "focal-1", "stable", "1:stable", ""] {
2263            assert!(
2264                matches!(Version::parse_lenient(s), Version::Opaque(_)),
2265                "{s} should still be Opaque"
2266            );
2267        }
2268    }
2269
2270    /// asserts the strings are in strictly ascending order, every pair.
2271    fn assert_ascending(versions: &[&str]) {
2272        for (i, a) in versions.iter().enumerate() {
2273            for b in &versions[i + 1..] {
2274                assert_eq!(
2275                    compare_versions(a, b),
2276                    Some(Ordering::Less),
2277                    "expected {a} < {b}"
2278                );
2279                assert_eq!(
2280                    compare_versions(b, a),
2281                    Some(Ordering::Greater),
2282                    "expected {b} > {a}"
2283                );
2284                assert!(is_version_downgrade(b, a), "expected {b} -> {a} downgrade");
2285                assert!(!is_version_downgrade(a, b), "expected {a} -> {b} upgrade");
2286            }
2287        }
2288    }
2289
2290    #[test]
2291    fn pep440_release_cycle_ordering() {
2292        assert_ascending(&[
2293            "1.0.dev1",
2294            "1.0a1",
2295            "1.0a2",
2296            "1.0b1",
2297            "1.0rc1",
2298            "1.0",
2299            "1.0.post1",
2300            "1.0.1",
2301        ]);
2302    }
2303
2304    #[test]
2305    fn pep440_dev_ordering_within_segments() {
2306        assert_ascending(&["1.0.dev1", "1.0a1.dev1", "1.0a1", "1.0"]);
2307        assert_ascending(&["1.0", "1.0.post1.dev1", "1.0.post1"]);
2308    }
2309
2310    #[test]
2311    fn pep440_epoch_ordering() {
2312        assert_ascending(&["2.0", "1!1.0", "1!2.0", "2!0.1"]);
2313    }
2314
2315    #[test]
2316    fn pep440_spelling_aliases() {
2317        for (canonical, aliases) in [
2318            ("1.0a1", ["1.0alpha1", "1.0.ALPHA.1", "1.0-a-1"]),
2319            ("1.0b1", ["1.0beta1", "1.0.BETA.1", "1.0_b_1"]),
2320            ("1.0rc1", ["1.0c1", "1.0pre1", "1.0preview1"]),
2321            ("1.0.post1", ["1.0rev1", "1.0r1", "1.0-POST-1"]),
2322        ] {
2323            for alias in aliases {
2324                assert_eq!(
2325                    compare_versions(canonical, alias),
2326                    Some(Ordering::Equal),
2327                    "{alias} should normalize to {canonical}"
2328                );
2329            }
2330        }
2331        // an omitted number is an implicit 0, so 1.0rc < 1.0rc1
2332        assert_eq!(compare_versions("1.0rc", "1.0rc0"), Some(Ordering::Equal));
2333        assert_eq!(compare_versions("1.0rc", "1.0rc1"), Some(Ordering::Less));
2334    }
2335
2336    #[test]
2337    fn pep440_compares_against_semver_and_numeric() {
2338        use Ordering::{Equal, Greater, Less};
2339
2340        for (a, b, expected) in [
2341            // the silently-skipped transitions: one side parses Semver
2342            ("4.2.0rc1", "4.2.0", Less),
2343            ("1.0rc1", "1.0", Less),
2344            ("1.0.dev1", "1.0", Less),
2345            ("1.0", "1.0.post1", Less),
2346            ("1!1.0", "2.0", Greater),
2347            ("1.0.post1", "1.0.1", Less),
2348            // implicit zero padding across the two spellings of one release
2349            ("1.0.post0", "1.0.0.post0", Equal),
2350            // ...and against a four-part version, which parses Numeric
2351            ("1.2.3.4rc1", "1.2.3.4", Less),
2352            ("1.2.3.4.dev1", "1.2.3.3", Greater),
2353            // a semver pre-release that is also a PEP 440 pre-release
2354            ("1.0.0-rc1", "1.0rc2", Less),
2355            ("1.0.0-alpha.1", "1.0b1", Less),
2356        ] {
2357            assert_eq!(compare_versions(a, b), Some(expected), "{a} vs {b}");
2358            assert_eq!(
2359                compare_versions(b, a),
2360                Some(expected.reverse()),
2361                "{b} vs {a}"
2362            );
2363        }
2364    }
2365
2366    #[test]
2367    fn pep440_local_version_ordering() {
2368        // a local label outranks the same version without one
2369        assert_ascending(&["1.0rc1", "1.0rc1+ubuntu", "1.0rc1+ubuntu.1"]);
2370        assert_ascending(&["1.0rc1+abc", "1.0rc1+1"]);
2371        assert_ascending(&["1.0rc1+build.9", "1.0rc1+build.10"]);
2372        assert_eq!(
2373            compare_versions("1.0rc1+UBUNTU-1", "1.0rc1+ubuntu.1"),
2374            Some(Ordering::Equal)
2375        );
2376    }
2377
2378    #[test]
2379    fn pep440_stays_uncomparable_against_deb_and_opaque() {
2380        for (a, b) in [
2381            ("1.0rc1", "2:1.0"),
2382            ("1.0rc1", "1.0.0~rc1"),
2383            ("1.0rc1", "deadbeef"),
2384            // a semver pre-release with no PEP 440 reading
2385            ("1.0.0-foo.bar", "1.0rc1"),
2386        ] {
2387            assert_eq!(compare_versions(a, b), None, "{a} vs {b}");
2388            assert_eq!(compare_versions(b, a), None, "{b} vs {a}");
2389        }
2390    }
2391
2392    #[test]
2393    fn downgrade_pep440_gate() {
2394        // the false positive: a normal Python pre-release progression
2395        assert!(!is_version_downgrade("1.0.dev1", "1.0a1"));
2396        assert!(is_version_downgrade("1.0a1", "1.0.dev1"));
2397        // the silent skips
2398        assert!(!is_version_downgrade("4.2.0rc1", "4.2.0"));
2399        assert!(is_version_downgrade("4.2.0", "4.2.0rc1"));
2400        assert!(!is_version_downgrade("1.0", "1.0.post1"));
2401        assert!(is_version_downgrade("1.0.post1", "1.0"));
2402        assert!(!is_version_downgrade("1.0rc1", "1.0rc1"));
2403    }
2404
2405    // --- letter-suffixed OS package versions (OpenSSL, tzdata, Alpine) ---
2406
2407    /// `pattern` with its `@` replaced by each letter of `a`..`z` in turn.
2408    fn letter_suffixed(pattern: &str) -> Vec<String> {
2409        ('a'..='z')
2410            .map(|c| pattern.replace('@', &c.to_string()))
2411            .collect()
2412    }
2413
2414    #[test]
2415    fn bare_single_letter_suffix_parses_as_deb() {
2416        for pattern in ["1.0.2@", "2024@", "1.1.1@-r0", "1.0@"] {
2417            for s in letter_suffixed(pattern) {
2418                assert!(
2419                    matches!(Version::parse_lenient(&s), Version::Deb { .. }),
2420                    "{s} should parse as Deb"
2421                );
2422            }
2423        }
2424    }
2425
2426    #[test]
2427    fn letter_suffixed_versions_order_across_the_alphabet() {
2428        for pattern in ["1.0.2@", "2024@", "1.1.1@-r0"] {
2429            let versions = letter_suffixed(pattern);
2430            let refs: Vec<&str> = versions.iter().map(String::as_str).collect();
2431            assert_ascending(&refs);
2432        }
2433        assert_ascending(&["2024a", "2024h", "2025a", "2025b"]);
2434        assert_ascending(&["1.1.1a-r0", "1.1.1d-r0", "1.1.1d-r1", "1.1.1w-r0"]);
2435    }
2436
2437    #[test]
2438    fn bare_keyword_longer_than_one_letter_stays_pep440() {
2439        for s in [
2440            "1.0rc",
2441            "1.0.dev",
2442            "1.0.post",
2443            "1.0alpha",
2444            "1.0beta",
2445            "1.0pre",
2446            "1.0preview",
2447            "1.0rev",
2448            "2.0.post2.dev3",
2449        ] {
2450            assert!(
2451                matches!(Version::parse_lenient(s), Version::Pep440(_)),
2452                "{s} should still parse as Pep440"
2453            );
2454        }
2455    }
2456
2457    #[test]
2458    fn single_letter_alias_with_a_number_stays_pep440() {
2459        for s in [
2460            "1.0a1",
2461            "1.0b1",
2462            "1.0c1",
2463            "1.0r1",
2464            "1.0a0",
2465            "1.0-a-1",
2466            "1.0_b_2",
2467            "1.0.c.3",
2468            "1!2.0a1",
2469            "1.0a1+ubuntu.1",
2470        ] {
2471            assert!(
2472                matches!(Version::parse_lenient(s), Version::Pep440(_)),
2473                "{s} should still parse as Pep440"
2474            );
2475        }
2476    }
2477
2478    #[test]
2479    fn downgrade_letter_suffix_gate() {
2480        assert!(is_version_downgrade("1.0.2d", "1.0.2c"));
2481        assert!(!is_version_downgrade("1.0.2c", "1.0.2d"));
2482        assert!(is_version_downgrade("2025a", "2024h"));
2483        assert!(!is_version_downgrade("2024h", "2025a"));
2484        assert!(is_version_downgrade("1.1.1d-r0", "1.1.1a-r0"));
2485        assert!(!is_version_downgrade("1.1.1a-r0", "1.1.1d-r0"));
2486        assert!(!is_version_downgrade("1.0.2a", "1.0.2a"));
2487        // a base release and its letter releases are Semver against Deb
2488        assert_eq!(compare_versions("1.0.2", "1.0.2a"), None);
2489        assert!(!is_version_downgrade("1.0.2", "1.0.2a"));
2490        assert!(!is_version_downgrade("1.0.2a", "1.0.2"));
2491    }
2492
2493    #[test]
2494    fn downgrade_agrees_with_compare() {
2495        use Ordering::Greater;
2496
2497        for (a, b) in [
2498            ("2.0.0", "1.5.0"),
2499            ("1.0.0", "2.0.0"),
2500            ("1.0.0", "1.0.0"),
2501            ("2024.01.15", "2024.01.14"),
2502            ("2:1.0-3", "1:9.0-1"),
2503            ("1.0.0+build.10", "1.0.0+build.9"),
2504            ("deadbeef", "1.0.0"),
2505        ] {
2506            assert_eq!(
2507                is_version_downgrade(a, b),
2508                compare_versions(a, b) == Some(Greater),
2509                "{a} -> {b}"
2510            );
2511        }
2512    }
2513
2514    /// version strings spanning every shape the two entry points disagree about.
2515    const ECOSYSTEM_CORPUS: &[&str] = &[
2516        "1",
2517        "1.0",
2518        "1.0.0",
2519        "1.2.3",
2520        "v1.2.3",
2521        "2024.01.15",
2522        "1.2.3.4",
2523        "1.0.0-alpha.1",
2524        "1.0.0-alpha.2",
2525        "1.0.0-rc.1",
2526        "1.0.0+build.9",
2527        "1.0.0-foo.bar",
2528        "4.2.0rc1",
2529        "1.0.dev1",
2530        "1.0a1",
2531        "1!1.0",
2532        "1.0.post1",
2533        "1.0.2a",
2534        "1.2.3-1",
2535        "1.2.3-2",
2536        "1.2.3-1ubuntu2",
2537        "1.2.3-1build1",
2538        "1.2.3-1+deb11u1",
2539        "1.0~rc1",
2540        "2:1.0-3",
2541        "4.4.2-2.el7_9",
2542        "deadbeef",
2543        "",
2544    ];
2545
2546    #[test]
2547    fn unknown_ecosystem_parses_exactly_like_parse_lenient() {
2548        for eco in [
2549            None,
2550            Some("npm"),
2551            Some("cargo"),
2552            Some("golang"),
2553            Some("python"),
2554        ] {
2555            for s in ECOSYSTEM_CORPUS {
2556                assert_eq!(
2557                    Version::parse_for_ecosystem(eco, s),
2558                    Version::parse_lenient(s),
2559                    "{eco:?} / {s}"
2560                );
2561            }
2562        }
2563    }
2564
2565    #[test]
2566    fn unknown_ecosystem_orders_exactly_like_the_string_only_path() {
2567        for eco in [
2568            None,
2569            Some("npm"),
2570            Some("cargo"),
2571            Some("golang"),
2572            Some("python"),
2573        ] {
2574            for a in ECOSYSTEM_CORPUS {
2575                for b in ECOSYSTEM_CORPUS {
2576                    assert_eq!(
2577                        compare_versions_for_ecosystem(eco, a, b),
2578                        compare_versions(a, b),
2579                        "{eco:?} / {a} vs {b}"
2580                    );
2581                    assert_eq!(
2582                        is_version_downgrade_for_ecosystem(eco, a, b),
2583                        is_version_downgrade(a, b),
2584                        "{eco:?} / {a} -> {b}"
2585                    );
2586                }
2587            }
2588        }
2589    }
2590
2591    #[test]
2592    fn deb_ecosystem_parses_as_deb() {
2593        assert_eq!(
2594            Version::parse_for_ecosystem(Some("deb"), "1.2.3-1ubuntu2"),
2595            Version::Deb {
2596                epoch: 0,
2597                upstream: "1.2.3".into(),
2598                revision: "1ubuntu2".into(),
2599            }
2600        );
2601        assert!(matches!(
2602            Version::parse_for_ecosystem(Some("deb"), "1.2.3"),
2603            Version::Deb { .. }
2604        ));
2605        assert!(matches!(
2606            Version::parse_for_ecosystem(Some("deb"), "1.0.0-alpha.1"),
2607            Version::Deb { .. }
2608        ));
2609    }
2610
2611    #[test]
2612    fn ecosystem_match_ignores_case() {
2613        // each string parses differently on the lenient path, so a row fails
2614        // if the upper-case spelling stops selecting its ecosystem
2615        for (upper, lower, s) in [
2616            ("DEB", "deb", "1.2.3-1ubuntu2"),
2617            ("RPM", "rpm", "5.1.8-2.fc35"),
2618            ("MAVEN", "maven", "1.0-SNAPSHOT"),
2619            ("NuGet", "nuget", "1.0.0-rc"),
2620            ("PyPI", "pypi", "1.0.2a"),
2621            ("APK", "apk", "1.0-r1"),
2622        ] {
2623            assert_eq!(
2624                Version::parse_for_ecosystem(Some(upper), s),
2625                Version::parse_for_ecosystem(Some(lower), s),
2626                "{upper} / {s}"
2627            );
2628        }
2629    }
2630
2631    #[test]
2632    fn deb_ecosystem_does_not_retry_a_non_deb_string_as_semver() {
2633        assert_eq!(
2634            Version::parse_for_ecosystem(Some("deb"), "4.4.2-2.el7_9"),
2635            Version::Opaque("4.4.2-2.el7_9".into())
2636        );
2637        assert!(matches!(
2638            Version::parse_for_ecosystem(Some("deb"), "v1.2.3-1ubuntu2"),
2639            Version::Deb { .. }
2640        ));
2641    }
2642
2643    /// every expectation checked against `dpkg --compare-versions` on Debian.
2644    #[test]
2645    fn deb_ecosystem_strips_a_v_prefix_instead_of_skipping_the_pair() {
2646        use Ordering::{Greater, Less};
2647
2648        for (a, b, expected) in [
2649            ("v1.2.3", "v1.2.4", Less),
2650            ("v1.2.10", "v1.2.9", Greater),
2651            ("V1.2.3", "V1.2.4", Less),
2652            ("v1.2.3-1ubuntu2", "v1.2.3-2", Less),
2653        ] {
2654            assert_eq!(
2655                compare_versions_for_ecosystem(Some("deb"), a, b),
2656                Some(expected),
2657                "{a} vs {b}"
2658            );
2659            assert_eq!(
2660                compare_versions_for_ecosystem(Some("deb"), b, a),
2661                Some(expected.reverse()),
2662                "{b} vs {a}"
2663            );
2664        }
2665
2666        assert!(is_version_downgrade_for_ecosystem(
2667            Some("deb"),
2668            "v1.2.4",
2669            "v1.2.3"
2670        ));
2671    }
2672
2673    /// every expectation checked against `dpkg --compare-versions` on Debian.
2674    #[test]
2675    fn deb_ecosystem_orders_revisions_the_way_dpkg_does() {
2676        use Ordering::{Greater, Less};
2677
2678        for (a, b, expected) in [
2679            ("1.2.3-1ubuntu2", "1.2.3-2", Less),
2680            ("1.2.3-1build1", "1.2.3-2", Less),
2681            ("1.2.3-2ubuntu0.1", "1.2.3-3", Less),
2682            ("1.2.3-1+deb11u1", "1.2.3-2", Less),
2683            ("1.2.3-1+deb11u1", "1.2.3-1+deb11u2", Less),
2684            ("1.2.3-1ubuntu2", "1.2.3-1ubuntu1", Greater),
2685            ("1.2.3-1", "1.2.3-10", Less),
2686            ("1.2.3", "1.2.3-1", Less),
2687            ("1.0-1", "1.0", Greater),
2688            ("1.0~rc1", "1.0", Less),
2689            ("1.0~rc1-1", "1.0-1", Less),
2690            ("1.2.3-1~bpo11+1", "1.2.3-1", Less),
2691            ("2:1.0-1", "10.0-1", Greater),
2692            ("1.1.1n-0+deb11u5", "1.1.1o-1", Less),
2693        ] {
2694            assert_eq!(
2695                compare_versions_for_ecosystem(Some("deb"), a, b),
2696                Some(expected),
2697                "{a} vs {b}"
2698            );
2699            assert_eq!(
2700                compare_versions_for_ecosystem(Some("deb"), b, a),
2701                Some(expected.reverse()),
2702                "{b} vs {a}"
2703            );
2704        }
2705    }
2706
2707    #[test]
2708    fn deb_ecosystem_clears_the_false_downgrade_the_string_only_path_reports() {
2709        assert!(!is_version_downgrade_for_ecosystem(
2710            Some("deb"),
2711            "1.2.3-1ubuntu2",
2712            "1.2.3-2"
2713        ));
2714        assert!(is_version_downgrade("1.2.3-1ubuntu2", "1.2.3-2"));
2715        assert!(is_version_downgrade_for_ecosystem(
2716            Some("deb"),
2717            "1.2.3-2",
2718            "1.2.3-1ubuntu2"
2719        ));
2720    }
2721
2722    #[test]
2723    fn deb_ecosystem_catches_the_downgrades_the_string_only_path_passed() {
2724        for (old, new) in [
2725            ("1.2.3-2", "1.2.3-1ubuntu2"),
2726            ("1.2.3-3", "1.2.3-2ubuntu0.1"),
2727            ("1.2.3-1+deb11u2", "1.2.3-1+deb11u1"),
2728        ] {
2729            assert!(!is_version_downgrade(old, new), "{old} -> {new}");
2730            assert!(
2731                is_version_downgrade_for_ecosystem(Some("deb"), old, new),
2732                "{old} -> {new}"
2733            );
2734        }
2735    }
2736
2737    #[test]
2738    fn deb_ecosystem_orders_plus_revisions_the_string_only_path_read_as_equal() {
2739        assert_eq!(
2740            compare_versions("1.2.3-1+deb11u1", "1.2.3-1+deb11u2"),
2741            Some(Ordering::Equal)
2742        );
2743        assert_eq!(
2744            compare_versions_for_ecosystem(Some("deb"), "1.2.3-1+deb11u1", "1.2.3-1+deb11u2"),
2745            Some(Ordering::Less)
2746        );
2747    }
2748
2749    #[test]
2750    fn deb_ecosystem_makes_previously_uncomparable_pairs_comparable() {
2751        for (a, b) in [("1.0-1", "1.0"), ("1.0~rc1", "1.0"), ("1.0.2a", "1.0.2")] {
2752            assert_eq!(compare_versions(a, b), None, "{a} vs {b}");
2753            assert!(
2754                compare_versions_for_ecosystem(Some("deb"), a, b).is_some(),
2755                "{a} vs {b}"
2756            );
2757        }
2758    }
2759
2760    /// rpm's own `tests/rpmvercmp.at` assertion list, one case per row.
2761    /// `expected` is how `a` orders relative to `b`.
2762    #[test]
2763    fn rpmvercmp_upstream_vectors() {
2764        use Ordering::{Equal, Greater, Less};
2765
2766        for (a, b, expected) in [
2767            ("1.0", "1.0", Equal),
2768            ("1.0", "2.0", Less),
2769            ("2.0", "1.0", Greater),
2770            ("2.0.1", "2.0.1", Equal),
2771            ("2.0", "2.0.1", Less),
2772            ("2.0.1", "2.0", Greater),
2773            ("2.0.1a", "2.0.1a", Equal),
2774            ("2.0.1a", "2.0.1", Greater),
2775            ("2.0.1", "2.0.1a", Less),
2776            ("5.5p1", "5.5p1", Equal),
2777            ("5.5p1", "5.5p2", Less),
2778            ("5.5p2", "5.5p1", Greater),
2779            ("5.5p10", "5.5p10", Equal),
2780            ("5.5p1", "5.5p10", Less),
2781            ("5.5p10", "5.5p1", Greater),
2782            ("10xyz", "10.1xyz", Less),
2783            ("10.1xyz", "10xyz", Greater),
2784            ("xyz10", "xyz10", Equal),
2785            ("xyz10", "xyz10.1", Less),
2786            ("xyz10.1", "xyz10", Greater),
2787            ("xyz.4", "xyz.4", Equal),
2788            ("xyz.4", "8", Less),
2789            ("8", "xyz.4", Greater),
2790            ("xyz.4", "2", Less),
2791            ("2", "xyz.4", Greater),
2792            ("5.5p2", "5.6p1", Less),
2793            ("5.6p1", "5.5p2", Greater),
2794            ("5.6p1", "6.5p1", Less),
2795            ("6.5p1", "5.6p1", Greater),
2796            ("6.0.rc1", "6.0", Greater),
2797            ("6.0", "6.0.rc1", Less),
2798            ("10b2", "10a1", Greater),
2799            ("10a2", "10b2", Less),
2800            ("1.0aa", "1.0aa", Equal),
2801            ("1.0a", "1.0aa", Less),
2802            ("1.0aa", "1.0a", Greater),
2803            ("10.0001", "10.0001", Equal),
2804            ("10.0001", "10.1", Equal),
2805            ("10.1", "10.0001", Equal),
2806            ("10.0001", "10.0039", Less),
2807            ("10.0039", "10.0001", Greater),
2808            ("4.999.9", "5.0", Less),
2809            ("5.0", "4.999.9", Greater),
2810            ("20101121", "20101121", Equal),
2811            ("20101121", "20101122", Less),
2812            ("20101122", "20101121", Greater),
2813            ("2_0", "2_0", Equal),
2814            ("2.0", "2_0", Equal),
2815            ("2_0", "2.0", Equal),
2816            ("a", "a", Equal),
2817            ("a+", "a+", Equal),
2818            ("a+", "a_", Equal),
2819            ("a_", "a+", Equal),
2820            ("+a", "+a", Equal),
2821            ("+a", "_a", Equal),
2822            ("_a", "+a", Equal),
2823            ("+_", "+_", Equal),
2824            ("_+", "+_", Equal),
2825            ("_+", "_+", Equal),
2826            ("+", "_", Equal),
2827            ("_", "+", Equal),
2828            ("1.0~rc1", "1.0~rc1", Equal),
2829            ("1.0~rc1", "1.0", Less),
2830            ("1.0", "1.0~rc1", Greater),
2831            ("1.0~rc1", "1.0~rc2", Less),
2832            ("1.0~rc2", "1.0~rc1", Greater),
2833            ("1.0~rc1~git123", "1.0~rc1~git123", Equal),
2834            ("1.0~rc1~git123", "1.0~rc1", Less),
2835            ("1.0~rc1", "1.0~rc1~git123", Greater),
2836            ("1.0^", "1.0^", Equal),
2837            ("1.0^", "1.0", Greater),
2838            ("1.0", "1.0^", Less),
2839            ("1.0^git1", "1.0^git1", Equal),
2840            ("1.0^git1", "1.0", Greater),
2841            ("1.0", "1.0^git1", Less),
2842            ("1.0^git1", "1.0^git2", Less),
2843            ("1.0^git2", "1.0^git1", Greater),
2844            ("1.0^git1", "1.01", Less),
2845            ("1.01", "1.0^git1", Greater),
2846            ("1.0^20160101", "1.0^20160101", Equal),
2847            ("1.0^20160101", "1.0.1", Less),
2848            ("1.0.1", "1.0^20160101", Greater),
2849            ("1.0^20160101^git1", "1.0^20160101^git1", Equal),
2850            ("1.0^20160102", "1.0^20160101^git1", Greater),
2851            ("1.0^20160101^git1", "1.0^20160102", Less),
2852            ("1.0~rc1^git1", "1.0~rc1^git1", Equal),
2853            ("1.0~rc1^git1", "1.0~rc1", Greater),
2854            ("1.0~rc1", "1.0~rc1^git1", Less),
2855            ("1.0^git1~pre", "1.0^git1~pre", Equal),
2856            ("1.0^git1", "1.0^git1~pre", Greater),
2857            ("1.0^git1~pre", "1.0^git1", Less),
2858            // upstream keeps these as documented quirks: the alpha run is
2859            // compared against "fc", so 'b' loses and 'g' wins
2860            ("1b.fc17", "1b.fc17", Equal),
2861            ("1b.fc17", "1.fc17", Less),
2862            ("1.fc17", "1b.fc17", Greater),
2863            ("1g.fc17", "1g.fc17", Equal),
2864            ("1g.fc17", "1.fc17", Greater),
2865            ("1.fc17", "1g.fc17", Less),
2866            // non-ASCII bytes are separators, so these are all equal
2867            ("1.1.α", "1.1.α", Equal),
2868            ("1.1.α", "1.1.β", Equal),
2869            ("1.1.β", "1.1.α", Equal),
2870            ("1.1.αα", "1.1.α", Equal),
2871            ("1.1.α", "1.1.ββ", Equal),
2872            ("1.1.ββ", "1.1.αα", Equal),
2873        ] {
2874            assert_eq!(rpmvercmp(a, b), expected, "{a} vs {b}");
2875        }
2876    }
2877
2878    /// derived from the algorithm: upstream's vectors exercise `rpmvercmp`
2879    /// alone, never the epoch and release `parseEVR` splits off ahead of it.
2880    #[test]
2881    fn rpm_ecosystem_orders_epoch_then_version_then_release() {
2882        use Ordering::{Equal, Greater, Less};
2883
2884        for (a, b, expected) in [
2885            ("2:1.0-1", "1:9.9-9", Greater),
2886            ("1.0-1", "0:1.0-1", Equal),
2887            ("1.1-1", "1.0-9", Greater),
2888            ("1.0-2", "1.0-10", Less),
2889            ("1.0-1.el8", "1.0-1.el9", Less),
2890            ("1.0-0", "1.0-1", Less),
2891            // an absent release sorts below every release, including `0`
2892            ("1.0", "1.0-0", Less),
2893        ] {
2894            assert_eq!(
2895                compare_versions_for_ecosystem(Some("rpm"), a, b),
2896                Some(expected),
2897                "{a} vs {b}"
2898            );
2899            assert_eq!(
2900                compare_versions_for_ecosystem(Some("rpm"), b, a),
2901                Some(expected.reverse()),
2902                "{b} vs {a}"
2903            );
2904        }
2905    }
2906
2907    /// the pairs rpm and dpkg return different verdicts for. every `deb`
2908    /// expectation was checked against `dpkg --compare-versions`.
2909    #[test]
2910    fn rpm_and_deb_disagree_on_ordinary_versions() {
2911        use Ordering::{Equal, Greater, Less};
2912
2913        for (a, b, deb, rpm) in [
2914            // an alpha run against a digit run: dpkg ranks the letter above the
2915            // digit, rpm below it
2916            ("1.a", "1.1", Some(Greater), Some(Less)),
2917            ("1.fc35", "1.1", Some(Greater), Some(Less)),
2918            // `_` is a plain separator in rpm and outside the Debian alphabet
2919            ("1.0", "1_0", None, Some(Equal)),
2920            // `^` marks a post-release snapshot, which sorts above the base
2921            ("1.0^20200101gitabc", "1.0", None, Some(Greater)),
2922            // a stock RHEL release string, unreadable under the Debian alphabet
2923            ("4.4.2-2.el7_9", "4.4.2-3.el7_9", None, Some(Less)),
2924        ] {
2925            assert_eq!(
2926                compare_versions_for_ecosystem(Some("deb"), a, b),
2927                deb,
2928                "deb: {a} vs {b}"
2929            );
2930            assert_eq!(
2931                compare_versions_for_ecosystem(Some("rpm"), a, b),
2932                rpm,
2933                "rpm: {a} vs {b}"
2934            );
2935        }
2936    }
2937
2938    #[test]
2939    fn rpm_ecosystem_reverses_a_gate_the_deb_rules_fire_backwards() {
2940        assert!(is_version_downgrade_for_ecosystem(
2941            Some("deb"),
2942            "1.a",
2943            "1.1"
2944        ));
2945        assert!(!is_version_downgrade_for_ecosystem(
2946            Some("rpm"),
2947            "1.a",
2948            "1.1"
2949        ));
2950        assert!(is_version_downgrade_for_ecosystem(
2951            Some("rpm"),
2952            "1.1",
2953            "1.a"
2954        ));
2955    }
2956
2957    #[test]
2958    fn rpm_ecosystem_parses_as_rpm() {
2959        assert_eq!(
2960            Version::parse_for_ecosystem(Some("rpm"), "5.1.8-2.fc35"),
2961            Version::Rpm {
2962                epoch: 0,
2963                version: "5.1.8".into(),
2964                release: "2.fc35".into(),
2965            }
2966        );
2967        assert_eq!(
2968            Version::parse_for_ecosystem(Some("rpm"), "1:2.36.1-2.fc35"),
2969            Version::Rpm {
2970                epoch: 1,
2971                version: "2.36.1".into(),
2972                release: "2.fc35".into(),
2973            }
2974        );
2975        assert_eq!(
2976            Version::parse_for_ecosystem(Some("rpm"), "4.4.2-2.el7_9"),
2977            Version::Rpm {
2978                epoch: 0,
2979                version: "4.4.2".into(),
2980                release: "2.el7_9".into(),
2981            }
2982        );
2983        assert!(matches!(
2984            Version::parse_for_ecosystem(Some("rpm"), "1.2.3"),
2985            Version::Rpm { .. }
2986        ));
2987        assert!(matches!(
2988            Version::parse_for_ecosystem(Some("rpm"), "1.0.0-alpha.1"),
2989            Version::Rpm { .. }
2990        ));
2991    }
2992
2993    #[test]
2994    fn rpm_ecosystem_keeps_codenames_and_hashes_opaque() {
2995        for s in ["deadbeef", "focal", "", "stable", "1.0 "] {
2996            assert_eq!(
2997                Version::parse_for_ecosystem(Some("rpm"), s),
2998                Version::Opaque(s.to_string()),
2999                "{s}"
3000            );
3001        }
3002    }
3003
3004    #[test]
3005    fn rpm_ecosystem_strips_a_v_prefix_instead_of_skipping_the_pair() {
3006        assert!(matches!(
3007            Version::parse_for_ecosystem(Some("rpm"), "v1.2.3-1"),
3008            Version::Rpm { .. }
3009        ));
3010        assert_eq!(
3011            compare_versions_for_ecosystem(Some("rpm"), "v1.2.3", "v1.2.4"),
3012            Some(Ordering::Less)
3013        );
3014    }
3015
3016    #[test]
3017    fn parse_lenient_never_produces_an_ecosystem_only_variant() {
3018        for s in ECOSYSTEM_CORPUS.iter().copied().chain([
3019            // rpm
3020            "1.0^20200101",
3021            "1_0",
3022            "1.a",
3023            "5.1.8-2.fc35",
3024            // nuget
3025            "1.0.0-alpha",
3026            "1.2.3.4",
3027            "1.0.0+sha",
3028            "1.0.0.1-rc.1",
3029            // apk
3030            "1.2.3-r4",
3031            "1.0_alpha1",
3032            "1.0~abcdef",
3033            "1.2.3a-r1",
3034            // maven
3035            "1.0-SNAPSHOT",
3036            "2.0.0.Final",
3037            "1.7.0_80",
3038            "1-sp",
3039        ]) {
3040            assert!(
3041                !matches!(
3042                    Version::parse_lenient(s),
3043                    Version::Rpm { .. }
3044                        | Version::Nuget { .. }
3045                        | Version::Apk(_)
3046                        | Version::Maven(_)
3047                ),
3048                "{s}"
3049            );
3050        }
3051    }
3052
3053    /// Maven's documented "End Result Examples", one case per row.
3054    /// `expected` is how `a` orders relative to `b`.
3055    #[test]
3056    fn maven_documented_ordering_examples() {
3057        use Ordering::{Equal, Greater, Less};
3058
3059        for (a, b, expected) in [
3060            ("1", "1.1", Less),
3061            ("1-snapshot", "1", Less),
3062            ("1", "1-sp", Less),
3063            ("1-foo2", "1-foo10", Less),
3064            ("1.foo", "1-foo", Equal),
3065            ("1-foo", "1-1", Less),
3066            ("1-1", "1.1", Less),
3067            ("1.ga", "1-ga", Equal),
3068            ("1-ga", "1-0", Equal),
3069            ("1-0", "1_0", Equal),
3070            ("1_0", "1.0", Equal),
3071            ("1.0", "1", Equal),
3072            ("1-sp", "1-ga", Greater),
3073            ("1-sp.1", "1-ga.1", Greater),
3074            ("1-sp-1", "1-ga-1", Less),
3075            ("1-a1", "1-alpha-1", Equal),
3076            ("1.0-alpha1", "1.0-ALPHA1", Equal),
3077            ("1.7", "1.K", Greater),
3078            ("5.zebra", "5.aardvark", Greater),
3079            ("1.α", "1.b", Greater),
3080        ] {
3081            assert_eq!(maven_cmp(a, b), expected, "{a} vs {b}");
3082            assert_eq!(maven_cmp(b, a), expected.reverse(), "{b} vs {a}");
3083        }
3084    }
3085
3086    /// Maven's documented splitting and trimming examples: each row is a
3087    /// version and the spelling it reduces to.
3088    #[test]
3089    fn maven_documented_splitting_and_trimming_examples() {
3090        for (version, reduced) in [
3091            ("1-1.foo-bar1baz-.1", "1-1.foo-bar-1-baz-0.1"),
3092            ("1.0.0", "1"),
3093            ("1.ga", "1"),
3094            ("1.final", "1"),
3095            ("1.0", "1"),
3096            ("1.", "1"),
3097            ("1-", "1"),
3098            ("1_", "1"),
3099            ("1.0.0-foo.0.0", "1-foo"),
3100            ("1.0.0-0.0.0", "1"),
3101        ] {
3102            assert_eq!(maven_parse(version), maven_parse(reduced), "{version}");
3103        }
3104    }
3105
3106    #[test]
3107    fn maven_ranks_qualifiers_in_the_documented_order() {
3108        let ascending = [
3109            "1-alpha",
3110            "1-beta",
3111            "1-milestone",
3112            "1-rc",
3113            "1-snapshot",
3114            "1",
3115            "1-sp",
3116        ];
3117
3118        for (i, a) in ascending.iter().enumerate() {
3119            for b in &ascending[i + 1..] {
3120                assert_eq!(maven_cmp(a, b), Ordering::Less, "{a} vs {b}");
3121                assert_eq!(maven_cmp(b, a), Ordering::Greater, "{b} vs {a}");
3122            }
3123            // an unrecognized qualifier outranks every named one
3124            assert_eq!(maven_cmp(a, "1-zzz"), Ordering::Less, "{a} vs 1-zzz");
3125        }
3126        assert_eq!(maven_cmp("1-zzz", "1-aaa"), Ordering::Greater);
3127    }
3128
3129    #[test]
3130    fn maven_folds_qualifier_aliases() {
3131        for (a, b) in [
3132            ("1-cr", "1-rc"),
3133            ("1-cr1", "1-rc1"),
3134            ("1-ga", "1"),
3135            ("1-final", "1"),
3136            ("1-release", "1"),
3137            ("1-a1", "1-alpha1"),
3138            ("1-b2", "1-beta2"),
3139            ("1-m3", "1-milestone3"),
3140            ("1-RC1", "1-rc1"),
3141        ] {
3142            assert_eq!(maven_cmp(a, b), Ordering::Equal, "{a} vs {b}");
3143        }
3144
3145        // the one-letter shorthands expand only directly before a digit
3146        assert_eq!(maven_cmp("1-a", "1-alpha"), Ordering::Greater);
3147        assert_eq!(maven_cmp("1-a.1", "1-alpha.1"), Ordering::Greater);
3148    }
3149
3150    #[test]
3151    fn maven_folds_a_dotted_qualifier_to_the_hyphenated_form() {
3152        for (a, b) in [
3153            ("1.0.0.CR1", "1.0.0-RC1"),
3154            ("1.0.0.Final", "1.0.0"),
3155            ("1.0.0.GA", "1.0.0-ga"),
3156            ("2.0.0.Final", "2.0.0-Final"),
3157            ("1.0.0.Alpha1", "1.0.0-a1"),
3158            ("3.1.0.RELEASE", "3.1.0"),
3159        ] {
3160            assert_eq!(maven_cmp(a, b), Ordering::Equal, "{a} vs {b}");
3161        }
3162
3163        for (a, b) in [
3164            ("1.0.0.CR1", "1.0.0-CR2"),
3165            ("1.0.0.Alpha1", "1.0.0-RC1"),
3166            ("1.0.0.CR1", "1.0.0"),
3167            ("2.0.a", "2-1"),
3168            ("3.1.0.M1", "3.1.0-RC1"),
3169            ("1.0.0.Beta1", "1.0.0.CR1"),
3170        ] {
3171            assert_eq!(maven_cmp(a, b), Ordering::Less, "{a} vs {b}");
3172            assert_eq!(maven_cmp(b, a), Ordering::Greater, "{b} vs {a}");
3173        }
3174    }
3175
3176    /// JBoss, Spring, Hibernate and Netty, each rung also placed against the
3177    /// hyphenated spelling of its neighbours.
3178    #[test]
3179    fn maven_orders_the_published_dotted_ladders() {
3180        for ladder in [
3181            &[
3182                "1.0.0.Alpha1",
3183                "1.0.0-Beta1",
3184                "1.0.0.CR1",
3185                "1.0.0-CR2",
3186                "1.0.0.Final",
3187            ][..],
3188            &[
3189                "3.1.0.M1",
3190                "3.1.0-M2",
3191                "3.1.0.RC1",
3192                "3.1.0-RELEASE",
3193                "3.1.1.RELEASE",
3194            ][..],
3195            &["5.4.2.Final", "5.4.10.Final", "5.5.0.Alpha1", "5.5.0.Final"][..],
3196            &["4.1.9.Final", "4.1.65.Final", "4.1.65.1.Final"][..],
3197        ] {
3198            for (i, a) in ladder.iter().enumerate() {
3199                for b in &ladder[i + 1..] {
3200                    assert_eq!(maven_cmp(a, b), Ordering::Less, "{a} vs {b}");
3201                    assert_eq!(maven_cmp(b, a), Ordering::Greater, "{b} vs {a}");
3202                }
3203            }
3204        }
3205    }
3206
3207    #[test]
3208    fn maven_nests_a_qualifier_reached_past_an_item() {
3209        assert_eq!(maven_cmp("1-0.alpha", "1-alpha"), Ordering::Greater);
3210        assert_eq!(maven_cmp("1-0.beta", "1-0.alpha"), Ordering::Greater);
3211        assert_eq!(maven_cmp("1-0.alpha", "1-1"), Ordering::Less);
3212        assert_eq!(maven_cmp("1-0.alpha", "1"), Ordering::Less);
3213    }
3214
3215    #[test]
3216    fn maven_declines_a_version_nested_past_the_depth_cap() {
3217        let ok = format!("1{}", "-1".repeat(MAVEN_MAX_DEPTH - 2));
3218        let deep = format!("1{}", "-1".repeat(MAVEN_MAX_DEPTH));
3219
3220        assert!(super::maven_parse(&ok).is_some());
3221        assert!(super::maven_parse(&deep).is_none());
3222        assert_eq!(
3223            Version::parse_for_ecosystem(Some("maven"), &ok),
3224            Version::Maven(ok)
3225        );
3226        assert_eq!(
3227            Version::parse_for_ecosystem(Some("maven"), &deep),
3228            Version::Opaque(deep)
3229        );
3230    }
3231
3232    #[test]
3233    fn maven_declines_a_version_that_would_overflow_the_stack() {
3234        for deep in [format!("1{}", "-1".repeat(200_000)), "1a".repeat(200_000)] {
3235            assert_eq!(
3236                Version::parse_for_ecosystem(Some("maven"), &deep),
3237                Version::Opaque(deep.clone())
3238            );
3239            assert_eq!(
3240                Version::Maven(deep.clone()).partial_cmp_lenient(&Version::Maven(deep)),
3241                None
3242            );
3243        }
3244    }
3245
3246    #[test]
3247    fn maven_ordering_is_antisymmetric_and_transitive_on_the_documented_vectors() {
3248        const CORPUS: &[&str] = &[
3249            "1",
3250            "1.0",
3251            "1.1",
3252            "1-1",
3253            "1.foo",
3254            "1-foo",
3255            "1.bar",
3256            "1-bar",
3257            "1-alpha",
3258            "1-a1",
3259            "1-beta",
3260            "1-milestone",
3261            "1-rc",
3262            "1-cr",
3263            "1-snapshot",
3264            "1-ga",
3265            "1-sp",
3266            "1-sp.1",
3267            "1-sp-1",
3268            "1-ga-1",
3269            "1.0.0-foo.0.0",
3270            "1_0",
3271            "2",
3272            "1.0.1",
3273            "1.0-alpha1",
3274        ];
3275
3276        for a in CORPUS {
3277            for b in CORPUS {
3278                assert_eq!(
3279                    maven_cmp(a, b),
3280                    maven_cmp(b, a).reverse(),
3281                    "asymmetric: {a} vs {b}"
3282                );
3283                for c in CORPUS {
3284                    let (ab, bc) = (maven_cmp(a, b), maven_cmp(b, c));
3285                    if ab == bc || bc == Ordering::Equal {
3286                        assert_eq!(maven_cmp(a, c), ab, "intransitive: {a}, {b}, {c}");
3287                    }
3288                }
3289            }
3290        }
3291    }
3292
3293    #[test]
3294    fn maven_compares_numeric_tokens_beyond_u64() {
3295        assert_eq!(
3296            maven_cmp("1.99999999999999999999999", "1.99999999999999999999998"),
3297            Ordering::Greater
3298        );
3299        assert_eq!(maven_cmp("1.0000000000000000000001", "1.2"), Ordering::Less);
3300    }
3301
3302    /// the case the string-only path cannot order at all: `1.0-SNAPSHOT` reads
3303    /// as Debian and `1.0` as semver, and a mixed pair is `None`.
3304    #[test]
3305    fn maven_ecosystem_orders_a_snapshot_against_its_release() {
3306        assert_eq!(compare_versions("1.0-SNAPSHOT", "1.0"), None);
3307
3308        assert_eq!(
3309            compare_versions_for_ecosystem(Some("maven"), "1.0-SNAPSHOT", "1.0"),
3310            Some(Ordering::Less)
3311        );
3312        assert!(!is_version_downgrade_for_ecosystem(
3313            Some("maven"),
3314            "1.0-SNAPSHOT",
3315            "1.0"
3316        ));
3317        assert!(is_version_downgrade_for_ecosystem(
3318            Some("maven"),
3319            "1.0",
3320            "1.0-SNAPSHOT"
3321        ));
3322    }
3323
3324    #[test]
3325    fn maven_ecosystem_makes_previously_uncomparable_pairs_comparable() {
3326        use Ordering::{Equal, Greater, Less};
3327
3328        for (a, b, expected) in [
3329            ("1.0-SNAPSHOT", "1.0", Less),
3330            ("1.0-M1", "1.0", Less),
3331            ("1.0-sp1", "1.0", Greater),
3332            // a JBoss-style `.Final` release is the release itself
3333            ("2.0.0.Final", "2.0.0", Equal),
3334            ("1.0-cr1", "1.0-rc1", Equal),
3335            // `_` is outside the Debian alphabet, so a JDK version is opaque
3336            ("1.7.0_80", "1.7.0_79", Greater),
3337        ] {
3338            assert_eq!(compare_versions(a, b), None, "{a} vs {b}");
3339            assert_eq!(
3340                compare_versions_for_ecosystem(Some("maven"), a, b),
3341                Some(expected),
3342                "{a} vs {b}"
3343            );
3344            assert_eq!(
3345                compare_versions_for_ecosystem(Some("maven"), b, a),
3346                Some(expected.reverse()),
3347                "{b} vs {a}"
3348            );
3349        }
3350    }
3351
3352    #[test]
3353    fn maven_ecosystem_reverses_a_gate_the_string_only_path_fires_backwards() {
3354        // read as Debian revisions, `Final` sorts below `SNAPSHOT`; Maven ranks
3355        // the release above every snapshot
3356        assert_eq!(
3357            compare_versions("1.0-Final", "1.0-SNAPSHOT"),
3358            Some(Ordering::Less)
3359        );
3360        assert!(is_version_downgrade("1.0-SNAPSHOT", "1.0-Final"));
3361        assert!(!is_version_downgrade("1.0-Final", "1.0-SNAPSHOT"));
3362
3363        assert_eq!(
3364            compare_versions_for_ecosystem(Some("maven"), "1.0-Final", "1.0-SNAPSHOT"),
3365            Some(Ordering::Greater)
3366        );
3367        assert!(!is_version_downgrade_for_ecosystem(
3368            Some("maven"),
3369            "1.0-SNAPSHOT",
3370            "1.0-Final"
3371        ));
3372        assert!(is_version_downgrade_for_ecosystem(
3373            Some("maven"),
3374            "1.0-Final",
3375            "1.0-SNAPSHOT"
3376        ));
3377    }
3378
3379    #[test]
3380    fn maven_ecosystem_parses_as_maven() {
3381        assert_eq!(
3382            Version::parse_for_ecosystem(Some("maven"), "1.0-SNAPSHOT"),
3383            Version::Maven("1.0-SNAPSHOT".into())
3384        );
3385        for s in [
3386            "1.2.3",
3387            "1.0.0-alpha.1",
3388            "2.0.0.Final",
3389            "1.7.0_80",
3390            "1.0+b1",
3391        ] {
3392            assert!(
3393                matches!(
3394                    Version::parse_for_ecosystem(Some("maven"), s),
3395                    Version::Maven(_)
3396                ),
3397                "{s}"
3398            );
3399        }
3400    }
3401
3402    #[test]
3403    fn maven_ecosystem_keeps_codenames_and_hashes_opaque() {
3404        for s in [
3405            "deadbeef",
3406            "RELEASE",
3407            "LATEST",
3408            "",
3409            "master-SNAPSHOT",
3410            "1.0 ",
3411        ] {
3412            assert_eq!(
3413                Version::parse_for_ecosystem(Some("maven"), s),
3414                Version::Opaque(s.to_string()),
3415                "{s}"
3416            );
3417        }
3418    }
3419
3420    #[test]
3421    fn maven_ecosystem_strips_a_v_prefix_instead_of_skipping_the_pair() {
3422        assert!(matches!(
3423            Version::parse_for_ecosystem(Some("maven"), "v1.2.3"),
3424            Version::Maven(_)
3425        ));
3426        assert_eq!(
3427            compare_versions_for_ecosystem(Some("maven"), "v1.2.3", "v1.2.4"),
3428            Some(Ordering::Less)
3429        );
3430    }
3431
3432    fn nuget_cmp(a: &str, b: &str) -> Ordering {
3433        compare_versions_for_ecosystem(Some("nuget"), a, b)
3434            .unwrap_or_else(|| panic!("{a} vs {b} is not a NuGet version"))
3435    }
3436
3437    /// asserts the strings are in strictly ascending NuGet order, every pair.
3438    fn assert_nuget_ascending(versions: &[&str]) {
3439        for (i, a) in versions.iter().enumerate() {
3440            for b in &versions[i + 1..] {
3441                assert_eq!(nuget_cmp(a, b), Ordering::Less, "{a} vs {b}");
3442                assert_eq!(nuget_cmp(b, a), Ordering::Greater, "{b} vs {a}");
3443                assert!(
3444                    is_version_downgrade_for_ecosystem(Some("nuget"), b, a),
3445                    "expected {b} -> {a} downgrade"
3446                );
3447                assert!(
3448                    !is_version_downgrade_for_ecosystem(Some("nuget"), a, b),
3449                    "expected {a} -> {b} upgrade"
3450                );
3451            }
3452        }
3453    }
3454
3455    /// every pair derived from NuGet.Versioning's documented rules.
3456    #[test]
3457    fn nuget_documented_ordering_examples() {
3458        use Ordering::{Equal, Greater, Less};
3459
3460        for (a, b, expected) in [
3461            ("1", "1.0.0.0", Equal),
3462            ("1.0", "1.0.0.0", Equal),
3463            ("1.0.0", "1.0.0.0", Equal),
3464            ("1.01", "1.1", Equal),
3465            ("1.0.0.010", "1.0.0.10", Equal),
3466            ("1.0.0.1", "1.0.0", Greater),
3467            ("1.0.0.9", "1.0.1", Less),
3468            ("1.0.0-alpha", "1.0.0", Less),
3469            ("1.0.0.1-alpha", "1.0.0.1", Less),
3470            ("2.0.0.0", "2.0.0-rc", Greater),
3471            ("1.0.0-alpha", "1.0.0-BETA", Less),
3472            ("1.0.0-Alpha", "1.0.0-alpha", Equal),
3473            ("1.0.0-1", "1.0.0-alpha", Less),
3474            ("1.0.0-01", "1.0.0-1", Equal),
3475            ("1.0.0-2", "1.0.0-10", Less),
3476            ("1.0.0-alpha", "1.0.0-alpha.1", Less),
3477            ("1.0.0-alpha", "1.0.0-Alpha.1", Less),
3478            ("1.0.0-rc.1+build", "1.0.0-rc.2", Less),
3479            // an empty label list is not a pre-release
3480            ("1.0.0-", "1.0.0", Equal),
3481            // a digit run past NuGet's `int.TryParse` is an ordinary string
3482            ("1.0.0-99999999999", "1.0.0-alpha", Less),
3483        ] {
3484            assert_eq!(nuget_cmp(a, b), expected, "{a} vs {b}");
3485            assert_eq!(nuget_cmp(b, a), expected.reverse(), "{b} vs {a}");
3486        }
3487    }
3488
3489    #[test]
3490    fn nuget_ignores_build_metadata_for_ordering_and_equality() {
3491        for (a, b) in [
3492            ("1.0.0+sha1", "1.0.0+sha2"),
3493            ("1.0.0+a", "1.0.0"),
3494            ("1.0.0-rc+a", "1.0.0-rc+b"),
3495            ("1.0.0+meta-with-dashes", "1.0.0+0.1"),
3496        ] {
3497            assert_eq!(nuget_cmp(a, b), Ordering::Equal, "{a} vs {b}");
3498            assert_eq!(
3499                Version::parse_for_ecosystem(Some("nuget"), a),
3500                Version::parse_for_ecosystem(Some("nuget"), b),
3501                "{a} vs {b}"
3502            );
3503        }
3504    }
3505
3506    #[test]
3507    fn nuget_orders_the_dotnet_release_ladder() {
3508        assert_nuget_ascending(&[
3509            "6.0.0-alpha.1",
3510            "6.0.0-Beta.1",
3511            "6.0.0-preview.7.21377.19",
3512            "6.0.0-RC.1.21451.13",
3513            "6.0.0-rc.2.21480.5",
3514            "6.0.0",
3515            "6.0.0.1",
3516            "6.0.1-preview.1",
3517            "6.0.1",
3518            "6.1.0",
3519        ]);
3520        assert_nuget_ascending(&["1.0.0-1", "1.0.0-2", "1.0.0-10", "1.0.0-a", "1.0.0-a.1"]);
3521        assert_nuget_ascending(&["13.0.1", "13.0.3", "13.0.10", "13.1.0"]);
3522    }
3523
3524    #[test]
3525    fn nuget_ordering_is_antisymmetric_and_transitive() {
3526        const CORPUS: &[&str] = &[
3527            "1",
3528            "1.0",
3529            "1.0.0",
3530            "1.0.0.0",
3531            "1.0.0.1",
3532            "1.0.1",
3533            "1.1",
3534            "2",
3535            "1.0.0-alpha",
3536            "1.0.0-ALPHA",
3537            "1.0.0-alpha.1",
3538            "1.0.0-alpha.beta",
3539            "1.0.0-beta",
3540            "1.0.0-rc",
3541            "1.0.0-1",
3542            "1.0.0-01",
3543            "1.0.0-2",
3544            "1.0.0-10",
3545            "1.0.0+meta",
3546            "1.0.0-rc+meta",
3547            "1.0.0.1-rc",
3548        ];
3549
3550        for a in CORPUS {
3551            for b in CORPUS {
3552                assert_eq!(
3553                    nuget_cmp(a, b),
3554                    nuget_cmp(b, a).reverse(),
3555                    "asymmetric: {a} vs {b}"
3556                );
3557                for c in CORPUS {
3558                    let (ab, bc) = (nuget_cmp(a, b), nuget_cmp(b, c));
3559                    if ab == bc || bc == Ordering::Equal {
3560                        assert_eq!(nuget_cmp(a, c), ab, "intransitive: {a}, {b}, {c}");
3561                    }
3562                }
3563            }
3564        }
3565    }
3566
3567    /// a leading zero in a release label is not a semver identifier, so the
3568    /// string-only path reads the version as Debian and every pair is mixed.
3569    #[test]
3570    fn nuget_ecosystem_makes_previously_uncomparable_pairs_comparable() {
3571        use Ordering::{Equal, Less};
3572
3573        for (a, b, expected) in [
3574            ("1.0.0-01", "1.0.0-1", Equal),
3575            ("1.0.0-01", "1.0.0-alpha", Less),
3576            ("1.0.0-01", "1.0.0", Less),
3577            ("1.0.0-01", "1.0.0.1", Less),
3578            ("1.0.0-01", "1.0.0-rc.1", Less),
3579        ] {
3580            assert_eq!(compare_versions(a, b), None, "{a} vs {b}");
3581            assert_eq!(nuget_cmp(a, b), expected, "{a} vs {b}");
3582            assert_eq!(nuget_cmp(b, a), expected.reverse(), "{b} vs {a}");
3583        }
3584    }
3585
3586    /// semver orders release labels case-sensitively, so an upper-case label
3587    /// sorts below every lower-case one.
3588    #[test]
3589    fn nuget_ecosystem_reverses_gates_the_string_only_path_fires_backwards() {
3590        use Ordering::{Equal, Greater, Less};
3591
3592        for (a, b, inferred, nuget) in [
3593            ("1.0.0-alpha", "1.0.0-BETA", Greater, Less),
3594            ("3.0.0-beta", "3.0.0-RC", Greater, Less),
3595            ("5.0.0-preview.1", "5.0.0-RC.1", Greater, Less),
3596            ("1.0.0-Alpha", "1.0.0-alpha", Less, Equal),
3597            ("1.0.0-alpha", "1.0.0-Alpha.1", Greater, Less),
3598        ] {
3599            assert_eq!(compare_versions(a, b), Some(inferred), "{a} vs {b}");
3600            assert_eq!(nuget_cmp(a, b), nuget, "{a} vs {b}");
3601        }
3602
3603        assert!(is_version_downgrade("3.0.0-beta", "3.0.0-RC"));
3604        assert!(!is_version_downgrade_for_ecosystem(
3605            Some("nuget"),
3606            "3.0.0-beta",
3607            "3.0.0-RC"
3608        ));
3609        assert!(is_version_downgrade_for_ecosystem(
3610            Some("nuget"),
3611            "3.0.0-RC",
3612            "3.0.0-beta"
3613        ));
3614    }
3615
3616    #[test]
3617    fn nuget_ecosystem_parses_as_nuget() {
3618        assert_eq!(
3619            Version::parse_for_ecosystem(Some("nuget"), "1.2.3.4-rc.1+sha"),
3620            Version::Nuget {
3621                version: [1, 2, 3, 4],
3622                release: vec!["rc".into(), "1".into()],
3623            }
3624        );
3625        for s in ["1", "1.2", "1.2.3", "1.2.3.4", "1.0.0-alpha.1", "1.0.0+b1"] {
3626            assert!(
3627                matches!(
3628                    Version::parse_for_ecosystem(Some("nuget"), s),
3629                    Version::Nuget { .. }
3630                ),
3631                "{s}"
3632            );
3633        }
3634    }
3635
3636    #[test]
3637    fn nuget_ecosystem_keeps_codenames_and_hashes_opaque() {
3638        for s in [
3639            "deadbeef",
3640            "",
3641            "latest",
3642            "1.0.0.0.0",
3643            "1.0.0.99999999999999999999",
3644            "1.0.0+",
3645            "1.0.0+α",
3646            "1.0.0-α",
3647            "1.0.0-a..b",
3648            "1.0.0 ",
3649            "1.0.0~rc1",
3650            "2:1.0-3",
3651        ] {
3652            assert_eq!(
3653                Version::parse_for_ecosystem(Some("nuget"), s),
3654                Version::Opaque(s.to_string()),
3655                "{s}"
3656            );
3657        }
3658    }
3659
3660    #[test]
3661    fn nuget_ecosystem_strips_a_v_prefix_instead_of_skipping_the_pair() {
3662        assert!(matches!(
3663            Version::parse_for_ecosystem(Some("nuget"), "v1.2.3"),
3664            Version::Nuget { .. }
3665        ));
3666        assert_eq!(
3667            compare_versions_for_ecosystem(Some("nuget"), "v1.2.3", "v1.2.4"),
3668            Some(Ordering::Less)
3669        );
3670    }
3671
3672    #[test]
3673    fn pypi_ecosystem_orders_a_bare_letter_pre_release_below_its_release() {
3674        assert_eq!(compare_versions("1.0.2a", "1.0.2"), None);
3675
3676        assert_eq!(
3677            compare_versions_for_ecosystem(Some("pypi"), "1.0.2a", "1.0.2"),
3678            Some(Ordering::Less)
3679        );
3680        assert!(!is_version_downgrade_for_ecosystem(
3681            Some("pypi"),
3682            "1.0.2a",
3683            "1.0.2"
3684        ));
3685        assert!(is_version_downgrade_for_ecosystem(
3686            Some("pypi"),
3687            "1.0.2",
3688            "1.0.2a"
3689        ));
3690    }
3691
3692    #[test]
3693    fn pypi_ecosystem_makes_previously_uncomparable_pairs_comparable() {
3694        use Ordering::{Equal, Greater, Less};
3695
3696        for (a, b, expected) in [
3697            ("1.0.2a", "1.0.2", Less),
3698            ("1.0.2c", "1.0.2rc0", Equal),
3699            ("1.0.2r", "1.0.2", Greater),
3700            ("1.0-1", "1.0", Greater),
3701            ("1.0-1", "1.0.post1", Equal),
3702            ("1.0+abc", "1.0", Greater),
3703            ("1.0+abc", "1.0.1", Less),
3704            ("2024a", "2024", Less),
3705            ("1.0.2a", "1!0.1", Less),
3706        ] {
3707            assert_eq!(compare_versions(a, b), None, "{a} vs {b}");
3708            assert_eq!(
3709                compare_versions_for_ecosystem(Some("pypi"), a, b),
3710                Some(expected),
3711                "{a} vs {b}"
3712            );
3713            assert_eq!(
3714                compare_versions_for_ecosystem(Some("pypi"), b, a),
3715                Some(expected.reverse()),
3716                "{b} vs {a}"
3717            );
3718        }
3719    }
3720
3721    #[test]
3722    fn pypi_ecosystem_reverses_a_gate_the_string_only_path_fires_backwards() {
3723        // read as Debian upstream versions, a letter sorts below `+`; PEP 440
3724        // ranks a local label below the post release
3725        assert_eq!(compare_versions("1.0+0", "1.0r"), Some(Ordering::Greater));
3726        assert!(is_version_downgrade("1.0+0", "1.0r"));
3727        assert!(!is_version_downgrade("1.0r", "1.0+0"));
3728
3729        assert_eq!(
3730            compare_versions_for_ecosystem(Some("pypi"), "1.0+0", "1.0r"),
3731            Some(Ordering::Less)
3732        );
3733        assert!(!is_version_downgrade_for_ecosystem(
3734            Some("pypi"),
3735            "1.0+0",
3736            "1.0r"
3737        ));
3738        assert!(is_version_downgrade_for_ecosystem(
3739            Some("pypi"),
3740            "1.0r",
3741            "1.0+0"
3742        ));
3743    }
3744
3745    /// PEP 440 §"Summary of permitted suffixes and relative ordering", one
3746    /// strictly ascending ladder.
3747    #[test]
3748    fn pypi_ecosystem_orders_the_documented_ladder() {
3749        let ladder = [
3750            "1.0.dev456",
3751            "1.0a1",
3752            "1.0a2.dev456",
3753            "1.0a12.dev456",
3754            "1.0a12",
3755            "1.0b1.dev456",
3756            "1.0b2",
3757            "1.0b2.post345.dev456",
3758            "1.0b2.post345",
3759            "1.0rc1.dev456",
3760            "1.0rc1",
3761            "1.0",
3762            "1.0+abc.5",
3763            "1.0+abc.7",
3764            "1.0+5",
3765            "1.0.post456.dev34",
3766            "1.0.post456",
3767            "1.0.15",
3768            "1.1.dev1",
3769            "1.1",
3770            "2!0.5",
3771        ];
3772        for (i, a) in ladder.iter().enumerate() {
3773            for (j, b) in ladder.iter().enumerate() {
3774                assert_eq!(
3775                    compare_versions_for_ecosystem(Some("pypi"), a, b),
3776                    Some(i.cmp(&j)),
3777                    "{a} vs {b}"
3778                );
3779            }
3780        }
3781    }
3782
3783    #[test]
3784    fn pypi_ecosystem_folds_spelling_aliases_and_separators() {
3785        for (a, b) in [
3786            ("1.0alpha1", "1.0a1"),
3787            ("1.0-alpha-1", "1.0a1"),
3788            ("1.0_ALPHA_1", "1.0a1"),
3789            ("1.0.beta.2", "1.0b2"),
3790            ("1.0pre1", "1.0rc1"),
3791            ("1.0PREVIEW1", "1.0rc1"),
3792            ("1.0c1", "1.0rc1"),
3793            ("1.0a", "1.0a0"),
3794            ("1.0.rev2", "1.0.post2"),
3795            ("1.0-r2", "1.0.post2"),
3796            ("1.0-2", "1.0.post2"),
3797            ("1.0.dev", "1.0.dev0"),
3798            ("V1.0", "1.0"),
3799        ] {
3800            assert_eq!(
3801                Version::parse_for_ecosystem(Some("pypi"), a),
3802                Version::parse_for_ecosystem(Some("pypi"), b),
3803                "{a} vs {b}"
3804            );
3805        }
3806    }
3807
3808    #[test]
3809    fn pypi_ecosystem_parses_as_pep440() {
3810        for s in [
3811            "1",
3812            "1.0",
3813            "1.2.3",
3814            "1.2.3.4",
3815            "v1.2.3",
3816            "1.0.2a",
3817            "1!1.0",
3818            "1.0.post1",
3819            "1.0.dev1",
3820            "1.0+ubuntu1",
3821            "1.0-1",
3822        ] {
3823            assert!(
3824                matches!(
3825                    Version::parse_for_ecosystem(Some("pypi"), s),
3826                    Version::Pep440(_)
3827                ),
3828                "{s}"
3829            );
3830        }
3831    }
3832
3833    #[test]
3834    fn pypi_ecosystem_keeps_non_pep440_strings_opaque() {
3835        for s in [
3836            "deadbeef",
3837            "",
3838            "1.0 ",
3839            "1.0.1x",
3840            "1.0_1",
3841            "1.0~rc1",
3842            "2:1.0-3",
3843            "1.2.3-1ubuntu2",
3844            "4.4.2-2.el7_9",
3845            "1.0.0-foo.bar",
3846            "2024h",
3847            "1.0-1-1",
3848            "1.0.post1-1",
3849            "1.0+",
3850        ] {
3851            assert_eq!(
3852                Version::parse_for_ecosystem(Some("pypi"), s),
3853                Version::Opaque(s.to_string()),
3854                "{s}"
3855            );
3856        }
3857    }
3858
3859    #[test]
3860    fn pypi_ecosystem_strips_a_v_prefix_instead_of_skipping_the_pair() {
3861        assert!(matches!(
3862            Version::parse_for_ecosystem(Some("pypi"), "v1.2.3"),
3863            Version::Pep440(_)
3864        ));
3865        assert_eq!(
3866            compare_versions_for_ecosystem(Some("pypi"), "v1.2.3", "v1.2.4"),
3867            Some(Ordering::Less)
3868        );
3869    }
3870
3871    #[test]
3872    fn pypi_leaves_the_inferred_path_alone() {
3873        for s in ECOSYSTEM_CORPUS.iter().copied().chain([
3874            "1.0.2a",
3875            "2024h",
3876            "1.1.1a-r0",
3877            "1.0-1",
3878            "1.0+abc",
3879            "1.0r",
3880        ]) {
3881            assert_eq!(
3882                Version::parse_for_ecosystem(None, s),
3883                Version::parse_lenient(s),
3884                "{s}"
3885            );
3886        }
3887        assert!(matches!(
3888            Version::parse_lenient("1.0.2a"),
3889            Version::Deb { .. }
3890        ));
3891        assert!(matches!(
3892            Version::parse_lenient("1.0-1"),
3893            Version::Deb { .. }
3894        ));
3895    }
3896
3897    fn apk_cmp(a: &str, b: &str) -> Ordering {
3898        compare_versions_for_ecosystem(Some("apk"), a, b)
3899            .unwrap_or_else(|| panic!("{a} vs {b} is not an apk version"))
3900    }
3901
3902    /// asserts the strings are in strictly ascending apk order, every pair.
3903    fn assert_apk_ascending(versions: &[&str]) {
3904        for (i, a) in versions.iter().enumerate() {
3905            for b in &versions[i + 1..] {
3906                assert_eq!(apk_cmp(a, b), Ordering::Less, "{a} vs {b}");
3907                assert_eq!(apk_cmp(b, a), Ordering::Greater, "{b} vs {a}");
3908                assert!(
3909                    is_version_downgrade_for_ecosystem(Some("apk"), b, a),
3910                    "expected {b} -> {a} downgrade"
3911                );
3912                assert!(
3913                    !is_version_downgrade_for_ecosystem(Some("apk"), a, b),
3914                    "expected {a} -> {b} upgrade"
3915                );
3916            }
3917        }
3918    }
3919
3920    #[test]
3921    fn apk_orders_the_package_revision_above_the_version_it_rebuilds() {
3922        assert_apk_ascending(&[
3923            "1.2.3",
3924            "1.2.3-r0",
3925            "1.2.3-r1",
3926            "1.2.3-r9",
3927            "1.2.3-r10",
3928            "1.2.4-r0",
3929        ]);
3930    }
3931
3932    #[test]
3933    fn apk_ranks_the_suffix_ladder() {
3934        assert_apk_ascending(&[
3935            "1.0_alpha",
3936            "1.0_alpha1",
3937            "1.0_alpha2",
3938            "1.0_beta",
3939            "1.0_pre",
3940            "1.0_pre1",
3941            "1.0_rc",
3942            "1.0_rc2",
3943            "1.0",
3944            "1.0_cvs",
3945            "1.0_svn",
3946            "1.0_git",
3947            "1.0_hg",
3948            "1.0_p",
3949            "1.0_p1",
3950        ]);
3951        assert_apk_ascending(&["1.0_alpha1", "1.0_alpha1_git", "1.0_alpha1_git1", "1.0"]);
3952    }
3953
3954    /// every pair derived from apk-tools' own token rules.
3955    #[test]
3956    fn apk_documented_ordering_examples() {
3957        use Ordering::{Equal, Greater, Less};
3958
3959        for (a, b, expected) in [
3960            // a missing part is absent, not an implicit zero
3961            ("1.0", "1.0.0", Less),
3962            ("1.0", "1.0a", Less),
3963            ("1.0a", "1.0b", Less),
3964            // a leading zero turns the part into a string comparison
3965            ("1.07", "1.1", Less),
3966            ("1.007", "1.07", Less),
3967            ("1.0", "1.00", Less),
3968            ("1.10", "1.9", Greater),
3969            // the leading part is numeric whatever it is written like
3970            ("01.0", "1.0", Equal),
3971            // `~hash` is a post-suffix, and outranks the package revision
3972            ("1.0", "1.0~abc", Less),
3973            ("1.0~abc", "1.0~abd", Less),
3974            ("1.0-r1", "1.0~abc", Less),
3975            ("1.0~abc", "1.0~abc-r1", Less),
3976            // a suffix number is present or absent, not an implicit zero
3977            ("1.0_alpha", "1.0_alpha0", Less),
3978        ] {
3979            assert_eq!(apk_cmp(a, b), expected, "{a} vs {b}");
3980            assert_eq!(apk_cmp(b, a), expected.reverse(), "{b} vs {a}");
3981        }
3982    }
3983
3984    /// the `-rN` revision the string-only path reads as a semver pre-release.
3985    #[test]
3986    fn apk_ecosystem_reverses_gates_the_string_only_path_fires_backwards() {
3987        use Ordering::{Greater, Less};
3988
3989        for (a, b, inferred, apk) in [
3990            ("1.2.3-r4", "1.2.3", Less, Greater),
3991            ("1.2.3-r4", "1.2.3-r10", Greater, Less),
3992            ("1.2.3-r9", "1.2.3-r10", Greater, Less),
3993            ("3.1.4-r2", "3.1.4-r13", Greater, Less),
3994        ] {
3995            assert_eq!(compare_versions(a, b), Some(inferred), "{a} vs {b}");
3996            assert_eq!(apk_cmp(a, b), apk, "{a} vs {b}");
3997        }
3998
3999        // the rebuild the string-only path calls a downgrade
4000        assert!(is_version_downgrade("1.2.3-r4", "1.2.3-r10"));
4001        assert!(!is_version_downgrade_for_ecosystem(
4002            Some("apk"),
4003            "1.2.3-r4",
4004            "1.2.3-r10"
4005        ));
4006
4007        // the downgrade the string-only path waves through
4008        assert!(!is_version_downgrade("1.2.3-r10", "1.2.3-r4"));
4009        assert!(is_version_downgrade_for_ecosystem(
4010            Some("apk"),
4011            "1.2.3-r10",
4012            "1.2.3-r4"
4013        ));
4014    }
4015
4016    /// a `_suffix` version the string-only path cannot read at all.
4017    #[test]
4018    fn apk_ecosystem_makes_previously_uncomparable_pairs_comparable() {
4019        use Ordering::{Greater, Less};
4020
4021        for (a, b, expected) in [
4022            ("1.0_p1", "1.0", Greater),
4023            ("1.0_git20240101", "1.0", Greater),
4024            ("1.0_cvs", "1.0_svn", Less),
4025            ("1.0_p1", "1.0_p2", Less),
4026            ("1.0~abc", "1.0", Greater),
4027        ] {
4028            assert_eq!(compare_versions(a, b), None, "{a} vs {b}");
4029            assert_eq!(apk_cmp(a, b), expected, "{a} vs {b}");
4030            assert_eq!(apk_cmp(b, a), expected.reverse(), "{b} vs {a}");
4031        }
4032    }
4033
4034    #[test]
4035    fn apk_ecosystem_parses_as_apk() {
4036        assert_eq!(
4037            Version::parse_for_ecosystem(Some("apk"), "v1.2.3a_alpha1~abcdef-r4"),
4038            Version::Apk("1.2.3a_alpha1~abcdef-r4".to_string())
4039        );
4040        for s in ["1", "1.2.3", "1.2.3a", "1.2.3-r0", "1.0_pre2", "20240101"] {
4041            assert!(
4042                matches!(
4043                    Version::parse_for_ecosystem(Some("apk"), s),
4044                    Version::Apk(_)
4045                ),
4046                "{s}"
4047            );
4048        }
4049    }
4050
4051    /// the spellings apk's own tokenizer does not run to the end of.
4052    #[test]
4053    fn apk_ecosystem_declines_what_apk_rejects() {
4054        for s in [
4055            "",
4056            "abc",
4057            "1.0.",
4058            "1.0a1",
4059            "1.0ab",
4060            "1.0_",
4061            "1.0_foo",
4062            "1.0_p1_",
4063            "1.0~",
4064            "1.0~zz",
4065            "1.0+meta",
4066            "1.0-1",
4067            "1.0-r",
4068            "1.0-r1-r2",
4069            "1.0-r1~abc",
4070            "1.0-1ubuntu2",
4071            "-r1",
4072            "1:1.0-r0",
4073        ] {
4074            assert!(
4075                matches!(
4076                    Version::parse_for_ecosystem(Some("apk"), s),
4077                    Version::Opaque(_)
4078                ),
4079                "{s} should be opaque"
4080            );
4081        }
4082    }
4083
4084    #[test]
4085    fn apk_ordering_is_antisymmetric_and_transitive() {
4086        const CORPUS: &[&str] = &[
4087            "1",
4088            "1.0",
4089            "1.00",
4090            "01.0",
4091            "1.0.0",
4092            "1.0.1",
4093            "1.0a",
4094            "1.0b",
4095            "1.07",
4096            "1.1",
4097            "1.10",
4098            "1.9",
4099            "2",
4100            "1.0_alpha",
4101            "1.0_alpha0",
4102            "1.0_alpha1",
4103            "1.0_beta",
4104            "1.0_pre",
4105            "1.0_rc1",
4106            "1.0_cvs",
4107            "1.0_git",
4108            "1.0_p",
4109            "1.0_p1",
4110            "1.0~abc",
4111            "1.0~abd",
4112            "1.0-r0",
4113            "1.0-r1",
4114            "1.0-r10",
4115            "1.0~abc-r1",
4116            "1.0_p1-r1",
4117        ];
4118
4119        for a in CORPUS {
4120            for b in CORPUS {
4121                assert_eq!(
4122                    apk_cmp(a, b),
4123                    apk_cmp(b, a).reverse(),
4124                    "asymmetric: {a} vs {b}"
4125                );
4126                for c in CORPUS {
4127                    let (ab, bc) = (apk_cmp(a, b), apk_cmp(b, c));
4128                    if ab == bc || bc == Ordering::Equal {
4129                        assert_eq!(apk_cmp(a, c), ab, "intransitive: {a}, {b}, {c}");
4130                    }
4131                }
4132            }
4133        }
4134    }
4135    #[test]
4136    fn distinct_variants_stay_uncomparable_outside_semver_numeric_pep440() {
4137        let samples = [
4138            Version::parse_for_ecosystem(Some("deb"), "1.2.3-1"),
4139            Version::parse_for_ecosystem(Some("rpm"), "1.2.3-1"),
4140            Version::parse_for_ecosystem(Some("maven"), "1.2.3-1"),
4141            Version::parse_for_ecosystem(Some("maven"), "1.2.3"),
4142            Version::parse_for_ecosystem(Some("nuget"), "1.2.3-1"),
4143            Version::parse_for_ecosystem(Some("nuget"), "1.2.3"),
4144            Version::parse_for_ecosystem(Some("apk"), "1.2.3-r1"),
4145            Version::parse_for_ecosystem(Some("pypi"), "1.2.3"),
4146            Version::parse_lenient("1.2.3"),
4147            Version::parse_lenient("2024.01.15"),
4148            Version::parse_lenient("4.2.0rc1"),
4149            Version::parse_lenient("deadbeef"),
4150        ];
4151        // guard the samples: every variant must be present, or a sample that
4152        // stopped parsing as its variant would silently test nothing
4153        let kinds: Vec<_> = samples.iter().map(std::mem::discriminant).collect();
4154        let mut distinct = Vec::new();
4155        for k in &kinds {
4156            if !distinct.contains(k) {
4157                distinct.push(*k);
4158            }
4159        }
4160        assert_eq!(distinct.len(), 9, "{samples:?}");
4161        // only semver, numeric and pep440 order against each other
4162        let inferred = |v: &Version| {
4163            matches!(
4164                v,
4165                Version::Semver(_) | Version::Numeric(_) | Version::Pep440(_)
4166            )
4167        };
4168        for (a, ka) in samples.iter().zip(&kinds) {
4169            for (b, kb) in samples.iter().zip(&kinds) {
4170                if ka == kb || (inferred(a) && inferred(b)) {
4171                    continue;
4172                }
4173                assert_eq!(a.partial_cmp_lenient(b), None, "{a:?} vs {b:?}");
4174            }
4175        }
4176    }
4177}