Skip to main content

vivacity_core/
version.rs

1//! Subset of Composer versioning needed by the platform check: numeric
2//! versions `X[.Y[.Z[.W]]]` with an optional stability suffix (`-dev`,
3//! `-alpha.N`, `-beta.N`, `-RC.N`, `-patch.N`), compared like
4//! `composer/semver` (4-component normalisation, dev < alpha < beta < RC <
5//! stable < patch). Branches (`dev-master`, `1.x-dev`) are outside this
6//! subset: `parse` returns an error and the caller treats the package as
7//! out of scope rather than guessing.
8//!
9//! Parity is held by the differential tests against
10//! `Composer\Semver\Semver::satisfies` (tests/oracle_semver.rs).
11
12use std::cmp::Ordering;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
15pub enum Stability {
16    Dev,
17    Alpha,
18    Beta,
19    Rc,
20    Stable,
21    Patch,
22}
23
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct Version {
26    pub parts: [u64; 4],
27    pub stability: Stability,
28    /// Pre-release number (`-beta2` -> 2), 0 if absent.
29    pub pre_number: u64,
30}
31
32#[derive(Debug, thiserror::Error, PartialEq, Eq)]
33#[error("version outside the supported subset: {0:?}")]
34pub struct UnsupportedVersion(pub String);
35
36impl Version {
37    pub fn parse(input: &str) -> Result<Self, UnsupportedVersion> {
38        let s = input.trim();
39        let s = s
40            .strip_prefix('v')
41            .or_else(|| s.strip_prefix('V'))
42            .unwrap_or(s);
43        if s.is_empty() {
44            return Err(UnsupportedVersion(input.to_owned()));
45        }
46
47        // Split off the stability suffix: `1.2.3-beta2`, `1.2.3beta2`, `1.2.3-dev`.
48        let (num, suffix) = split_stability(s);
49        let (stability, pre_number) = parse_stability(suffix, input)?;
50
51        let mut parts = [0u64; 4];
52        let mut n = 0usize;
53        for piece in num.split('.') {
54            if n >= 4 || piece.is_empty() || !piece.bytes().all(|b| b.is_ascii_digit()) {
55                return Err(UnsupportedVersion(input.to_owned()));
56            }
57            parts[n] = piece
58                .parse()
59                .map_err(|_| UnsupportedVersion(input.to_owned()))?;
60            n += 1;
61        }
62        if n == 0 {
63            return Err(UnsupportedVersion(input.to_owned()));
64        }
65        Ok(Version {
66            parts,
67            stability,
68            pre_number,
69        })
70    }
71}
72
73/// Splits `1.2.3-beta2` / `1.2.3beta2` / `1.2.3_RC1` into (numeric, suffix).
74/// The numeric part and the stability suffix: `VersionParser::normalize`
75/// allows one `.`, `_` or `-` between them (`1.2.3.stable`, `2.0.0.beta1`,
76/// `1.0-b3` all count).
77fn split_stability(s: &str) -> (&str, &str) {
78    match s.find(|c: char| !(c.is_ascii_digit() || c == '.')) {
79        Some(i) => {
80            let (num, suffix) = (&s[..i], &s[i..]);
81            // Exactly one separator: `[._-]?` in the regex.
82            if let Some(n) = num.strip_suffix('.') {
83                (n, suffix)
84            } else {
85                (num, suffix.strip_prefix(['-', '_', '.']).unwrap_or(suffix))
86            }
87        }
88        // `1.2.3.` is `1.2.3.0`: the optional separator with no modifier.
89        None => (s.strip_suffix('.').unwrap_or(s), ""),
90    }
91}
92
93fn parse_stability(suffix: &str, original: &str) -> Result<(Stability, u64), UnsupportedVersion> {
94    if suffix.is_empty() {
95        return Ok((Stability::Stable, 0));
96    }
97    let lower = suffix.to_ascii_lowercase();
98    let (word, digits) = match lower.find(|c: char| c.is_ascii_digit()) {
99        Some(i) => (&lower[..i], &lower[i..]),
100        None => (lower.as_str(), ""),
101    };
102    let word = word.trim_end_matches(['-', '_', '.']);
103    let stability = match word {
104        "dev" => Stability::Dev,
105        "alpha" | "a" => Stability::Alpha,
106        "beta" | "b" => Stability::Beta,
107        "rc" => Stability::Rc,
108        "patch" | "pl" | "p" => Stability::Patch,
109        "stable" | "" => Stability::Stable,
110        _ => return Err(UnsupportedVersion(original.to_owned())),
111    };
112    let pre_number = if digits.is_empty() {
113        0
114    } else {
115        digits
116            .parse()
117            .map_err(|_| UnsupportedVersion(original.to_owned()))?
118    };
119    Ok((stability, pre_number))
120}
121
122impl PartialOrd for Version {
123    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
124        Some(self.cmp(other))
125    }
126}
127
128impl Ord for Version {
129    fn cmp(&self, other: &Self) -> Ordering {
130        self.parts
131            .cmp(&other.parts)
132            .then(self.stability.cmp(&other.stability))
133            .then(self.pre_number.cmp(&other.pre_number))
134    }
135}
136
137/// Composer's "pretty -> normalized" normalisation (VersionParser::normalize),
138/// for the subset met in locks: numeric versions (-> 4 components + canonical
139/// suffix), `dev-*` branches (unchanged) and numeric branches `N.x-dev`
140/// (x -> 9999999, padded to 4 components).
141/// Parity held by tests/oracle_normalize.rs.
142pub fn normalize_pretty(input: &str) -> Result<String, UnsupportedVersion> {
143    let s = input.trim();
144    // composer/semver 3: a `dev-` branch stays as written (`dev-master` is
145    // `dev-master`; only `normalizeDefaultBranch`, never called here, maps
146    // it to `9999999-dev`), the prefix itself lowercased (`DEV-MASTER` ->
147    // `dev-MASTER`).
148    if s.len() >= 4 && s[..4].eq_ignore_ascii_case("dev-") {
149        let rest = &s[4..];
150        if rest.is_empty() {
151            return Err(UnsupportedVersion(input.to_owned()));
152        }
153        return Ok(format!("dev-{rest}"));
154    }
155    let stripped = s
156        .strip_prefix('v')
157        .or_else(|| s.strip_prefix('V'))
158        .unwrap_or(s);
159
160    // Numeric branch `1.2.x-dev` / `1.x-dev`.
161    if let Some(stem) = stripped
162        .strip_suffix(".x-dev")
163        .or_else(|| stripped.strip_suffix(".X-dev"))
164    {
165        // The digit runs are kept as written (`2026.04.x-dev` stays
166        // `2026.04.9999999.9999999-dev`): VersionParser concatenates the
167        // matched strings, it never re-prints numbers.
168        let mut out: Vec<String> = Vec::new();
169        for piece in stem.split('.') {
170            if piece.is_empty() || !piece.bytes().all(|b| b.is_ascii_digit()) || out.len() >= 3 {
171                return Err(UnsupportedVersion(input.to_owned()));
172            }
173            out.push(piece.to_owned());
174        }
175        while out.len() < 4 {
176            out.push("9999999".to_owned());
177        }
178        return Ok(format!("{}-dev", out.join(".")));
179    }
180
181    let (num, suffix) = split_stability(stripped);
182    let (stability, _) = parse_stability(suffix, input)?;
183    // Same rule: `1.02` is `1.02.0.0`, `v01.2.3` is `01.2.3.0`.
184    let mut parts: Vec<&str> = Vec::new();
185    for piece in num.split('.') {
186        if parts.len() >= 4 || piece.is_empty() || !piece.bytes().all(|b| b.is_ascii_digit()) {
187            return Err(UnsupportedVersion(input.to_owned()));
188        }
189        parts.push(piece);
190    }
191    if parts.is_empty() {
192        return Err(UnsupportedVersion(input.to_owned()));
193    }
194    while parts.len() < 4 {
195        parts.push("0");
196    }
197    let base = parts.join(".");
198    let word = match stability {
199        Stability::Stable => return Ok(base),
200        Stability::Dev => "dev",
201        Stability::Alpha => "alpha",
202        Stability::Beta => "beta",
203        Stability::Rc => "RC",
204        Stability::Patch => "patch",
205    };
206    // Suffixes without a number stay bare (`-alpha`), else the number is
207    // appended as written (`RC01` keeps its zero).
208    let digits: String = suffix.chars().filter(char::is_ascii_digit).collect();
209    if digits.is_empty() {
210        Ok(format!("{base}-{word}"))
211    } else {
212        Ok(format!("{base}-{word}{digits}"))
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219
220    fn v(s: &str) -> Version {
221        Version::parse(s).expect(s)
222    }
223
224    #[test]
225    fn parses_and_orders() {
226        assert_eq!(v("8.5.10").parts, [8, 5, 10, 0]);
227        assert_eq!(v("v1.2").parts, [1, 2, 0, 0]);
228        assert!(v("8.1") < v("8.1.1"));
229        assert!(v("7.4.33") < v("8.0.0"));
230        assert!(v("1.0.0-dev") < v("1.0.0-alpha1"));
231        assert!(v("1.0.0-alpha2") < v("1.0.0-beta1"));
232        assert!(v("1.0.0-RC1") < v("1.0.0"));
233        assert!(v("1.0.0") < v("1.0.0-patch1"));
234        assert!(v("1.0.0-beta1") < v("1.0.0-beta2"));
235        assert_eq!(v("1.0"), v("1.0.0.0"));
236    }
237
238    #[test]
239    fn rejects_out_of_subset() {
240        for s in ["dev-master", "1.x-dev", "abc", "", "1.2.3.4.5", "1.2-foo"] {
241            assert!(Version::parse(s).is_err(), "{s} should have been rejected");
242        }
243    }
244}