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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
use crate::{
scheme::Scheme,
specifier::Specifier,
version::{Version, VersionError},
};
use core::{
fmt::{self, Display},
str,
};
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum FormatToken<'fs, S: Scheme> {
Specifier(&'static S::Specifier),
/// A literal holds an array of bytes from the format string. Note that this make contained
/// escaped brackets, so these bytes are not necessarily what will match the version string.
Literal(&'fs [u8]),
}
impl<'fs, S: Scheme> Clone for FormatToken<'fs, S> {
// manually implemented because the derive macro would want Scheme to be Clone, which really
// feels unnecessary.
fn clone(&self) -> Self {
match self {
FormatToken::Specifier(spec) => FormatToken::Specifier(*spec),
FormatToken::Literal(text) => FormatToken::Literal(text),
}
}
}
impl<'fs, S: Scheme> Display for FormatToken<'fs, S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FormatToken::Specifier(spec) => write!(f, "{spec}"),
FormatToken::Literal(text) => {
let text_str = unsafe { str::from_utf8_unchecked(text) };
f.write_str(text_str)
}
}
}
}
/// An error that occurred while parsing a format string.
#[allow(clippy::module_name_repetitions)]
#[non_exhaustive]
#[derive(thiserror::Error, Debug, PartialEq)]
pub enum FormatError {
/// The specifier is not terminated with a closing bracket.
#[error(
"specifier in format should be terminated with a closing square bracket (`>`), got `{pattern}`"
)]
UnterminatedSpecifier {
/// The unterminated specifier string
pattern: String,
},
/// The specifier is not a valid specifier for the scheme
#[error("specifier `{spec}` is not valid in {scheme_name} format")]
UnacceptableSpecifier {
/// The specifier
spec: String,
/// The scheme name
scheme_name: &'static str,
},
/// Two adjacent specifiers were not decreasing or decreased by more than one "step". In other
/// words, the specifiers are not in the correct order of significance.
///
/// # Examples
///
/// - `<MAJOR><MAJOR>`: not decreasing
/// - `<MAJOR><MINOR><PATCH><MINOR>`: last minor does not decrease
/// - `<YYYY><DD>`: decreasing by more than one step (days are only relative to months)
#[error("specifiers must step decrease by their significance, got `{next}` after `{prev}`")]
SpecifiersMustStepDecrease {
/// The first specifier
prev: String,
/// The second specifier
next: String,
},
/// The first specifier in a format is not allowed to be there
#[error(
"in {scheme_name} format, first specifier should be {expected_first}, got `{first_spec}`"
)]
WrongFirstSpecifier {
/// The specifier
first_spec: String,
/// The scheme name
scheme_name: &'static str,
/// A (possibly comma-separated) list of expected specifiers
expected_first: String,
},
/// The last specifier in a format does not complete the format
#[error(
"in {scheme_name} format, last specifier should be {expected_last}, got `{last_spec}`"
)]
Incomplete {
/// The last specifier
last_spec: String,
/// The scheme name
scheme_name: &'static str,
/// A (possibly comma-separated) list of expected specifiers
expected_last: String,
},
/// The format string should contain at least one specifier
#[error("format should contain at least one specifier")]
NoSpecifiersInFormat,
}
/// A Format describes the structure of a version, comprised of *specifiers* and *literal text*.
///
/// Later, the `Format` can be used to parse a version string into a
/// [`Version`](crate::version::Version) struct.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Format<'fs, S: Scheme> {
pub(crate) tokens: Vec<FormatToken<'fs, S>>,
}
impl<'fs, S: Scheme> Format<'fs, S> {
pub(crate) fn parse(format_str: &'fs str) -> Result<Self, FormatError> {
let mut format = format_str.as_bytes();
let mut tokens = Vec::with_capacity(S::MAX_TOKENS);
let mut last_spec: Option<&'static S::Specifier> = None;
while !format.is_empty() {
let matched_spec = S::Specifier::all()
.iter()
.find(|spec| format.starts_with(spec.format_pattern()));
let consume_len = if let Some(&spec) = matched_spec {
// check that specifiers are in order
if let Some(last_spec) = last_spec {
if !last_spec.can_be_left_adjacent_to(spec) {
return Err(FormatError::SpecifiersMustStepDecrease {
prev: last_spec.to_string(),
next: spec.to_string(),
});
}
} else {
// check that this is an ok first spec
if !spec.can_be_first() {
return Err(FormatError::WrongFirstSpecifier {
first_spec: spec.to_string(),
scheme_name: S::name(),
expected_first: S::first_variants_string(),
});
}
}
last_spec = Some(spec);
tokens.push(FormatToken::Specifier(spec));
spec.format_pattern().len()
} else {
// check if its escaped brackets, an unknown/unterminated specifier, or finally,
// just a literal.
let (literal, consume_len) = if format.starts_with(b"<<") {
// escaped opening bracket
(&format[0..2], 2)
} else if format.starts_with(&[b'<']) {
// determine if unknown or unterminated specifier. we technically don't need to
// error here: could just parse this as a literal because, above, we've already
// exhausted all known specifiers, but this helps the user.
let closing_index = format[1..]
.iter()
.position(|c| *c == b'>')
.map(|index| {
// 1 for opening bracket that we skipped
index + 1
})
.ok_or_else(|| {
// didn't find closing bracket
FormatError::UnterminatedSpecifier {
pattern: unsafe { std::str::from_utf8_unchecked(format) }
.to_string(),
}
})?;
// found closing, but unknown for this scheme
return Err(FormatError::UnacceptableSpecifier {
spec: unsafe { std::str::from_utf8_unchecked(&format[..=closing_index]) }
.to_string(),
scheme_name: S::name(),
});
} else {
// any other literal.
(&format[0..1], 1)
};
// we can add this literal to the last token if it was also a literal.
// this will help us cut down on the total number of tokens and therefore, regex
// groups later.
if let Some(FormatToken::Literal(last_literal)) = tokens.last_mut() {
// fast str "concat": we just increase the length of the last literal by the
// size of the new literal. this works because the additional char is in
// contiguous memory and we know that the length of the underlying string is at
// least this long.
*last_literal = unsafe {
core::slice::from_raw_parts(
last_literal.as_ptr(), //same ptr
last_literal.len() + literal.len(), // new len
)
};
} else {
tokens.push(FormatToken::Literal(literal));
}
consume_len
};
format = &format[consume_len..];
}
if let Some(last_spec) = last_spec {
if !last_spec.can_be_last() {
return Err(FormatError::Incomplete {
last_spec: last_spec.to_string(),
scheme_name: S::name(),
expected_last: S::last_variants_string(),
});
}
} else {
return Err(FormatError::NoSpecifiersInFormat);
}
Ok(Self { tokens })
}
/// Parses a version string with this format and return a [`Version`] object.
///
/// A version string is valid for a format if it matches the format exactly. This means that:
///
/// - Specifiers (e.g. `<MAJOR>`) in the format are replaced with the numeric values. See the
/// [table](crate#table) for how these values are expressed (such as zero-padding).
///
/// Note: The values in `version_str` are *not* validated to be actual dates. For example,
/// `2021.02.31` is valid for the format `<YYYY>.<MM>.<DD>`, even though February 31st does
/// not exist.
///
/// - Literal text in the format must match the version string exactly.
///
/// # Errors
///
/// - If the version string does not match the format string, returns a
/// [`VersionError::VersionFormatMismatch`].
pub fn new_version<'vs>(&self, version_str: &'vs str) -> Result<Version<'vs, S>, VersionError> {
Version::parse(version_str, self)
}
}
impl<'fs, S: Scheme> Display for Format<'fs, S> {
/// Display a format as a format string.
///
/// # Example
///
/// ```
/// use nextver::prelude::*;
///
/// let format_str = "<YYYY>.<MM>.<DD>";
/// let format = Cal::new_format(format_str).unwrap();
/// assert_eq!(format_str, format.to_string());
/// ```
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
for token in &self.tokens {
f.write_str(&token.to_string())?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
scheme::{Cal, CalSem, Sem},
specifier::{
CALSEM_MINOR, CALSEM_MONTH_SHORT, CALSEM_WEEK_SHORT, CALSEM_YEAR_FULL, CAL_DAY_SHORT,
CAL_MONTH_SHORT, CAL_WEEK_SHORT, CAL_YEAR_FULL, SEM_MAJOR, SEM_MINOR, SEM_PATCH,
},
};
use itertools::Itertools;
use rstest::*;
use std::iter;
#[fixture]
fn literal_parts() -> [&'static str; 3] {
static LITERAL_PARTS: [&str; 3] = [
"the quick brown fox jumps over the lazy dog",
"😉",
"the end",
];
LITERAL_PARTS
}
#[rstest]
fn test_sem_literal(literal_parts: [&'static str; 3]) {
let [first, middle, last] = literal_parts;
let format_str = &format!("{}<MAJOR>{}<MINOR>{}", &first, &middle, &last);
let sem_format = Sem::new_format(format_str);
assert_eq!(Ok(format_str), sem_format.map(|f| f.to_string()).as_ref());
}
#[rstest]
fn test_cal_literal(literal_parts: [&'static str; 3]) {
let [first, middle, last] = literal_parts;
let format_str = &format!("{}<YYYY>{}<MM>{}", &first, &middle, &last);
let cal_format = Cal::new_format(format_str);
assert_eq!(Ok(format_str), cal_format.map(|f| f.to_string()).as_ref());
}
#[rstest]
fn test_calsem_literal(literal_parts: [&'static str; 3]) {
let [first, middle, last] = literal_parts;
let format_str = &format!("{}<YYYY>{}<PATCH>{}", &first, &middle, &last);
let calsem_format = CalSem::new_format(format_str);
assert_eq!(
Ok(format_str),
calsem_format.map(|f| f.to_string()).as_ref()
);
}
/// test all semantic format sequences parse ok. these are:
///
/// - `<MAJOR>`
/// - `<MAJOR>`, `<MINOR>`
/// - `<MAJOR>`, `<MINOR>`, `<PATCH>`
#[test]
fn test_sem_parse_ok() {
let format_strings = ["<MAJOR><MINOR><PATCH>", "<MAJOR><MINOR>", "<MAJOR>"];
for format_string in format_strings {
let actual = Sem::new_format(format_string);
assert_eq!(Ok(format_string), actual.map(|f| f.to_string()).as_deref());
}
}
/// Returns an iterator of two-tuples of (specifier, pattern) for all valid calendar specifiers.
///
/// These are:
///
/// - `[<year>]`
/// - `[<year>]`, `[<month>]`
/// - `[<year>]`, `[<month>]`, `[<day>]`
/// - `[<year>]`, `[<week>]`
#[fixture]
fn all_valid_cal_specs_product() -> impl Iterator<Item = Vec<&'static str>> {
let years = || iter::once(vec!["<YYYY>", "<YY>", "<0Y>"]);
let months = || iter::once(vec!["<MM>", "<0M>"]);
let weeks = || iter::once(vec!["<WW>", "<0W>"]);
let days = || iter::once(vec!["<DD>", "<0D>"]);
let years_product = years().multi_cartesian_product();
let years_months_product = years().chain(months()).multi_cartesian_product();
let years_months_days_product = years()
.chain(months())
.chain(days())
.multi_cartesian_product();
let years_weeks_product = years().chain(weeks()).multi_cartesian_product();
years_product
.chain(years_months_product)
.chain(years_months_days_product)
.chain(years_weeks_product)
}
#[rstest]
fn test_cal_parse_ok(all_valid_cal_specs_product: impl Iterator<Item = Vec<&'static str>>) {
for spec_sequence in all_valid_cal_specs_product {
let format_string = &spec_sequence.join("");
let actual = Cal::new_format(format_string);
assert_eq!(Ok(format_string), actual.map(|f| f.to_string()).as_ref());
}
}
/// Returns an iterator of two-tuples of (specifier, pattern) for all valid calendar specifiers.
///
/// These are:
///
/// - `[<year>]`, REST
/// - `[<year>]`, `[<month>]`, REST
/// - `[<year>]`, `[<month>]`, `[<day>]`, REST
/// - `[<year>]`, `[<week>]`, REST
///
/// where REST is either:
///
/// - `<MINOR>`, `<PATCH>`
/// - `<PATCH>`
#[fixture]
fn all_valid_calsem_specs_product(
all_valid_cal_specs_product: impl Iterator<Item = Vec<&'static str>>,
) -> impl Iterator<Item = Vec<&'static str>> {
all_valid_cal_specs_product
// augment each of these products with the three possible semantic suffix combinations
.flat_map(|iter| {
vec![
[iter.clone(), vec!["<MINOR>"], vec!["<PATCH>"]].concat(),
[iter, vec!["<PATCH>"]].concat(),
]
})
}
#[rstest]
fn test_calsem_parse_ok(
all_valid_calsem_specs_product: impl Iterator<Item = Vec<&'static str>>,
) {
for spec_sequence in all_valid_calsem_specs_product {
let format_string = &spec_sequence.join("");
let actual = CalSem::new_format(format_string);
assert_eq!(Ok(format_string), actual.map(|f| f.to_string()).as_ref());
}
}
#[test]
fn test_bad_sem_format() {
use super::FormatError::*;
use crate::scheme::priv_trait::Scheme;
// not exhaustive, just a sample
let args = [
("", NoSpecifiersInFormat),
("foo", NoSpecifiersInFormat),
(
"<MINOR>",
WrongFirstSpecifier {
first_spec: SEM_MINOR.to_string(),
scheme_name: Sem::name(),
expected_first: Sem::first_variants_string(),
},
),
(
"<MAJOR><MAJOR>",
SpecifiersMustStepDecrease {
prev: SEM_MAJOR.to_string(),
next: SEM_MAJOR.to_string(),
},
),
(
"<MAJOR><PATCH>",
SpecifiersMustStepDecrease {
prev: SEM_MAJOR.to_string(),
next: SEM_PATCH.to_string(),
},
),
(
"<MAJOR><YYYY>",
UnacceptableSpecifier {
spec: "<YYYY>".to_string(),
scheme_name: Sem::name(),
},
),
(
"<MAJOR",
UnterminatedSpecifier {
pattern: "<MAJOR".to_string(),
},
),
];
for (format, err) in args {
let actual = Sem::new_format(format);
assert_eq!(Err(err), actual);
}
}
#[test]
fn test_bad_cal_format() {
use super::FormatError::*;
use crate::scheme::priv_trait::Scheme;
// not exhaustive, just a sample
let args = [
("", NoSpecifiersInFormat),
("foo", NoSpecifiersInFormat),
(
"<MM>",
WrongFirstSpecifier {
first_spec: CAL_MONTH_SHORT.to_string(),
scheme_name: Cal::name(),
expected_first: Cal::first_variants_string(),
},
),
(
"<YYYY><MINOR>",
UnacceptableSpecifier {
spec: "<MINOR>".to_string(),
scheme_name: Cal::name(),
},
),
(
"<YYYY><MM><WW>",
SpecifiersMustStepDecrease {
prev: CAL_MONTH_SHORT.to_string(),
next: CAL_WEEK_SHORT.to_string(),
},
),
(
"<YYYY><DD>",
SpecifiersMustStepDecrease {
prev: CAL_YEAR_FULL.to_string(),
next: CAL_DAY_SHORT.to_string(),
},
),
(
"<YYYY",
UnterminatedSpecifier {
pattern: "<YYYY".to_string(),
},
),
];
for (format, err) in args {
let actual = Cal::new_format(format);
assert_eq!(Err(err), actual);
}
}
#[test]
fn test_bad_calsem_format() {
use super::FormatError::*;
use crate::scheme::priv_trait::Scheme;
// not exhaustive, just a sample
let args = [
("", NoSpecifiersInFormat),
("foo", NoSpecifiersInFormat),
(
"<YYYY",
UnterminatedSpecifier {
pattern: "<YYYY".to_string(),
},
),
(
"<YYYY><FOO>",
UnacceptableSpecifier {
spec: "<FOO>".to_string(),
scheme_name: CalSem::name(),
},
),
(
"<YYYY>",
Incomplete {
last_spec: CALSEM_YEAR_FULL.to_string(),
scheme_name: CalSem::name(),
expected_last: CalSem::last_variants_string(),
},
),
(
"<MM>",
WrongFirstSpecifier {
first_spec: CAL_MONTH_SHORT.to_string(),
scheme_name: CalSem::name(),
expected_first: CalSem::first_variants_string(),
},
),
(
"<YYYY><MM><WW><PATCH>",
SpecifiersMustStepDecrease {
prev: CALSEM_MONTH_SHORT.to_string(),
next: CALSEM_WEEK_SHORT.to_string(),
},
),
(
"<YYYY><DD><MINOR>",
SpecifiersMustStepDecrease {
prev: CALSEM_YEAR_FULL.to_string(),
next: CAL_DAY_SHORT.to_string(),
},
),
(
"<YYYY><MINOR>",
Incomplete {
last_spec: CALSEM_MINOR.to_string(),
scheme_name: CalSem::name(),
expected_last: CalSem::last_variants_string(),
},
),
];
for (format, err) in args {
let actual = CalSem::new_format(format);
assert_eq!(Err(err), actual);
}
}
#[test]
fn test_bracket_escape() {
let format = r"<YYYY><<YYYY>";
let actual = Cal::new_format(format);
assert_eq!(
Ok(vec![
FormatToken::Specifier(&CAL_YEAR_FULL),
FormatToken::Literal(b"<<YYYY>"),
])
.as_ref(),
actual.as_ref().map(|f| &f.tokens)
);
let round_tripped_format = actual.unwrap().to_string();
assert_eq!(format, round_tripped_format);
}
#[test]
fn test_sem_eq() {
let format1 = Sem::new_format("<MAJOR><MINOR>").unwrap();
let format2 = Sem::new_format("<MAJOR><MINOR>").unwrap();
assert_eq!(format1, format2);
}
#[test]
fn test_sem_neq() {
let format1 = Sem::new_format("<MAJOR><MINOR>").unwrap();
let format2 = Sem::new_format("<MAJOR>").unwrap();
assert_ne!(format1, format2);
}
#[test]
fn test_cal_eq() {
let format1 = Cal::new_format("<YYYY><MM>").unwrap();
let format2 = Cal::new_format("<YYYY><MM>").unwrap();
assert_eq!(format1, format2);
}
#[test]
fn test_cal_neq() {
let format1 = Cal::new_format("<YYYY><MM>").unwrap();
let format2 = Cal::new_format("<YYYY><0M>").unwrap();
assert_ne!(format1, format2);
}
#[test]
fn test_calsem_eq() {
let format1 = CalSem::new_format("<YYYY><PATCH>").unwrap();
let format2 = CalSem::new_format("<YYYY><PATCH>").unwrap();
assert_eq!(format1, format2);
}
#[test]
fn test_calsem_neq() {
let format1 = CalSem::new_format("<0Y><PATCH>").unwrap();
let format2 = CalSem::new_format("<YYYY><PATCH>").unwrap();
assert_ne!(format1, format2);
}
}