use std::cmp::Ordering; use std::fmt; 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}") } } 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 } } fn cmp_full(&self, other: &Version) -> Ordering { compare(self.epoch_as_i64(), &self.pkgver, &self.pkgrel, other.epoch_as_i64(), &other.pkgver, &other.pkgrel) } fn epoch_as_i64(&self) -> i64 { self.epoch.trim().parse().unwrap_or(0) } pub fn display(&self) -> String { self.to_string() } } 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, } } 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() } 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; } 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) } } fn preceded_by_separator(s: &[u8], k: usize) -> bool { k > 0 && !is_alnum(s[k - 1]) } 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); } } (Chunk::Num(_), Chunk::Alpha(_)) => return Ordering::Greater, (Chunk::Alpha(_), Chunk::Num(_)) => return Ordering::Less, _ => {} } i = na; j = nb; } } pub fn is_downgrade(current: &str, new: &str) -> bool { vercmp(current, new) == Ordering::Greater } // ------------------------------------------------------------- dep strings -- #[derive(Debug, Clone, PartialEq, Eq)] enum DepOp { Any, Eq, Ge, Le, Gt, 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)] struct Dep { pub name: String, pub op: DepOp, pub version: Option, } impl Dep { fn parse(s: &str) -> Option { let s = s.trim(); if s.is_empty() { return None; } 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 }) } /// Only the tests inside this module ask for a `Dep`'s name; production /// reads the field. Gated so the release build does not compile it. #[cfg(test)] fn name(&self) -> &str { &self.name } /// Constraint checking is exercised only by this module's tests today; no /// production path compares a dependency against an installed version yet. #[cfg(test)] 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), } } } fn parse_deps(list: &[String]) -> Vec { list.iter().filter_map(|s| Dep::parse(s)).collect() } 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() { 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() { 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")); } // --------------------------------------------------------------------- // Moved verbatim from tests/versions.rs: every test here is a function of // its arguments alone — no database, no fixture, no temporary directory — // which is what makes it a unit test of this module rather than a consumer // of it. // --------------------------------------------------------------------- const ORDERED: &[(&str, &str)] = &[ ("v1.2.3", "v1.2.4"), ("1.0", "1.1"), ("1.1", "1.2"), ("1.2", "2.0"), ("2.0", "2.1.0"), ("2.1.0", "2.1.1"), ("1.0rc1", "1.0"), ("1.0", "1.0.0"), ("1.0.0", "1.0.1"), ("1.0.1", "1.1.0"), ("1.1", "1.1.0"), ("1", "1.0"), ("1.0", "1.0.1"), ("1.0.1", "1.1"), ("1.1", "1.1.1"), ("1.1.1", "1.2"), ("1.2", "1.2.2"), ("1.2.2", "1.3"), ("1.3", "1.3.1"), ("1.3.1", "1.4"), ("1.4", "1.4.1"), ("1.4.1", "2.0"), ("2.0", "2.0.1"), ("2.0.1", "2.1.0"), ("2.1.0", "2.1.1"), ("2.1.1", "3.0"), ("3.0", "3.0.1"), ("3.0.1", "4.0"), ("1.0.a", "1.0.1"), ("1.0.b", "1.0.2"), ("1.0.2", "1.0.2.a"), ("1.0.2.a", "1.0.2.aa"), ("1.0.2.aa", "1.0.2.b"), ("1.0.2.b", "1.0.2.bb"), ("1.0.2.bb", "1.0.3"), ("1.0.3a", "1.0.3b"), ("1.0.3b", "1.1"), ("1.1a", "1.2"), ("1:0.8", "2:0.1"), ("2:0.1", "3:0.1"), ("1.0-1", "1.0-2"), ("1.0-2", "1.0-3"), ("1.0-3", "1.1-1"), ("1:1.0-1", "1:1.0-2"), ("1:1.0-2", "2:0.1-1"), ("2.5", "2.24"), ("2.0", "2.0.01"), ]; #[test] fn vercmp_orders_the_canonical_vectors() { for (a, b) in ORDERED { assert_eq!(vercmp(a, b), Ordering::Less, "vercmp({a:?}, {b:?}) should be Less"); assert_eq!( vercmp(b, a), Ordering::Greater, "vercmp({b:?}, {a:?}) should be Greater (comparison must be antisymmetric)" ); } } fn sign(o: Ordering) -> i32 { match o { Ordering::Less => -1, Ordering::Equal => 0, Ordering::Greater => 1, } } #[test] fn vercmp_matches_the_recorded_oracle() { let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("testcorpus/vercmp-oracle.tsv"); let table = std::fs::read_to_string(&path) .expect("testcorpus/vercmp-oracle.tsv; regenerate with tools/gen-vercmp-oracle.py"); let mut recorded = std::collections::HashMap::new(); let mut checked = 0; for line in table.lines().filter(|l| !l.starts_with('#') && !l.is_empty()) { let mut cols = line.split('\t'); let (a, b) = (cols.next().unwrap(), cols.next().unwrap()); let theirs: i32 = cols.next().unwrap().parse().expect("verdict column"); assert_eq!( sign(vercmp_string(a, b)), theirs, "vercmp({a:?}, {b:?}) disagrees with the recorded oracle" ); checked += 1; recorded.insert((a, b), theirs); } assert!(checked >= 1089, "the cross-product should be substantial, checked {checked}"); for ((a, b), verdict) in &recorded { assert_eq!( recorded.get(&(*b, *a)), Some(&-*verdict), "the recorded table is not antisymmetric at {a:?} / {b:?}" ); } } #[test] fn the_live_vercmp_tier_is_recorded_not_silently_absent() { if std::env::var("AUR_LIVE_VERCMP").is_err() { println!("note: AUR_LIVE_VERCMP unset; the live vercmp differential is skipped, not passed"); return; } if std::process::Command::new("vercmp").arg("1").arg("2").output().is_err() { println!("note: AUR_LIVE_VERCMP set but pacman's vercmp is not on PATH; tier skipped"); return; } let fragments = [ "1", "1.0", "1.0.0", "1.0.1", "1.1", "2", "2.0", "1.0a", "1.0rc1", "1.0.2a", "1.0.2.1", "1.0.2.a", "1.0.2.aa", "1.0.2.b", "1.0.2z", "1.0z", "1.0.z", "0.9", "10", "2.24", "2.5", "1.02", "1.0_2", "1.0.p", "1.0.3a", "1.0.3b", "1.a", "1a", "1.0+git", "1.0~beta", "2.0_1", "1.0.x", "2024.01", ]; let mut checked = 0; for a in fragments { for b in fragments { let theirs = std::process::Command::new("vercmp").arg(a).arg(b).output().expect("vercmp"); let theirs: i32 = String::from_utf8_lossy(&theirs.stdout).trim().parse().expect("vercmp output"); assert_eq!(sign(vercmp_string(a, b)), theirs, "vercmp({a:?}, {b:?}) disagrees with pacman"); checked += 1; } } assert!(checked > 1000, "the cross-product should be substantial, checked {checked}"); } #[test] fn equal_versions_compare_equal_and_leading_zeros_do_not_matter() { for (a, b) in [ ("1.0-1", "1.0-1"), ("1:1.0-1", "1:1.0-1"), ("1.02-1", "1.2-1"), ("01.0-1", "1.0-1"), ("1.0-01", "1.0-1"), ] { assert_eq!(vercmp(a, b), Ordering::Equal, "{a} vs {b}"); } } #[test] fn an_epoch_always_beats_a_larger_version_without_one() { assert_eq!(vercmp("1:0.1-1", "9.9.9-1"), Ordering::Greater); assert_eq!(vercmp("9.9.9-1", "1:0.1-1"), Ordering::Less); assert_eq!(vercmp("0:1.0-1", "1.0-1"), Ordering::Equal); assert_eq!(vercmp("1:1.0-1", "1.0-1"), Ordering::Greater); } #[test] fn a_pkgrel_reset_under_a_newer_pkgver_is_still_an_upgrade() { assert_eq!(vercmp("1.2.3-4", "1.2.4-1"), Ordering::Less); assert!(!is_downgrade("1.2.3-4", "1.2.4-1")); assert!(is_downgrade("1.2.4-1", "1.2.3-9")); } #[test] fn alpha_numeric_boundaries_follow_the_chunk_rule() { assert_eq!(vercmp("1.0.1", "1.0.a"), Ordering::Greater); assert_eq!(vercmp("1.0.a", "1.0.1"), Ordering::Less); assert_eq!(vercmp("1.0", "1.0.1"), Ordering::Less); assert_eq!(vercmp("1.0", "1.0a"), Ordering::Greater); assert_eq!(vercmp("1.0rc1", "1.0"), Ordering::Less); assert_eq!(vercmp("1.0", "1.0rc1"), Ordering::Greater); } #[test] fn dependency_strings_parse_with_their_constraints() { let cases = [ ("gcc", "gcc", DepOp::Any, None), ("python>=3.11", "python", DepOp::Ge, Some("3.11")), ("openssl<3", "openssl", DepOp::Lt, Some("3")), ("glibc>=2.39-1", "glibc", DepOp::Ge, Some("2.39-1")), ("linux-api-headers=6.0", "linux-api-headers", DepOp::Eq, Some("6.0")), ("gcc-libs<=13.2.1-2", "gcc-libs", DepOp::Le, Some("13.2.1-2")), ("foo>=1:2.3-4", "foo", DepOp::Ge, Some("1:2.3-4")), ("python-pytest: for tests", "python-pytest", DepOp::Any, None), ]; for (src, name, op, ver) in cases { let d = Dep::parse(src).unwrap_or_else(|| panic!("failed to parse {src:?}")); assert_eq!(d.name(), name, "{src:?} name"); assert_eq!(d.op, op, "{src:?} operator"); assert_eq!(d.version.as_deref(), ver, "{src:?} version"); } assert!(Dep::parse("").is_none()); assert!(Dep::parse(">=1.0").is_none()); assert_eq!(dep_names(&["python>=3.11".into(), "gcc".into()]), vec!["python", "gcc"]); } #[test] fn version_constraints_are_satisfied_by_the_right_versions() { let d = Dep::parse("glibc>=2.39-1").unwrap(); assert!(d.satisfied_by("2.39-1")); assert!(d.satisfied_by("2.40-1")); assert!(!d.satisfied_by("2.38-1")); assert!(Dep::parse("foo>=1.0").unwrap().satisfied_by("1:0.1-1")); assert!(Dep::parse("foo=1.0-1").unwrap().satisfied_by("1.0-1")); assert!(!Dep::parse("foo=1.0-1").unwrap().satisfied_by("1.0-2")); assert!(Dep::parse("foo").unwrap().satisfied_by("0")); } #[test] fn provides_and_conflicts_use_the_same_grammar() { for src in ["aur-build", "aur-build=0.1-1", "virtual-thing>=1.0"] { let d = Dep::parse(src).expect(src); assert!(!d.name().is_empty()); assert!(!d.name().contains(['>', '<', '='])); } assert_eq!(dep_names(&["aur-build=0.1-1".into(), "other".into()]), vec!["aur-build", "other"]); } #[test] fn full_version_round_trips_through_split() { for (epoch, pkgver, pkgrel, full) in [ ("0", "1.2.3", "4", "1.2.3-4".to_string()), ("1", "1.2.3", "4", "1:1.2.3-4".to_string()), ("2", "1.0", "1", "2:1.0-1".to_string()), ] { assert_eq!(full_version(epoch, pkgver, pkgrel), full); let (e, v, r) = split_full_version(&full); assert_eq!((e.as_str(), v.as_str(), r.as_str()), (epoch, pkgver, pkgrel), "round trip of {full}"); } } }