Skip to main content

lux_lib/package/version/
mod.rs

1use std::{
2    cmp::{self, Ordering},
3    fmt::Display,
4    str::FromStr,
5};
6
7use itertools::Itertools;
8use miette::Diagnostic;
9use nonempty::NonEmpty;
10use semver::{Comparator, Error as SemverError, Op, Prerelease};
11use serde::{de, Deserialize, Deserializer, Serialize};
12use thiserror::Error;
13
14mod req;
15mod spec_rev;
16mod upgrade;
17
18use spec_rev::split_specrev;
19
20pub use req::{FromReqError, ReqError, VersionReq};
21pub(crate) use spec_rev::SpecRevIterator;
22pub use spec_rev::{SpecRev, SpecRevParseError};
23
24#[derive(Clone, Eq, PartialEq, Hash, Debug)]
25pub enum Version {
26    /// **SemVer version** as defined by <https://semver.org>,
27    /// but a bit more lenient for compatibility with luarocks
28    SemVer(SemVer),
29    /// A known **Dev** version
30    DevVer(DevVer),
31    /// An arbitrary string version.
32    /// Yes, luarocks-site allows arbitrary string versions in the root manifest
33    /// ┻━┻ ︵ヽ(`Д´)ノ︵ ┻━┻
34    StringVer(StringVer),
35}
36
37impl HasModRev for Version {
38    fn to_modrev_string(&self) -> String {
39        match self {
40            Self::SemVer(ver) => ver.to_modrev_string(),
41            Self::DevVer(ver) => ver.to_modrev_string(),
42            Self::StringVer(ver) => ver.to_modrev_string(),
43        }
44    }
45}
46
47impl Version {
48    pub fn parse(text: &str) -> Result<Self, Error> {
49        Version::from_str(text)
50    }
51    /// The package version without its spec revision.
52    pub fn to_version_string(&self) -> String {
53        self.to_modrev_string()
54    }
55    /// Note that this loses the specrev information.
56    pub fn into_version_req(&self) -> VersionReq {
57        match self {
58            Version::DevVer(DevVer { modrev, .. }) => VersionReq::DevVer(modrev.to_owned()),
59            Version::StringVer(StringVer { modrev, .. }) => {
60                VersionReq::StringVer(modrev.to_owned())
61            }
62            Version::SemVer(SemVer { version, .. }) => {
63                let version = version.to_owned();
64                VersionReq::SemVer(semver::VersionReq {
65                    comparators: vec![Comparator {
66                        op: Op::Exact,
67                        major: version.major,
68                        minor: Some(version.minor),
69                        patch: Some(version.patch),
70                        pre: version.pre,
71                    }],
72                })
73            }
74        }
75    }
76
77    /// A `~>` version requirement that allows non-breaking updates, or `None` if this is
78    /// not a SemVer version.
79    /// Following the SemVer conventions around zero versions, the most significant non-zero
80    /// component is kept, so that only the components to its right may change.
81    pub(crate) fn to_pessimistic_version_req(&self) -> Option<String> {
82        let Version::SemVer(sem_ver) = self else {
83            return None;
84        };
85        let version = &sem_ver.version;
86        Some(match (version.major, version.minor) {
87            (0, 0) => format!("~> 0.0.{}", version.patch),
88            (0, minor) => format!("~> 0.{minor}"),
89            (major, _) => format!("~> {major}"),
90        })
91    }
92
93    pub(crate) fn is_semver(&self) -> bool {
94        matches!(self, Version::SemVer(_))
95    }
96
97    pub(crate) fn default_dev_version() -> Self {
98        Self::DevVer(DevVer::default())
99    }
100
101    pub(crate) fn default_dev_version_with_specrev(specrev: SpecRev) -> Self {
102        Self::DevVer(DevVer::default_with_specrev(specrev))
103    }
104
105    pub(crate) fn with_specrev(mut self, specrev: SpecRev) -> Self {
106        match &mut self {
107            Self::SemVer(version) => version.specrev = specrev,
108            Self::DevVer(version) => version.specrev = specrev,
109            Self::StringVer(version) => version.specrev = specrev,
110        }
111        self
112    }
113}
114
115impl TryFrom<VersionReq> for Version {
116    type Error = FromReqError;
117
118    fn try_from(req: VersionReq) -> Result<Self, Self::Error> {
119        match req {
120            VersionReq::SemVer(version_req) => {
121                match NonEmpty::try_from(version_req.comparators.clone()) {
122                    Ok(comparators)
123                        if comparators
124                            .iter()
125                            .any(|comparator| comparator.op != semver::Op::Exact) =>
126                    {
127                        Err(FromReqError::NonExactVersionReq(VersionReq::SemVer(
128                            version_req,
129                        )))
130                    }
131                    Ok(comparators) => {
132                        let comparator = comparators.first();
133                        let version = semver::Version {
134                            major: comparator.major,
135                            minor: comparator.minor.unwrap_or(0),
136                            patch: comparator.patch.unwrap_or(0),
137                            pre: comparator.pre.clone(),
138                            build: semver::BuildMetadata::EMPTY,
139                        };
140                        Ok(Version::SemVer(SemVer {
141                            version,
142                            component_count: comparator_component_count(comparator),
143                            specrev: 1.into(),
144                        }))
145                    }
146                    Err(_) => Err(FromReqError::NonExactVersionReq(VersionReq::SemVer(
147                        version_req,
148                    ))),
149                }
150            }
151            VersionReq::DevVer(modrev) => Ok(Version::DevVer(DevVer {
152                modrev,
153                specrev: 1.into(),
154            })),
155            VersionReq::StringVer(modrev) => Ok(Version::StringVer(StringVer {
156                modrev,
157                specrev: 1.into(),
158            })),
159            except @ VersionReq::SemVerExcept { .. } => {
160                Err(FromReqError::NonExactVersionReq(except))
161            }
162            VersionReq::Any => Err(FromReqError::Any),
163        }
164    }
165}
166
167#[derive(Error, Debug, Diagnostic)]
168#[non_exhaustive]
169pub enum Error {
170    #[error(transparent)]
171    #[diagnostic(transparent)]
172    Specrev(#[from] SpecRevParseError),
173    #[error("failed to parse version")]
174    Version(#[from] SemverError),
175}
176
177impl Serialize for Version {
178    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
179    where
180        S: serde::Serializer,
181    {
182        match self {
183            Version::SemVer(version) => version.serialize(serializer),
184            Version::DevVer(version) => version.serialize(serializer),
185            Version::StringVer(version) => version.serialize(serializer),
186        }
187    }
188}
189
190impl<'de> Deserialize<'de> for Version {
191    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
192    where
193        D: Deserializer<'de>,
194    {
195        let s = String::deserialize(deserializer)?;
196        Self::from_str(&s).map_err(de::Error::custom)
197    }
198}
199
200impl Display for Version {
201    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202        match self {
203            Version::SemVer(version) => version.fmt(f),
204            Version::DevVer(version) => version.fmt(f),
205            Version::StringVer(version) => version.fmt(f),
206        }
207    }
208}
209
210impl PartialOrd for Version {
211    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
212        Some(self.cmp(other))
213    }
214}
215
216impl Ord for Version {
217    fn cmp(&self, other: &Self) -> Ordering {
218        match (self, other) {
219            (Version::SemVer(a), Version::SemVer(b)) => a.cmp(b),
220            (Version::SemVer(..), Version::DevVer(..)) => Ordering::Less,
221            (Version::SemVer(..), Version::StringVer(..)) => Ordering::Greater,
222            (Version::DevVer(..), Version::SemVer(..)) => Ordering::Greater,
223            (Version::DevVer(a), Version::DevVer(b)) => a.cmp(b),
224            (Version::DevVer(..), Version::StringVer(..)) => Ordering::Greater,
225            (Version::StringVer(a), Version::StringVer(b)) => a.cmp(b),
226            (Version::StringVer(..), Version::SemVer(..)) => Ordering::Less,
227            (Version::StringVer(..), Version::DevVer(..)) => Ordering::Less,
228        }
229    }
230}
231
232impl FromStr for Version {
233    type Err = Error;
234
235    fn from_str(text: &str) -> Result<Self, Self::Err> {
236        let (modrev, specrev) = split_specrev(text)?;
237        match modrev {
238            "scm" => Ok(Version::DevVer(DevVer {
239                modrev: DevVersion::Scm,
240                specrev,
241            })),
242            "dev" => Ok(Version::DevVer(DevVer {
243                modrev: DevVersion::Dev,
244                specrev,
245            })),
246            modrev => match parse_version(modrev) {
247                Ok(version) => Ok(Version::SemVer(SemVer {
248                    component_count: cmp::min(text.chars().filter(|c| *c == '.').count() + 1, 3),
249                    version,
250                    specrev,
251                })),
252                Err(_) => Ok(Version::StringVer(StringVer {
253                    modrev: modrev.into(),
254                    specrev,
255                })),
256            },
257        }
258    }
259}
260
261// TODO: Stop deriving Eq here
262
263#[derive(Clone, Eq, PartialEq, Hash, Debug)]
264pub struct SemVer {
265    pub(crate) version: semver::Version,
266    pub(crate) component_count: usize,
267    pub(crate) specrev: SpecRev,
268}
269
270impl HasModRev for SemVer {
271    fn to_modrev_string(&self) -> String {
272        self.version.to_string()
273    }
274}
275
276impl Display for SemVer {
277    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278        if self
279            .version
280            .pre
281            .as_str()
282            .chars()
283            .any(|c| c.is_ascii_alphabetic())
284        {
285            // pre-release instead of specrev
286            return self.version.fmt(f);
287        }
288        let (version_str, remainder) = split_semver_version(&self.version.to_string());
289        let mut luarocks_version_str = version_str.split('.').take(self.component_count).join(".");
290        if let Some(remainder) = remainder {
291            // luarocks allows and arbitrary number of '.' separators
292            // We treat anything after the third '.' as a semver prerelease/build version,
293            // so we have to convert it back for luarocks.
294            luarocks_version_str.push_str(&format!(".{remainder}"));
295        }
296        let str = format!("{}-{}", luarocks_version_str, self.specrev);
297        str.fmt(f)
298    }
299}
300
301fn split_semver_version(version_str: &str) -> (String, Option<String>) {
302    if let Some(pos) = version_str.rfind('-') {
303        if let Some(pre_build_str) = version_str.get(pos + 1..) {
304            (version_str[..pos].into(), Some(pre_build_str.into()))
305        } else {
306            (version_str[..pos].into(), None)
307        }
308    } else {
309        (version_str.into(), None)
310    }
311}
312
313impl Serialize for SemVer {
314    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
315    where
316        S: serde::Serializer,
317    {
318        self.to_string().serialize(serializer)
319    }
320}
321
322impl Ord for SemVer {
323    fn cmp(&self, other: &Self) -> Ordering {
324        match cmp_versions(&self.version, &other.version) {
325            Ordering::Equal => self.specrev.cmp(&other.specrev),
326            ord => ord,
327        }
328    }
329}
330
331/// Compare two LuaRocks versions.
332/// ┻━┻ ︵╰(°□°╰) Luarocks allows for an arbitrary number of version digits (e.g. `2.1.0.10`),
333/// which Lux treats as a SemVer prerelease.
334fn cmp_versions(a: &semver::Version, b: &semver::Version) -> Ordering {
335    match (a.major, a.minor, a.patch).cmp(&(b.major, b.minor, b.patch)) {
336        Ordering::Equal => cmp_prerelease(&a.pre, &b.pre),
337        ord => ord,
338    }
339}
340
341pub(super) fn comparator_component_count(comparator: &Comparator) -> usize {
342    if comparator.patch.is_some() {
343        3
344    } else if comparator.minor.is_some() {
345        2
346    } else {
347        1
348    }
349}
350
351impl PartialOrd for SemVer {
352    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
353        Some(self.cmp(other))
354    }
355}
356
357#[derive(Clone, Eq, PartialEq, PartialOrd, Ord, Hash, Debug, Serialize, Deserialize, Default)]
358#[serde(rename_all = "lowercase")]
359pub enum DevVersion {
360    #[default]
361    Dev,
362    Scm,
363}
364
365impl Display for DevVersion {
366    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
367        match self {
368            Self::Dev => "dev".fmt(f),
369            Self::Scm => "scm".fmt(f),
370        }
371    }
372}
373
374#[derive(Clone, Eq, PartialEq, Hash, Debug, Default)]
375pub struct DevVer {
376    pub(crate) modrev: DevVersion,
377    pub(crate) specrev: SpecRev,
378}
379
380impl DevVer {
381    fn default_with_specrev(specrev: SpecRev) -> Self {
382        Self {
383            modrev: DevVersion::default(),
384            specrev,
385        }
386    }
387}
388
389impl HasModRev for DevVer {
390    fn to_modrev_string(&self) -> String {
391        self.modrev.to_string().to_lowercase()
392    }
393}
394
395impl Display for DevVer {
396    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
397        let str = format!("{}-{}", self.modrev, self.specrev);
398        str.fmt(f)
399    }
400}
401
402impl Serialize for DevVer {
403    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
404    where
405        S: serde::Serializer,
406    {
407        self.to_string().serialize(serializer)
408    }
409}
410
411impl Ord for DevVer {
412    fn cmp(&self, other: &Self) -> Ordering {
413        // NOTE: We compare specrevs first for dev versions
414        let result = self.specrev.cmp(&other.specrev);
415        if result == Ordering::Equal {
416            return self.modrev.cmp(&other.modrev);
417        }
418        result
419    }
420}
421
422impl PartialOrd for DevVer {
423    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
424        Some(self.cmp(other))
425    }
426}
427
428#[derive(Clone, Eq, PartialEq, Hash, Debug)]
429pub struct StringVer {
430    pub(crate) modrev: String,
431    pub(crate) specrev: SpecRev,
432}
433
434impl HasModRev for StringVer {
435    fn to_modrev_string(&self) -> String {
436        self.modrev.to_string()
437    }
438}
439
440impl Display for StringVer {
441    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
442        let str = format!("{}-{}", self.modrev, self.specrev);
443        str.fmt(f)
444    }
445}
446
447impl Serialize for StringVer {
448    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
449    where
450        S: serde::Serializer,
451    {
452        self.to_string().serialize(serializer)
453    }
454}
455
456impl Ord for StringVer {
457    fn cmp(&self, other: &Self) -> Ordering {
458        // NOTE: We compare specrevs first for dev versions
459        let result = self.specrev.cmp(&other.specrev);
460        if result == Ordering::Equal {
461            return self.modrev.cmp(&other.modrev);
462        }
463        result
464    }
465}
466
467impl PartialOrd for StringVer {
468    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
469        Some(self.cmp(other))
470    }
471}
472
473pub(crate) trait HasModRev {
474    /// If a version has a modrev (and possibly a specrev),
475    /// this is equivalent to `to_string()`, but includes only the modrev.
476    fn to_modrev_string(&self) -> String;
477}
478
479/// Parses a Version from a string, automatically supplying any missing details (i.e. missing
480/// minor/patch sections).
481fn parse_version(s: &str) -> Result<semver::Version, SemverError> {
482    let version_str = correct_version_string(s);
483    semver::Version::parse(&version_str)
484}
485
486fn cmp_prerelease(a: &Prerelease, b: &Prerelease) -> Ordering {
487    match (a.is_empty(), b.is_empty()) {
488        (true, true) => Ordering::Equal,
489        (false, true) => Ordering::Greater,
490        (true, false) => Ordering::Less,
491        (false, false) => a.cmp(b),
492    }
493}
494
495/// ┻━┻ ︵╰(°□°╰) Luarocks allows for an arbitrary number of version digits
496/// This function attempts to correct a non-semver compliant version string,
497/// by swapping the third '.' out with a '-', converting the non-semver
498/// compliant digits to a pre-release identifier.
499fn correct_version_string(version: &str) -> String {
500    let version = append_minor_patch_if_missing(version);
501    correct_prerelease_version_string(&version)
502}
503
504fn correct_prerelease_version_string(version: &str) -> String {
505    if version.contains('-') {
506        return version.to_string();
507    }
508    let parts: Vec<&str> = version.split('.').collect();
509    if parts.len() > 3 {
510        format!(
511            "{}.{}.{}-{}",
512            parts[0],
513            parts[1],
514            parts[2],
515            parts[3..].join(".")
516        )
517    } else {
518        version.to_string()
519    }
520}
521
522/// Recursively append .0 until the version string has a minor or patch version
523fn append_minor_patch_if_missing(version: &str) -> String {
524    if version.matches('.').count() < 2 {
525        append_minor_patch_if_missing(&format!("{version}.0"))
526    } else {
527        version.to_string()
528    }
529}
530
531#[cfg(test)]
532mod tests {
533    use super::*;
534
535    #[test]
536    fn parse_semver_version() {
537        assert_eq!(
538            Version::parse("1-1").unwrap(),
539            Version::SemVer(SemVer {
540                version: "1.0.0".parse().unwrap(),
541                component_count: 1,
542                specrev: 1.into(),
543            })
544        );
545        assert_eq!(
546            Version::parse("1.0-1").unwrap(),
547            Version::SemVer(SemVer {
548                version: "1.0.0".parse().unwrap(),
549                component_count: 2,
550                specrev: 1.into(),
551            })
552        );
553        assert_eq!(
554            Version::parse("1.0.0-1").unwrap(),
555            Version::SemVer(SemVer {
556                version: "1.0.0".parse().unwrap(),
557                component_count: 3,
558                specrev: 1.into()
559            })
560        );
561        assert_eq!(
562            Version::parse("1.0.0-1").unwrap(),
563            Version::SemVer(SemVer {
564                version: "1.0.0".parse().unwrap(),
565                component_count: 3,
566                specrev: 1.into()
567            })
568        );
569        assert_eq!(
570            Version::parse("1.0.0-10-1").unwrap(),
571            Version::SemVer(SemVer {
572                version: "1.0.0-10".parse().unwrap(),
573                component_count: 3,
574                specrev: 1.into()
575            })
576        );
577        assert_eq!(
578            Version::parse("1.0.0.10-1").unwrap(),
579            Version::SemVer(SemVer {
580                version: "1.0.0-10".parse().unwrap(),
581                component_count: 3,
582                specrev: 1.into()
583            })
584        );
585        assert_eq!(
586            Version::parse("1.0.0.10.0-1").unwrap(),
587            Version::SemVer(SemVer {
588                version: "1.0.0-10.0".parse().unwrap(),
589                component_count: 3,
590                specrev: 1.into()
591            })
592        );
593    }
594
595    #[test]
596    fn to_pessimistic_version_req() {
597        for (version, req, expected) in [
598            ("1.5.6-2", "~> 1", ">=1.0.0, <2.0.0"),
599            ("0.5.6-2", "~> 0.5", ">=0.5.0, <0.6.0"),
600            ("0.0.6-2", "~> 0.0.6", ">=0.0.6, <0.0.7"),
601        ] {
602            let pessimistic = Version::parse(version)
603                .unwrap()
604                .to_pessimistic_version_req()
605                .unwrap();
606            assert_eq!(pessimistic, req);
607            let req = VersionReq::parse(&pessimistic).unwrap();
608            assert_eq!(req.to_string(), expected);
609        }
610
611        let req = VersionReq::parse("~> 1").unwrap();
612        assert!(req.matches(&Version::parse("1.9.0-2").unwrap()));
613        assert!(!req.matches(&Version::parse("2.0.0-1").unwrap()));
614
615        let req = VersionReq::parse("~> 0.5").unwrap();
616        assert!(req.matches(&Version::parse("0.5.9-1").unwrap()));
617        assert!(!req.matches(&Version::parse("0.6.0-1").unwrap()));
618
619        assert_eq!(
620            Version::parse("scm").unwrap().to_pessimistic_version_req(),
621            None
622        );
623    }
624
625    #[test]
626    fn four_component_versions_sort_after_base_version() {
627        let base = Version::parse("2.1.0-1").unwrap();
628        let extended = Version::parse("2.1.0.10-1").unwrap();
629        assert!(extended > base);
630        assert!(base < extended);
631        assert_eq!(
632            Version::parse("2.1.0.10-1").unwrap(),
633            Version::parse("2.1.0.10-1").unwrap()
634        );
635    }
636
637    #[test]
638    fn four_component_version_satisfies_greater_eq_req() {
639        let req = VersionReq::parse(">= 2.1.0").unwrap();
640        assert!(req.matches(&Version::parse("2.1.0.10-1").unwrap()));
641        assert!(req.matches(&Version::parse("2.1.0-1").unwrap()));
642        assert!(!req.matches(&Version::parse("2.0.9-1").unwrap()));
643    }
644
645    #[test]
646    fn parse_semver_prerelease() {
647        let prerelease = Version::parse("1.2.3-alpha.1").unwrap();
648        assert_eq!(
649            prerelease,
650            Version::SemVer(SemVer {
651                version: "1.2.3-alpha.1".parse().unwrap(),
652                component_count: 3,
653                specrev: 1.into()
654            })
655        );
656        assert_eq!(prerelease.to_string(), "1.2.3-alpha.1");
657        assert_eq!(Version::parse("1.2.3-1").unwrap().to_string(), "1.2.3-1");
658        assert_eq!(Version::parse(&prerelease.to_string()).unwrap(), prerelease);
659    }
660
661    #[test]
662    fn prerelease_req_matches() {
663        let req = VersionReq::parse("=1.2.3-alpha.1").unwrap();
664        assert!(req.matches(&Version::parse("1.2.3-alpha.1").unwrap()));
665        assert!(!req.matches(&Version::parse("1.2.3-alpha.2").unwrap()));
666    }
667
668    #[test]
669    fn parse_dev_version() {
670        assert_eq!(
671            Version::parse("dev-1").unwrap(),
672            Version::DevVer(DevVer {
673                modrev: DevVersion::Dev,
674                specrev: 1.into()
675            })
676        );
677        assert_eq!(
678            Version::parse("scm-1").unwrap(),
679            Version::DevVer(DevVer {
680                modrev: DevVersion::Scm,
681                specrev: 1.into()
682            })
683        );
684        assert_eq!(
685            Version::parse("git-1").unwrap(),
686            Version::StringVer(StringVer {
687                modrev: "git".into(),
688                specrev: 1.into()
689            })
690        );
691        assert_eq!(
692            Version::parse("scm-1").unwrap(),
693            Version::DevVer(DevVer {
694                modrev: DevVersion::Scm,
695                specrev: 1.into()
696            })
697        );
698    }
699
700    #[test]
701    fn parse_dev_version_req() {
702        assert_eq!(
703            VersionReq::parse("dev").unwrap(),
704            VersionReq::DevVer(DevVersion::Dev)
705        );
706        assert_eq!(
707            VersionReq::parse("scm").unwrap(),
708            VersionReq::DevVer(DevVersion::Scm)
709        );
710        assert_eq!(
711            VersionReq::parse("git").unwrap(),
712            VersionReq::StringVer("git".into())
713        );
714        assert_eq!(
715            VersionReq::parse("==dev").unwrap(),
716            VersionReq::DevVer(DevVersion::Dev)
717        );
718        assert_eq!(
719            VersionReq::parse("==git").unwrap(),
720            VersionReq::StringVer("git".into())
721        );
722        assert_eq!(
723            VersionReq::parse("== dev").unwrap(),
724            VersionReq::DevVer(DevVersion::Dev)
725        );
726        assert_eq!(
727            VersionReq::parse("== scm").unwrap(),
728            VersionReq::DevVer(DevVersion::Scm)
729        );
730        assert_eq!(
731            VersionReq::parse("@dev").unwrap(),
732            VersionReq::DevVer(DevVersion::Dev)
733        );
734        assert_eq!(
735            VersionReq::parse("@git").unwrap(),
736            VersionReq::StringVer("git".into())
737        );
738        assert_eq!(
739            VersionReq::parse("@ dev").unwrap(),
740            VersionReq::DevVer(DevVersion::Dev)
741        );
742        assert_eq!(
743            VersionReq::parse("@ scm").unwrap(),
744            VersionReq::DevVer(DevVersion::Scm)
745        );
746        assert_eq!(
747            VersionReq::parse(">1-1,<1.2-2").unwrap(),
748            VersionReq::SemVer(">1,<1.2".parse().unwrap())
749        );
750        assert_eq!(
751            VersionReq::parse("> 1-1, < 1.2-2").unwrap(),
752            VersionReq::SemVer("> 1, < 1.2".parse().unwrap())
753        );
754        assert_eq!(
755            VersionReq::parse("> 2.1.0.10, < 2.1.1").unwrap(),
756            VersionReq::SemVer("> 2.1.0-10, < 2.1.1".parse().unwrap())
757        );
758    }
759
760    #[test]
761    fn parse_any_version_req() {
762        assert_eq!(VersionReq::parse("*").unwrap(), VersionReq::Any);
763    }
764
765    #[test]
766    fn not_equal_version_req() {
767        let req = VersionReq::parse("~= 1.5").unwrap();
768        assert!(req.matches(&Version::parse("1.4.0").unwrap()));
769        assert!(req.matches(&Version::parse("1.6.0").unwrap()));
770        assert!(!req.matches(&Version::parse("1.5.0").unwrap()));
771        assert!(!req.matches(&Version::parse("1.5.0-1").unwrap()));
772        assert_eq!(req.to_string(), "~= 1.5.0");
773        assert_eq!(req, VersionReq::parse("!= 1.5").unwrap());
774
775        let req = VersionReq::parse(">= 1.0, ~= 1.5").unwrap();
776        assert!(req.matches(&Version::parse("1.4.0").unwrap()));
777        assert!(!req.matches(&Version::parse("1.5.0").unwrap()));
778        assert!(!req.matches(&Version::parse("0.9.0").unwrap()));
779        assert_eq!(req.to_string(), ">=1.0, ~= 1.5.0");
780        assert_eq!(VersionReq::parse(&req.to_string()).unwrap(), req);
781
782        let req = VersionReq::parse("~= 1.5, ~= 2.0").unwrap();
783        assert_eq!(req.to_string(), "~= 1.5.0, ~= 2.0.0");
784    }
785
786    #[test]
787    fn package_version_req_semver_roundtrips() {
788        let req = VersionReq::parse("==0.7.1").unwrap();
789        assert_eq!(req.to_string(), "==0.7.1");
790
791        let req = VersionReq::parse("0.7.1").unwrap();
792        assert_eq!(req.to_string(), "==0.7.1");
793
794        let req = VersionReq::parse(">=0.7.1").unwrap();
795        assert_eq!(req.to_string(), ">=0.7.1");
796
797        let req = VersionReq::parse(">0.7.1").unwrap();
798        assert_eq!(req.to_string(), ">0.7.1");
799
800        let req = VersionReq::parse("<0.7.1").unwrap();
801        assert_eq!(req.to_string(), "<0.7.1");
802
803        let req = VersionReq::parse("~> 0.7.1").unwrap();
804        assert_eq!(req.to_string(), ">=0.7.1, <0.7.2");
805    }
806
807    #[test]
808    fn package_version_req_devver_roundtrips() {
809        let req = VersionReq::parse("==scm").unwrap();
810        assert_eq!(req.to_string(), "==scm");
811
812        let req = VersionReq::parse("@scm").unwrap();
813        assert_eq!(req.to_string(), "==scm");
814
815        let req = VersionReq::parse("scm").unwrap();
816        assert_eq!(req.to_string(), "==scm");
817
818        let req = VersionReq::parse("==a144124839f027a2d0a95791936c478d047126fc").unwrap();
819        assert_eq!(
820            req.to_string(),
821            "==a144124839f027a2d0a95791936c478d047126fc"
822        );
823    }
824}