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
//! A versioned package declaration

use errors::Result;
use std::collections::HashMap;
use std::fmt;
use {AsPackage, RpPackage, RpPackageFormat, Version};

#[derive(Debug, Serialize, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RpVersionedPackage {
    pub package: RpPackage,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<Version>,
}

impl AsPackage for RpVersionedPackage {
    /// Convert into a package by piping the version through the provided function.
    fn try_as_package(&self) -> Result<&RpPackage> {
        Err("cannot be converted".into())
    }

    fn prefix_with(self, prefix: RpPackage) -> Self {
        prefix.join_versioned(self)
    }
}

impl RpVersionedPackage {
    pub fn new(package: RpPackage, version: Option<Version>) -> RpVersionedPackage {
        RpVersionedPackage {
            package: package,
            version: version,
        }
    }

    /// Convert into a package by piping the version through the provided function.
    pub fn to_package<V>(&self, version_fn: V) -> RpPackage
    where
        V: FnOnce(&Version) -> String,
    {
        let mut parts = Vec::new();

        parts.extend(self.package.parts().cloned());

        if let Some(ref version) = self.version {
            parts.push(version_fn(version));
        }

        RpPackage::new(parts)
    }

    pub fn without_version(self) -> RpVersionedPackage {
        RpVersionedPackage::new(self.package, None)
    }

    /// Replace all keyword components in this package.
    pub fn with_replacements(self, keywords: &HashMap<String, String>) -> Self {
        Self {
            package: self.package.with_replacements(keywords),
            ..self
        }
    }

    /// Apply the given naming policy to this package.
    pub fn with_naming<N>(self, naming: N) -> Self
    where
        N: Fn(&str) -> String,
    {
        Self {
            package: self.package.with_naming(naming),
            ..self
        }
    }
}

impl fmt::Display for RpVersionedPackage {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        RpPackageFormat(&self.package, self.version.as_ref()).fmt(f)
    }
}