reproto_core/
rp_versioned_package.rs

1//! A versioned package declaration
2
3use errors::Result;
4use std::borrow::Cow;
5use std::collections::HashMap;
6use std::fmt;
7use {AsPackage, RpPackage, RpPackageFormat, Version};
8
9#[derive(Debug, Serialize, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
10pub struct RpVersionedPackage {
11    pub package: RpPackage,
12    #[serde(skip_serializing_if = "Option::is_none")]
13    pub version: Option<Version>,
14}
15
16impl AsPackage for RpVersionedPackage {
17    /// Convert into a package by piping the version through the provided function.
18    fn try_as_package<'a>(&'a self) -> Result<Cow<'a, RpPackage>> {
19        Ok(Cow::Owned(self.to_package(|v| {
20            v.to_string()
21        })))
22    }
23
24    fn prefix_with(self, prefix: RpPackage) -> Self {
25        prefix.join_versioned(self)
26    }
27}
28
29impl RpVersionedPackage {
30    pub fn new(package: RpPackage, version: Option<Version>) -> RpVersionedPackage {
31        RpVersionedPackage {
32            package: package,
33            version: version,
34        }
35    }
36
37    /// Convert into a package by piping the version through the provided function.
38    pub fn to_package<V>(&self, version_fn: V) -> RpPackage
39    where
40        V: FnOnce(&Version) -> String,
41    {
42        let mut parts = Vec::new();
43
44        parts.extend(self.package.parts().cloned());
45
46        if let Some(ref version) = self.version {
47            parts.push(version_fn(version));
48        }
49
50        RpPackage::new(parts)
51    }
52
53    pub fn without_version(self) -> RpVersionedPackage {
54        RpVersionedPackage::new(self.package, None)
55    }
56
57    /// Replace all keyword components in this package.
58    pub fn with_replacements(self, keywords: &HashMap<String, String>) -> Self {
59        Self {
60            package: self.package.with_replacements(keywords),
61            ..self
62        }
63    }
64
65    /// Apply the given naming policy to this package.
66    pub fn with_naming<N>(self, naming: N) -> Self
67    where
68        N: Fn(&str) -> String,
69    {
70        Self {
71            package: self.package.with_naming(naming),
72            ..self
73        }
74    }
75}
76
77impl fmt::Display for RpVersionedPackage {
78    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
79        RpPackageFormat(&self.package, self.version.as_ref()).fmt(f)
80    }
81}