Skip to main content

alpm_types/version/
base.rs

1//! The base components for [alpm-package-version].
2//!
3//! An [alpm-package-version] is defined by the [alpm-epoch], [alpm-pkgver] and [alpm-pkgrel]
4//! components.
5//!
6//! [alpm-package-version]: https://alpm.archlinux.page/specifications/alpm-package-version.7.html
7//! [alpm-epoch]: https://alpm.archlinux.page/specifications/alpm-epoch.7.html
8//! [alpm-pkgver]: https://alpm.archlinux.page/specifications/alpm-pkgver.7.html
9//! [alpm-pkgrel]: https://alpm.archlinux.page/specifications/alpm-pkgrel.7.html
10
11use std::{
12    cmp::Ordering,
13    fmt::{Display, Formatter},
14    str::FromStr,
15};
16
17use alpm_parsers::prelude::*;
18#[cfg(feature = "serde")]
19use serde::{Deserialize, Serialize};
20#[cfg(feature = "serde")]
21use serde_with::DeserializeFromStr;
22use winnow::{
23    ascii::{dec_uint, digit1},
24    combinator::opt,
25    error::ErrMode,
26    token::take_while,
27};
28
29#[cfg(doc)]
30use crate::Version;
31use crate::{Error, VersionSegments};
32
33/// An epoch of a package
34///
35/// Epoch is used to indicate the downgrade of a package and is prepended to a version, delimited by
36/// a `":"` (e.g. `1:` is added to `0.10.0-1` to form `1:0.10.0-1` which then orders newer than
37/// `1.0.0-1`).
38/// See [alpm-epoch] for details on the format.
39///
40/// An Epoch wraps a [`usize`].
41///
42/// ## Examples
43/// ```
44/// use std::str::FromStr;
45///
46/// use alpm_types::Epoch;
47///
48/// assert!(Epoch::from_str("0").is_ok());
49/// assert!(Epoch::from_str("1").is_ok());
50/// ```
51///
52/// [alpm-epoch]: https://alpm.archlinux.page/specifications/alpm-epoch.7.html
53#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
54#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
55pub struct Epoch(pub usize);
56
57impl Epoch {
58    /// Create a new Epoch
59    pub fn new(epoch: usize) -> Self {
60        Epoch(epoch)
61    }
62
63    /// Returns `true`, if the value of the [`Epoch`] is zero.
64    pub fn is_zero(&self) -> bool {
65        self.0 == 0
66    }
67}
68
69impl AlpmParser for Epoch {
70    /// Recognizes an [`Epoch`] in a string slice.
71    ///
72    /// # Errors
73    ///
74    /// Returns an error if `input` does not begin with a valid _alpm_epoch_.
75    fn parser<'a>(input: &mut Input<'a>) -> PResult<'a, Self> {
76        dec_uint
77            .expected_text("non-negative decimal integer")
78            .map(Self)
79            .layer("alpm-epoch")
80            .parse_next(input)
81    }
82
83    fn delimiter_error_context<'a, O, P>(
84        parser: P,
85    ) -> impl Parser<Input<'a>, O, ErrMode<ParseStack<'a>>>
86    where
87        P: Parser<Input<'a>, O, ErrMode<ParseStack<'a>>>,
88    {
89        parser
90            .expected_text("positive non-zero decimal integer")
91            .layer("alpm-epoch")
92    }
93}
94
95impl FromStr for Epoch {
96    type Err = Error;
97    /// Create an Epoch from a string and return it in a Result
98    fn from_str(s: &str) -> Result<Self, Self::Err> {
99        Ok(Self::parser_until_eof.parse(Input::new(s))?)
100    }
101}
102
103impl Display for Epoch {
104    fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result {
105        write!(fmt, "{}", self.0)
106    }
107}
108
109/// The release version of a package.
110///
111/// A [`PackageRelease`] wraps a [`usize`] for its `major` version and an optional [`usize`] for its
112/// `minor` version.
113///
114/// [`PackageRelease`] is used to indicate the build version of a package.
115/// It is mostly useful in conjunction with a [`PackageVersion`] (see [`Version`]).
116/// Refer to [alpm-pkgrel] for more details on the format.
117///
118/// ## Examples
119/// ```
120/// use std::str::FromStr;
121///
122/// use alpm_types::PackageRelease;
123///
124/// assert!(PackageRelease::from_str("1").is_ok());
125/// assert!(PackageRelease::from_str("1.1").is_ok());
126/// assert!(PackageRelease::from_str("0").is_ok());
127/// assert!(PackageRelease::from_str("a").is_err());
128/// assert!(PackageRelease::from_str("1.a").is_err());
129/// ```
130///
131/// [alpm-pkgrel]: https://alpm.archlinux.page/specifications/alpm-pkgrel.7.html
132#[derive(Clone, Debug, Eq, PartialEq)]
133#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
134pub struct PackageRelease {
135    /// The major version of this package release.
136    pub major: usize,
137    /// The optional minor version of this package release.
138    pub minor: Option<usize>,
139}
140
141impl PackageRelease {
142    /// Creates a new [`PackageRelease`] from a `major` and optional `minor` integer version.
143    ///
144    /// ## Examples
145    /// ```
146    /// use alpm_types::PackageRelease;
147    ///
148    /// # fn main() {
149    /// let release = PackageRelease::new(1, Some(2));
150    /// assert_eq!(format!("{release}"), "1.2");
151    /// # }
152    /// ```
153    pub fn new(major: usize, minor: Option<usize>) -> Self {
154        PackageRelease { major, minor }
155    }
156}
157
158impl AlpmParser for PackageRelease {
159    /// Recognizes a [`PackageRelease`] in a string slice.
160    ///
161    /// # Errors
162    ///
163    /// Returns an error if `input` does not begin with a valid [`PackageRelease`].
164    fn parser<'a>(input: &mut Input<'a>) -> PResult<'a, Self> {
165        let parser = move |input: &mut Input<'a>| -> PResult<'a, Self> {
166            let major = digit1
167                .try_map(FromStr::from_str)
168                .label("package release")
169                .expected_text("positive decimal integer")
170                .parse_next(input)?;
171
172            // If we find a dot, also expect there to be a minor version number
173            let minor = if opt('.').parse_next(input)?.is_some() {
174                let minor = digit1
175                    .try_map(FromStr::from_str)
176                    .label("package release")
177                    .expected_text("single '.' followed by positive decimal integer")
178                    .parse_next(input)?;
179
180                Some(minor)
181            } else {
182                None
183            };
184
185            Ok(Self { major, minor })
186        };
187
188        parser.layer("alpm-pkgrel").parse_next(input)
189    }
190
191    fn delimiter_error_context<'a, O, P>(
192        parser: P,
193    ) -> impl Parser<Input<'a>, O, ErrMode<ParseStack<'a>>>
194    where
195        P: Parser<Input<'a>, O, ErrMode<ParseStack<'a>>>,
196    {
197        parser
198            .label("package release")
199            .expected_text("single '.' followed by positive decimal integer")
200            .layer("alpm-pkgrel")
201    }
202}
203
204impl FromStr for PackageRelease {
205    type Err = Error;
206    /// Creates a [`PackageRelease`] from a string slice.
207    ///
208    /// Delegates to [`PackageRelease::parser`].
209    ///
210    /// # Errors
211    ///
212    /// Returns an error if [`PackageRelease::parser`] fails.
213    fn from_str(s: &str) -> Result<Self, Self::Err> {
214        Ok(Self::parser_until_eof.parse(Input::new(s))?)
215    }
216}
217
218impl Display for PackageRelease {
219    fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result {
220        write!(fmt, "{}", self.major)?;
221        if let Some(minor) = self.minor {
222            write!(fmt, ".{minor}")?;
223        }
224        Ok(())
225    }
226}
227
228impl PartialOrd for PackageRelease {
229    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
230        Some(self.cmp(other))
231    }
232}
233
234impl Ord for PackageRelease {
235    fn cmp(&self, other: &Self) -> Ordering {
236        let major_order = self.major.cmp(&other.major);
237        if major_order != Ordering::Equal {
238            return major_order;
239        }
240
241        match (self.minor, other.minor) {
242            (None, None) => Ordering::Equal,
243            (None, Some(_)) => Ordering::Less,
244            (Some(_), None) => Ordering::Greater,
245            (Some(minor), Some(other_minor)) => minor.cmp(&other_minor),
246        }
247    }
248}
249
250/// A pkgver of a package
251///
252/// PackageVersion is used to denote the upstream version of a package.
253///
254/// A PackageVersion wraps a `String`, which is guaranteed to only contain ASCII characters,
255/// excluding the ':', '/', '-', '<', '>', '=', or any whitespace characters and must be at least
256/// one character long.
257///
258/// NOTE: This implementation of PackageVersion is stricter than that of libalpm/pacman. It does not
259/// allow empty strings `""`.
260///
261/// ## Examples
262/// ```
263/// use std::str::FromStr;
264///
265/// use alpm_types::PackageVersion;
266///
267/// assert!(PackageVersion::new("1".to_string()).is_ok());
268/// assert!(PackageVersion::new("1.1".to_string()).is_ok());
269/// assert!(PackageVersion::new("foo".to_string()).is_ok());
270/// assert!(PackageVersion::new("0".to_string()).is_ok());
271/// assert!(PackageVersion::new(".0.1".to_string()).is_ok());
272/// assert!(PackageVersion::new("=1.0".to_string()).is_err());
273/// assert!(PackageVersion::new("1<0".to_string()).is_err());
274/// ```
275#[derive(Clone, Debug, Eq)]
276#[cfg_attr(feature = "serde", derive(DeserializeFromStr, Serialize))]
277pub struct PackageVersion(pub(crate) String);
278
279impl PackageVersion {
280    /// Create a new PackageVersion from a string and return it in a Result
281    pub fn new(pkgver: String) -> Result<Self, Error> {
282        PackageVersion::from_str(pkgver.as_str())
283    }
284
285    /// Return an iterator over all segments of this version.
286    pub fn segments(&self) -> VersionSegments<'_> {
287        VersionSegments::new(&self.0)
288    }
289}
290
291impl AlpmParser for PackageVersion {
292    /// Recognizes a [`PackageVersion`] in a string slice.
293    ///
294    /// # Errors
295    ///
296    /// Returns an error if `input` does not begin with a valid [alpm-pkgver].
297    ///
298    /// [alpm-pkgver]: https://alpm.archlinux.page/specifications/alpm-pkgver.7.html
299    fn parser<'a>(input: &mut Input<'a>) -> PResult<'a, Self> {
300        // General rule for all characters:
301        // only ASCII except for ':', '/', '-', '<', '>', '=' or any whitespace
302        let allowed = |c: char| {
303            c.is_ascii() && ![':', '/', '-', '<', '>', '='].contains(&c) && !c.is_whitespace()
304        };
305
306        take_while(1.., allowed)
307            .label("character")
308            .expected_text("an ASCII character, except for ':', '/', '-', '<', '>', '=', or any whitespace characters")
309            .layer("alpm-pkgver")
310            .map(|s: &str| Self(s.to_string()))
311            .parse_next(input)
312    }
313
314    fn delimiter_error_context<'a, O, P>(
315        parser: P,
316    ) -> impl Parser<Input<'a>, O, ErrMode<ParseStack<'a>>>
317    where
318        P: Parser<Input<'a>, O, ErrMode<ParseStack<'a>>>,
319    {
320        parser.label("character")
321            .expected_text("an ASCII character, except for ':', '/', '-', '<', '>', '=', or any whitespace character")
322            .layer("alpm-pkgver")
323    }
324}
325
326impl AsRef<str> for PackageVersion {
327    /// Returns a reference to the inner string slice.
328    fn as_ref(&self) -> &str {
329        &self.0
330    }
331}
332
333impl FromStr for PackageVersion {
334    type Err = Error;
335    /// Create a PackageVersion from a string and return it in a Result
336    fn from_str(s: &str) -> Result<Self, Self::Err> {
337        Ok(Self::parser_until_eof.parse(Input::new(s))?)
338    }
339}
340
341impl Display for PackageVersion {
342    fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result {
343        write!(fmt, "{}", self.as_ref())
344    }
345}
346
347#[cfg(test)]
348mod tests {
349    use insta::assert_snapshot;
350    use rstest::rstest;
351    use testresult::TestResult;
352
353    use super::*;
354    use crate::configure_insta;
355
356    #[rstest]
357    #[case("0", Epoch(0))]
358    #[case("1", Epoch(1))]
359    fn epoch(#[case] version: &str, #[case] expected: Epoch) -> TestResult {
360        assert_eq!(expected, Epoch::from_str(version)?);
361
362        Ok(())
363    }
364
365    #[rstest]
366    #[case("-0", "expected non-negative decimal integer")]
367    #[case("z", "expected non-negative decimal integer")]
368    fn epoch_parse_failure(#[case] input: &str, #[case] err_snippet: &str) {
369        let Err(Error::ParseError(err_msg)) = Epoch::from_str(input) else {
370            panic!("'{input}' erroneously parsed as Epoch")
371        };
372        assert!(
373            err_msg.contains(err_snippet),
374            "Error:\n=====\n{err_msg}\n=====\nshould contain snippet:\n\n{err_snippet}"
375        );
376    }
377
378    /// Make sure that we can parse valid **pkgver** strings.
379    #[rstest]
380    #[case("foo")]
381    #[case("1.0.0")]
382    // sadly, this is valid
383    #[case(".xd")]
384    fn valid_pkgver(#[case] pkgver: &str) -> TestResult {
385        let parsed = PackageVersion::new(pkgver.to_string());
386        assert!(parsed.is_ok(), "Expected pkgver {pkgver} to be valid.");
387        assert_eq!(
388            parsed.as_ref()?.to_string(),
389            pkgver,
390            "Expected parsed PackageVersion representation '{}' to be identical to input '{}'",
391            parsed?,
392            pkgver
393        );
394
395        Ok(())
396    }
397
398    /// Ensure that invalid **pkgver**s are throwing errors.
399    #[rstest]
400    #[case("1:foo")]
401    #[case("foo-1")]
402    #[case("foo/1")]
403    // ß is not ASCII
404    #[case("ß")]
405    #[case("1.ß")]
406    #[case("")]
407    fn invalid_pkgver(#[case] pkgver: &str) {
408        let (test_name, _guard) = configure_insta();
409
410        let Err(Error::ParseError(err_msg)) = PackageVersion::new(pkgver.to_string()) else {
411            panic!("Expected pkgver {pkgver} to be invalid.")
412        };
413
414        assert_snapshot!(test_name, err_msg.to_string());
415    }
416
417    /// Make sure that invalid package versions don't deserialize.
418    #[cfg(feature = "serde")]
419    #[rstest]
420    #[case("1:foo")]
421    #[case("foo-1")]
422    fn package_version_deserialize_error(#[case] input: &str) {
423        let Err(serde_json::Error { .. }) =
424            serde_json::from_str::<PackageVersion>(&format!("\"{input}\""))
425        else {
426            panic!("'{input}' erroneously deserialized as a PackageVersion")
427        };
428    }
429
430    /// Make sure that we can parse valid **pkgrel** strings.
431    #[rstest]
432    #[case("0")]
433    #[case("1")]
434    #[case("10")]
435    #[case("1.0")]
436    #[case("10.5")]
437    #[case("0.1")]
438    fn valid_pkgrel(#[case] pkgrel: &str) -> TestResult {
439        let parsed = PackageRelease::from_str(pkgrel);
440        assert!(parsed.is_ok(), "Expected pkgrel {pkgrel} to be valid.");
441        assert_eq!(
442            parsed.as_ref()?.to_string(),
443            pkgrel,
444            "Expected parsed PackageRelease representation '{}' to be identical to input '{}'",
445            parsed?,
446            pkgrel
447        );
448
449        Ok(())
450    }
451
452    /// Ensure that invalid **pkgrel**s are throwing errors.
453    #[rstest]
454    #[case(".1")]
455    #[case("1.")]
456    #[case("1..1")]
457    #[case("-1")]
458    #[case("a")]
459    #[case("1.a")]
460    #[case("1.0.0")]
461    #[case("")]
462    fn invalid_pkgrel(#[case] pkgrel: &str) {
463        let (test_name, _guard) = configure_insta();
464
465        let Err(Error::ParseError(err_msg)) = PackageRelease::from_str(pkgrel) else {
466            panic!("'{pkgrel}' erroneously parsed as PackageRelease")
467        };
468
469        assert_snapshot!(test_name, err_msg.to_string());
470    }
471
472    /// Test that pkgrel ordering works as intended
473    #[rstest]
474    #[case("1", "1.0", Ordering::Less)]
475    #[case("1.0", "2", Ordering::Less)]
476    #[case("1", "1.1", Ordering::Less)]
477    #[case("1.0", "1.1", Ordering::Less)]
478    #[case("0", "1.1", Ordering::Less)]
479    #[case("1", "11", Ordering::Less)]
480    #[case("1", "1", Ordering::Equal)]
481    #[case("1.2", "1.2", Ordering::Equal)]
482    #[case("2.0", "2.0", Ordering::Equal)]
483    #[case("2", "1.0", Ordering::Greater)]
484    #[case("1.1", "1", Ordering::Greater)]
485    #[case("1.1", "1.0", Ordering::Greater)]
486    #[case("1.1", "0", Ordering::Greater)]
487    #[case("11", "1", Ordering::Greater)]
488    fn pkgrel_cmp(
489        #[case] first: &str,
490        #[case] second: &str,
491        #[case] order: Ordering,
492    ) -> TestResult {
493        let first = PackageRelease::from_str(first)?;
494        let second = PackageRelease::from_str(second)?;
495        assert_eq!(
496            first.cmp(&second),
497            order,
498            "{first} should be {order:?} to {second}"
499        );
500
501        Ok(())
502    }
503}