//! Version comparison and dependency-string parsing. //! //! Hand-written rather than bound to libalpm (DESIGN.md §4). The algorithm is //! the ALPM one and is fully specified: compare epoch numerically, then compare //! `pkgver` chunk-wise, then `pkgrel` chunk-wise. A chunk is a maximal run of //! digits or a maximal run of non-digits; non-alphanumeric characters are //! ignored. A numeric chunk always sorts before an alphabetic chunk, so `1.5` //! < `1.5a` and `1.1` < `1.a`. use std::cmp::Ordering; use std::fmt; /// `epoch:pkgver-pkgrel` as pacman displays it, with the epoch omitted when 0. pub fn full_version(epoch: &str, pkgver: &str, pkgrel: &str) -> String { let e = epoch.trim(); if e.is_empty() || e == "0" { format!("{pkgver}-{pkgrel}") } else { format!("{e}:{pkgver}-{pkgrel}") } } /// Parse a full `epoch:pkgver-pkgrel` string back into its parts. pub fn split_full_version(v: &str) -> (String, String, String) { let (epoch, rest) = match v.split_once(':') { Some((e, r)) => (e.to_string(), r.to_string()), None => ("0".to_string(), v.to_string()), }; match rest.rsplit_once('-') { Some((pv, pr)) => (epoch, pv.to_string(), pr.to_string()), None => (epoch, rest, "1".to_string()), } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Version { pub epoch: String, pub pkgver: String, pub pkgrel: String, } impl fmt::Display for Version { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", full_version(&self.epoch, &self.pkgver, &self.pkgrel)) } } impl Version { pub fn parse(v: &str) -> Self { let (epoch, pkgver, pkgrel) = split_full_version(v); Self { epoch, pkgver, pkgrel } } pub fn cmp_full(&self, other: &Version) -> Ordering { compare(self.epoch_as_i64(), &self.pkgver, &self.pkgrel, other.epoch_as_i64(), &other.pkgver, &other.pkgrel) } pub fn epoch_as_i64(&self) -> i64 { self.epoch.trim().parse().unwrap_or(0) } pub fn display(&self) -> String { self.to_string() } } /// Compare `epoch:pkgver-pkgrel` triples the way pacman does. pub fn compare( epoch_a: i64, pkgver_a: &str, pkgrel_a: &str, epoch_b: i64, pkgver_b: &str, pkgrel_b: &str, ) -> Ordering { match epoch_a.cmp(&epoch_b) { Ordering::Equal => {} o => return o, } match vercmp_string(pkgver_a, pkgver_b) { Ordering::Equal => vercmp_string(pkgrel_a, pkgrel_b), o => o, } } /// Compare two full version strings (`1.2.3-1`, `1:2-3`). pub fn vercmp(a: &str, b: &str) -> Ordering { let va = Version::parse(a); let vb = Version::parse(b); va.cmp_full(&vb) } fn is_alnum(c: u8) -> bool { c.is_ascii_alphanumeric() } /// The chunk starting at `k`, and the index just past it. enum Chunk<'a> { Num(u128), Alpha(&'a str), None, } fn read_chunk(s: &[u8], k: usize) -> (Chunk<'_>, usize) { if k >= s.len() { return (Chunk::None, k); } if s[k].is_ascii_digit() { let mut i = k; while i < s.len() && s[i].is_ascii_digit() { i += 1; } // Leading zeros are not significant. let digits = std::str::from_utf8(&s[k..i]).unwrap_or("0").trim_start_matches('0'); (Chunk::Num(digits.parse::().unwrap_or(0)), i) } else if s[k].is_ascii_alphabetic() { let mut i = k; while i < s.len() && s[i].is_ascii_alphabetic() { i += 1; } (Chunk::Alpha(std::str::from_utf8(&s[k..i]).unwrap_or("")), i) } else { (Chunk::None, k) } } /// Was the character before `k` a separator? A chunk at the very start of a /// version counts as attached. fn preceded_by_separator(s: &[u8], k: usize) -> bool { k > 0 && !is_alnum(s[k - 1]) } /// ALPM's `vercmp`, character-wise. /// /// Three rules do all the work, and each one is surprising the first time: /// /// 1. A numeric chunk is newer than an alphabetic chunk at the same position, so /// `1.0.1` > `1.0.a`. /// 2. When one string runs out, the other side decides by its *next raw /// character*: a letter there makes the exhausted string newer (`1.0` > /// `1.0a`, the `1.0rc1 < 1.0` rule), anything else makes it older /// (`1.0` < `1.0.1`). /// 3. Separators are not merely skipped. An alphabetic chunk that follows a /// separator is newer than one glued to the previous chunk, whatever the /// letters are: `1.0.a` > `1.0z`. Two versions that differ only in where the /// dot sits are *not* equal, which is the part a chunk-splitting /// implementation gets wrong. /// /// The cross-product test in `tests/versions.rs` checks this against pacman's own /// `vercmp` over ~1100 pairs, which is the only reason anyone can be confident /// about rule 3. pub fn vercmp_string(a: &str, b: &str) -> Ordering { let (a, b) = (a.as_bytes(), b.as_bytes()); let (mut i, mut j) = (0usize, 0usize); loop { // End-of-string checks come before skipping separators, because whether // the next character is glued or separated is exactly what decides them. match (i >= a.len(), j >= b.len()) { (true, true) => return Ordering::Equal, (true, false) => { return if j < b.len() && b[j].is_ascii_alphabetic() { Ordering::Greater } else { Ordering::Less } } (false, true) => { return if i < a.len() && a[i].is_ascii_alphabetic() { Ordering::Less } else { Ordering::Greater } } (false, false) => {} } while i < a.len() && !is_alnum(a[i]) { i += 1; } while j < b.len() && !is_alnum(b[j]) { j += 1; } if i >= a.len() && j >= b.len() { return Ordering::Equal; } if i >= a.len() || j >= b.len() { let alpha = if i >= a.len() { j < b.len() && b[j].is_ascii_alphabetic() } else { i < a.len() && a[i].is_ascii_alphabetic() }; let a_first = i >= a.len(); return match (a_first, alpha) { (true, true) => Ordering::Greater, (true, false) => Ordering::Less, (false, true) => Ordering::Less, (false, false) => Ordering::Greater, }; } let (ca, na) = read_chunk(a, i); let (cb, nb) = read_chunk(b, j); match (ca, cb) { (Chunk::Num(x), Chunk::Num(y)) => { if x != y { return x.cmp(&y); } } (Chunk::Alpha(x), Chunk::Alpha(y)) => { let (xa, yb) = (preceded_by_separator(a, i), preceded_by_separator(b, j)); if xa != yb { return xa.cmp(&yb); } if x != y { return x.cmp(y); } } // A numeric chunk is always newer than an alphabetic one. (Chunk::Num(_), Chunk::Alpha(_)) => return Ordering::Greater, (Chunk::Alpha(_), Chunk::Num(_)) => return Ordering::Less, _ => {} } i = na; j = nb; } } /// True if `new` is a downgrade relative to `current` (§16: maintainer reverted). pub fn is_downgrade(current: &str, new: &str) -> bool { vercmp(current, new) == Ordering::Greater } /// True if `new` is exactly equal to `current` in the pacman sense. pub fn same_version(current: &str, new: &str) -> bool { vercmp(current, new) == Ordering::Equal } // ------------------------------------------------------------- dep strings -- #[derive(Debug, Clone, PartialEq, Eq)] pub enum DepOp { /// `foo` Any, /// `foo=1.2` Eq, /// `foo>=1.2` Ge, /// `foo<=1.2` Le, /// `foo>1.2` Gt, /// `foo<1.2` Lt, } impl fmt::Display for DepOp { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match self { DepOp::Any => "", DepOp::Eq => "=", DepOp::Ge => ">=", DepOp::Le => "<=", DepOp::Gt => ">", DepOp::Lt => "<", }) } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Dep { pub name: String, pub op: DepOp, pub version: Option, } impl Dep { /// Parse one dependency string, e.g. `python>=3.11`, `gcc`, `foo=1.2-3`. /// /// Returns `None` for an empty or malformed string rather than failing the /// whole recipe: a weird `optdepends` line must not break detection. pub fn parse(s: &str) -> Option { let s = s.trim(); if s.is_empty() { return None; } // optdepends carry a `: description` suffix. let s = match s.split_once(':') { Some((head, _desc)) if !head.contains(['>', '<', '=']) => head, _ => s, }; for (tok, op) in [ (">=", DepOp::Ge), ("<=", DepOp::Le), ("=", DepOp::Eq), (">", DepOp::Gt), ("<", DepOp::Lt), ] { if let Some((name, ver)) = s.split_once(tok) { let name = name.trim(); if name.is_empty() { return None; } return Some(Dep { name: name.to_string(), op, version: Some(ver.trim().to_string()), }); } } Some(Dep { name: s.trim().to_string(), op: DepOp::Any, version: None }) } /// The bare package name, which is what we resolve against our index. pub fn name(&self) -> &str { &self.name } /// Does a candidate version satisfy this constraint? pub fn satisfied_by(&self, version: &str) -> bool { match self.op { DepOp::Any => true, DepOp::Eq => vercmp(version, self.version.as_deref().unwrap_or("0")) == Ordering::Equal, DepOp::Ge => vercmp(version, self.version.as_deref().unwrap_or("0")) != Ordering::Less, DepOp::Le => vercmp(version, self.version.as_deref().unwrap_or("0")) != Ordering::Greater, DepOp::Gt => vercmp(version, self.version.as_deref().unwrap_or("0")) == Ordering::Greater, DepOp::Lt => vercmp(version, self.version.as_deref().unwrap_or("0")) == Ordering::Less, } } } impl fmt::Display for Dep { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match &self.version { Some(v) => write!(f, "{}{}{}", self.name, self.op, v), None => write!(f, "{}", self.name), } } } /// Parse a whole `depends=()` style list, dropping unparseable entries. pub fn parse_deps(list: &[String]) -> Vec { list.iter().filter_map(|s| Dep::parse(s)).collect() } /// Strip a `name=version` constraint down to the name, for index resolution. pub fn dep_names(list: &[String]) -> Vec { parse_deps(list).into_iter().map(|d| d.name).collect() } #[cfg(test)] mod tests { use super::*; fn ord(a: &str, b: &str) -> Ordering { vercmp(a, b) } #[test] fn alpm_version_ordering() { // The classic ALPM test vectors. assert_eq!(ord("1.0-1", "1.0-1"), Ordering::Equal); assert_eq!(ord("1.0-1", "1.0-2"), Ordering::Less); assert_eq!(ord("1.1-1", "1.0-1"), Ordering::Greater); assert_eq!(ord("1.10-1", "1.9-1"), Ordering::Greater, "numeric chunks compare numerically"); assert_eq!(ord("1.0.a-1", "1.0.1-1"), Ordering::Less, "a numeric chunk is newer than an alphabetic one"); assert_eq!(ord("1.5-1", "1.5.0-1"), Ordering::Less, "a trailing numeric chunk is newer"); assert_eq!(ord("1:1.0-1", "2.0-1"), Ordering::Greater, "epoch dominates"); assert_eq!(ord("1.0-1", "1.0_2-1"), Ordering::Less, "non-alnum separators are ignored"); assert_eq!(ord("1.0.0-1", "1.0-1"), Ordering::Greater, "a trailing numeric chunk is newer"); assert_eq!(ord("01.0-1", "1.0-1"), Ordering::Equal, "leading zeros are not significant"); } #[test] fn full_version_formatting() { assert_eq!(full_version("0", "1.0", "1"), "1.0-1"); assert_eq!(full_version("", "1.0", "1"), "1.0-1"); assert_eq!(full_version("2", "1.0", "3"), "2:1.0-3"); assert_eq!(split_full_version("2:1.0-3").0, "2"); assert_eq!(split_full_version("1.0-3"), ("0".into(), "1.0".into(), "3".into())); } #[test] fn pkgrel_reset_is_a_new_version() { // §3: a pkgrel reset is a major signal. assert_eq!(ord("1.0-7", "1.0-1"), Ordering::Greater); assert!(is_downgrade("1.0-7", "1.0-1")); } #[test] fn dep_strings_parse() { assert_eq!(Dep::parse("foo").unwrap(), Dep { name: "foo".into(), op: DepOp::Any, version: None }); assert_eq!(Dep::parse("foo>=1.2").unwrap().op, DepOp::Ge); assert_eq!(Dep::parse("foo<=1.2").unwrap().op, DepOp::Le); assert_eq!(Dep::parse("foo=1.2-3").unwrap().version.as_deref(), Some("1.2-3")); assert_eq!(Dep::parse("python-numpy").unwrap().name, "python-numpy"); assert_eq!(Dep::parse("cmake: for building").unwrap().name, "cmake"); assert!(Dep::parse("").is_none()); } #[test] fn version_constraints_are_checked() { let d = Dep::parse("python>=3.11").unwrap(); assert!(d.satisfied_by("3.12-1")); assert!(!d.satisfied_by("3.10-1")); assert!(Dep::parse("foo").unwrap().satisfied_by("anything")); } }