Skip to main content

libtea_core/
pep440.rs

1//! Python package versions (PEP 440, the "Version specifiers" specification
2//! of the Python Packaging User Guide), parsed and ordered.
3//!
4//! **Experimental:** may change in a 0.x minor release.
5//!
6//! [`Pep440Version::parse`] accepts what the specification's "Appendix:
7//! Parsing version strings with regular expressions" accepts (the
8//! `VERSION_PATTERN` used by the `packaging` library), case-insensitively:
9//! an optional `v`, an epoch (`1!`), a release (`1.2.3`), a pre-release
10//! (`a`, `b`, `rc` and their alternative spellings), a post-release (`.post1`,
11//! `-1`), a developmental release (`.dev1`) and a local label (`+ubuntu.1`).
12//! Surrounding whitespace is **not** stripped: a version with whitespace is
13//! an error, as it is inside a `vers` range.
14//!
15//! Ordering is the specification's: trailing zeros of the release do not
16//! count (`1.0 == 1.0.0`), `1.0.dev1 < 1.0a1 < 1.0 < 1.0.post1`, and a local
17//! label sorts after the same version without one. Equality and hashing
18//! follow the ordering, so `1.0` and `1.0.0` are equal; [`Pep440Version::as_str`]
19//! still returns what was written, and `Display` prints the normalized form.
20//!
21//! This is ordering only, as a `vers:pypi` range needs. The specifier
22//! semantics of PEP 440 itself (`~=`, `==1.*`, the exclusion of pre-releases
23//! by `<`) are not implemented.
24
25use std::cmp::Ordering;
26use std::fmt;
27use std::hash::{Hash, Hasher};
28
29use thiserror::Error;
30
31/// Inputs longer than this are rejected with [`Pep440Error::TooLong`].
32pub const MAX_PEP440_BYTES: usize = 1024;
33
34/// Why a string is not a PEP 440 version.
35///
36/// **Experimental:** may change in a 0.x minor release.
37#[derive(Debug, Clone, PartialEq, Eq, Error)]
38#[non_exhaustive]
39pub enum Pep440Error {
40    /// Longer than [`MAX_PEP440_BYTES`].
41    #[error("version is longer than {MAX_PEP440_BYTES} bytes")]
42    TooLong,
43    /// Not a version in the form the specification accepts.
44    #[error("not a PEP 440 version")]
45    Invalid,
46    /// A number does not fit in 64 bits.
47    #[error("a number in the version does not fit in 64 bits")]
48    NumberTooLarge,
49}
50
51/// The kind of a pre-release, in ascending order.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
53enum PreRelease {
54    /// `a`, also spelled `alpha`.
55    Alpha,
56    /// `b`, also spelled `beta`.
57    Beta,
58    /// `rc`, also spelled `c`, `pre` and `preview`.
59    ReleaseCandidate,
60}
61
62impl PreRelease {
63    /// The normalized spelling.
64    fn as_str(self) -> &'static str {
65        match self {
66            Self::Alpha => "a",
67            Self::Beta => "b",
68            Self::ReleaseCandidate => "rc",
69        }
70    }
71}
72
73/// One dot-separated part of a local version label.
74#[derive(Debug, Clone, PartialEq, Eq, Hash)]
75enum LocalSegment {
76    Number(u64),
77    Text(String),
78}
79
80impl Ord for LocalSegment {
81    /// The specification: numeric parts sort after alphanumeric ones; numbers
82    /// compare as numbers, text lexicographically (already lowercase).
83    fn cmp(&self, other: &Self) -> Ordering {
84        match (self, other) {
85            (Self::Number(a), Self::Number(b)) => a.cmp(b),
86            (Self::Text(a), Self::Text(b)) => a.cmp(b),
87            (Self::Text(_), Self::Number(_)) => Ordering::Less,
88            (Self::Number(_), Self::Text(_)) => Ordering::Greater,
89        }
90    }
91}
92
93impl PartialOrd for LocalSegment {
94    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
95        Some(self.cmp(other))
96    }
97}
98
99/// A parsed PEP 440 version.
100///
101/// **Experimental:** may change in a 0.x minor release.
102///
103/// ```
104/// use libtea_core::pep440::Pep440Version;
105///
106/// let v = |s: &str| Pep440Version::parse(s).unwrap();
107/// assert!(v("1.0.dev1") < v("1.0a1"));
108/// assert!(v("1.0a1") < v("1.0"));
109/// assert!(v("1.0") < v("1.0.post1"));
110/// assert!(v("1.0") < v("1.0+local.1"));
111/// assert_eq!(v("1.0"), v("1.0.0"));
112/// assert_eq!(v("V1.0-ALPHA.2").to_string(), "1.0a2");
113/// assert_eq!(v("V1.0-ALPHA.2").as_str(), "V1.0-ALPHA.2");
114/// ```
115#[derive(Debug, Clone)]
116pub struct Pep440Version {
117    original: String,
118    epoch: u64,
119    release: Vec<u64>,
120    pre: Option<(PreRelease, u64)>,
121    post: Option<u64>,
122    dev: Option<u64>,
123    local: Vec<LocalSegment>,
124}
125
126impl Pep440Version {
127    /// Parse a version as the specification's regular expression does.
128    ///
129    /// # Errors
130    ///
131    /// [`Pep440Error::Invalid`] for text that is not a version (including
132    /// any whitespace or non-ASCII character), [`Pep440Error::NumberTooLarge`]
133    /// for a number above `u64::MAX`, and [`Pep440Error::TooLong`] for text
134    /// longer than [`MAX_PEP440_BYTES`].
135    pub fn parse(text: &str) -> Result<Self, Pep440Error> {
136        if text.len() > MAX_PEP440_BYTES {
137            return Err(Pep440Error::TooLong);
138        }
139        if !text.is_ascii() {
140            return Err(Pep440Error::Invalid);
141        }
142        let lower = text.to_ascii_lowercase();
143        let mut cursor = Cursor {
144            rest: lower.as_str(),
145        };
146        cursor.eat("v");
147
148        let first = cursor.number()?.ok_or(Pep440Error::Invalid)?;
149        let (epoch, first) = if cursor.eat("!") {
150            (first, cursor.number()?.ok_or(Pep440Error::Invalid)?)
151        } else {
152            (0, first)
153        };
154        let mut release = vec![first];
155        while cursor.rest.starts_with('.')
156            && cursor.rest[1..].starts_with(|c: char| c.is_ascii_digit())
157        {
158            cursor.eat(".");
159            release.push(cursor.number()?.ok_or(Pep440Error::Invalid)?);
160        }
161
162        let pre = cursor.labelled(&[
163            ("alpha", PreRelease::Alpha),
164            ("a", PreRelease::Alpha),
165            ("beta", PreRelease::Beta),
166            ("b", PreRelease::Beta),
167            ("preview", PreRelease::ReleaseCandidate),
168            ("pre", PreRelease::ReleaseCandidate),
169            ("c", PreRelease::ReleaseCandidate),
170            ("rc", PreRelease::ReleaseCandidate),
171        ])?;
172        // `-N` is an implicit post-release; otherwise a spelled one.
173        let post = match cursor.rest.strip_prefix('-') {
174            Some(after) if after.starts_with(|c: char| c.is_ascii_digit()) => {
175                cursor.eat("-");
176                cursor.number()?
177            }
178            _ => cursor
179                .labelled(&[("post", ()), ("rev", ()), ("r", ())])?
180                .map(|((), n)| n),
181        };
182        let dev = cursor.labelled(&[("dev", ())])?.map(|((), n)| n);
183
184        let mut local = Vec::new();
185        if cursor.eat("+") {
186            for part in cursor.rest.split(['.', '-', '_']) {
187                if part.is_empty() || !part.bytes().all(|b| b.is_ascii_alphanumeric()) {
188                    return Err(Pep440Error::Invalid);
189                }
190                local.push(if part.bytes().all(|b| b.is_ascii_digit()) {
191                    LocalSegment::Number(part.parse().map_err(|_| Pep440Error::NumberTooLarge)?)
192                } else {
193                    LocalSegment::Text(part.to_owned())
194                });
195            }
196            cursor.rest = "";
197        }
198        if !cursor.rest.is_empty() {
199            return Err(Pep440Error::Invalid);
200        }
201        Ok(Self {
202            original: text.to_owned(),
203            epoch,
204            release,
205            pre,
206            post,
207            dev,
208            local,
209        })
210    }
211
212    /// Exactly the text that was parsed.
213    #[must_use]
214    pub fn as_str(&self) -> &str {
215        &self.original
216    }
217
218    /// Whether this is a pre-release or a developmental release.
219    #[must_use]
220    pub fn is_prerelease(&self) -> bool {
221        self.pre.is_some() || self.dev.is_some()
222    }
223
224    /// The release without trailing zeros, for ordering and hashing.
225    fn trimmed_release(&self) -> &[u64] {
226        let end = self
227            .release
228            .iter()
229            .rposition(|n| *n != 0)
230            .map_or(0, |index| index + 1);
231        &self.release[..end]
232    }
233
234    /// The specification's sort key, after the epoch and release: a
235    /// developmental release of a final version sorts before its
236    /// pre-releases, no pre-release after them; no post-release before any;
237    /// no developmental release after any.
238    fn suffix_key(&self) -> SuffixKey {
239        let pre = match (self.pre, self.post, self.dev) {
240            (None, None, Some(_)) => (0, None),
241            (Some(pre), _, _) => (1, Some(pre)),
242            (None, _, _) => (2, None),
243        };
244        let dev = self.dev.map_or((1, 0), |n| (0, n));
245        (pre, self.post, dev)
246    }
247}
248
249impl Ord for Pep440Version {
250    fn cmp(&self, other: &Self) -> Ordering {
251        self.epoch
252            .cmp(&other.epoch)
253            .then_with(|| self.trimmed_release().cmp(other.trimmed_release()))
254            .then_with(|| self.suffix_key().cmp(&other.suffix_key()))
255            // No local label sorts before any; `Vec` ordering does that, as
256            // an empty vector is less than any other.
257            .then_with(|| self.local.cmp(&other.local))
258    }
259}
260
261impl PartialOrd for Pep440Version {
262    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
263        Some(self.cmp(other))
264    }
265}
266
267impl PartialEq for Pep440Version {
268    fn eq(&self, other: &Self) -> bool {
269        self.cmp(other) == Ordering::Equal
270    }
271}
272
273impl Eq for Pep440Version {}
274
275impl Hash for Pep440Version {
276    fn hash<H: Hasher>(&self, state: &mut H) {
277        self.epoch.hash(state);
278        self.trimmed_release().hash(state);
279        self.suffix_key().hash(state);
280        self.local.hash(state);
281    }
282}
283
284impl fmt::Display for Pep440Version {
285    /// The normalized form: `[N!]N(.N)*[{a|b|rc}N][.postN][.devN][+local]`.
286    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287        if self.epoch != 0 {
288            write!(f, "{}!", self.epoch)?;
289        }
290        for (index, part) in self.release.iter().enumerate() {
291            if index > 0 {
292                f.write_str(".")?;
293            }
294            write!(f, "{part}")?;
295        }
296        if let Some((kind, n)) = self.pre {
297            write!(f, "{}{n}", kind.as_str())?;
298        }
299        if let Some(n) = self.post {
300            write!(f, ".post{n}")?;
301        }
302        if let Some(n) = self.dev {
303            write!(f, ".dev{n}")?;
304        }
305        for (index, part) in self.local.iter().enumerate() {
306            f.write_str(if index == 0 { "+" } else { "." })?;
307            match part {
308                LocalSegment::Number(n) => write!(f, "{n}")?,
309                LocalSegment::Text(text) => f.write_str(text)?,
310            }
311        }
312        Ok(())
313    }
314}
315
316/// The pre-, post- and dev-release part of the sort key, in that order.
317type SuffixKey = ((u8, Option<(PreRelease, u64)>), Option<u64>, (u8, u64));
318
319/// The unparsed rest of a lowercased version.
320struct Cursor<'a> {
321    rest: &'a str,
322}
323
324impl Cursor<'_> {
325    fn eat(&mut self, prefix: &str) -> bool {
326        match self.rest.strip_prefix(prefix) {
327            Some(rest) => {
328                self.rest = rest;
329                true
330            }
331            None => false,
332        }
333    }
334
335    /// A run of digits, or `None` when there is none.
336    fn number(&mut self) -> Result<Option<u64>, Pep440Error> {
337        let end = self
338            .rest
339            .find(|c: char| !c.is_ascii_digit())
340            .unwrap_or(self.rest.len());
341        if end == 0 {
342            return Ok(None);
343        }
344        let (digits, rest) = self.rest.split_at(end);
345        self.rest = rest;
346        digits
347            .parse()
348            .map(Some)
349            .map_err(|_| Pep440Error::NumberTooLarge)
350    }
351
352    /// `[-_.]? label [-_.]? N?`, with the first label that matches; the
353    /// number defaults to 0. Nothing is consumed when no label matches.
354    fn labelled<T: Copy>(&mut self, labels: &[(&str, T)]) -> Result<Option<(T, u64)>, Pep440Error> {
355        let after_separator = self.rest.strip_prefix(['-', '_', '.']).unwrap_or(self.rest);
356        let Some((value, rest)) = labels.iter().find_map(|(label, value)| {
357            after_separator
358                .strip_prefix(label)
359                .map(|rest| (*value, rest))
360        }) else {
361            return Ok(None);
362        };
363        self.rest = rest.strip_prefix(['-', '_', '.']).unwrap_or(rest);
364        let number = self.number()?.unwrap_or(0);
365        Ok(Some((value, number)))
366    }
367}
368
369#[cfg(test)]
370mod tests {
371    use super::*;
372
373    fn v(text: &str) -> Pep440Version {
374        Pep440Version::parse(text).unwrap()
375    }
376
377    #[test]
378    fn the_specification_order() {
379        // The ordering example of the specification's "Summary of permitted
380        // suffixes and relative ordering", plus epochs and local labels.
381        let ordered = [
382            "1.dev0",
383            "1.0.dev456",
384            "1.0a1",
385            "1.0a2.dev456",
386            "1.0a12.dev456",
387            "1.0a12",
388            "1.0b1.dev456",
389            "1.0b2",
390            "1.0b2.post345.dev456",
391            "1.0b2.post345",
392            "1.0rc1.dev456",
393            "1.0rc1",
394            "1.0",
395            "1.0+abc.5",
396            "1.0+abc.7",
397            "1.0+5",
398            "1.0.post456.dev34",
399            "1.0.post456",
400            "1.0.15",
401            "1.1.dev1",
402            "1!0.1",
403        ];
404        for pair in ordered.windows(2) {
405            assert!(v(pair[0]) < v(pair[1]), "{} < {}", pair[0], pair[1]);
406        }
407    }
408
409    #[test]
410    fn alternative_spellings_normalize() {
411        for (input, normalized) in [
412            ("1.0", "1.0"),
413            ("v1.0", "1.0"),
414            ("1.0ALPHA1", "1.0a1"),
415            ("1.0-a.1", "1.0a1"),
416            ("1.0_beta", "1.0b0"),
417            ("1.0c1", "1.0rc1"),
418            ("1.0pre2", "1.0rc2"),
419            ("1.0preview2", "1.0rc2"),
420            ("1.0-1", "1.0.post1"),
421            ("1.0-r4", "1.0.post4"),
422            ("1.0rev", "1.0.post0"),
423            ("1.0.post", "1.0.post0"),
424            ("1.0-dev", "1.0.dev0"),
425            ("1.0a.post1", "1.0a0.post1"),
426            ("1.0+Ubuntu-1_2", "1.0+ubuntu.1.2"),
427            ("01.002", "1.2"),
428            ("0!1.0", "1.0"),
429            ("2!1.0rc1.post2.dev3+x", "2!1.0rc1.post2.dev3+x"),
430        ] {
431            let parsed = v(input);
432            assert_eq!(parsed.to_string(), normalized, "{input}");
433            assert_eq!(parsed.as_str(), input);
434            assert_eq!(v(normalized), parsed, "{input}");
435            assert_eq!(v(normalized).to_string(), normalized, "idempotent: {input}");
436        }
437    }
438
439    #[test]
440    fn equality_ignores_trailing_zeros_and_spelling() {
441        assert_eq!(v("1.0"), v("1.0.0.0"));
442        assert_eq!(v("1"), v("1.0"));
443        assert_eq!(v("1.0rc1"), v("1.0c1"));
444        assert_ne!(v("1.0"), v("1.0+0"));
445        assert_ne!(v("1.0"), v("1.0.post0"));
446        let hash = |x: &Pep440Version| {
447            use std::collections::hash_map::DefaultHasher;
448            let mut h = DefaultHasher::new();
449            x.hash(&mut h);
450            h.finish()
451        };
452        assert_eq!(hash(&v("1.0")), hash(&v("1.0.0")));
453        assert!(v("1.0a1").is_prerelease());
454        assert!(v("1.0.dev1").is_prerelease());
455        assert!(!v("1.0.post1").is_prerelease());
456    }
457
458    #[test]
459    fn rejected() {
460        for text in [
461            "",
462            "v",
463            "1.",
464            ".1",
465            "1..0",
466            "1.0-",
467            "1.0+",
468            "1.0+a..b",
469            "1.0+a b",
470            " 1.0",
471            "1.0 ",
472            "1.0a1a1",
473            "1.0.post1.post2",
474            "1.0dev1.dev2",
475            "1!",
476            "!1",
477            "1.0-x",
478            "1.0.x",
479            "1.0é",
480            "1.0+a/b",
481            "1.0+-a",
482            "latest",
483        ] {
484            assert_eq!(
485                Pep440Version::parse(text).err(),
486                Some(Pep440Error::Invalid),
487                "{text:?}"
488            );
489        }
490        assert_eq!(
491            Pep440Version::parse("18446744073709551616").err(),
492            Some(Pep440Error::NumberTooLarge)
493        );
494        assert_eq!(
495            Pep440Version::parse(&"1.".repeat(600)).err(),
496            Some(Pep440Error::TooLong)
497        );
498    }
499}