Skip to main content

alpm_types/version/
pkg_full.rs

1//! The [alpm-package-version] form _full_ and _full with epoch_.
2//!
3//! [alpm-package-version]: https://alpm.archlinux.page/specifications/alpm-package-version.7.html
4
5use std::{
6    cmp::Ordering,
7    fmt::{Display, Formatter},
8    str::FromStr,
9};
10
11use alpm_parsers::prelude::*;
12#[cfg(feature = "serde")]
13use serde::{Deserialize, Serialize};
14use winnow::{combinator::opt, error::ErrMode};
15
16use crate::{Epoch, Error, PackageRelease, PackageVersion, Version};
17
18/// A package version with mandatory [`PackageRelease`].
19///
20/// Tracks an optional [`Epoch`], a [`PackageVersion`] and a [`PackageRelease`].
21/// This reflects the _full_ and _full with epoch_ forms of [alpm-package-version].
22///
23/// # Note
24///
25/// If [`PackageRelease`] should be optional for your use-case, use [`Version`] instead.
26///
27/// # Examples
28///
29/// ```
30/// use std::str::FromStr;
31///
32/// use alpm_types::FullVersion;
33///
34/// # fn main() -> testresult::TestResult {
35/// // A full version.
36/// let version = FullVersion::from_str("1.0.0-1")?;
37///
38/// // A full version with epoch.
39/// let version = FullVersion::from_str("1:1.0.0-1")?;
40/// # Ok(())
41/// # }
42/// ```
43///
44/// [alpm-package-version]: https://alpm.archlinux.page/specifications/alpm-package-version.7.html
45#[derive(Clone, Debug, Eq, PartialEq)]
46#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
47pub struct FullVersion {
48    /// The version of the package
49    pub pkgver: PackageVersion,
50    /// The release of the package
51    pub pkgrel: PackageRelease,
52    /// The epoch of the package
53    pub epoch: Option<Epoch>,
54}
55
56impl FullVersion {
57    /// Creates a new [`FullVersion`].
58    ///
59    /// # Examples
60    ///
61    /// ```
62    /// use alpm_types::{Epoch, FullVersion, PackageRelease, PackageVersion};
63    ///
64    /// # fn main() -> testresult::TestResult {
65    /// // A full version.
66    /// let version = FullVersion::new(
67    ///     PackageVersion::new("1.0.0".to_string())?,
68    ///     PackageRelease::new(1, None),
69    ///     None,
70    /// );
71    ///
72    /// // A full version with epoch.
73    /// let version = FullVersion::new(
74    ///     PackageVersion::new("1.0.0".to_string())?,
75    ///     PackageRelease::new(1, None),
76    ///     Some(Epoch::new(1)),
77    /// );
78    /// # Ok(())
79    /// # }
80    /// ```
81    pub fn new(pkgver: PackageVersion, pkgrel: PackageRelease, epoch: Option<Epoch>) -> Self {
82        Self {
83            pkgver,
84            pkgrel,
85            epoch,
86        }
87    }
88
89    /// Compares `self` to another [`FullVersion`] and returns a number.
90    ///
91    /// - `1` if `self` is newer than `other`
92    /// - `0` if `self` and `other` are equal
93    /// - `-1` if `self` is older than `other`
94    ///
95    /// This output behavior is based on the behavior of the [vercmp] tool.
96    ///
97    /// Delegates to [`FullVersion::cmp`] for comparison.
98    /// The rules and algorithms used for comparison are explained in more detail in
99    /// [alpm-package-version] and [alpm-pkgver].
100    ///
101    /// # Examples
102    ///
103    /// ```
104    /// use std::str::FromStr;
105    ///
106    /// use alpm_types::FullVersion;
107    ///
108    /// # fn main() -> Result<(), alpm_types::Error> {
109    /// assert_eq!(
110    ///     FullVersion::from_str("1.0.0-1")?.vercmp(&FullVersion::from_str("0.1.0-1")?),
111    ///     1
112    /// );
113    /// assert_eq!(
114    ///     FullVersion::from_str("1.0.0-1")?.vercmp(&FullVersion::from_str("1.0.0-1")?),
115    ///     0
116    /// );
117    /// assert_eq!(
118    ///     FullVersion::from_str("0.1.0-1")?.vercmp(&FullVersion::from_str("1.0.0-1")?),
119    ///     -1
120    /// );
121    /// # Ok(())
122    /// # }
123    /// ```
124    ///
125    /// [alpm-package-version]: https://alpm.archlinux.page/specifications/alpm-package-version.7.html
126    /// [alpm-pkgver]: https://alpm.archlinux.page/specifications/alpm-pkgver.7.html
127    /// [vercmp]: https://man.archlinux.org/man/vercmp.8
128    pub fn vercmp(&self, other: &FullVersion) -> i8 {
129        match self.cmp(other) {
130            Ordering::Less => -1,
131            Ordering::Equal => 0,
132            Ordering::Greater => 1,
133        }
134    }
135}
136
137impl AlpmParser for FullVersion {
138    /// Recognizes a [`FullVersion`] in a string slice.
139    ///
140    /// # Errors
141    ///
142    /// Returns an error if `input` does not begin with a valid  [alpm-package-version] (_full_ or
143    /// _full with epoch_).
144    ///
145    /// [alpm-package-version]: https://alpm.archlinux.page/specifications/alpm-package-version.7.html
146    fn parser<'a>(input: &mut Input<'a>) -> PResult<'a, Self> {
147        let parser = move |input: &mut Input<'a>| -> PResult<'a, Self> {
148            // Parse an optional epoch, which advances the cursor until after a ':', e.g.:
149            // "1:1.0.0-1" -> "1.0.0-1"
150            //
151            // If no epoch exists, the cursor does not move.
152            let epoch = opt(Epoch::parser_until_inclusive(":")).parse_next(input)?;
153
154            // Advance the parser until the next '-', e.g.:
155            // "1.0.0-1" -> "-1"
156            let pkgver: PackageVersion = PackageVersion::parser.parse_next(input)?;
157
158            "-".expected_text("the '-' delimiter that divides the alpm-pkgver and alpm-pkgrel")
159                .parse_next(input)?;
160
161            // Consume the delimiter '-'
162            // "-1" -> "1"
163            // and parse everything until eof as a PackageRelease, e.g.:
164            // "1" -> ""
165            let pkgrel: PackageRelease = PackageRelease::parser.parse_next(input)?;
166
167            Ok(Self {
168                epoch,
169                pkgver,
170                pkgrel,
171            })
172        };
173
174        parser.layer("full alpm-package-version").parse_next(input)
175    }
176
177    fn delimiter_error_context<'a, O, P>(
178        parser: P,
179    ) -> impl Parser<Input<'a>, O, ErrMode<ParseStack<'a>>>
180    where
181        P: Parser<Input<'a>, O, ErrMode<ParseStack<'a>>>,
182    {
183        parser
184            .description(concat!(
185                "The package version must end with a valid package release.\n",
186                "I.e. a positive integer followed by an optional `.` and another positive integer",
187            ))
188            .layer("full alpm-package-version")
189    }
190}
191
192impl Display for FullVersion {
193    /// Formats the [`FullVersion`].
194    ///
195    /// # Note
196    ///
197    /// If an [`Epoch`] exists, it is only written, if its value is not `0` (the value `0` is the
198    /// implied default and not shown).
199    fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result {
200        if let Some(epoch) = self.epoch
201            && epoch.0 != 0
202        {
203            write!(fmt, "{epoch}:")?;
204        }
205        write!(fmt, "{}-{}", self.pkgver, self.pkgrel)?;
206
207        Ok(())
208    }
209}
210
211impl FromStr for FullVersion {
212    type Err = Error;
213    /// Creates a new [`FullVersion`] from a string slice.
214    ///
215    /// Delegates to [`FullVersion::parser_until_eof`](ParserUntil::parser_until_eof).
216    ///
217    /// # Errors
218    ///
219    /// Returns an error if [`Version::parser`] fails.
220    fn from_str(s: &str) -> Result<Self, Self::Err> {
221        Ok(Self::parser_until_eof.parse(Input::new(s))?)
222    }
223}
224
225impl Ord for FullVersion {
226    /// Compares `self` to another [`FullVersion`].
227    ///
228    /// The comparison rules and algorithms are explained in more detail in [alpm-package-version]
229    /// and [alpm-pkgver].
230    ///
231    /// # Examples
232    ///
233    /// ```
234    /// use std::{cmp::Ordering, str::FromStr};
235    ///
236    /// use alpm_types::FullVersion;
237    ///
238    /// # fn main() -> testresult::TestResult {
239    /// // Examples for "full"
240    /// let version_a = FullVersion::from_str("1.0.0-1")?;
241    /// let version_b = FullVersion::from_str("1.0.0-2")?;
242    /// assert_eq!(version_a.cmp(&version_b), Ordering::Less);
243    /// assert_eq!(version_b.cmp(&version_a), Ordering::Greater);
244    ///
245    /// let version_a = FullVersion::from_str("1.0.0-1")?;
246    /// let version_b = FullVersion::from_str("1.0.0-1")?;
247    /// assert_eq!(version_a.cmp(&version_b), Ordering::Equal);
248    ///
249    /// // Examples for "full with epoch"
250    /// let version_a = FullVersion::from_str("1:1.0.0-1")?;
251    /// let version_b = FullVersion::from_str("1.0.0-2")?;
252    /// assert_eq!(version_a.cmp(&version_b), Ordering::Greater);
253    /// assert_eq!(version_b.cmp(&version_a), Ordering::Less);
254    ///
255    /// let version_a = FullVersion::from_str("1:1.0.0-1")?;
256    /// let version_b = FullVersion::from_str("1:1.0.0-1")?;
257    /// assert_eq!(version_a.cmp(&version_b), Ordering::Equal);
258    /// # Ok(())
259    /// # }
260    /// ```
261    ///
262    /// [alpm-package-version]: https://alpm.archlinux.page/specifications/alpm-package-version.7.html
263    /// [alpm-pkgver]: https://alpm.archlinux.page/specifications/alpm-pkgver.7.html
264    fn cmp(&self, other: &Self) -> Ordering {
265        match (self.epoch, other.epoch) {
266            (Some(self_epoch), Some(other_epoch)) if self_epoch.cmp(&other_epoch).is_ne() => {
267                return self_epoch.cmp(&other_epoch);
268            }
269            (Some(_), None) => return Ordering::Greater,
270            (None, Some(_)) => return Ordering::Less,
271            (_, _) => {}
272        }
273
274        let pkgver_cmp = self.pkgver.cmp(&other.pkgver);
275        if pkgver_cmp.is_ne() {
276            return pkgver_cmp;
277        }
278
279        self.pkgrel.cmp(&other.pkgrel)
280    }
281}
282
283impl PartialOrd for FullVersion {
284    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
285        Some(self.cmp(other))
286    }
287}
288
289impl TryFrom<Version> for FullVersion {
290    type Error = crate::Error;
291
292    /// Creates a [`FullVersion`] from a [`Version`].
293    ///
294    /// # Errors
295    ///
296    /// Returns an error if `value.pkgrel` is [`None`].
297    fn try_from(value: Version) -> Result<Self, Self::Error> {
298        Ok(Self {
299            pkgver: value.pkgver,
300            pkgrel: value.pkgrel.ok_or(Error::MissingComponent {
301                component: "pkgrel",
302            })?,
303            epoch: value.epoch,
304        })
305    }
306}
307
308impl TryFrom<&Version> for FullVersion {
309    type Error = crate::Error;
310
311    /// Creates a [`FullVersion`] from a [`Version`] reference.
312    ///
313    /// # Errors
314    ///
315    /// Returns an error if `value.pkgrel` is [`None`].
316    fn try_from(value: &Version) -> Result<Self, Self::Error> {
317        Self::try_from(value.clone())
318    }
319}
320
321impl From<FullVersion> for Version {
322    /// Creates a [`Version`] from a [`FullVersion`].
323    fn from(value: FullVersion) -> Self {
324        Self {
325            pkgver: value.pkgver,
326            pkgrel: Some(value.pkgrel),
327            epoch: value.epoch,
328        }
329    }
330}
331
332impl From<&FullVersion> for Version {
333    /// Creates a [`Version`] from a [`FullVersion`] reference.
334    fn from(value: &FullVersion) -> Self {
335        Self::from(value.clone())
336    }
337}
338
339#[cfg(test)]
340mod tests {
341    use insta::assert_snapshot;
342    use log::{LevelFilter, debug};
343    use rstest::rstest;
344    use simplelog::{ColorChoice, Config, TermLogger, TerminalMode};
345    use testresult::TestResult;
346
347    use super::*;
348    use crate::configure_insta;
349
350    /// Initialize a logger that shows trace messages on stderr.
351    fn init_logger() {
352        if TermLogger::init(
353            LevelFilter::Trace,
354            Config::default(),
355            TerminalMode::Stderr,
356            ColorChoice::Auto,
357        )
358        .is_err()
359        {
360            debug!("Not initializing another logger, as one is initialized already.");
361        }
362    }
363
364    /// Ensures that valid [`FullVersion`] strings are parsed successfully as expected.
365    #[rstest]
366    #[case::full_with_epoch(
367        "1:foo-1",
368        FullVersion {
369            pkgver: PackageVersion::from_str("foo")?,
370            epoch: Some(Epoch::from_str("1")?),
371            pkgrel: PackageRelease::from_str("1")?,
372        },
373    )]
374    #[case::full(
375        "foo-1",
376        FullVersion {
377            pkgver: PackageVersion::from_str("foo")?,
378            epoch: None,
379            pkgrel: PackageRelease::from_str("1")?
380        }
381    )]
382    fn valid_full_version_from_string(
383        #[case] version: &str,
384        #[case] expected: FullVersion,
385    ) -> TestResult {
386        init_logger();
387
388        assert_eq!(
389            FullVersion::from_str(version)?,
390            expected,
391            "Expected valid parsing for FullVersion {version}"
392        );
393
394        Ok(())
395    }
396
397    /// Ensures that invalid [`FullVersion`] strings lead to parse errors.
398    #[rstest]
399    #[case::two_pkgrel("1:foo-1-1")]
400    #[case::two_epoch("1:1:foo-1")]
401    #[case::empty_string("")]
402    #[case::colon(":")]
403    #[case::dot(".")]
404    #[case::no_pkgrel_with_epoch("1:1.0.0")]
405    #[case::no_pkgrel("1.0.0")]
406    #[case::no_pkgrel_dash_end("1.0.0-")]
407    #[case::starts_with_dash("-1foo:1")]
408    #[case::ends_with_colon("1-foo:")]
409    #[case::ends_with_colon_number("1-foo:1")]
410    fn parse_error_in_full_version_from_string(#[case] input: &str) {
411        init_logger();
412
413        let (test_name, _guard) = configure_insta();
414
415        let Err(Error::ParseError(err_msg)) = FullVersion::from_str(input) else {
416            panic!("'{input}' erroneously parsed as a FullVersion")
417        };
418
419        assert_snapshot!(test_name, err_msg.to_string());
420    }
421
422    /// Ensures that [`FullVersion`] can be created from a compatible [`Version`].
423    #[rstest]
424    #[case::full_with_epoch(Version::from_str("1:1.0.0-1")?, FullVersion::from_str("1:1.0.0-1")?)]
425    #[case::full(Version::from_str("1.0.0-1")?, FullVersion::from_str("1.0.0-1")?)]
426    fn full_version_try_from_version_succeeds(
427        #[case] version: Version,
428        #[case] expected: FullVersion,
429    ) -> TestResult {
430        assert_eq!(FullVersion::try_from(&version)?, expected);
431        Ok(())
432    }
433
434    /// Ensures that [`FullVersion`] fails to be created from an incompatible [`Version`].
435    #[rstest]
436    #[case::minimal_with_epoch(Version::from_str("1:1.0.0")?)]
437    #[case::minimal(Version::from_str("1.0.0")?)]
438    fn full_version_try_from_version_fails_on_incompatible_version(
439        #[case] version: Version,
440    ) -> TestResult {
441        let Err(Error::MissingComponent {
442            component: "pkgrel",
443        }) = FullVersion::try_from(&version)
444        else {
445            panic!("Expected to fail with Error::MissingComponent");
446        };
447
448        Ok(())
449    }
450
451    /// Ensures that [`Version`] can be created from [`FullVersion`] (and [`FullVersion`]
452    /// reference).
453    #[rstest]
454    #[case::full_with_epoch(Version::from_str("1:1.0.0-1")?, FullVersion::from_str("1:1.0.0-1")?)]
455    #[case::full(Version::from_str("1.0.0-1")?, FullVersion::from_str("1.0.0-1")?)]
456    fn version_from_full_version(
457        #[case] version: Version,
458        #[case] full_version: FullVersion,
459    ) -> TestResult {
460        assert_eq!(Version::from(&full_version), version);
461        Ok(())
462    }
463
464    /// Ensures that [`FullVersion`] is properly serialized back to its string representation.
465    #[rstest]
466    #[case::with_epoch("1:1-1")]
467    #[case::plain("1-1")]
468    fn full_version_to_string(#[case] input: &str) -> TestResult {
469        assert_eq!(format!("{}", FullVersion::from_str(input)?), input);
470        Ok(())
471    }
472
473    /// Ensures that [`FullVersion`]s can be compared.
474    ///
475    /// For more detailed version comparison tests refer to the unit tests for [`Version`] and
476    /// [`PackageRelease`].
477    #[rstest]
478    #[case::full_equal("1.0.0-1", "1.0.0-1", Ordering::Equal)]
479    #[case::full_less("1.0.0-1", "1.0.0-2", Ordering::Less)]
480    #[case::full_greater("1.0.0-2", "1.0.0-1", Ordering::Greater)]
481    #[case::full_with_epoch_equal("1:1.0.0-1", "1:1.0.0-1", Ordering::Equal)]
482    #[case::full_with_epoch_less("1.0.0-1", "1:1.0.0-1", Ordering::Less)]
483    #[case::full_with_epoch_less("1:1.0.0-1", "2:1.0.0-1", Ordering::Less)]
484    #[case::full_with_epoch_greater("1:1.0.0-1", "1.0.0-1", Ordering::Greater)]
485    #[case::full_with_epoch_greater("2:1.0.0-1", "1:1.0.0-1", Ordering::Greater)]
486    fn full_version_comparison(
487        #[case] version_a: &str,
488        #[case] version_b: &str,
489        #[case] expected: Ordering,
490    ) -> TestResult {
491        let version_a = FullVersion::from_str(version_a)?;
492        let version_b = FullVersion::from_str(version_b)?;
493
494        // Derive the expected vercmp binary exitcode from the expected Ordering.
495        let vercmp_result = match &expected {
496            Ordering::Equal => 0,
497            Ordering::Greater => 1,
498            Ordering::Less => -1,
499        };
500
501        let ordering = version_a.cmp(&version_b);
502        assert_eq!(
503            ordering, expected,
504            "Failed to compare '{version_a}' and '{version_b}'. Expected {expected:?} got {ordering:?}"
505        );
506
507        assert_eq!(version_a.vercmp(&version_b), vercmp_result);
508
509        // If we find the `vercmp` binary, also run the test against the actual binary.
510        #[cfg(feature = "_compatibility_tests")]
511        {
512            let output = std::process::Command::new("vercmp")
513                .arg(version_a.to_string())
514                .arg(version_b.to_string())
515                .output()?;
516            let result = String::from_utf8_lossy(&output.stdout);
517            assert_eq!(result.trim(), vercmp_result.to_string());
518        }
519
520        // Now check that the opposite holds true as well.
521        let reverse_vercmp_result = match &expected {
522            Ordering::Equal => 0,
523            Ordering::Greater => -1,
524            Ordering::Less => 1,
525        };
526        let reverse_expected = match &expected {
527            Ordering::Equal => Ordering::Equal,
528            Ordering::Greater => Ordering::Less,
529            Ordering::Less => Ordering::Greater,
530        };
531
532        let reverse_ordering = version_b.cmp(&version_a);
533        assert_eq!(
534            reverse_ordering, reverse_expected,
535            "Failed to compare '{version_a}' and '{version_b}'. Expected {expected:?} got {ordering:?}"
536        );
537
538        assert_eq!(version_b.vercmp(&version_a), reverse_vercmp_result);
539
540        Ok(())
541    }
542}