version_spec 0.11.2

A specification for working with partial, full, or aliased versions. Supports semver and calver.
Documentation
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
use crate::syntax::*;
use compact_str::CompactString;
use pest::error::*;
use pest::{Parser, Span, iterators::Pair};
use pest_derive::Parser;

#[derive(Parser)]
#[grammar = "syntax.pest"]
pub struct SyntaxParser;

fn is_wildcard(input: &str) -> bool {
    matches!(input, "" | "*" | "x" | "X")
}

pub(crate) fn calendar_year(year: u32) -> u32 {
    if year.to_string().len() < 4 {
        year + 2000
    } else {
        year
    }
}

#[doc(hidden)]
pub fn parse_semver<T: AsRef<str>>(input: T) -> Result<Version, pest::error::Error<Rule>> {
    let pairs = SyntaxParser::parse(Rule::parse_semver, input.as_ref().trim())?;
    let mut version = Version::default();

    for pair in pairs {
        handle_version(pair, &mut version)?;
    }

    Ok(version)
}

#[doc(hidden)]
pub fn parse_semver_req<T: AsRef<str>>(input: T) -> Result<Requirement, pest::error::Error<Rule>> {
    let input = input.as_ref().trim();
    let mut req = Requirement::default();

    if is_wildcard(input) {
        req.op = Op::Wildcard;

        return Ok(req);
    }

    let pairs = SyntaxParser::parse(Rule::parse_semver_req, input)?;

    for pair in pairs {
        handle_requirement(pair, &mut req)?;
    }

    Ok(req)
}

#[doc(hidden)]
pub fn parse_semver_range<T: AsRef<str>>(input: T) -> Result<Range, pest::error::Error<Rule>> {
    let input = input.as_ref().trim();
    let mut range = Range::default();

    if is_wildcard(input) {
        return Ok(range);
    }

    let pairs = SyntaxParser::parse(Rule::parse_semver_range, input)?;

    for pair in pairs {
        handle_range(pair, &mut range)?;
    }

    Ok(range)
}

#[doc(hidden)]
pub fn parse_calver<T: AsRef<str>>(input: T) -> Result<Version, pest::error::Error<Rule>> {
    let pairs = SyntaxParser::parse(Rule::parse_calver, input.as_ref().trim())?;
    let mut version = Version::default();

    for pair in pairs {
        handle_version(pair, &mut version)?;
    }

    Ok(version)
}

#[doc(hidden)]
pub fn parse_calver_req<T: AsRef<str>>(input: T) -> Result<Requirement, pest::error::Error<Rule>> {
    let input = input.as_ref().trim();
    let mut req = Requirement::default();

    if is_wildcard(input) {
        req.kind = VersionKind::Calendar;
        req.op = Op::Wildcard;

        return Ok(req);
    }

    let pairs = SyntaxParser::parse(Rule::parse_calver_req, input)?;

    for pair in pairs {
        handle_requirement(pair, &mut req)?;
    }

    Ok(req)
}

#[doc(hidden)]
pub fn parse_calver_range<T: AsRef<str>>(input: T) -> Result<Range, pest::error::Error<Rule>> {
    let input = input.as_ref().trim();
    let mut range = Range::default();

    if is_wildcard(input) {
        return Ok(range);
    }

    let pairs = SyntaxParser::parse(Rule::parse_calver_range, input)?;

    for pair in pairs {
        handle_range(pair, &mut range)?;
    }

    Ok(range)
}

#[doc(hidden)]
pub fn parse_alias<T: AsRef<str>>(input: T) -> Result<CompactString, pest::error::Error<Rule>> {
    let input = input.as_ref().trim();

    SyntaxParser::parse(Rule::parse_alias, input)?;

    Ok(CompactString::new(input))
}

fn parse_int(pair: Pair<Rule>, message: &str) -> Result<u32, Error<Rule>> {
    pair.as_str().parse::<u32>().map_err(|error| {
        Error::new_from_span(
            ErrorVariant::CustomError {
                message: format!("{message}: {error}"),
            },
            pair.as_span(),
        )
    })
}

fn parse_int_opt(pair: Pair<Rule>, message: &str) -> Result<Option<u32>, Error<Rule>> {
    match pair.as_str() {
        "*" | "x" | "X" => Ok(None),
        _ => parse_int(pair, message).map(Some),
    }
}

// Mirror the semver crate, where a numeric part cannot follow
// a wildcard part, for example "*.1" or "1.*.1"
fn verify_wildcard_order(
    previous: Option<u32>,
    current: Option<u32>,
    span: Span,
) -> Result<(), Error<Rule>> {
    if previous.is_none() && current.is_some() {
        return Err(Error::new_from_span(
            ErrorVariant::CustomError {
                message: "a version part cannot follow a wildcard part".to_owned(),
            },
            span,
        ));
    }

    Ok(())
}

fn handle_version(pair: Pair<Rule>, version: &mut Version) -> Result<(), pest::error::Error<Rule>> {
    for inner in pair.into_inner() {
        match inner.as_rule() {
            // Extract information
            Rule::scope => version.scope = Some(CompactString::new(inner.as_str())),

            Rule::pre => version.prerelease = Some(CompactString::new(inner.as_str())),

            Rule::build => version.build = Some(CompactString::new(inner.as_str())),

            Rule::major => {
                version.kind = VersionKind::Semantic;
                version.major = parse_int(inner, "failed to parse major version")?;
            }

            Rule::minor => {
                version.minor = parse_int(inner, "failed to parse minor version")?;
            }

            Rule::patch => {
                version.patch = parse_int(inner, "failed to parse patch version")?;
            }

            Rule::year => {
                version.kind = VersionKind::Calendar;
                version.major = parse_int(inner, "failed to parse year").map(calendar_year)?;
            }

            Rule::month => {
                version.minor = parse_int(inner, "failed to parse month")?;
            }

            Rule::day => {
                version.patch = parse_int(inner, "failed to parse day")?;
            }

            // Continue parsing
            Rule::parse_semver | Rule::parse_calver | Rule::semver | Rule::calver => {
                handle_version(inner, version)?;
            }

            // End of input
            Rule::EOI => {}

            // Error for unhandled rules
            _ => {
                unreachable!();
            }
        }
    }

    Ok(())
}

fn handle_requirement(
    pair: Pair<Rule>,
    req: &mut Requirement,
) -> Result<(), pest::error::Error<Rule>> {
    let mut has_op = false;

    for inner in pair.into_inner() {
        match inner.as_rule() {
            // Extract information
            Rule::req_scope => req.scope = Some(CompactString::new(inner.as_str())),

            Rule::pre => req.prerelease = Some(CompactString::new(inner.as_str())),

            // Build metadata is accepted for compatibility, but ignored
            Rule::build => {}

            Rule::op => {
                has_op = true;
                req.op = match inner.as_str() {
                    "=" | "==" => Op::Exact,
                    ">" => Op::Greater,
                    ">=" => Op::GreaterEq,
                    "<" => Op::Less,
                    "<=" => Op::LessEq,
                    "~" => Op::Tilde,
                    "^" => Op::Caret,
                    "*" | "x" | "X" => Op::Wildcard,
                    _ => unreachable!(),
                };
            }

            Rule::major_req => {
                req.kind = VersionKind::Semantic;
                req.major = parse_int_opt(inner, "failed to parse major version")?;

                // A wildcard part, like "*" or "1.*", is a wildcard match,
                // unless an operator was explicitly defined
                if !has_op && req.major.is_none() {
                    req.op = Op::Wildcard;
                }
            }

            Rule::minor_req => {
                let span = inner.as_span();

                req.minor = parse_int_opt(inner, "failed to parse minor version")?;

                verify_wildcard_order(req.major, req.minor, span)?;

                if !has_op && req.minor.is_none() {
                    req.op = Op::Wildcard;
                }
            }

            Rule::patch_req => {
                let span = inner.as_span();

                req.patch = parse_int_opt(inner, "failed to parse patch version")?;

                verify_wildcard_order(req.minor, req.patch, span)?;

                if !has_op && req.patch.is_none() {
                    req.op = Op::Wildcard;
                }
            }

            Rule::year_req => {
                req.kind = VersionKind::Calendar;
                req.major = parse_int_opt(inner, "failed to parse year")
                    .map(|year| year.map(calendar_year))?;

                // A wildcard part, like "*" or "2000-*", is a wildcard match,
                // unless an operator was explicitly defined
                if !has_op && req.major.is_none() {
                    req.op = Op::Wildcard;
                }
            }

            Rule::month_req => {
                let span = inner.as_span();

                req.minor = parse_int_opt(inner, "failed to parse month")?;

                verify_wildcard_order(req.major, req.minor, span)?;

                if !has_op && req.minor.is_none() {
                    req.op = Op::Wildcard;
                }
            }

            Rule::day_req => {
                let span = inner.as_span();

                req.patch = parse_int_opt(inner, "failed to parse day")?;

                verify_wildcard_order(req.minor, req.patch, span)?;

                if !has_op && req.patch.is_none() {
                    req.op = Op::Wildcard;
                }
            }

            // Continue parsing
            Rule::parse_semver_req
            | Rule::parse_calver_req
            | Rule::semver_req
            | Rule::calver_req => {
                handle_requirement(inner, req)?;
            }

            // End of input
            Rule::EOI => {}

            // Error for unhandled rules
            _ => {
                unreachable!();
            }
        }
    }

    Ok(())
}

fn handle_between(pair: Pair<Rule>) -> Result<Clause, pest::error::Error<Rule>> {
    let mut left = None;
    let mut right = None;

    for inner in pair.into_inner() {
        match inner.as_rule() {
            // Extract information
            Rule::semver | Rule::calver => {
                let mut version = Version::default();

                handle_version(inner, &mut version)?;

                if left.is_none() {
                    left = Some(version);
                } else {
                    right = Some(version);
                }
            }

            // Error for unhandled rules
            _ => {
                unreachable!();
            }
        }
    }

    // The grammar requires both versions
    match (left, right) {
        (Some(left), Some(right)) => Ok(Clause::Between(Box::new(left), Box::new(right))),
        _ => unreachable!(),
    }
}

fn handle_clause(pair: Pair<Rule>) -> Result<Clause, pest::error::Error<Rule>> {
    let mut reqs = vec![];

    for inner in pair.into_inner() {
        match inner.as_rule() {
            // Extract information
            Rule::semver_between | Rule::calver_between => {
                return handle_between(inner);
            }

            Rule::semver_req | Rule::calver_req => {
                let mut req = Requirement::default();

                handle_requirement(inner, &mut req)?;

                reqs.push(req);
            }

            Rule::and => {}

            // Error for unhandled rules
            _ => {
                unreachable!();
            }
        }
    }

    // The grammar requires at least one requirement
    Ok(if reqs.len() == 1 {
        Clause::Only(reqs.remove(0))
    } else {
        Clause::All(reqs)
    })
}

fn handle_range(pair: Pair<Rule>, range: &mut Range) -> Result<(), pest::error::Error<Rule>> {
    for inner in pair.into_inner() {
        match inner.as_rule() {
            // Extract information
            Rule::semver_clause | Rule::calver_clause => {
                range.clauses.push(handle_clause(inner)?);
            }

            Rule::or => {}

            // Continue parsing
            Rule::parse_semver_range
            | Rule::parse_calver_range
            | Rule::semver_range
            | Rule::calver_range => {
                handle_range(inner, range)?;
            }

            // End of input
            Rule::EOI => {}

            // Error for unhandled rules
            _ => {
                unreachable!();
            }
        }
    }

    Ok(())
}