summaryrefslogtreecommitdiffstats
path: root/src/pkgver/mod.rs
blob: 75be3083ac728e28cf642086bddb926f3a27ef19 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
//! 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<Chunk<'_>> {
    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::<u128>().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<String>,
}

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<Dep> {
        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<Dep> {
    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<String> {
    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::Greater, "alpha sorts after numeric");
        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"));
    }
}