Skip to main content

lux_lib/package/version/
req.rs

1use std::{cmp::Ordering, fmt::Display, str::FromStr};
2
3use html_escape::decode_html_entities;
4use itertools::Itertools;
5use miette::Diagnostic;
6use semver::{Comparator, Error as SemverError, Op};
7use serde::{Deserialize, Deserializer};
8use thiserror::Error;
9
10use super::{
11    cmp_prerelease, correct_prerelease_version_string, correct_version_string, DevVersion, Version,
12};
13
14#[derive(Debug, Error, Diagnostic)]
15pub enum FromReqError {
16    #[error("cannot parse version from non-exact version requirement '{0}'")]
17    NonExactVersionReq(semver::VersionReq),
18    #[error("cannot parse version from version requirement '*' (any version)")]
19    Any,
20}
21
22/// Based on `semver`'s matching, but with the prerelease compared as an extension
23/// for compatibility with LuaRocks.
24/// The "prereleases only match prerelease comparators" rule is not applied.
25fn comparator_matches(comparator: &Comparator, version: &semver::Version) -> bool {
26    match comparator.op {
27        Op::Exact | Op::Wildcard => matches_exact(comparator, version),
28        Op::Greater => matches_greater(comparator, version),
29        Op::GreaterEq => matches_greater(comparator, version) || matches_exact(comparator, version),
30        Op::Less => matches_less(comparator, version),
31        Op::LessEq => matches_less(comparator, version) || matches_exact(comparator, version),
32        Op::Tilde => matches_tilde(comparator, version),
33        Op::Caret => matches_caret(comparator, version),
34        _ => false,
35    }
36}
37
38fn matches_exact(comparator: &Comparator, version: &semver::Version) -> bool {
39    if version.major != comparator.major {
40        return false;
41    }
42    if let Some(minor) = comparator.minor {
43        if version.minor != minor {
44            return false;
45        }
46    }
47    if let Some(patch) = comparator.patch {
48        if version.patch != patch {
49            return false;
50        }
51    }
52    version.pre == comparator.pre
53}
54
55fn matches_greater(comparator: &Comparator, version: &semver::Version) -> bool {
56    if version.major != comparator.major {
57        return version.major > comparator.major;
58    }
59    match comparator.minor {
60        None => return false,
61        Some(minor) => {
62            if version.minor != minor {
63                return version.minor > minor;
64            }
65        }
66    }
67    match comparator.patch {
68        None => return false,
69        Some(patch) => {
70            if version.patch != patch {
71                return version.patch > patch;
72            }
73        }
74    }
75    cmp_prerelease(&version.pre, &comparator.pre) == Ordering::Greater
76}
77
78fn matches_less(comparator: &Comparator, version: &semver::Version) -> bool {
79    if version.major != comparator.major {
80        return version.major < comparator.major;
81    }
82    match comparator.minor {
83        None => return false,
84        Some(minor) => {
85            if version.minor != minor {
86                return version.minor < minor;
87            }
88        }
89    }
90    match comparator.patch {
91        None => return false,
92        Some(patch) => {
93            if version.patch != patch {
94                return version.patch < patch;
95            }
96        }
97    }
98    cmp_prerelease(&version.pre, &comparator.pre) == Ordering::Less
99}
100
101fn matches_tilde(comparator: &Comparator, version: &semver::Version) -> bool {
102    if version.major != comparator.major {
103        return false;
104    }
105    if let Some(minor) = comparator.minor {
106        if version.minor != minor {
107            return false;
108        }
109    }
110    if let Some(patch) = comparator.patch {
111        if version.patch != patch {
112            return version.patch > patch;
113        }
114    }
115    cmp_prerelease(&version.pre, &comparator.pre) != Ordering::Less
116}
117
118fn matches_caret(comparator: &Comparator, version: &semver::Version) -> bool {
119    if version.major != comparator.major {
120        return false;
121    }
122    let minor = match comparator.minor {
123        None => return true,
124        Some(minor) => minor,
125    };
126    let patch = match comparator.patch {
127        None => {
128            if comparator.major > 0 {
129                return version.minor >= minor;
130            } else {
131                return version.minor == minor;
132            }
133        }
134        Some(patch) => patch,
135    };
136    if comparator.major > 0 {
137        if version.minor != minor {
138            return version.minor > minor;
139        } else if version.patch != patch {
140            return version.patch > patch;
141        }
142    } else if minor > 0 {
143        if version.minor != minor {
144            return false;
145        } else if version.patch != patch {
146            return version.patch > patch;
147        }
148    } else if version.minor != minor || version.patch != patch {
149        return false;
150    }
151    cmp_prerelease(&version.pre, &comparator.pre) != Ordering::Less
152}
153
154#[derive(Error, Debug, Diagnostic)]
155#[non_exhaustive]
156#[error(transparent)]
157pub struct ReqError(#[from] SemverError);
158
159/// **SemVer version** requirement as defined by <https://semver.org>.
160/// or a **Dev** version requirement, which can be one of "dev", "scm", or "git"
161#[derive(Clone, Eq, PartialEq, Hash, Debug)]
162pub enum VersionReq {
163    /// A VersionReq that matches a SemVer version.
164    SemVer(semver::VersionReq),
165    /// A VersionReq that matches only known dev versions.
166    DevVer(DevVersion),
167    /// A VersionReq that matches a arbitrary string version.
168    StringVer(String),
169    /// A VersionReq that has no version constraint.
170    Any,
171}
172
173impl VersionReq {
174    /// Returns a `VersionReq` that matches any version.
175    pub fn any() -> Self {
176        VersionReq::Any
177    }
178
179    pub fn parse(text: &str) -> Result<Self, ReqError> {
180        VersionReq::from_str(text)
181    }
182
183    pub fn matches(&self, version: &Version) -> bool {
184        match (self, version) {
185            (VersionReq::SemVer(req), Version::SemVer(ver)) => req
186                .comparators
187                .iter()
188                .all(|comparator| comparator_matches(comparator, &ver.version)),
189            (VersionReq::DevVer(req), Version::DevVer(ver)) => req == &ver.modrev,
190            (VersionReq::StringVer(req), Version::StringVer(ver)) => req == &ver.modrev,
191            (VersionReq::Any, _) => true,
192            _ => false,
193        }
194    }
195
196    pub fn is_any(&self) -> bool {
197        matches!(self, VersionReq::Any)
198    }
199
200    /// Returns true if this requirement pins the Luau dialect (`lua = "luau"`).
201    pub fn is_luau(&self) -> bool {
202        matches!(self, VersionReq::StringVer(req) if req == "luau")
203    }
204}
205
206impl Display for VersionReq {
207    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
208        match self {
209            VersionReq::SemVer(version_req) => {
210                let mut str = version_req.to_string();
211                if str.starts_with("=") {
212                    str = str.replacen("=", "==", 1);
213                } else if str.starts_with("^") {
214                    str = str.replacen("^", "~>", 1);
215                }
216                str.fmt(f)
217            }
218            VersionReq::DevVer(name_req) => write!(f, "=={}", name_req),
219            VersionReq::StringVer(name_req) => write!(f, "=={}", name_req),
220            VersionReq::Any => f.write_str("any"),
221        }
222    }
223}
224
225impl<'de> Deserialize<'de> for VersionReq {
226    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
227    where
228        D: Deserializer<'de>,
229    {
230        String::deserialize(deserializer)?
231            .parse()
232            .map_err(serde::de::Error::custom)
233    }
234}
235
236impl FromStr for VersionReq {
237    type Err = ReqError;
238
239    fn from_str(text: &str) -> Result<Self, Self::Err> {
240        let text = correct_version_req_str(text);
241
242        let trimmed = text.trim_start_matches('=').trim_start_matches('@').trim();
243
244        match parse_version_req(&text) {
245            Ok(ver) if ver.comparators.is_empty() => Ok(VersionReq::Any),
246            Ok(ver) => Ok(VersionReq::SemVer(ver)),
247            Err(_) => match trimmed {
248                "scm" => Ok(VersionReq::DevVer(DevVersion::Scm)),
249                "dev" => Ok(VersionReq::DevVer(DevVersion::Dev)),
250                ver => Ok(VersionReq::StringVer(ver.to_string())),
251            },
252        }
253    }
254}
255
256fn correct_version_req_str(text: &str) -> String {
257    text.chars()
258        .chunk_by(|t| t.is_alphanumeric() || matches!(t, '-' | '_' | '.'))
259        .into_iter()
260        .map(|(is_version_str, chars)| (is_version_str, chars.collect::<String>()))
261        .map(|(is_version_str, chunk)| {
262            if is_version_str && !is_known_dev_version_str(&chunk) {
263                let version_str = trim_specrev(&chunk);
264                correct_prerelease_version_string(version_str)
265            } else {
266                chunk
267            }
268        })
269        .collect::<String>()
270}
271
272fn trim_specrev(version_str: &str) -> &str {
273    if let Some(pos) = version_str.rfind('-') {
274        let suffix = &version_str[pos + 1..];
275        if suffix.chars().all(|c| c.is_ascii_digit()) {
276            &version_str[..pos]
277        } else {
278            version_str
279        }
280    } else {
281        version_str
282    }
283}
284
285fn is_known_dev_version_str(text: &str) -> bool {
286    matches!(text, "dev" | "scm")
287}
288
289/// Transform LuaRocks constraints into constraints that can be parsed by the semver crate.
290fn parse_version_req(version_constraints: &str) -> Result<semver::VersionReq, SemverError> {
291    let unescaped = decode_html_entities(version_constraints)
292        .to_string()
293        .as_str()
294        .to_owned();
295    let transformed = match unescaped {
296        s if s.starts_with("~>") => parse_pessimistic_version_constraint(s)?,
297        s if s.starts_with("@") => format!("={}", &s[1..]),
298        // The semver crate only understands "= version", unlike luarocks which understands "== version".
299        s if s.starts_with("==") => s[1..].to_string(),
300        s if s // semver parses no constraint prefix as ^, unlike luarocks which reads it as "=="
301            .find(|c: char| c.is_alphanumeric())
302            .is_some_and(|idx| idx == 0) =>
303        {
304            format!("={}", s)
305        }
306        s => s,
307    };
308
309    let version_req = semver::VersionReq::parse(&transformed)?;
310    Ok(version_req)
311}
312
313fn parse_pessimistic_version_constraint(version_constraint: String) -> Result<String, SemverError> {
314    // pessimistic operator
315    let min_version_str = &version_constraint[2..].trim();
316    let min_version = semver::Version::parse(&correct_version_string(min_version_str))?;
317
318    let max_version = match min_version_str.matches('.').count() {
319        0 => semver::Version {
320            major: &min_version.major + 1,
321            ..min_version.clone()
322        },
323        1 => semver::Version {
324            minor: &min_version.minor + 1,
325            ..min_version.clone()
326        },
327        _ => semver::Version {
328            patch: &min_version.patch + 1,
329            ..min_version.clone()
330        },
331    };
332
333    Ok(format!(">= {min_version}, < {max_version}"))
334}