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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
use std::borrow::Cow;
use std::cmp::Ordering;
use std::fmt::Formatter;
use std::hash::{Hash, Hasher};
use std::ops::Bound;
use std::str::FromStr;
use crate::{
Operator, OperatorParseError, Version, VersionPattern, VersionPatternParseError, version,
};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
#[cfg(feature = "tracing")]
use tracing::warn;
/// Sorted version specifiers, such as `>=2.1,<3`.
///
/// Python requirements can contain multiple version specifier so we need to store them in a list,
/// such as `>1.2,<2.0` being `[">1.2", "<2.0"]`.
///
/// ```rust
/// # use std::str::FromStr;
/// # use uv_pep440::{VersionSpecifiers, Version, Operator};
///
/// let version = Version::from_str("1.19").unwrap();
/// let version_specifiers = VersionSpecifiers::from_str(">=1.16, <2.0").unwrap();
/// assert!(version_specifiers.contains(&version));
/// // VersionSpecifiers derefs into a list of specifiers
/// assert_eq!(version_specifiers.iter().position(|specifier| *specifier.operator() == Operator::LessThan), Some(1));
/// ```
#[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Hash)]
#[cfg_attr(
feature = "rkyv",
derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)
)]
#[cfg_attr(feature = "rkyv", rkyv(derive(Debug)))]
pub struct VersionSpecifiers(Box<[VersionSpecifier]>);
impl std::ops::Deref for VersionSpecifiers {
type Target = [VersionSpecifier];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl VersionSpecifiers {
/// Matches all versions.
pub fn empty() -> Self {
Self(Box::new([]))
}
/// The number of specifiers.
pub fn len(&self) -> usize {
self.0.len()
}
/// Whether all specifiers match the given version.
pub fn contains(&self, version: &Version) -> bool {
self.iter().all(|specifier| specifier.contains(version))
}
/// Returns `true` if there are no specifiers.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Sort the specifiers.
fn from_unsorted(mut specifiers: Vec<VersionSpecifier>) -> Self {
// TODO(konsti): This seems better than sorting on insert and not getting the size hint,
// but i haven't measured it.
//
// Tie-break on the operator so semantically equivalent same-version intervals such as
// `>=1.4.4,<=1.4.4` and `<=1.4.4,>=1.4.4` normalize to the same representation.
specifiers.sort_by(|a, b| {
a.version()
.cmp(b.version())
.then_with(|| a.operator().cmp(b.operator()))
});
Self(specifiers.into_boxed_slice())
}
/// Returns the [`VersionSpecifiers`] whose union represents the given range.
///
/// This function is not applicable to ranges involving pre-release versions.
pub fn from_release_only_bounds<'a>(
mut bounds: impl Iterator<Item = (Bound<&'a Version>, Bound<&'a Version>)>,
) -> Self {
let mut specifiers = Vec::new();
let Some((start, mut next)) = bounds.next() else {
return Self::empty();
};
// Add specifiers for the holes between the bounds.
for (lower, upper) in bounds {
let specifier = match (next, lower) {
// Ex) [3.7, 3.8.5), (3.8.5, 3.9] -> >=3.7,!=3.8.5,<=3.9
(Bound::Excluded(prev), Bound::Excluded(lower)) if prev == lower => {
Some(VersionSpecifier::not_equals_version(prev.clone()))
}
// Ex) [3.7, 3.8), (3.8, 3.9] -> >=3.7,!=3.8.*,<=3.9
(Bound::Excluded(prev), Bound::Included(lower)) => {
match *prev.only_release_trimmed().release() {
[major] if *lower.only_release_trimmed().release() == [major, 1] => {
Some(VersionSpecifier::not_equals_star_version(Version::new([
major, 0,
])))
}
[major, minor]
if *lower.only_release_trimmed().release() == [major, minor + 1] =>
{
Some(VersionSpecifier::not_equals_star_version(Version::new([
major, minor,
])))
}
_ => None,
}
}
_ => None,
};
if let Some(specifier) = specifier {
specifiers.push(specifier);
} else {
#[cfg(feature = "tracing")]
warn!(
"Ignoring unsupported gap in `requires-python` version: {next:?} -> {lower:?}"
);
}
next = upper;
}
let end = next;
// Add the specifiers for the bounding range.
specifiers.extend(VersionSpecifier::from_release_only_bounds((start, end)));
Self::from_unsorted(specifiers)
}
}
impl FromIterator<VersionSpecifier> for VersionSpecifiers {
fn from_iter<T: IntoIterator<Item = VersionSpecifier>>(iter: T) -> Self {
Self::from_unsorted(iter.into_iter().collect())
}
}
impl IntoIterator for VersionSpecifiers {
type Item = VersionSpecifier;
type IntoIter = std::vec::IntoIter<VersionSpecifier>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_vec().into_iter()
}
}
impl FromStr for VersionSpecifiers {
type Err = VersionSpecifiersParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
parse_version_specifiers(s).map(Self::from_unsorted)
}
}
impl From<VersionSpecifier> for VersionSpecifiers {
fn from(specifier: VersionSpecifier) -> Self {
Self(Box::new([specifier]))
}
}
impl std::fmt::Display for VersionSpecifiers {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for (idx, version_specifier) in self.0.iter().enumerate() {
// Separate version specifiers by comma, but we need one comma less than there are
// specifiers
if idx == 0 {
write!(f, "{version_specifier}")?;
} else {
write!(f, ", {version_specifier}")?;
}
}
Ok(())
}
}
impl Default for VersionSpecifiers {
fn default() -> Self {
Self::empty()
}
}
impl<'de> Deserialize<'de> for VersionSpecifiers {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct Visitor;
impl de::Visitor<'_> for Visitor {
type Value = VersionSpecifiers;
fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
f.write_str("a string")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
VersionSpecifiers::from_str(v).map_err(de::Error::custom)
}
}
deserializer.deserialize_str(Visitor)
}
}
impl Serialize for VersionSpecifiers {
#[allow(unstable_name_collisions)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(
&self
.iter()
.map(ToString::to_string)
.collect::<Vec<String>>()
.join(","),
)
}
}
/// Error with span information (unicode width) inside the parsed line
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct VersionSpecifiersParseError {
// Clippy complains about this error type being too big (at time of
// writing, over 150 bytes). That does seem a little big, so we box things.
inner: Box<VersionSpecifiersParseErrorInner>,
}
#[derive(Debug, Eq, PartialEq, Clone)]
struct VersionSpecifiersParseErrorInner {
/// The underlying error that occurred.
err: VersionSpecifierParseError,
/// The string that failed to parse
line: String,
/// The starting byte offset into the original string where the error
/// occurred.
start: usize,
/// The ending byte offset into the original string where the error
/// occurred.
end: usize,
}
impl std::fmt::Display for VersionSpecifiersParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use unicode_width::UnicodeWidthStr;
let VersionSpecifiersParseErrorInner {
ref err,
ref line,
start,
end,
} = *self.inner;
writeln!(f, "Failed to parse version: {err}:")?;
writeln!(f, "{line}")?;
let indent = line[..start].width();
let point = line[start..end].width();
writeln!(f, "{}{}", " ".repeat(indent), "^".repeat(point))?;
Ok(())
}
}
impl VersionSpecifiersParseError {
/// The string that failed to parse
pub fn line(&self) -> &String {
&self.inner.line
}
}
impl std::error::Error for VersionSpecifiersParseError {}
/// A version range such as `>1.2.3`, `<=4!5.6.7-a8.post9.dev0` or `== 4.1.*`. Parse with
/// [`VersionSpecifier::from_str`].
///
/// ```rust
/// use std::str::FromStr;
/// use uv_pep440::{Version, VersionSpecifier};
///
/// let version = Version::from_str("1.19").unwrap();
/// let version_specifier = VersionSpecifier::from_str("== 1.*").unwrap();
/// assert!(version_specifier.contains(&version));
/// ```
///
/// [`PartialEq`], [`Hash`] and [`Ord`] distinguish `~=` specifiers by their
/// release segment count, since `~=10.1.0` (`>=10.1.0, <10.2`) and `~=10.1`
/// (`>=10.1, <11`) match different version sets per PEP 440. For other
/// operators, trailing zeros are insignificant.
#[derive(Debug, Clone)]
#[cfg_attr(
feature = "rkyv",
derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)
)]
#[cfg_attr(feature = "rkyv", rkyv(derive(Debug)))]
pub struct VersionSpecifier {
/// ~=|==|!=|<=|>=|<|>|===, plus whether the version ended with a star
pub(crate) operator: Operator,
/// The whole version part behind the operator
pub(crate) version: Version,
}
impl PartialEq for VersionSpecifier {
fn eq(&self, other: &Self) -> bool {
if self.operator != other.operator {
return false;
}
// `~=` semantics depend on the exact release segment count.
if self.operator == Operator::TildeEqual
&& self.version.release().len() != other.version.release().len()
{
return false;
}
self.version == other.version
}
}
impl Eq for VersionSpecifier {}
impl Hash for VersionSpecifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.operator.hash(state);
// Include the release length for `~=` so that `~=10.1` and `~=10.1.0`
// hash differently, matching our `PartialEq`.
if self.operator == Operator::TildeEqual {
self.version.release().len().hash(state);
}
self.version.hash(state);
}
}
impl PartialOrd for VersionSpecifier {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for VersionSpecifier {
fn cmp(&self, other: &Self) -> Ordering {
self.operator
.cmp(&other.operator)
.then_with(|| self.version.cmp(&other.version))
.then_with(|| {
// Break `~=` ties on release length to stay consistent with `PartialEq`.
if self.operator == Operator::TildeEqual {
self.version
.release()
.len()
.cmp(&other.version.release().len())
} else {
Ordering::Equal
}
})
}
}
impl<'de> Deserialize<'de> for VersionSpecifier {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct Visitor;
impl de::Visitor<'_> for Visitor {
type Value = VersionSpecifier;
fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
f.write_str("a string")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
VersionSpecifier::from_str(v).map_err(de::Error::custom)
}
}
deserializer.deserialize_str(Visitor)
}
}
/// <https://github.com/serde-rs/serde/issues/1316#issue-332908452>
impl Serialize for VersionSpecifier {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.collect_str(self)
}
}
impl VersionSpecifier {
/// Build from parts, validating that the operator is allowed with that version. The last
/// parameter indicates a trailing `.*`, to differentiate between `1.1.*` and `1.1`
pub fn from_pattern(
operator: Operator,
version_pattern: VersionPattern,
) -> Result<Self, VersionSpecifierBuildError> {
let star = version_pattern.is_wildcard();
let version = version_pattern.into_version();
// Check if there are star versions and if so, switch operator to star version
let operator = if star {
match operator.to_star() {
Some(starop) => starop,
None => {
return Err(BuildErrorKind::OperatorWithStar { operator }.into());
}
}
} else {
operator
};
Self::from_version(operator, version)
}
/// Create a new version specifier from an operator and a version.
pub fn from_version(
operator: Operator,
version: Version,
) -> Result<Self, VersionSpecifierBuildError> {
// "Local version identifiers are NOT permitted in this version specifier."
if version.is_local() && !operator.is_local_compatible() {
return Err(BuildErrorKind::OperatorLocalCombo { operator, version }.into());
}
if operator == Operator::TildeEqual && version.release().len() < 2 {
return Err(BuildErrorKind::CompatibleRelease.into());
}
Ok(Self { operator, version })
}
/// Remove all non-release parts of the version.
///
/// The marker decision diagram relies on the assumption that the negation of a marker tree is
/// the complement of the marker space. However, pre-release versions violate this assumption.
///
/// For example, the marker `python_full_version > '3.9' or python_full_version <= '3.9'`
/// does not match `python_full_version == 3.9.0a0` and so cannot simplify to `true`. However,
/// its negation, `python_full_version > '3.9' and python_full_version <= '3.9'`, also does not
/// match `3.9.0a0` and simplifies to `false`, which violates the algebra decision diagrams
/// rely on. For this reason we ignore pre-release versions entirely when evaluating markers.
///
/// Note that `python_version` cannot take on pre-release values as it is truncated to just the
/// major and minor version segments. Thus using release-only specifiers is definitely necessary
/// for `python_version` to fully simplify any ranges, such as
/// `python_version > '3.9' or python_version <= '3.9'`, which is always `true` for
/// `python_version`. For `python_full_version` however, this decision is a semantic change.
///
/// For Python versions, the major.minor is considered the API version, so unlike the rules
/// for package versions in PEP 440, we Python `3.9.0a0` is acceptable for `>= "3.9"`.
#[must_use]
pub fn only_release(self) -> Self {
Self {
operator: self.operator,
version: self.version.only_release(),
}
}
/// Remove all parts of the version beyond the minor segment of the release.
#[must_use]
pub fn only_minor_release(&self) -> Self {
Self {
operator: self.operator,
version: self.version.only_minor_release(),
}
}
/// `==<version>`
pub fn equals_version(version: Version) -> Self {
Self {
operator: Operator::Equal,
version,
}
}
/// `==<version>.*`
pub fn equals_star_version(version: Version) -> Self {
Self {
operator: Operator::EqualStar,
version,
}
}
/// `!=<version>.*`
pub fn not_equals_star_version(version: Version) -> Self {
Self {
operator: Operator::NotEqualStar,
version,
}
}
/// `!=<version>`
pub fn not_equals_version(version: Version) -> Self {
Self {
operator: Operator::NotEqual,
version,
}
}
/// `>=<version>`
pub fn greater_than_equal_version(version: Version) -> Self {
Self {
operator: Operator::GreaterThanEqual,
version,
}
}
/// `><version>`
pub fn greater_than_version(version: Version) -> Self {
Self {
operator: Operator::GreaterThan,
version,
}
}
/// `<=<version>`
pub fn less_than_equal_version(version: Version) -> Self {
Self {
operator: Operator::LessThanEqual,
version,
}
}
/// `<<version>`
pub fn less_than_version(version: Version) -> Self {
Self {
operator: Operator::LessThan,
version,
}
}
/// Get the operator, e.g. `>=` in `>= 2.0.0`
pub fn operator(&self) -> &Operator {
&self.operator
}
/// Get the version, e.g. `2.0.0` in `<= 2.0.0`
pub fn version(&self) -> &Version {
&self.version
}
/// Whether the version marker includes a prerelease.
pub fn any_prerelease(&self) -> bool {
self.version.any_prerelease()
}
/// Returns the version specifiers whose union represents the given range.
///
/// This function is not applicable to ranges involving pre-release versions.
pub fn from_release_only_bounds(
bounds: (Bound<&Version>, Bound<&Version>),
) -> impl Iterator<Item = Self> {
let (b1, b2) = match bounds {
(Bound::Included(v1), Bound::Included(v2)) if v1 == v2 => {
(Some(Self::equals_version(v1.clone())), None)
}
// `v >= 3.7 && v < 3.8` is equivalent to `v == 3.7.*`
(Bound::Included(v1), Bound::Excluded(v2)) => {
match *v1.only_release_trimmed().release() {
[major] if *v2.only_release_trimmed().release() == [major, 1] => {
let version = Version::new([major, 0]);
(Some(Self::equals_star_version(version)), None)
}
[major, minor]
if *v2.only_release_trimmed().release() == [major, minor + 1] =>
{
let version = Version::new([major, minor]);
(Some(Self::equals_star_version(version)), None)
}
_ => (
Self::from_lower_bound(Bound::Included(v1)),
Self::from_upper_bound(Bound::Excluded(v2)),
),
}
}
(lower, upper) => (Self::from_lower_bound(lower), Self::from_upper_bound(upper)),
};
b1.into_iter().chain(b2)
}
/// Returns a version specifier representing the given lower bound.
fn from_lower_bound(bound: Bound<&Version>) -> Option<Self> {
match bound {
Bound::Included(version) => {
Some(Self::from_version(Operator::GreaterThanEqual, version.clone()).unwrap())
}
Bound::Excluded(version) => {
Some(Self::from_version(Operator::GreaterThan, version.clone()).unwrap())
}
Bound::Unbounded => None,
}
}
/// Returns a version specifier representing the given upper bound.
fn from_upper_bound(bound: Bound<&Version>) -> Option<Self> {
match bound {
Bound::Included(version) => {
Some(Self::from_version(Operator::LessThanEqual, version.clone()).unwrap())
}
Bound::Excluded(version) => {
Some(Self::from_version(Operator::LessThan, version.clone()).unwrap())
}
Bound::Unbounded => None,
}
}
/// Whether the given version satisfies the version range.
///
/// For example, `>=1.19,<2.0` contains `1.21`, but not `2.0`.
///
/// See:
/// - <https://peps.python.org/pep-0440/#version-specifiers>
/// - <https://github.com/pypa/packaging/blob/e184feef1a28a5c574ec41f5c263a3a573861f5a/packaging/specifiers.py#L362-L496>
pub fn contains(&self, version: &Version) -> bool {
// "Except where specifically noted below, local version identifiers MUST NOT be permitted
// in version specifiers, and local version labels MUST be ignored entirely when checking
// if candidate versions match a given version specifier."
let this = self.version();
let other = if this.local().is_empty() && !version.local().is_empty() {
Cow::Owned(version.clone().without_local())
} else {
Cow::Borrowed(version)
};
match self.operator {
Operator::Equal => other.as_ref() == this,
Operator::EqualStar => {
this.epoch() == other.epoch()
&& self
.version
.release()
.iter()
// Pad the version with zeros if it's shorter than the specifier
// prefix, e.g., version "2" (== "2.0") should NOT match "==2.1.*"
// because 2.0 != 2.1.
.zip(other.release().iter().chain(std::iter::repeat(&0)))
.all(|(this, other)| this == other)
}
#[allow(deprecated)]
Operator::ExactEqual => {
#[cfg(feature = "tracing")]
{
warn!("Using arbitrary equality (`===`) is discouraged");
}
self.version.to_string() == version.to_string()
}
Operator::NotEqual => this != other.as_ref(),
Operator::NotEqualStar => {
this.epoch() != other.epoch()
|| !this
.release()
.iter()
// Pad the version with zeros if it's shorter than the specifier
// prefix, e.g., version "2" (== "2.0") should match "!=2.1.*"
// because 2.0 != 2.1.
.zip(other.release().iter().chain(std::iter::repeat(&0)))
.all(|(this, other)| this == other)
}
Operator::TildeEqual => {
// "For a given release identifier V.N, the compatible release clause is
// approximately equivalent to the pair of comparison clauses: `>= V.N, == V.*`"
// First, we test that every but the last digit matches.
// We know that this must hold true since we checked it in the constructor
assert!(this.release().len() > 1);
if this.epoch() != other.epoch() {
return false;
}
if !this.release()[..this.release().len() - 1]
.iter()
.zip(&*other.release())
.all(|(this, other)| this == other)
{
return false;
}
// According to PEP 440, this ignores the pre-release special rules
// pypa/packaging disagrees: https://github.com/pypa/packaging/issues/617
other.as_ref() >= this
}
Operator::GreaterThan => {
if other.epoch() > this.epoch() {
return true;
}
if version::compare_release(&this.release(), &other.release()) == Ordering::Equal {
// This special case is here so that, unless the specifier itself
// includes is a post-release version, that we do not accept
// post-release versions for the version mentioned in the specifier
// (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0).
if !this.is_post() && other.is_post() {
return false;
}
// We already checked that self doesn't have a local version
if other.is_local() {
return false;
}
}
other.as_ref() > this
}
Operator::GreaterThanEqual => other.as_ref() >= this,
Operator::LessThan => {
if other.epoch() < this.epoch() {
return true;
}
// The exclusive ordered comparison <V MUST NOT allow a pre-release of the specified
// version unless the specified version is itself a pre-release. E.g., <3.1 should
// not match 3.1.dev0, but should match both 3.0.dev0 and 3.0, while <3.1.dev1 does
// match 3.1.dev0, 3.0.dev0 and 3.0.
if version::compare_release(&this.release(), &other.release()) == Ordering::Equal
&& !this.any_prerelease()
&& other.any_prerelease()
{
return false;
}
other.as_ref() < this
}
Operator::LessThanEqual => other.as_ref() <= this,
}
}
/// Whether this version specifier rejects versions below a lower cutoff.
pub fn has_lower_bound(&self) -> bool {
match self.operator() {
Operator::Equal
| Operator::EqualStar
| Operator::ExactEqual
| Operator::TildeEqual
| Operator::GreaterThan
| Operator::GreaterThanEqual => true,
Operator::LessThanEqual
| Operator::LessThan
| Operator::NotEqualStar
| Operator::NotEqual => false,
}
}
}
impl FromStr for VersionSpecifier {
type Err = VersionSpecifierParseError;
/// Parses a version such as `>= 1.19`, `== 1.1.*`,`~=1.0+abc.5` or `<=1!2012.2`
fn from_str(spec: &str) -> Result<Self, Self::Err> {
let mut s = unscanny::Scanner::new(spec);
s.eat_while(|c: char| c.is_whitespace());
// operator but we don't know yet if it has a star
let operator = s.eat_while(['=', '!', '~', '<', '>']);
if operator.is_empty() {
// Attempt to parse the version from the rest of the scanner to provide a more useful error message in MissingOperator.
// If it is not able to be parsed (i.e. not a valid version), it will just be None and no additional info will be added to the error message.
s.eat_while(|c: char| c.is_whitespace());
let version = s.eat_while(|c: char| !c.is_whitespace());
s.eat_while(|c: char| c.is_whitespace());
return Err(ParseErrorKind::MissingOperator(VersionOperatorBuildError {
version_pattern: VersionPattern::from_str(version).ok(),
})
.into());
}
let operator = Operator::from_str(operator).map_err(ParseErrorKind::InvalidOperator)?;
s.eat_while(|c: char| c.is_whitespace());
let version = s.eat_while(|c: char| !c.is_whitespace());
if version.is_empty() {
return Err(ParseErrorKind::MissingVersion.into());
}
let vpat = version.parse().map_err(ParseErrorKind::InvalidVersion)?;
let version_specifier =
Self::from_pattern(operator, vpat).map_err(ParseErrorKind::InvalidSpecifier)?;
s.eat_while(|c: char| c.is_whitespace());
if !s.done() {
return Err(ParseErrorKind::InvalidTrailing(s.after().to_string()).into());
}
Ok(version_specifier)
}
}
impl std::fmt::Display for VersionSpecifier {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.operator == Operator::EqualStar || self.operator == Operator::NotEqualStar {
return write!(f, "{}{}.*", self.operator, self.version);
}
write!(f, "{}{}", self.operator, self.version)
}
}
/// An error that can occur when constructing a version specifier.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VersionSpecifierBuildError {
// We box to shrink the error type's size. This in turn keeps Result<T, E>
// smaller and should lead to overall better codegen.
kind: Box<BuildErrorKind>,
}
impl std::error::Error for VersionSpecifierBuildError {}
impl std::fmt::Display for VersionSpecifierBuildError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match *self.kind {
BuildErrorKind::OperatorLocalCombo {
operator: ref op,
ref version,
} => {
let local = version.local();
write!(
f,
"Operator {op} is incompatible with versions \
containing non-empty local segments (`+{local}`)",
)
}
BuildErrorKind::OperatorWithStar { operator: ref op } => {
write!(
f,
"Operator {op} cannot be used with a wildcard version specifier",
)
}
BuildErrorKind::CompatibleRelease => {
write!(
f,
"The ~= operator requires at least two segments in the release version"
)
}
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct VersionOperatorBuildError {
version_pattern: Option<VersionPattern>,
}
impl std::error::Error for VersionOperatorBuildError {}
impl std::fmt::Display for VersionOperatorBuildError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "Unexpected end of version specifier, expected operator")?;
if let Some(version_pattern) = &self.version_pattern {
let version_specifier =
VersionSpecifier::from_pattern(Operator::Equal, version_pattern.clone()).unwrap();
write!(f, ". Did you mean `{version_specifier}`?")?;
}
Ok(())
}
}
/// The specific kind of error that can occur when building a version specifier
/// from an operator and version pair.
#[derive(Clone, Debug, Eq, PartialEq)]
enum BuildErrorKind {
/// Occurs when one attempts to build a version specifier with
/// a version containing a non-empty local segment with and an
/// incompatible operator.
OperatorLocalCombo {
/// The operator given.
operator: Operator,
/// The version given.
version: Version,
},
/// Occurs when a version specifier contains a wildcard, but is used with
/// an incompatible operator.
OperatorWithStar {
/// The operator given.
operator: Operator,
},
/// Occurs when the compatible release operator (`~=`) is used with a
/// version that has fewer than 2 segments in its release version.
CompatibleRelease,
}
impl From<BuildErrorKind> for VersionSpecifierBuildError {
fn from(kind: BuildErrorKind) -> Self {
Self {
kind: Box::new(kind),
}
}
}
/// An error that can occur when parsing or constructing a version specifier.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VersionSpecifierParseError {
// We box to shrink the error type's size. This in turn keeps Result<T, E>
// smaller and should lead to overall better codegen.
kind: Box<ParseErrorKind>,
}
impl std::error::Error for VersionSpecifierParseError {}
impl std::fmt::Display for VersionSpecifierParseError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
// Note that even though we have nested error types here, since we
// don't expose them through std::error::Error::source, we emit them
// as part of the error message here. This makes the error a bit
// more self-contained. And it's not clear how useful it is exposing
// internal errors.
match *self.kind {
ParseErrorKind::InvalidOperator(ref err) => err.fmt(f),
ParseErrorKind::InvalidVersion(ref err) => err.fmt(f),
ParseErrorKind::InvalidSpecifier(ref err) => err.fmt(f),
ParseErrorKind::MissingOperator(ref err) => err.fmt(f),
ParseErrorKind::MissingVersion => {
write!(f, "Unexpected end of version specifier, expected version")
}
ParseErrorKind::InvalidTrailing(ref trail) => {
write!(f, "Trailing `{trail}` is not allowed")
}
}
}
}
/// The specific kind of error that occurs when parsing a single version
/// specifier from a string.
#[derive(Clone, Debug, Eq, PartialEq)]
enum ParseErrorKind {
InvalidOperator(OperatorParseError),
InvalidVersion(VersionPatternParseError),
InvalidSpecifier(VersionSpecifierBuildError),
MissingOperator(VersionOperatorBuildError),
MissingVersion,
InvalidTrailing(String),
}
impl From<ParseErrorKind> for VersionSpecifierParseError {
fn from(kind: ParseErrorKind) -> Self {
Self {
kind: Box::new(kind),
}
}
}
/// Parse a list of specifiers such as `>= 1.0, != 1.3.*, < 2.0`.
fn parse_version_specifiers(
spec: &str,
) -> Result<Vec<VersionSpecifier>, VersionSpecifiersParseError> {
let mut version_ranges = Vec::new();
if spec.is_empty() {
return Ok(version_ranges);
}
let mut start: usize = 0;
let separator = ",";
for version_range_spec in spec.split(separator) {
match VersionSpecifier::from_str(version_range_spec) {
Err(err) => {
return Err(VersionSpecifiersParseError {
inner: Box::new(VersionSpecifiersParseErrorInner {
err,
line: spec.to_string(),
start,
end: start + version_range_spec.len(),
}),
});
}
Ok(version_range) => {
version_ranges.push(version_range);
}
}
start += version_range_spec.len();
start += separator.len();
}
Ok(version_ranges)
}
/// A simple `~=` version specifier with a major, minor and (optional) patch version, e.g., `~=3.13`
/// or `~=3.13.0`.
#[derive(Clone, Debug)]
pub struct TildeVersionSpecifier<'a> {
inner: Cow<'a, VersionSpecifier>,
}
impl<'a> TildeVersionSpecifier<'a> {
/// Create a new [`TildeVersionSpecifier`] from a [`VersionSpecifier`] value.
///
/// If a [`Operator::TildeEqual`] is not used, or the version includes more than minor and patch
/// segments, this will return [`None`].
fn from_specifier(specifier: VersionSpecifier) -> Option<Self> {
TildeVersionSpecifier::new(Cow::Owned(specifier))
}
/// Create a new [`TildeVersionSpecifier`] from a [`VersionSpecifier`] reference.
///
/// See [`TildeVersionSpecifier::from_specifier`].
pub fn from_specifier_ref(specifier: &'a VersionSpecifier) -> Option<Self> {
TildeVersionSpecifier::new(Cow::Borrowed(specifier))
}
fn new(specifier: Cow<'a, VersionSpecifier>) -> Option<Self> {
if specifier.operator != Operator::TildeEqual {
return None;
}
if specifier.version().release().len() < 2 || specifier.version().release().len() > 3 {
return None;
}
if specifier.version().any_prerelease()
|| specifier.version().is_local()
|| specifier.version().is_post()
{
return None;
}
Some(Self { inner: specifier })
}
/// Whether a patch version is present in this tilde version specifier.
pub fn has_patch(&self) -> bool {
self.inner.version.release().len() == 3
}
/// Construct the lower and upper bounding version specifiers for this tilde version specifier,
/// e.g., for `~=3.13` this would return `>=3.13` and `<4` and for `~=3.13.0` it would
/// return `>=3.13.0` and `<3.14`.
pub fn bounding_specifiers(&self) -> (VersionSpecifier, VersionSpecifier) {
let release = self.inner.version().release();
let lower = self.inner.version.clone();
let upper = if self.has_patch() {
Version::new([release[0], release[1] + 1])
} else {
Version::new([release[0] + 1])
};
(
VersionSpecifier::greater_than_equal_version(lower),
VersionSpecifier::less_than_version(upper),
)
}
/// Construct a new tilde `VersionSpecifier` with the given patch version appended.
pub fn with_patch_version(&self, patch: u64) -> TildeVersionSpecifier<'_> {
let mut release = self.inner.version.release().to_vec();
if self.has_patch() {
release.pop();
}
release.push(patch);
TildeVersionSpecifier::from_specifier(
VersionSpecifier::from_version(Operator::TildeEqual, Version::new(release))
.expect("We should always derive a valid new version specifier"),
)
.expect("We should always derive a new tilde version specifier")
}
}
impl std::fmt::Display for TildeVersionSpecifier<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.inner)
}
}
#[cfg(test)]
mod tests {
use std::{cmp::Ordering, str::FromStr};
use indoc::indoc;
use crate::LocalSegment;
use super::*;
/// <https://peps.python.org/pep-0440/#version-matching>
#[test]
fn test_equal() {
let version = Version::from_str("1.1.post1").unwrap();
assert!(
!VersionSpecifier::from_str("== 1.1")
.unwrap()
.contains(&version)
);
assert!(
VersionSpecifier::from_str("== 1.1.post1")
.unwrap()
.contains(&version)
);
assert!(
VersionSpecifier::from_str("== 1.1.*")
.unwrap()
.contains(&version)
);
}
const VERSIONS_ALL: &[&str] = &[
// Implicit epoch of 0
"1.0.dev456",
"1.0a1",
"1.0a2.dev456",
"1.0a12.dev456",
"1.0a12",
"1.0b1.dev456",
"1.0b2",
"1.0b2.post345.dev456",
"1.0b2.post345",
"1.0b2-346",
"1.0c1.dev456",
"1.0c1",
"1.0rc2",
"1.0c3",
"1.0",
"1.0.post456.dev34",
"1.0.post456",
"1.1.dev1",
"1.2+123abc",
"1.2+123abc456",
"1.2+abc",
"1.2+abc123",
"1.2+abc123def",
"1.2+1234.abc",
"1.2+123456",
"1.2.r32+123456",
"1.2.rev33+123456",
// Explicit epoch of 1
"1!1.0.dev456",
"1!1.0a1",
"1!1.0a2.dev456",
"1!1.0a12.dev456",
"1!1.0a12",
"1!1.0b1.dev456",
"1!1.0b2",
"1!1.0b2.post345.dev456",
"1!1.0b2.post345",
"1!1.0b2-346",
"1!1.0c1.dev456",
"1!1.0c1",
"1!1.0rc2",
"1!1.0c3",
"1!1.0",
"1!1.0.post456.dev34",
"1!1.0.post456",
"1!1.1.dev1",
"1!1.2+123abc",
"1!1.2+123abc456",
"1!1.2+abc",
"1!1.2+abc123",
"1!1.2+abc123def",
"1!1.2+1234.abc",
"1!1.2+123456",
"1!1.2.r32+123456",
"1!1.2.rev33+123456",
];
/// <https://github.com/pypa/packaging/blob/237ff3aa348486cf835a980592af3a59fccd6101/tests/test_version.py#L666-L707>
/// <https://github.com/pypa/packaging/blob/237ff3aa348486cf835a980592af3a59fccd6101/tests/test_version.py#L709-L750>
///
/// These tests are a lot shorter than the pypa/packaging version since we implement all
/// comparisons through one method
#[test]
fn test_operators_true() {
let versions: Vec<Version> = VERSIONS_ALL
.iter()
.map(|version| Version::from_str(version).unwrap())
.collect();
// Below we'll generate every possible combination of VERSIONS_ALL that
// should be true for the given operator
let operations = [
// Verify that the less than (<) operator works correctly
versions
.iter()
.enumerate()
.flat_map(|(i, x)| {
versions[i + 1..]
.iter()
.map(move |y| (x, y, Ordering::Less))
})
.collect::<Vec<_>>(),
// Verify that the equal (==) operator works correctly
versions
.iter()
.map(move |x| (x, x, Ordering::Equal))
.collect::<Vec<_>>(),
// Verify that the greater than (>) operator works correctly
versions
.iter()
.enumerate()
.flat_map(|(i, x)| versions[..i].iter().map(move |y| (x, y, Ordering::Greater)))
.collect::<Vec<_>>(),
]
.into_iter()
.flatten();
for (a, b, ordering) in operations {
assert_eq!(a.cmp(b), ordering, "{a} {ordering:?} {b}");
}
}
const VERSIONS_0: &[&str] = &[
"1.0.dev456",
"1.0a1",
"1.0a2.dev456",
"1.0a12.dev456",
"1.0a12",
"1.0b1.dev456",
"1.0b2",
"1.0b2.post345.dev456",
"1.0b2.post345",
"1.0b2-346",
"1.0c1.dev456",
"1.0c1",
"1.0rc2",
"1.0c3",
"1.0",
"1.0.post456.dev34",
"1.0.post456",
"1.1.dev1",
"1.2+123abc",
"1.2+123abc456",
"1.2+abc",
"1.2+abc123",
"1.2+abc123def",
"1.2+1234.abc",
"1.2+123456",
"1.2.r32+123456",
"1.2.rev33+123456",
];
const SPECIFIERS_OTHER: &[&str] = &[
"== 1.*", "== 1.0.*", "== 1.1.*", "== 1.2.*", "== 2.*", "~= 1.0", "~= 1.0b1", "~= 1.1",
"~= 1.2", "~= 2.0",
];
const EXPECTED_OTHER: &[[bool; 10]] = &[
[
true, true, false, false, false, false, false, false, false, false,
],
[
true, true, false, false, false, false, false, false, false, false,
],
[
true, true, false, false, false, false, false, false, false, false,
],
[
true, true, false, false, false, false, false, false, false, false,
],
[
true, true, false, false, false, false, false, false, false, false,
],
[
true, true, false, false, false, false, false, false, false, false,
],
[
true, true, false, false, false, false, true, false, false, false,
],
[
true, true, false, false, false, false, true, false, false, false,
],
[
true, true, false, false, false, false, true, false, false, false,
],
[
true, true, false, false, false, false, true, false, false, false,
],
[
true, true, false, false, false, false, true, false, false, false,
],
[
true, true, false, false, false, false, true, false, false, false,
],
[
true, true, false, false, false, false, true, false, false, false,
],
[
true, true, false, false, false, false, true, false, false, false,
],
[
true, true, false, false, false, true, true, false, false, false,
],
[
true, true, false, false, false, true, true, false, false, false,
],
[
true, true, false, false, false, true, true, false, false, false,
],
[
true, false, true, false, false, true, true, false, false, false,
],
[
true, false, false, true, false, true, true, true, true, false,
],
[
true, false, false, true, false, true, true, true, true, false,
],
[
true, false, false, true, false, true, true, true, true, false,
],
[
true, false, false, true, false, true, true, true, true, false,
],
[
true, false, false, true, false, true, true, true, true, false,
],
[
true, false, false, true, false, true, true, true, true, false,
],
[
true, false, false, true, false, true, true, true, true, false,
],
[
true, false, false, true, false, true, true, true, true, false,
],
[
true, false, false, true, false, true, true, true, true, false,
],
];
/// Test for tilde equal (~=) and star equal (== x.y.*) recorded from pypa/packaging
///
/// Well, except for <https://github.com/pypa/packaging/issues/617>
#[test]
fn test_operators_other() {
let versions = VERSIONS_0
.iter()
.map(|version| Version::from_str(version).unwrap());
let specifiers: Vec<_> = SPECIFIERS_OTHER
.iter()
.map(|specifier| VersionSpecifier::from_str(specifier).unwrap())
.collect();
for (version, expected) in versions.zip(EXPECTED_OTHER) {
let actual = specifiers
.iter()
.map(|specifier| specifier.contains(&version));
for ((actual, expected), _specifier) in actual.zip(expected).zip(SPECIFIERS_OTHER) {
assert_eq!(actual, *expected);
}
}
}
#[test]
fn test_arbitrary_equality() {
assert!(
VersionSpecifier::from_str("=== 1.2a1")
.unwrap()
.contains(&Version::from_str("1.2a1").unwrap())
);
assert!(
!VersionSpecifier::from_str("=== 1.2a1")
.unwrap()
.contains(&Version::from_str("1.2a1+local").unwrap())
);
}
#[test]
fn test_equal_star_short_version_bug() {
// Version "2" (equivalent to 2.0) should NOT match "==2.1.*"
let specifier = VersionSpecifier::from_str("==2.1.*").unwrap();
let version = Version::from_str("2").unwrap();
assert!(
!specifier.contains(&version),
"Bug: version '2' incorrectly matches '==2.1.*'"
);
// Version "2" (equivalent to 2.0) SHOULD match "!=2.1.*"
let specifier = VersionSpecifier::from_str("!=2.1.*").unwrap();
let version = Version::from_str("2").unwrap();
assert!(
specifier.contains(&version),
"Bug: version '2' should match '!=2.1.*' (2.0 is not in 2.1 family)"
);
// Verify existing behavior still works: "2" matches "==2.0.*"
let specifier = VersionSpecifier::from_str("==2.0.*").unwrap();
let version = Version::from_str("2").unwrap();
assert!(
specifier.contains(&version),
"version '2' should match '==2.0.*'"
);
// And "2" should NOT match "!=2.0.*"
let specifier = VersionSpecifier::from_str("!=2.0.*").unwrap();
let version = Version::from_str("2").unwrap();
assert!(
!specifier.contains(&version),
"version '2' should not match '!=2.0.*'"
);
// Local versions: local segment should be ignored for prefix matching.
// "2+local" (== "2.0") should NOT match "==2.1.*"
let specifier = VersionSpecifier::from_str("==2.1.*").unwrap();
let version = Version::from_str("2+local").unwrap();
assert!(
!specifier.contains(&version),
"version '2+local' should not match '==2.1.*'"
);
// "2+local" (== "2.0") SHOULD match "!=2.1.*"
let specifier = VersionSpecifier::from_str("!=2.1.*").unwrap();
let version = Version::from_str("2+local").unwrap();
assert!(
specifier.contains(&version),
"version '2+local' should match '!=2.1.*'"
);
}
#[test]
fn test_specifiers_true() {
let pairs = [
// Test the equality operation
("2.0", "==2"),
("2.0", "==2.0"),
("2.0", "==2.0.0"),
("2.0+deadbeef", "==2"),
("2.0+deadbeef", "==2.0"),
("2.0+deadbeef", "==2.0.0"),
("2.0+deadbeef", "==2+deadbeef"),
("2.0+deadbeef", "==2.0+deadbeef"),
("2.0+deadbeef", "==2.0.0+deadbeef"),
("2.0+deadbeef.0", "==2.0.0+deadbeef.00"),
// Test the equality operation with a prefix
("2.dev1", "==2.*"),
("2a1", "==2.*"),
("2a1.post1", "==2.*"),
("2b1", "==2.*"),
("2b1.dev1", "==2.*"),
("2c1", "==2.*"),
("2c1.post1.dev1", "==2.*"),
("2c1.post1.dev1", "==2.0.*"),
("2rc1", "==2.*"),
("2rc1", "==2.0.*"),
("2", "==2.*"),
("2", "==2.0.*"),
("2", "==0!2.*"),
("0!2", "==2.*"),
("2.0", "==2.*"),
("2.0.0", "==2.*"),
("2.1+local.version", "==2.1.*"),
// Test the in-equality operation
("2.1", "!=2"),
("2.1", "!=2.0"),
("2.0.1", "!=2"),
("2.0.1", "!=2.0"),
("2.0.1", "!=2.0.0"),
("2.0", "!=2.0+deadbeef"),
// Test the in-equality operation with a prefix
("2.0", "!=3.*"),
("2.1", "!=2.0.*"),
// Test the greater than equal operation
("2.0", ">=2"),
("2.0", ">=2.0"),
("2.0", ">=2.0.0"),
("2.0.post1", ">=2"),
("2.0.post1.dev1", ">=2"),
("3", ">=2"),
// Test the less than equal operation
("2.0", "<=2"),
("2.0", "<=2.0"),
("2.0", "<=2.0.0"),
("2.0.dev1", "<=2"),
("2.0a1", "<=2"),
("2.0a1.dev1", "<=2"),
("2.0b1", "<=2"),
("2.0b1.post1", "<=2"),
("2.0c1", "<=2"),
("2.0c1.post1.dev1", "<=2"),
("2.0rc1", "<=2"),
("1", "<=2"),
// Test the greater than operation
("3", ">2"),
("2.1", ">2.0"),
("2.0.1", ">2"),
("2.1.post1", ">2"),
("2.1+local.version", ">2"),
("2.post2", ">2.post1"),
// Test the less than operation
("1", "<2"),
("2.0", "<2.1"),
("2.0.dev0", "<2.1"),
// https://github.com/astral-sh/uv/issues/12834
("0.1a1", "<0.1a2"),
("0.1dev1", "<0.1dev2"),
("0.1dev1", "<0.1a1"),
// Test the compatibility operation
("1", "~=1.0"),
("1.0.1", "~=1.0"),
("1.1", "~=1.0"),
("1.9999999", "~=1.0"),
("1.1", "~=1.0a1"),
("2022.01.01", "~=2022.01.01"),
// Test that epochs are handled sanely
("2!1.0", "~=2!1.0"),
("2!1.0", "==2!1.*"),
("2!1.0", "==2!1.0"),
("2!1.0", "!=1.0"),
("1.0", "!=2!1.0"),
("1.0", "<=2!0.1"),
("2!1.0", ">=2.0"),
("1.0", "<2!0.1"),
("2!1.0", ">2.0"),
// Test some normalization rules
("2.0.5", ">2.0dev"),
];
for (s_version, s_spec) in pairs {
let version = s_version.parse::<Version>().unwrap();
let spec = s_spec.parse::<VersionSpecifier>().unwrap();
assert!(
spec.contains(&version),
"{s_version} {s_spec}\nversion repr: {:?}\nspec version repr: {:?}",
version.as_bloated_debug(),
spec.version.as_bloated_debug(),
);
}
}
#[test]
fn test_specifier_false() {
let pairs = [
// Test the equality operation
("2.1", "==2"),
("2.1", "==2.0"),
("2.1", "==2.0.0"),
("2.0", "==2.0+deadbeef"),
// Test the equality operation with a prefix
("2.0", "==3.*"),
("2.1", "==2.0.*"),
// Test the in-equality operation
("2.0", "!=2"),
("2.0", "!=2.0"),
("2.0", "!=2.0.0"),
("2.0+deadbeef", "!=2"),
("2.0+deadbeef", "!=2.0"),
("2.0+deadbeef", "!=2.0.0"),
("2.0+deadbeef", "!=2+deadbeef"),
("2.0+deadbeef", "!=2.0+deadbeef"),
("2.0+deadbeef", "!=2.0.0+deadbeef"),
("2.0+deadbeef.0", "!=2.0.0+deadbeef.00"),
// Test the in-equality operation with a prefix
("2.dev1", "!=2.*"),
("2a1", "!=2.*"),
("2a1.post1", "!=2.*"),
("2b1", "!=2.*"),
("2b1.dev1", "!=2.*"),
("2c1", "!=2.*"),
("2c1.post1.dev1", "!=2.*"),
("2c1.post1.dev1", "!=2.0.*"),
("2rc1", "!=2.*"),
("2rc1", "!=2.0.*"),
("2", "!=2.*"),
("2", "!=2.0.*"),
("2.0", "!=2.*"),
("2.0.0", "!=2.*"),
// Test the greater than equal operation
("2.0.dev1", ">=2"),
("2.0a1", ">=2"),
("2.0a1.dev1", ">=2"),
("2.0b1", ">=2"),
("2.0b1.post1", ">=2"),
("2.0c1", ">=2"),
("2.0c1.post1.dev1", ">=2"),
("2.0rc1", ">=2"),
("1", ">=2"),
// Test the less than equal operation
("2.0.post1", "<=2"),
("2.0.post1.dev1", "<=2"),
("3", "<=2"),
// Test the greater than operation
("1", ">2"),
("2.0.dev1", ">2"),
("2.0a1", ">2"),
("2.0a1.post1", ">2"),
("2.0b1", ">2"),
("2.0b1.dev1", ">2"),
("2.0c1", ">2"),
("2.0c1.post1.dev1", ">2"),
("2.0rc1", ">2"),
("2.0", ">2"),
("2.post2", ">2"),
("2.0.post1", ">2"),
("2.0.post1.dev1", ">2"),
("2.0+local.version", ">2"),
// Test the less than operation
("2.0.dev1", "<2"),
("2.0a1", "<2"),
("2.0a1.post1", "<2"),
("2.0b1", "<2"),
("2.0b2.dev1", "<2"),
("2.0c1", "<2"),
("2.0c1.post1.dev1", "<2"),
("2.0rc1", "<2"),
("2.0", "<2"),
("2.post1", "<2"),
("2.post1.dev1", "<2"),
("3", "<2"),
// Test the compatibility operation
("2.0", "~=1.0"),
("1.1.0", "~=1.0.0"),
("1.1.post1", "~=1.0.0"),
// Test that epochs are handled sanely
("1.0", "~=2!1.0"),
("2!1.0", "~=1.0"),
("2!1.0", "==1.0"),
("1.0", "==2!1.0"),
("2!1.0", "==1.*"),
("1.0", "==2!1.*"),
("2!1.0", "!=2!1.0"),
];
for (version, specifier) in pairs {
assert!(
!VersionSpecifier::from_str(specifier)
.unwrap()
.contains(&Version::from_str(version).unwrap()),
"{version} {specifier}"
);
}
}
#[test]
fn test_parse_version_specifiers() {
let result = VersionSpecifiers::from_str("~= 0.9, >= 1.0, != 1.3.4.*, < 2.0").unwrap();
assert_eq!(
result.0.as_ref(),
[
VersionSpecifier {
operator: Operator::TildeEqual,
version: Version::new([0, 9]),
},
VersionSpecifier {
operator: Operator::GreaterThanEqual,
version: Version::new([1, 0]),
},
VersionSpecifier {
operator: Operator::NotEqualStar,
version: Version::new([1, 3, 4]),
},
VersionSpecifier {
operator: Operator::LessThan,
version: Version::new([2, 0]),
}
]
);
}
#[test]
fn test_parse_error() {
let result = VersionSpecifiers::from_str("~= 0.9, %= 1.0, != 1.3.4.*");
assert_eq!(
result.unwrap_err().to_string(),
indoc! {r"
Failed to parse version: Unexpected end of version specifier, expected operator:
~= 0.9, %= 1.0, != 1.3.4.*
^^^^^^^
"}
);
}
#[test]
fn test_parse_specifier_missing_operator_error() {
let result = VersionSpecifiers::from_str("3.12");
assert_eq!(
result.unwrap_err().to_string(),
indoc! {"
Failed to parse version: Unexpected end of version specifier, expected operator. Did you mean `==3.12`?:
3.12
^^^^
"}
);
}
#[test]
fn test_parse_specifier_missing_operator_invalid_version_error() {
let result = VersionSpecifiers::from_str("blergh");
assert_eq!(
result.unwrap_err().to_string(),
indoc! {r"
Failed to parse version: Unexpected end of version specifier, expected operator:
blergh
^^^^^^
"}
);
}
#[test]
fn test_non_star_after_star() {
let result = VersionSpecifiers::from_str("== 0.9.*.1");
assert_eq!(
result.unwrap_err().inner.err,
ParseErrorKind::InvalidVersion(version::PatternErrorKind::WildcardNotTrailing.into())
.into(),
);
}
#[test]
fn test_star_wrong_operator() {
let result = VersionSpecifiers::from_str(">= 0.9.1.*");
assert_eq!(
result.unwrap_err().inner.err,
ParseErrorKind::InvalidSpecifier(
BuildErrorKind::OperatorWithStar {
operator: Operator::GreaterThanEqual,
}
.into()
)
.into(),
);
}
#[test]
fn test_invalid_word() {
let result = VersionSpecifiers::from_str("blergh");
assert_eq!(
result.unwrap_err().inner.err,
ParseErrorKind::MissingOperator(VersionOperatorBuildError {
version_pattern: None
})
.into(),
);
}
/// <https://github.com/pypa/packaging/blob/e184feef1a28a5c574ec41f5c263a3a573861f5a/tests/test_specifiers.py#L44-L84>
#[test]
fn test_invalid_specifier() {
let specifiers = [
// Operator-less specifier
(
"2.0",
ParseErrorKind::MissingOperator(VersionOperatorBuildError {
version_pattern: VersionPattern::from_str("2.0").ok(),
})
.into(),
),
// Invalid operator
(
"=>2.0",
ParseErrorKind::InvalidOperator(OperatorParseError {
got: "=>".to_string(),
})
.into(),
),
// Version-less specifier
("==", ParseErrorKind::MissingVersion.into()),
// Local segment on operators which don't support them
(
"~=1.0+5",
ParseErrorKind::InvalidSpecifier(
BuildErrorKind::OperatorLocalCombo {
operator: Operator::TildeEqual,
version: Version::new([1, 0])
.with_local_segments(vec![LocalSegment::Number(5)]),
}
.into(),
)
.into(),
),
(
">=1.0+deadbeef",
ParseErrorKind::InvalidSpecifier(
BuildErrorKind::OperatorLocalCombo {
operator: Operator::GreaterThanEqual,
version: Version::new([1, 0]).with_local_segments(vec![
LocalSegment::String("deadbeef".to_string()),
]),
}
.into(),
)
.into(),
),
(
"<=1.0+abc123",
ParseErrorKind::InvalidSpecifier(
BuildErrorKind::OperatorLocalCombo {
operator: Operator::LessThanEqual,
version: Version::new([1, 0])
.with_local_segments(vec![LocalSegment::String("abc123".to_string())]),
}
.into(),
)
.into(),
),
(
">1.0+watwat",
ParseErrorKind::InvalidSpecifier(
BuildErrorKind::OperatorLocalCombo {
operator: Operator::GreaterThan,
version: Version::new([1, 0])
.with_local_segments(vec![LocalSegment::String("watwat".to_string())]),
}
.into(),
)
.into(),
),
(
"<1.0+1.0",
ParseErrorKind::InvalidSpecifier(
BuildErrorKind::OperatorLocalCombo {
operator: Operator::LessThan,
version: Version::new([1, 0]).with_local_segments(vec![
LocalSegment::Number(1),
LocalSegment::Number(0),
]),
}
.into(),
)
.into(),
),
// Prefix matching on operators which don't support them
(
"~=1.0.*",
ParseErrorKind::InvalidSpecifier(
BuildErrorKind::OperatorWithStar {
operator: Operator::TildeEqual,
}
.into(),
)
.into(),
),
(
">=1.0.*",
ParseErrorKind::InvalidSpecifier(
BuildErrorKind::OperatorWithStar {
operator: Operator::GreaterThanEqual,
}
.into(),
)
.into(),
),
(
"<=1.0.*",
ParseErrorKind::InvalidSpecifier(
BuildErrorKind::OperatorWithStar {
operator: Operator::LessThanEqual,
}
.into(),
)
.into(),
),
(
">1.0.*",
ParseErrorKind::InvalidSpecifier(
BuildErrorKind::OperatorWithStar {
operator: Operator::GreaterThan,
}
.into(),
)
.into(),
),
(
"<1.0.*",
ParseErrorKind::InvalidSpecifier(
BuildErrorKind::OperatorWithStar {
operator: Operator::LessThan,
}
.into(),
)
.into(),
),
// Combination of local and prefix matching on operators which do
// support one or the other
(
"==1.0.*+5",
ParseErrorKind::InvalidVersion(
version::PatternErrorKind::WildcardNotTrailing.into(),
)
.into(),
),
(
"!=1.0.*+deadbeef",
ParseErrorKind::InvalidVersion(
version::PatternErrorKind::WildcardNotTrailing.into(),
)
.into(),
),
// Prefix matching cannot be used with a pre-release, post-release,
// dev or local version
(
"==2.0a1.*",
ParseErrorKind::InvalidVersion(
version::ErrorKind::UnexpectedEnd {
version: "2.0a1".to_string(),
remaining: ".*".to_string(),
}
.into(),
)
.into(),
),
(
"!=2.0a1.*",
ParseErrorKind::InvalidVersion(
version::ErrorKind::UnexpectedEnd {
version: "2.0a1".to_string(),
remaining: ".*".to_string(),
}
.into(),
)
.into(),
),
(
"==2.0.post1.*",
ParseErrorKind::InvalidVersion(
version::ErrorKind::UnexpectedEnd {
version: "2.0.post1".to_string(),
remaining: ".*".to_string(),
}
.into(),
)
.into(),
),
(
"!=2.0.post1.*",
ParseErrorKind::InvalidVersion(
version::ErrorKind::UnexpectedEnd {
version: "2.0.post1".to_string(),
remaining: ".*".to_string(),
}
.into(),
)
.into(),
),
(
"==2.0.dev1.*",
ParseErrorKind::InvalidVersion(
version::ErrorKind::UnexpectedEnd {
version: "2.0.dev1".to_string(),
remaining: ".*".to_string(),
}
.into(),
)
.into(),
),
(
"!=2.0.dev1.*",
ParseErrorKind::InvalidVersion(
version::ErrorKind::UnexpectedEnd {
version: "2.0.dev1".to_string(),
remaining: ".*".to_string(),
}
.into(),
)
.into(),
),
(
"==1.0+5.*",
ParseErrorKind::InvalidVersion(
version::ErrorKind::LocalEmpty { precursor: '.' }.into(),
)
.into(),
),
(
"!=1.0+deadbeef.*",
ParseErrorKind::InvalidVersion(
version::ErrorKind::LocalEmpty { precursor: '.' }.into(),
)
.into(),
),
// Prefix matching must appear at the end
(
"==1.0.*.5",
ParseErrorKind::InvalidVersion(
version::PatternErrorKind::WildcardNotTrailing.into(),
)
.into(),
),
// Compatible operator requires 2 digits in the release operator
(
"~=1",
ParseErrorKind::InvalidSpecifier(BuildErrorKind::CompatibleRelease.into()).into(),
),
// Cannot use a prefix matching after a .devN version
(
"==1.0.dev1.*",
ParseErrorKind::InvalidVersion(
version::ErrorKind::UnexpectedEnd {
version: "1.0.dev1".to_string(),
remaining: ".*".to_string(),
}
.into(),
)
.into(),
),
(
"!=1.0.dev1.*",
ParseErrorKind::InvalidVersion(
version::ErrorKind::UnexpectedEnd {
version: "1.0.dev1".to_string(),
remaining: ".*".to_string(),
}
.into(),
)
.into(),
),
];
for (specifier, error) in specifiers {
assert_eq!(VersionSpecifier::from_str(specifier).unwrap_err(), error);
}
}
#[test]
fn test_display_start() {
assert_eq!(
VersionSpecifier::from_str("== 1.1.*")
.unwrap()
.to_string(),
"==1.1.*"
);
assert_eq!(
VersionSpecifier::from_str("!= 1.1.*")
.unwrap()
.to_string(),
"!=1.1.*"
);
}
#[test]
fn test_version_specifiers_str() {
assert_eq!(
VersionSpecifiers::from_str(">= 3.7").unwrap().to_string(),
">=3.7"
);
assert_eq!(
VersionSpecifiers::from_str(">=3.7, < 4.0, != 3.9.0")
.unwrap()
.to_string(),
">=3.7, !=3.9.0, <4.0"
);
}
#[test]
fn test_version_specifiers_singular_interval() {
let lower_then_upper = VersionSpecifiers::from_str(">=1.4.4, <=1.4.4").unwrap();
let upper_then_lower = VersionSpecifiers::from_str("<=1.4.4, >=1.4.4").unwrap();
assert_eq!(lower_then_upper, upper_then_lower);
assert_eq!(lower_then_upper.to_string(), "<=1.4.4, >=1.4.4");
}
/// These occur in the simple api, e.g.
/// <https://pypi.org/simple/geopandas/?format=application/vnd.pypi.simple.v1+json>
#[test]
fn test_version_specifiers_empty() {
assert_eq!(VersionSpecifiers::from_str("").unwrap().to_string(), "");
}
/// All non-ASCII version specifiers are invalid, but the user can still
/// attempt to parse a non-ASCII string as a version specifier. This
/// ensures no panics occur and that the error reported has correct info.
#[test]
fn non_ascii_version_specifier() {
let s = "💩";
let err = s.parse::<VersionSpecifiers>().unwrap_err();
assert_eq!(err.inner.start, 0);
assert_eq!(err.inner.end, 4);
// The first test here is plain ASCII and it gives the
// expected result: the error starts at codepoint 12,
// which is the start of `>5.%`.
let s = ">=3.7, <4.0,>5.%";
let err = s.parse::<VersionSpecifiers>().unwrap_err();
assert_eq!(err.inner.start, 12);
assert_eq!(err.inner.end, 16);
// In this case, we replace a single ASCII codepoint
// with U+3000 IDEOGRAPHIC SPACE. Its *visual* width is
// 2 despite it being a single codepoint. This causes
// the offsets in the error reporting logic to become
// incorrect.
//
// ... it did. This bug was fixed by switching to byte
// offsets.
let s = ">=3.7,\u{3000}<4.0,>5.%";
let err = s.parse::<VersionSpecifiers>().unwrap_err();
assert_eq!(err.inner.start, 14);
assert_eq!(err.inner.end, 18);
}
/// Tests the human readable error messages generated from an invalid
/// sequence of version specifiers.
#[test]
fn error_message_version_specifiers_parse_error() {
let specs = ">=1.2.3, 5.4.3, >=3.4.5";
let err = VersionSpecifierParseError {
kind: Box::new(ParseErrorKind::MissingOperator(VersionOperatorBuildError {
version_pattern: VersionPattern::from_str("5.4.3").ok(),
})),
};
let inner = Box::new(VersionSpecifiersParseErrorInner {
err,
line: specs.to_string(),
start: 8,
end: 14,
});
let err = VersionSpecifiersParseError { inner };
assert_eq!(err, VersionSpecifiers::from_str(specs).unwrap_err());
assert_eq!(
err.to_string(),
"\
Failed to parse version: Unexpected end of version specifier, expected operator. Did you mean `==5.4.3`?:
>=1.2.3, 5.4.3, >=3.4.5
^^^^^^
"
);
}
/// Tests the human readable error messages generated when building an
/// invalid version specifier.
#[test]
fn error_message_version_specifier_build_error() {
let err = VersionSpecifierBuildError {
kind: Box::new(BuildErrorKind::CompatibleRelease),
};
let op = Operator::TildeEqual;
let v = Version::new([5]);
let vpat = VersionPattern::verbatim(v);
assert_eq!(err, VersionSpecifier::from_pattern(op, vpat).unwrap_err());
assert_eq!(
err.to_string(),
"The ~= operator requires at least two segments in the release version"
);
}
/// Tests the human readable error messages generated from parsing invalid
/// version specifier.
#[test]
fn error_message_version_specifier_parse_error() {
let err = VersionSpecifierParseError {
kind: Box::new(ParseErrorKind::InvalidSpecifier(
VersionSpecifierBuildError {
kind: Box::new(BuildErrorKind::CompatibleRelease),
},
)),
};
assert_eq!(err, VersionSpecifier::from_str("~=5").unwrap_err());
assert_eq!(
err.to_string(),
"The ~= operator requires at least two segments in the release version"
);
}
/// PEP 440 states that trailing zeros in `~=` specifiers control forward
/// compatibility, so `~=2.2` ≠ `~=2.2.0`. Non-`~=` specifiers are unaffected.
#[test]
fn trailing_zero_equality() {
let equal = [
// Non-`~=` operators: trailing zeros are insignificant.
(">=3.3", ">=3.3.0"),
("<2", "<2.0.0"),
("==1.2", "==1.2.0"),
// Identical `~=` specifiers.
("~=2.2.0", "~=2.2.0"),
];
for (a, b) in equal {
let a = VersionSpecifier::from_str(a).unwrap();
let b = VersionSpecifier::from_str(b).unwrap();
assert_eq!(a, b);
}
let not_equal = [
// PEP 440 forward-compat examples.
("~=2.2", "~=2.2.0"),
("~=1.4.5", "~=1.4.5.0"),
// Same release, different suffix.
("~=2.2.post3", "~=2.2.post5"),
// Different release length with matching suffix.
("~=2.2.post3", "~=2.2.0.post3"),
];
for (a, b) in not_equal {
let a = VersionSpecifier::from_str(a).unwrap();
let b = VersionSpecifier::from_str(b).unwrap();
assert_ne!(a, b);
}
}
/// Do not panic with `u64::MAX` causing an `u64::MAX + 1` overflow.
#[test]
fn bounding_specifiers_u64_max_rejected_at_parse_time() {
assert!(VersionSpecifier::from_str("~=3.18446744073709551615.0").is_err());
assert!(VersionSpecifier::from_str("~=18446744073709551615.0").is_err());
// u64::MAX - 1 is accepted and bounding_specifiers does not overflow.
let specifier = VersionSpecifier::from_str("~=3.18446744073709551614.0").unwrap();
let tilde = TildeVersionSpecifier::from_specifier(specifier).unwrap();
let (_lower, _upper) = tilde.bounding_specifiers();
}
}