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(VersionReq),
18 #[error("cannot parse version from version requirement '*' (any version)")]
19 Any,
20}
21
22fn 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
154fn semver_req_matches(req: &semver::VersionReq, version: &semver::Version) -> bool {
155 req.comparators
156 .iter()
157 .all(|comparator| comparator_matches(comparator, version))
158}
159
160#[derive(Error, Debug, Diagnostic)]
161#[non_exhaustive]
162#[error(transparent)]
163pub struct ReqError(#[from] SemverError);
164
165#[derive(Clone, Eq, PartialEq, Hash, Debug)]
168pub enum VersionReq {
169 SemVer(semver::VersionReq),
171 SemVerExcept {
174 req: semver::VersionReq,
175 excluded: Vec<semver::Version>,
176 },
177 DevVer(DevVersion),
179 StringVer(String),
181 Any,
183}
184
185impl VersionReq {
186 pub fn any() -> Self {
188 VersionReq::Any
189 }
190
191 pub fn parse(text: &str) -> Result<Self, ReqError> {
192 VersionReq::from_str(text)
193 }
194
195 pub fn matches(&self, version: &Version) -> bool {
196 match (self, version) {
197 (VersionReq::SemVer(req), Version::SemVer(ver)) => {
198 semver_req_matches(req, &ver.version)
199 }
200 (VersionReq::SemVerExcept { req, excluded }, Version::SemVer(ver)) => {
201 !excluded.contains(&ver.version) && semver_req_matches(req, &ver.version)
202 }
203 (VersionReq::DevVer(req), Version::DevVer(ver)) => req == &ver.modrev,
204 (VersionReq::StringVer(req), Version::StringVer(ver)) => req == &ver.modrev,
205 (VersionReq::Any, _) => true,
206 _ => false,
207 }
208 }
209
210 pub fn is_any(&self) -> bool {
211 matches!(self, VersionReq::Any)
212 }
213
214 pub fn is_luau(&self) -> bool {
216 matches!(self, VersionReq::StringVer(req) if req == "luau")
217 }
218}
219
220fn luarocks_req_str(req: &semver::VersionReq) -> String {
221 let mut str = req.to_string();
222 if str.starts_with("=") {
223 str = str.replacen("=", "==", 1);
224 } else if str.starts_with("^") {
225 str = str.replacen("^", "~>", 1);
226 }
227 str
228}
229
230impl Display for VersionReq {
231 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232 match self {
233 VersionReq::SemVer(version_req) => luarocks_req_str(version_req).fmt(f),
234 VersionReq::SemVerExcept { req, excluded } => {
235 let excluded = excluded.iter().format(", ~= ");
236 if req.comparators.is_empty() {
237 write!(f, "~= {excluded}")
238 } else {
239 write!(f, "{}, ~= {excluded}", luarocks_req_str(req))
240 }
241 }
242 VersionReq::DevVer(name_req) => write!(f, "=={}", name_req),
243 VersionReq::StringVer(name_req) => write!(f, "=={}", name_req),
244 VersionReq::Any => f.write_str("any"),
245 }
246 }
247}
248
249impl<'de> Deserialize<'de> for VersionReq {
250 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
251 where
252 D: Deserializer<'de>,
253 {
254 String::deserialize(deserializer)?
255 .parse()
256 .map_err(serde::de::Error::custom)
257 }
258}
259
260impl FromStr for VersionReq {
261 type Err = ReqError;
262
263 fn from_str(text: &str) -> Result<Self, Self::Err> {
264 let text = correct_version_req_str(text);
265
266 if text.contains("~=") || text.contains("!=") {
267 return parse_except_req(&text);
268 }
269
270 let trimmed = text.trim_start_matches('=').trim_start_matches('@').trim();
271
272 match parse_version_req(&text) {
273 Ok(ver) if ver.comparators.is_empty() => Ok(VersionReq::Any),
274 Ok(ver) => Ok(VersionReq::SemVer(ver)),
275 Err(_) => match trimmed {
276 "scm" => Ok(VersionReq::DevVer(DevVersion::Scm)),
277 "dev" => Ok(VersionReq::DevVer(DevVersion::Dev)),
278 ver => Ok(VersionReq::StringVer(ver.to_string())),
279 },
280 }
281 }
282}
283
284fn correct_version_req_str(text: &str) -> String {
285 text.chars()
286 .chunk_by(|t| t.is_alphanumeric() || matches!(t, '-' | '_' | '.'))
287 .into_iter()
288 .map(|(is_version_str, chars)| (is_version_str, chars.collect::<String>()))
289 .map(|(is_version_str, chunk)| {
290 if is_version_str && !is_known_dev_version_str(&chunk) {
291 let version_str = trim_specrev(&chunk);
292 correct_prerelease_version_string(version_str)
293 } else {
294 chunk
295 }
296 })
297 .collect::<String>()
298}
299
300fn trim_specrev(version_str: &str) -> &str {
301 if let Some(pos) = version_str.rfind('-') {
302 let suffix = &version_str[pos + 1..];
303 if suffix.chars().all(|c| c.is_ascii_digit()) {
304 &version_str[..pos]
305 } else {
306 version_str
307 }
308 } else {
309 version_str
310 }
311}
312
313fn is_known_dev_version_str(text: &str) -> bool {
314 matches!(text, "dev" | "scm")
315}
316
317fn parse_except_req(text: &str) -> Result<VersionReq, ReqError> {
318 let (constraints, excluded) = split_excluded_versions(text)?;
319 let req = if constraints.is_empty() {
320 semver::VersionReq::STAR
321 } else {
322 parse_version_req(&constraints)?
323 };
324 Ok(VersionReq::SemVerExcept { req, excluded })
325}
326
327fn split_excluded_versions(text: &str) -> Result<(String, Vec<semver::Version>), SemverError> {
328 let mut constraints = Vec::new();
329 let mut excluded = Vec::new();
330 for constraint in text.split(',').map(str::trim).filter(|c| !c.is_empty()) {
331 match constraint
332 .strip_prefix("~=")
333 .or_else(|| constraint.strip_prefix("!="))
334 {
335 Some(version) => {
336 excluded.push(semver::Version::parse(&correct_version_string(
337 version.trim(),
338 ))?);
339 }
340 None => constraints.push(constraint),
341 }
342 }
343 Ok((constraints.join(", "), excluded))
344}
345
346fn parse_version_req(version_constraints: &str) -> Result<semver::VersionReq, SemverError> {
348 let unescaped = decode_html_entities(version_constraints)
349 .to_string()
350 .as_str()
351 .to_owned();
352 let transformed = match unescaped {
353 s if s.starts_with("~>") => parse_pessimistic_version_constraint(s)?,
354 s if s.starts_with("@") => format!("={}", &s[1..]),
355 s if s.starts_with("==") => s[1..].to_string(),
357 s if s .find(|c: char| c.is_alphanumeric())
359 .is_some_and(|idx| idx == 0) =>
360 {
361 format!("={}", s)
362 }
363 s => s,
364 };
365
366 let version_req = semver::VersionReq::parse(&transformed)?;
367 Ok(version_req)
368}
369
370fn parse_pessimistic_version_constraint(version_constraint: String) -> Result<String, SemverError> {
371 let min_version_str = &version_constraint[2..].trim();
373 let min_version = semver::Version::parse(&correct_version_string(min_version_str))?;
374
375 let max_version = match min_version_str.matches('.').count() {
376 0 => semver::Version {
377 major: &min_version.major + 1,
378 ..min_version.clone()
379 },
380 1 => semver::Version {
381 minor: &min_version.minor + 1,
382 ..min_version.clone()
383 },
384 _ => semver::Version {
385 patch: &min_version.patch + 1,
386 ..min_version.clone()
387 },
388 };
389
390 Ok(format!(">= {min_version}, < {max_version}"))
391}