rpm-version 0.3.0

A library for dealing with RPM versions (NEVRA, EVR) correctly. Sort algorithm is identical to RPM.
Documentation
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use std::cmp::Ordering;

use pyo3::prelude::*;
use pyo3::types::PyType;

/// An RPM version specifier: Epoch, Version, Release.
///
/// Supports ordering via RPM's version comparison algorithm. See also the
/// module-level `evr_compare` function for comparing raw EVR strings.
#[pyclass(name = "Evr", frozen, eq, ord, hash, from_py_object)]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PyEvr(crate::Evr<'static>);

impl<'a> From<crate::Evr<'a>> for PyEvr {
    fn from(e: crate::Evr<'a>) -> Self {
        let (epoch, version, release) = e.values();
        PyEvr(crate::Evr::new(
            epoch.to_owned(),
            version.to_owned(),
            release.to_owned(),
        ))
    }
}

#[pymethods]
impl PyEvr {
    /// Construct an Evr from its three components.
    #[new]
    #[pyo3(signature = (epoch, version, release))]
    fn new(epoch: Option<&str>, version: &str, release: &str) -> Self {
        PyEvr(crate::Evr::new(
            epoch.unwrap_or("").to_owned(),
            version.to_owned(),
            release.to_owned(),
        ))
    }

    /// Parse an EVR string such as `"2.3.4-5"` or `"1:2.3.4-5"`.
    #[classmethod]
    fn parse(_cls: &Bound<'_, PyType>, evr: &str) -> Self {
        // parse_values returns slices that borrow from `evr`; convert to owned immediately.
        let (epoch, version, release) = crate::Evr::parse_values(evr);
        PyEvr(crate::Evr::new(
            epoch.to_owned(),
            version.to_owned(),
            release.to_owned(),
        ))
    }

    fn __repr__(&self) -> String {
        format!(
            "Evr(epoch={:?}, version={:?}, release={:?})",
            self.0.epoch(),
            self.0.version(),
            self.0.release(),
        )
    }

    fn __str__(&self) -> String {
        self.0.to_string()
    }

    /// The epoch string. Empty string means no epoch (equivalent to epoch 0).
    #[getter]
    fn epoch(&self) -> &str {
        self.0.epoch()
    }

    /// The version string.
    #[getter]
    fn version(&self) -> &str {
        self.0.version()
    }

    /// The release string.
    #[getter]
    fn release(&self) -> &str {
        self.0.release()
    }

    /// Write the EVR in normalized form, always including the epoch (e.g. `"0:1.2.3-4"`).
    fn as_normalized_form(&self) -> String {
        self.0.as_normalized_form()
    }
}

// ---------------------------------------------------------------------------
// Nevra
// ---------------------------------------------------------------------------

/// A full RPM NEVRA: Name, Epoch, Version, Release, Architecture.
///
/// Supports ordering via RPM's version comparison algorithm.
#[pyclass(name = "Nevra", frozen, eq, ord, hash, from_py_object)]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PyNevra(crate::Nevra<'static>);

impl<'a> From<crate::Nevra<'a>> for PyNevra {
    fn from(n: crate::Nevra<'a>) -> Self {
        let (name, epoch, version, release, arch) = n.values();
        PyNevra(crate::Nevra::new(
            name.to_owned(),
            epoch.to_owned(),
            version.to_owned(),
            release.to_owned(),
            arch.to_owned(),
        ))
    }
}

#[pymethods]
impl PyNevra {
    /// Construct a Nevra from its five components.
    #[new]
    #[pyo3(signature = (name, epoch, version, release, arch))]
    fn new(name: &str, epoch: Option<&str>, version: &str, release: &str, arch: &str) -> Self {
        PyNevra(crate::Nevra::new(
            name.to_owned(),
            epoch.unwrap_or("").to_owned(),
            version.to_owned(),
            release.to_owned(),
            arch.to_owned(),
        ))
    }

    /// Parse a NEVRA string such as `"foo-1.2.3-4.x86_64"` or `"foo-1:1.2.3-4.x86_64"`.
    #[classmethod]
    fn parse(_cls: &Bound<'_, PyType>, nevra: &str) -> Self {
        // parse_values returns slices that borrow from `nevra`; convert to owned immediately.
        let (name, epoch, version, release, arch) = crate::Nevra::parse_values(nevra);
        PyNevra(crate::Nevra::new(
            name.to_owned(),
            epoch.to_owned(),
            version.to_owned(),
            release.to_owned(),
            arch.to_owned(),
        ))
    }

    fn __repr__(&self) -> String {
        format!(
            "Nevra(name={:?}, epoch={:?}, version={:?}, release={:?}, arch={:?})",
            self.0.name(),
            self.0.epoch(),
            self.0.version(),
            self.0.release(),
            self.0.arch(),
        )
    }

    fn __str__(&self) -> String {
        self.0.to_string()
    }

    /// The package name.
    #[getter]
    fn name(&self) -> &str {
        self.0.name()
    }

    /// The epoch string. Empty string means no epoch (equivalent to epoch 0).
    #[getter]
    fn epoch(&self) -> &str {
        self.0.epoch()
    }

    /// The version string.
    #[getter]
    fn version(&self) -> &str {
        self.0.version()
    }

    /// The release string.
    #[getter]
    fn release(&self) -> &str {
        self.0.release()
    }

    /// The architecture string (e.g. `"x86_64"`, `"noarch"`).
    #[getter]
    fn arch(&self) -> &str {
        self.0.arch()
    }

    /// The EVR (Epoch, Version, Release) portion of this NEVRA as an `Evr` object.
    fn evr(&self) -> PyEvr {
        // evr() has &'a self receiver so we can't use it here; extract fields via the
        // plain &self accessors (epoch/version/release) and build a fresh Evr<'static>.
        PyEvr(crate::Evr::new(
            self.0.epoch().to_owned(),
            self.0.version().to_owned(),
            self.0.release().to_owned(),
        ))
    }

    /// Write the NEVRA in normalized form, always including the epoch
    /// (e.g. `"foo-0:1.2.3-4.x86_64"`).
    fn as_normalized_form(&self) -> String {
        self.0.as_normalized_form()
    }

    /// Write an NVRA string (no epoch), typically used for RPM filenames
    /// (e.g. `"foo-1.2.3-4.x86_64"`).
    fn nvra(&self) -> String {
        self.0.nvra()
    }
}

// ---------------------------------------------------------------------------
// Requirement
// ---------------------------------------------------------------------------

/// Comparison operator for an RPM dependency requirement.
#[pyclass(name = "ReqOperator", frozen, eq, eq_int, hash, from_py_object)]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum PyReqOperator {
    LT,
    LE,
    EQ,
    GE,
    GT,
}

impl From<PyReqOperator> for crate::ReqOperator {
    fn from(op: PyReqOperator) -> Self {
        match op {
            PyReqOperator::LT => crate::ReqOperator::LT,
            PyReqOperator::LE => crate::ReqOperator::LE,
            PyReqOperator::EQ => crate::ReqOperator::EQ,
            PyReqOperator::GE => crate::ReqOperator::GE,
            PyReqOperator::GT => crate::ReqOperator::GT,
        }
    }
}

impl From<crate::ReqOperator> for PyReqOperator {
    fn from(op: crate::ReqOperator) -> Self {
        match op {
            crate::ReqOperator::LT => PyReqOperator::LT,
            crate::ReqOperator::LE => PyReqOperator::LE,
            crate::ReqOperator::EQ => PyReqOperator::EQ,
            crate::ReqOperator::GE => PyReqOperator::GE,
            crate::ReqOperator::GT => PyReqOperator::GT,
        }
    }
}

/// Accepts either a string (`"<"`, `"<="`, `"="`, `">="`, `">"`) or a `ReqOperator` enum value.
#[derive(FromPyObject)]
enum OpArg {
    Enum(PyReqOperator),
    Str(String),
}

impl OpArg {
    fn into_req_operator(self) -> PyResult<crate::ReqOperator> {
        match self {
            OpArg::Enum(e) => Ok(e.into()),
            OpArg::Str(s) => match s.as_str() {
                "<" | "LT" => Ok(crate::ReqOperator::LT),
                "<=" | "LE" => Ok(crate::ReqOperator::LE),
                "=" | "==" | "EQ" => Ok(crate::ReqOperator::EQ),
                ">=" | "GE" => Ok(crate::ReqOperator::GE),
                ">" | "GT" => Ok(crate::ReqOperator::GT),
                _ => Err(pyo3::exceptions::PyValueError::new_err(format!(
                    "invalid operator: {s:?} (expected <, <=, =, >=, or >)"
                ))),
            },
        }
    }
}

/// An RPM dependency requirement: a package name with an optional version constraint.
///
/// A requirement like ``Requirement("foo", ">=", Evr.parse("2.0-1"))`` is satisfied
/// by any package named ``foo`` whose EVR is at least ``2.0-1``.
/// A requirement with no constraint (just a name) is satisfied by any version.
#[pyclass(name = "Requirement", frozen, eq, hash, from_py_object)]
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct PyRequirement(crate::Requirement<'static>);

#[pymethods]
impl PyRequirement {
    /// Construct a requirement.
    ///
    /// With just a name, any version satisfies.
    /// With an operator and EVR, only matching versions satisfy.
    #[new]
    #[pyo3(signature = (name, op=None, evr=None))]
    fn new(name: &str, op: Option<OpArg>, evr: Option<PyEvr>) -> PyResult<Self> {
        match (op, evr) {
            (None, None) => Ok(PyRequirement(crate::Requirement::new(name.to_owned()))),
            (Some(op_arg), Some(py_evr)) => {
                let op = op_arg.into_req_operator()?;
                let (epoch, version, release) = py_evr.0.values();
                let evr = crate::Evr::new(epoch.to_owned(), version.to_owned(), release.to_owned());
                Ok(PyRequirement(crate::Requirement::with_constraint(
                    name.to_owned(),
                    op,
                    evr,
                )))
            }
            _ => Err(pyo3::exceptions::PyValueError::new_err(
                "op and evr must both be provided, or both omitted",
            )),
        }
    }

    /// The required package name.
    #[getter]
    fn name(&self) -> &str {
        self.0.name()
    }

    /// The version constraint as (ReqOperator, Evr), or None.
    #[getter]
    fn constraint(&self) -> Option<(PyReqOperator, PyEvr)> {
        self.0
            .constraint()
            .map(|(op, evr)| (PyReqOperator::from(op), PyEvr::from(evr.clone())))
    }

    /// Check whether a given package name and EVR satisfy this requirement.
    fn satisfies(&self, name: &str, evr: &PyEvr) -> bool {
        self.0.satisfies(name, &evr.0)
    }

    fn __repr__(&self) -> String {
        format!("Requirement({})", self.0)
    }

    fn __str__(&self) -> String {
        self.0.to_string()
    }
}

// ---------------------------------------------------------------------------
// Module-level functions
// ---------------------------------------------------------------------------

/// Compare two EVR strings using RPM's version comparison algorithm.
///
/// Returns -1, 0, or 1 if `evr1` is less than, equal to, or greater than `evr2`.
///
/// # Example
/// ```python
/// assert evr_compare("1.2.3-4", "1.2.3-5") == -1
/// assert evr_compare("2:1.0-1", "1:9.9-1") == 1
/// ```
#[pyfunction]
fn evr_compare(evr1: &str, evr2: &str) -> i32 {
    match crate::rpm_evr_compare(evr1, evr2) {
        Ordering::Less => -1,
        Ordering::Equal => 0,
        Ordering::Greater => 1,
    }
}

/// Sort a list of EVR strings using RPM's version comparison algorithm.
///
/// Performs all parsing and comparison in Rust, avoiding per-comparison FFI overhead.
#[pyfunction]
fn evr_sort(evrs: Vec<String>) -> Vec<String> {
    let mut parsed: Vec<(crate::Evr<'_>, usize)> = evrs
        .iter()
        .enumerate()
        .map(|(i, s)| (crate::Evr::parse(s), i))
        .collect();
    parsed.sort_unstable();
    parsed.into_iter().map(|(_, i)| evrs[i].clone()).collect()
}

/// Sort a list of NEVRA strings using RPM's version comparison algorithm.
///
/// Performs all parsing and comparison in Rust, avoiding per-comparison FFI overhead.
#[pyfunction]
fn nevra_sort(nevras: Vec<String>) -> Vec<String> {
    let mut parsed: Vec<(crate::Nevra<'_>, usize)> = nevras
        .iter()
        .enumerate()
        .map(|(i, s)| (crate::Nevra::parse(s), i))
        .collect();
    parsed.sort_unstable();
    parsed.into_iter().map(|(_, i)| nevras[i].clone()).collect()
}

// ---------------------------------------------------------------------------
// Module registration
// ---------------------------------------------------------------------------

/// Python module exporting rpm_version functionality.
///
/// Register all public types with the Python interpreter.
#[pymodule]
pub fn rpm_version(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_class::<PyEvr>()?;
    m.add_class::<PyNevra>()?;
    m.add_class::<PyReqOperator>()?;
    m.add_class::<PyRequirement>()?;
    m.add_function(wrap_pyfunction!(evr_compare, m)?)?;
    m.add_function(wrap_pyfunction!(evr_sort, m)?)?;
    m.add_function(wrap_pyfunction!(nevra_sort, m)?)?;

    Ok(())
}