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