version_spec/
unresolved_spec.rs

1#![allow(clippy::from_over_into)]
2
3use crate::spec_error::SpecError;
4use crate::unresolved_parser::*;
5use crate::version_types::*;
6use crate::{VersionSpec, clean_version_req_string, clean_version_string, is_alias_name};
7use compact_str::CompactString;
8use human_sort::compare;
9use semver::Prerelease;
10use semver::VersionReq;
11use serde::{Deserialize, Serialize};
12use std::cmp::Ordering;
13use std::fmt::{Debug, Display};
14use std::str::FromStr;
15
16/// Represents an unresolved version or alias that must be resolved
17/// to a fully-qualified version.
18#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
19#[serde(untagged, into = "String", try_from = "String")]
20pub enum UnresolvedVersionSpec {
21    /// A special canary target.
22    Canary,
23    /// An alias that is used as a map to a version.
24    Alias(CompactString),
25    /// A partial version, requirement, or range (`^`, `~`, etc).
26    Req(VersionReq),
27    /// A list of requirements to match any against (joined by `||`).
28    ReqAny(Vec<VersionReq>),
29    /// A fully-qualified calendar version.
30    Calendar(CalVer),
31    /// A fully-qualified semantic version.
32    Semantic(SemVer),
33}
34
35impl UnresolvedVersionSpec {
36    /// Parse the provided string into an unresolved specification based
37    /// on the following rules, in order:
38    ///
39    /// - If the value "canary", map as `Canary` variant.
40    /// - If an alpha-numeric value that starts with a character, map as `Alias`.
41    /// - If contains `||`, split and parse each item with [`VersionReq`],
42    ///   and map as `ReqAny`.
43    /// - If contains `,` or ` ` (space), parse with [`VersionReq`], and map as `Req`.
44    /// - If starts with `=`, `^`, `~`, `>`, `<`, or `*`, parse with [`VersionReq`],
45    ///   and map as `Req`.
46    /// - Else parse as `Semantic` or `Calendar` types.
47    pub fn parse<T: AsRef<str>>(value: T) -> Result<Self, SpecError> {
48        Self::from_str(value.as_ref())
49    }
50
51    /// Return true if the provided alias matches the current specification.
52    pub fn is_alias<A: AsRef<str>>(&self, name: A) -> bool {
53        match self {
54            Self::Alias(alias) => alias == name.as_ref(),
55            _ => false,
56        }
57    }
58
59    /// Return true if the current specification is canary.
60    pub fn is_canary(&self) -> bool {
61        match self {
62            Self::Canary => true,
63            Self::Alias(alias) => alias == "canary",
64            _ => false,
65        }
66    }
67
68    /// Return true if the current specification is the "latest" alias.
69    pub fn is_latest(&self) -> bool {
70        match self {
71            Self::Alias(alias) => alias == "latest",
72            _ => false,
73        }
74    }
75
76    /// Convert the current unresolved specification to a resolved specification.
77    /// Note that this *does not* actually resolve or validate against a manifest,
78    /// and instead simply constructs the [`VersionSpec`].
79    ///
80    /// Furthermore, the `Req` and `ReqAny` variants will return a "latest" alias,
81    ///  as they are not resolved or valid versions.
82    pub fn to_resolved_spec(&self) -> VersionSpec {
83        match self {
84            Self::Canary => VersionSpec::Canary,
85            Self::Alias(alias) => VersionSpec::Alias(CompactString::new(alias)),
86            Self::Calendar(version) => VersionSpec::Calendar(version.to_owned()),
87            Self::Semantic(version) => VersionSpec::Semantic(version.to_owned()),
88            _ => VersionSpec::default(),
89        }
90    }
91
92    /// Convert the current unresolved specification to a partial string, where
93    /// minor and patch versions are omitted if not defined, and the comparator
94    /// operator is also omitted. For example, "~1.2" would simply print "1.2".
95    ///
96    /// Furthermore, `Canary` will return "canary", `ReqAny` will return "latest",
97    /// and aliases will return as-is.
98    pub fn to_partial_string(&self) -> String {
99        fn from_parts(
100            major: u64,
101            minor: Option<u64>,
102            patch: Option<u64>,
103            pre: &Prerelease,
104        ) -> String {
105            let mut version = format!("{major}");
106
107            minor.inspect(|m| {
108                version.push_str(&format!(".{m}"));
109            });
110
111            patch.inspect(|p| {
112                version.push_str(&format!(".{p}"));
113            });
114
115            if !pre.is_empty() {
116                version.push('-');
117                version.push_str(pre.as_str());
118            }
119
120            version
121        }
122
123        match self {
124            UnresolvedVersionSpec::Canary => "canary".into(),
125            UnresolvedVersionSpec::Alias(alias) => alias.to_string(),
126            UnresolvedVersionSpec::Req(req) => {
127                let req = req.comparators.first().unwrap();
128
129                from_parts(req.major, req.minor, req.patch, &req.pre)
130            }
131            UnresolvedVersionSpec::ReqAny(_) => "latest".into(),
132            UnresolvedVersionSpec::Calendar(ver) => {
133                from_parts(ver.major, Some(ver.minor), Some(ver.patch), &ver.pre)
134            }
135            UnresolvedVersionSpec::Semantic(ver) => {
136                from_parts(ver.major, Some(ver.minor), Some(ver.patch), &ver.pre)
137            }
138        }
139    }
140}
141
142#[cfg(feature = "schematic")]
143impl schematic::Schematic for UnresolvedVersionSpec {
144    fn schema_name() -> Option<String> {
145        Some("UnresolvedVersionSpec".into())
146    }
147
148    fn build_schema(mut schema: schematic::SchemaBuilder) -> schematic::Schema {
149        schema.set_description("Represents an unresolved version or alias that must be resolved to a fully-qualified version.");
150        schema.string_default()
151    }
152}
153
154impl Default for UnresolvedVersionSpec {
155    /// Returns a `latest` alias.
156    fn default() -> Self {
157        Self::Alias("latest".into())
158    }
159}
160
161impl FromStr for UnresolvedVersionSpec {
162    type Err = SpecError;
163
164    fn from_str(value: &str) -> Result<Self, Self::Err> {
165        if value == "canary" {
166            return Ok(UnresolvedVersionSpec::Canary);
167        }
168
169        let value = clean_version_string(value);
170
171        if is_alias_name(&value) {
172            return Ok(UnresolvedVersionSpec::Alias(CompactString::new(value)));
173        }
174
175        let value = clean_version_req_string(&value);
176
177        // OR requirements
178        if value.contains("||") {
179            let mut reqs = vec![];
180
181            for result in parse_multi(&value)? {
182                reqs.push(VersionReq::parse(&result)?);
183            }
184
185            return Ok(UnresolvedVersionSpec::ReqAny(reqs));
186        }
187
188        // Version or requirement
189        let (result, kind) = parse(value)?;
190
191        Ok(match kind {
192            ParseKind::Req => UnresolvedVersionSpec::Req(VersionReq::parse(&result)?),
193            ParseKind::Cal => UnresolvedVersionSpec::Calendar(CalVer::parse(&result)?),
194            _ => UnresolvedVersionSpec::Semantic(SemVer::parse(&result)?),
195        })
196    }
197}
198
199impl TryFrom<String> for UnresolvedVersionSpec {
200    type Error = SpecError;
201
202    fn try_from(value: String) -> Result<Self, Self::Error> {
203        Self::from_str(&value)
204    }
205}
206
207impl Into<String> for UnresolvedVersionSpec {
208    fn into(self) -> String {
209        self.to_string()
210    }
211}
212
213impl Display for UnresolvedVersionSpec {
214    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215        match self {
216            Self::Canary => write!(f, "canary"),
217            Self::Alias(alias) => write!(f, "{alias}"),
218            Self::Req(req) => write!(f, "{req}"),
219            Self::ReqAny(reqs) => write!(
220                f,
221                "{}",
222                reqs.iter()
223                    .map(|req| req.to_string())
224                    .collect::<Vec<_>>()
225                    .join(" || ")
226            ),
227            Self::Calendar(version) => write!(f, "{version}"),
228            Self::Semantic(version) => write!(f, "{version}"),
229        }
230    }
231}
232
233impl PartialEq<VersionSpec> for UnresolvedVersionSpec {
234    fn eq(&self, other: &VersionSpec) -> bool {
235        match (self, other) {
236            (Self::Canary, VersionSpec::Alias(a)) => a == "canary",
237            (Self::Alias(a1), VersionSpec::Alias(a2)) => a1 == a2,
238            (Self::Calendar(v1), VersionSpec::Calendar(v2)) => v1 == v2,
239            (Self::Semantic(v1), VersionSpec::Semantic(v2)) => v1 == v2,
240            _ => false,
241        }
242    }
243}
244
245impl AsRef<UnresolvedVersionSpec> for UnresolvedVersionSpec {
246    fn as_ref(&self) -> &UnresolvedVersionSpec {
247        self
248    }
249}
250
251impl PartialOrd<UnresolvedVersionSpec> for UnresolvedVersionSpec {
252    fn partial_cmp(&self, other: &UnresolvedVersionSpec) -> Option<Ordering> {
253        Some(self.cmp(other))
254    }
255}
256
257impl Ord for UnresolvedVersionSpec {
258    fn cmp(&self, other: &Self) -> Ordering {
259        match (self, other) {
260            (Self::Canary, Self::Canary) => Ordering::Equal,
261            (Self::Alias(l), Self::Alias(r)) => l.cmp(r),
262            (Self::Calendar(l), Self::Calendar(r)) => l.cmp(r),
263            (Self::Semantic(l), Self::Semantic(r)) => l.cmp(r),
264            _ => compare(&self.to_string(), &other.to_string()),
265        }
266    }
267}