//! 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) } #[derive(Debug, PartialEq, Eq)] enum Chunk<'a> { Num(u128), Alpha(&'a str), } /// Split into maximal digit / alpha runs, ignoring everything else. fn chunks(s: &str) -> Vec> { let b = s.as_bytes(); let mut out = Vec::new(); let mut i = 0; while i < b.len() { let c = b[i] as char; if c.is_ascii_digit() { let start = i; while i < b.len() && (b[i] as char).is_ascii_digit() { i += 1; } // Leading zeros are not significant. let digits = s[start..i].trim_start_matches('0'); out.push(Chunk::Num(digits.parse::().unwrap_or(0))); } else if c.is_ascii_alphabetic() { let start = i; while i < b.len() && (b[i] as char).is_ascii_alphabetic() { i += 1; } out.push(Chunk::Alpha(&s[start..i])); } else { i += 1; } } out } /// ALPM's `vercmp_string`: chunk-wise comparison where digits precede letters. pub fn vercmp_string(a: &str, b: &str) -> Ordering { let ca = chunks(a); let cb = chunks(b); let mut i = 0; loop { match (ca.get(i), cb.get(i)) { (None, None) => return Ordering::Equal, (None, Some(Chunk::Num(_))) => return Ordering::Less, (None, Some(Chunk::Alpha(_))) => return Ordering::Greater, (Some(Chunk::Num(_)), None) => return Ordering::Greater, (Some(Chunk::Alpha(_)), None) => return Ordering::Less, (Some(x), Some(y)) => { let o = match (x, y) { (Chunk::Num(x), Chunk::Num(y)) => x.cmp(y), (Chunk::Alpha(x), Chunk::Alpha(y)) => x.cmp(y), // A numeric chunk is always older than an alphabetic one. (Chunk::Num(_), Chunk::Alpha(_)) => Ordering::Less, (Chunk::Alpha(_), Chunk::Num(_)) => Ordering::Greater, }; if o != Ordering::Equal { return o; } i += 1; } } } } /// 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() }