-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathversion_range.py
More file actions
1270 lines (1035 loc) · 44 KB
/
Copy pathversion_range.py
File metadata and controls
1270 lines (1035 loc) · 44 KB
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
#
# Copyright (c) nexB Inc. and others.
# SPDX-License-Identifier: Apache-2.0
#
# Visit https://aboutcode.org and https://github.com/nexB/univers for support and download.
import attr
import semantic_version
from packaging.specifiers import InvalidSpecifier
from packaging.specifiers import SpecifierSet
from semantic_version.base import AllOf
from semantic_version.base import AnyOf
from univers import gem
from univers import maven
from univers import versions
from univers.conan.version_range import VersionRange as conan_version_range
from univers.utils import remove_spaces
from univers.version_constraint import VersionConstraint
from univers.version_constraint import contains_version
class InvalidVersionRange(Exception):
"""
Error for scheme-specific version syntax is not supported or not valid
"""
INVERTED_COMPARATORS = {
">=": "<",
"<=": ">",
"!=": "=",
"<": ">=",
">": "<=",
"=": "!=",
}
@attr.s(frozen=True, order=False, eq=True, hash=True)
class VersionRange:
"""
Base version range class. Subclasses must provide implement.
A VersionRange represents a list of constraints on the versions "timeline"
of a package.
"""
# Versioning scheme. By convention this is the same as the Package URL
# package type since this "defines" most commonly the versioning scheme of a
# package, such as "npm" (whose scheme is defined in the "node-semver" npm
# package. This could be something else though and a purl may be accompanied
# by a version range for another scheme; for example, a
# ``pkg:github/foo/bar`` purl could be accompanied by a a ``vers:npm/12.3``
# range. Subclasses MUST provide this.
scheme = None
# Version subclass to use with this versioning scheme, such as
# PypiVersion. Subclasses MUST provide this.
version_class = None
# A tuple of VersionConstraint that are signposts on the versions
# timeline
constraints = attr.ib(type=tuple, default=attr.Factory(tuple))
def __attrs_post_init__(self, *args, **kwargs):
constraints = tuple(sorted(self.constraints))
# Notes: setattr is used because this is an immutable frozen instance.
# See https://www.attrs.org/en/stable/init.html?#post-init
object.__setattr__(self, "constraints", constraints)
@classmethod
def from_native(cls, string):
"""
Return a VersionRange built from a scheme-specific, native version range
``string``. Subclasses can implement.
"""
return NotImplementedError
@classmethod
def from_natives(cls, strings):
"""
Return a VersionRange built from a ``strings`` list of scheme-
specific native version range strings. Subclasses can implement.
"""
return NotImplementedError
def to_native(self, *args, **kwargs):
"""
Return a native range string for this VersionRange. Subclasses can
implement. Optional ``args`` and ``kwargs`` allow subclass to require
extra arguments (such as a package name that some scheme may require
like for deb and rpm.)
"""
return NotImplementedError
@classmethod
def from_string(cls, vers, simplify=False, validate=False):
"""
Return a VersionRange built from a ``vers`` version range spec string,
such as "vers:npm/1.2.3,>=2.0.0"
"""
if not vers or not isinstance(vers, str) or not vers.strip():
raise ValueError("A vers string argument is required.")
# Spaces are not significant and removed in a canonical form.
vers = remove_spaces(vers)
# A version range specifier contains only printable ASCII letters, digits and
# punctuation.
is_ascii = len(vers) + 2 == len(ascii(vers))
if not is_ascii:
raise ValueError(f"Invalid non ASCII characters: {vers!r}")
# The URI scheme and versioning scheme are always lowercase as in ``vers:npm``.
uri_scheme, _, scheme_range_spec = vers.partition(":")
uri_scheme = uri_scheme.lower()
if uri_scheme != "vers":
raise ValueError(f"{vers!r} must start with the 'vers:' URI scheme.")
versioning_scheme, _, constraints = scheme_range_spec.partition("/")
versioning_scheme = versioning_scheme.lower()
range_class = RANGE_CLASS_BY_SCHEMES.get(versioning_scheme)
if not range_class:
raise ValueError(
f"{vers!r} has an unknown versioning scheme: " f"{versioning_scheme!r}.",
)
version_class = range_class.version_class
constraints = remove_spaces(constraints)
if not constraints:
raise ValueError(f"{vers!r} specifies no version range constraints.")
# There is only one star: "*" must only occur once and alone in a range,
# without any other constraint or version.
if constraints.startswith("*"):
if constraints != "*":
raise ValueError(f"{vers!r} contains an invalid '*' constraint.")
return range_class(
[VersionConstraint.from_string(string="*", version_class=version_class)]
)
parsed_constraints = []
constraints = constraints.strip("|")
for const in constraints.split("|"):
constraint = VersionConstraint.from_string(
string=const,
version_class=version_class,
)
parsed_constraints.append(constraint)
# Constraints are sorted by version**. The canonical ordering is the versions
# order. The ordering of ``<version-constraint>`` is not significant otherwise
# but this sort order is needed when check if a version is contained in a range.
parsed_constraints.sort()
if simplify:
parsed_constraints = VersionConstraint.simplify(parsed_constraints)
if validate:
VersionConstraint.validate(parsed_constraints)
return range_class(parsed_constraints)
@classmethod
def from_versions(cls, sequence):
"""
Return a VersionRange built from a list of version strings,
such as ["3.0.0", "1.0.1b", "3.0.2", "0.9.7a", "1.1.1ka"]
"""
if not cls.scheme or not cls.version_class:
return NotImplementedError
constraints = []
for version in sequence:
version_obj = cls.version_class(version)
constraint = VersionConstraint(comparator="=", version=version_obj)
constraints.append(constraint)
return cls(constraints=constraints)
def is_star(self):
return len(self.constraints) == 1 and self.constraints[0].is_star()
def invert(self):
"""
Return the inverse or complement of this VersionRange. For example, if this range is
">=1.0.0", the inverse is "<1.0.0".
>>> str(VersionRange.from_string("vers:npm/>=1.0.0").invert())
'vers:npm/<1.0.0'
"""
inverted_constraints = []
if self.is_star():
# The inverse of "*" is an empty range.
return None
for constraint in self.constraints:
inverted_constraints.append(constraint.invert())
return self.__class__(constraints=inverted_constraints)
def __str__(self):
constraints = "|".join(str(c) for c in sorted(self.constraints))
return f"vers:{self.scheme}/{constraints}"
to_string = __str__
def to_dict(self):
constraints = [c.to_dict() for c in self.constraints]
return dict(scheme=self.scheme, constraints=constraints)
def __contains__(self, version):
"""
Return True if this VersionRange contains the ``version`` Version
object. A version is contained in a VersionRange if it satisfies its
constraints according to ``vers`` rules.
"""
if not isinstance(version, self.version_class):
raise TypeError(
f"{version!r} is not of expected type: {self.version_class!r}",
)
return contains_version(version, self.constraints)
contains = __contains__
def __eq__(self, other):
return (
self.scheme == other.scheme
and self.version_class == other.version_class
and self.constraints == other.constraints
)
def from_cve_v4(data, scheme):
"""
Return a VersionRange build from the provided CVE V4 API ``data`` using the
provided versioning vers ``scheme``.
"""
def from_cve_v5(data, scheme):
"""
Return a VersionRange build from the provided CVE V5 API ``data`` using the
provided versioning vers ``scheme``.
See https://github.com/CVEProject/cve-schema/tree/master/schema/v5.0
``data`` can be:
- a mapping of collectionURL and versions:
{"collectionURL": "some URL", "versions": [{"versionValue": "1.0"}]}
"""
def from_osv_v1(data, scheme):
"""
Return a VersionRange build from the provided CVE V4 API data using the
provided versioning vers ``scheme``.
"""
def get_allof_constraints(cls, clause):
"""
Return a list of VersionConstraint given an AllOf ``clause``.
"""
if not isinstance(clause, AllOf):
raise ValueError(f"Unknown clause type: {clause!r}")
allof_constraints = []
for constraint in clause.clauses:
comparator = cls.vers_by_native_comparators[constraint.operator]
version = cls.version_class(str(constraint.target))
constraint = VersionConstraint(comparator=comparator, version=version)
allof_constraints.append(constraint)
return allof_constraints
def get_npm_version_constraints_from_semver_npm_spec(string, cls):
"""
Return a VersionConstraint for the provided ``string``.
"""
spec = semantic_version.NpmSpec(string)
clause = spec.clause.simplify()
if isinstance(clause, (AnyOf, AllOf)):
anyof_constraints = []
if isinstance(clause, AnyOf):
for allof_clause in clause.clauses:
anyof_constraints.extend(get_allof_constraints(cls, allof_clause))
elif isinstance(clause, AllOf):
alloc = get_allof_constraints(cls, clause)
anyof_constraints.extend(alloc)
else:
raise ValueError(f"Unknown clause type: {spec!r}")
return anyof_constraints
class NpmVersionRange(VersionRange):
scheme = "npm"
version_class = versions.SemverVersion
vers_by_native_comparators = {
"==": "=",
"<=": "<=",
">=": ">=",
"<": "<",
">": ">",
"=": "=", # This is not a native node-semver comparator, but is used in the gitlab version range for npm packages.
}
@classmethod
def from_native(cls, string):
"""
Return a VersionRange built from an npm "node-semver" range ``string``.
"""
# FIXME: code is entirely duplicated with the GemVersionRange
# an NpmSpec handles parsing of both the semver versions and node-semver
# ranges at once
if string == "*":
return cls(
constraints=[
VersionConstraint.from_string(string="*", version_class=cls.version_class)
]
)
constraints = []
vrc = cls.version_class
# A constraint item can be a comparator or a version or a version with comparator
# If it's empty continue
# If it's in `vers_by_native_comparators`, append it with the comparator and continue
# If it's a version, make version constraint from the version and use the comparator from the previous item and make comparator empty
# If it's a version with comparator, use split_req to get version and comparator to form constraint and make comparator empty
for range in string.split("||"):
if " - " in range:
constraints.extend(
get_npm_version_constraints_from_semver_npm_spec(string=range, cls=cls)
)
continue
comparator = ""
for constraint in range.split():
cmp = "".join([comparator, constraint])
if cmp in cls.vers_by_native_comparators:
comparator = cls.vers_by_native_comparators[cmp]
continue
if comparator:
if constraint.endswith(".x"):
constraints.extend(
get_npm_version_constraints_from_semver_npm_spec(
string=constraint, cls=cls
)
)
else:
constraint = constraint.lstrip("vV")
constraints.append(
VersionConstraint(comparator=comparator, version=vrc(constraint))
)
else:
if (
constraint.endswith(".x")
or constraint.startswith("~")
or constraint.startswith("^")
):
constraints.extend(
get_npm_version_constraints_from_semver_npm_spec(
string=constraint, cls=cls
)
)
else:
comparator, version_constraint = split_req(
string=constraint,
comparators=cls.vers_by_native_comparators,
default="=",
)
version_constraint = version_constraint.lstrip("vV")
constraints.append(
VersionConstraint(
comparator=comparator, version=vrc(version_constraint)
)
)
comparator = ""
return cls(constraints=constraints)
class ConanVersionRange(VersionRange):
scheme = "conan"
version_class = versions.ConanVersion
@classmethod
def from_native(cls, string):
"""
Return a VersionRange built from a conan range ``string``.
"""
condition_sets = conan_version_range(string).condition_sets
constraints = []
for conditions in condition_sets:
for condition in conditions.conditions:
comparator = condition.operator
version = condition.version
constraints.append(
VersionConstraint(
comparator=comparator, version=cls.version_class(str(version))
)
)
return cls(constraints=constraints)
class GemVersionRange(VersionRange):
"""
A version range implementation for Rubygems.
gem need its own versioning scheme as this is not semver.
See https//github.com/nexB/univers/issues/5
See https://github.com/ruby/ruby/blob/415671a28273e5bfbe9aa00a0e386f025720ac23/lib/rubygems/requirement.rb
See https//semver.org/spec/v2.0.0.html#spec-item-11
See https//snyk.io/blog/differences-in-version-handling-gems-and-npm/
See https://github.com/npm/node-semver/issues/112
"""
scheme = "gem"
version_class = versions.RubygemsVersion
vers_by_native_comparators = {
"=": "=",
"!=": "!=",
"<=": "<=",
">=": ">=",
"<": "<",
">": ">",
}
@classmethod
def from_native(cls, string):
"""
Return a VersionRange built from a Rubygem version range ``string``.
Gem version semantics are different from semver: there can be commonly
more than three segments and the operators are also different.
"""
gr = gem.GemRequirement.from_string(string).simplify()
constraints = []
for gc in gr.constraints:
version = cls.version_class(str(gc.version))
op = cls.vers_by_native_comparators[gc.op]
vc = VersionConstraint(comparator=op, version=version)
constraints.append(vc)
return cls(constraints=constraints)
def split_req(string, comparators, default=None, strip=""):
"""
Return a tuple of (vers comparator, version) strings given an common version
requirement``string`` such as "> 2.3" or "<= 2.3" using the ``comparators``
mapping of {native comparator: vers comparator}. Strip the ``string`` from
the provided leading of training characters in ``strip``.
If there is none of the ``comparators`` found in ``string``:
- Return the ``default`` vers comparator string if provided.
- Otherwise, raise a ValueError for an unknown comparator.
For example::
>>> comps = {"=": "=", "<=": "<=", ">=": ">="}
>>> assert split_req("= 2.3", comparators=comps) == ("=", "2.3",)
>>> assert split_req(" < = 2 . 3 ", comparators=comps) == ("<=", "2.3",)
>>> assert split_req(">= 2.3", comparators=comps) == (">=", "2.3",)
>>> assert split_req(">= 2.3", comparators=comps) == (">=", "2.3",)
>>> assert split_req("<= 2.3", comparators=comps) == ("<=", "2.3",)
>>> assert split_req("(< = 2.3 )", comparators=comps, strip=")(") == ("<=", "2.3",)
With a default, we return the default comparator::
>>> assert split_req("2.3,", comparators=comps, default="=", strip=",") == ("=", "2.3",)
Otherwise, a ValuaeError::
>>> try:
... split_req("~2.3", comparators=comps, )
... raise Exception("ValueError should be raised")
... except ValueError:
... pass
"""
constraint_string = remove_spaces(string).strip(strip)
for native_comparator, vers_comparator in comparators.items():
if constraint_string.startswith(native_comparator):
version = constraint_string.lstrip(native_comparator)
return vers_comparator, version
if default:
return default, constraint_string
raise ValueError(f"Unknown comparator in version requirement: {string!r} ")
class DebianVersionRange(VersionRange):
"""
Debian version ranges as seen in Debian manual for relationships:
https://www.debian.org/doc/debian-policy/ch-relationships.html
These are for defined one expression at a time. Multiple expressions each
com with a package name. Therefore there is no "range string" per se, instead
there is always a list of version constraints as an input. For instance::
libc6 (>> 2.23), libc6 (<< 2.24)'
Therefore native conversions are different.
"""
scheme = "deb"
version_class = versions.DebianVersion
vers_by_native_comparators = {
"=": "=",
"<=": "<=",
">=": ">=",
"<<": "<",
">>": ">",
# legacy
"<": "<",
">": ">",
}
@classmethod
def split(cls, string):
"""
Return a tuple of (vers comparator, version) strings given a Debian
version relationship ``string`` such as ">>2.3" or "(<< 2.3)". Raise a
ValueError for unknown comparators.
For example::
>>> assert DebianVersionRange.split("=2.3") == ("=", "2.3",)
>>> assert DebianVersionRange.split(" < = 2 . 3 ") == ("<=", "2.3",)
>>> assert DebianVersionRange.split("(>=2.3)") == (">=", "2.3",)
>>> assert DebianVersionRange.split(">=2.3") == (">=", "2.3",)
>>> assert DebianVersionRange.split("<=2.3") == ("<=", "2.3",)
>>> assert DebianVersionRange.split("<<2.3") == ("<", "2.3",)
>>> assert DebianVersionRange.split(">>2.3") == (">", "2.3",)
>>> assert DebianVersionRange.split(">2.3") == (">", "2.3",)
>>> assert DebianVersionRange.split("<2.3") == ("<", "2.3",)
>>> try:
... DebianVersionRange.split("~2.3")
... raise Exception("ValueError should be raised")
... except ValueError:
... pass
"""
return split_req(
string=string,
comparators=cls.vers_by_native_comparators,
strip=")(",
)
@classmethod
def build_constraint_from_string(cls, string):
"""
Return a VersionConstraint built from a single Debian version
relationship ``string``.
>>> vr = DebianVersionRange.build_constraint_from_string("= 5.0")
>>> assert str(vr) == "5.0"
>>> vr = DebianVersionRange.build_constraint_from_string("(>> 2.23)")
>>> assert str(vr) == ">2.23"
>>> vr = DebianVersionRange.build_constraint_from_string("<= 2.24")
>>> assert str(vr) == "<=2.24"
"""
comparator, version = cls.split(string)
version = cls.version_class(version)
return VersionConstraint(comparator=comparator, version=version)
@classmethod
def from_native(cls, string):
"""
Return a VersionRange built from a ``string`` single Debian
version relationship string.
For example::
>>> vr = DebianVersionRange.from_native("(= 3.5.6)")
>>> assert str(vr) == "vers:deb/3.5.6"
"""
return cls(constraints=[cls.build_constraint_from_string(string)])
@classmethod
def from_natives(cls, strings):
"""
Return a VersionRange built from a ``strings`` list of Debian
version relationships or a single relationship string.
For example::
>>> vr = DebianVersionRange.from_natives("= 3.5.6")
>>> assert str(vr) == "vers:deb/3.5.6"
>>> rels = ["(>= 2.8.16)"]
>>> vr = DebianVersionRange.from_natives(rels)
>>> assert str(vr) == "vers:deb/>=2.8.16"
>>> rels = [">= 1:1.1.4", "(>= 2.8.16)", "<= 2.8.16-z"]
>>> vr = DebianVersionRange.from_natives(rels)
>>> assert str(vr) == "vers:deb/>=2.8.16|<=2.8.16-z|>=1:1.1.4"
>>> rels = ["(>= 2:4.13.1)", "(<= 2:4.13.1-0ubuntu0.16.04.1.1~)"]
>>> vr = DebianVersionRange.from_natives(rels)
>>> assert str(vr) == "vers:deb/>=2:4.13.1|<=2:4.13.1-0ubuntu0.16.04.1.1~"
>>> rels = ["= 5.0", "(>> 2.23)", "< 2.24"]
>>> vr = DebianVersionRange.from_natives(rels)
>>> assert str(vr) == "vers:deb/>2.23|<2.24|5.0"
>>> rels = ["(<< 3:1.1.25~)", "(>> 2:1.1.24~)"]
>>> vr = DebianVersionRange.from_natives(rels)
>>> assert str(vr) == "vers:deb/>2:1.1.24~|<3:1.1.25~"
"""
if isinstance(strings, str):
return cls.from_native(strings)
constraints = [cls.build_constraint_from_string(rel) for rel in strings]
return cls(constraints=constraints)
class PypiVersionRange(VersionRange):
"""
PyPI PEP 440 version range.
For example:
>>> from univers.versions import PypiVersion
>>> constraints = [
... VersionConstraint(version=PypiVersion("2")),
... VersionConstraint(comparator=">=", version=PypiVersion("3")),
... VersionConstraint(comparator="<", version=PypiVersion("4")),
... VersionConstraint(version=PypiVersion("5")),
... ]
>>> range = PypiVersionRange(constraints=constraints)
>>> assert str(range) == "vers:pypi/2|>=3|<4|5"
"""
scheme = "pypi"
version_class = versions.PypiVersion
vers_by_native_comparators = {
# 01.01.01 is equal 1.1.1 e.g., with version normalization
"==": "=",
"!=": "!=",
"<=": "<=",
">=": ">=",
"<": "<",
">": ">",
# per https://www.python.org/dev/peps/pep-0440/#compatible-release
# For a given release identifier V.N, the compatible release clause is
# approximately equivalent to the pair of comparison clauses:
# >= V.N, == V.*
"~=": None,
# 01.01.01 is NOT equal to 1.1.1 using === which is strict string
# equality this is a rare and eventually non-suggested approach
"===": None,
}
@classmethod
def from_native(cls, string):
"""
Return a VersionRange built from a PyPI PEP440 version specifiers ``string``.
Raise an a univers.versions.InvalidVersion
"""
# TODO: environment markers are yet supported
# TODO: handle .* version, ~= and === operators
if ";" in string:
raise InvalidVersionRange(f"Unsupported PyPI environment marker: {string!r}")
unsupported_chars = ";\\/|{}()`?'\"\t\n "
string = "".join(string.split(" "))
if any(c in string for c in unsupported_chars):
raise InvalidVersionRange(
f"Unsupported character: {unsupported_chars!r} " f"in PyPI version: {string!r}"
)
try:
specifiers = SpecifierSet(string)
except InvalidSpecifier as e:
raise InvalidVersionRange() from e
# Note that in PyPI all constraints apply
constraints = []
unsupported_messages = []
for spec in specifiers:
operator = spec.operator
version = spec.version
if operator == "~=" or operator == "===":
msg = f"Unsupported PyPI version constraint operator: {spec!r}"
unsupported_messages.append(msg)
if str(version).endswith(".*"):
msg = f"Unsupported PyPI version: {spec!r}"
unsupported_messages.append(msg)
try:
version = cls.version_class(version)
comparator = cls.vers_by_native_comparators[operator]
constraint = VersionConstraint(comparator=comparator, version=version)
constraints.append(constraint)
except:
msg = f"Invalid PyPI version: {spec!r}"
unsupported_messages.append(msg)
if unsupported_messages:
raise InvalidVersionRange(*unsupported_messages)
return cls(constraints=constraints)
class MavenVersionRange(VersionRange):
"""
Maven version range as documented at
https://maven.apache.org/enforcer/enforcer-rules/versionRanges.html
"""
scheme = "maven"
version_class = versions.MavenVersion
@classmethod
def from_native(cls, string):
"""
Return a VersionRange built from a Maven version specifier ``string``.
"""
string = "".join(string.split(" "))
restrictions = maven.VersionRange(string).restrictions
constraints = []
for restriction in restrictions:
lower_bound = restriction.lower_bound
upper_bound = restriction.upper_bound
lower_inclusive = restriction.lower_bound_inclusive
upper_inclusive = restriction.upper_bound_inclusive
if lower_bound == upper_bound:
constraints.append(
VersionConstraint(comparator="=", version=cls.version_class(str(lower_bound)))
)
continue
if lower_bound:
if lower_inclusive:
comparator = ">="
else:
comparator = ">"
constraints.append(
VersionConstraint(
comparator=comparator, version=cls.version_class(str(lower_bound))
)
)
if upper_bound:
if upper_inclusive:
comparator = "<="
else:
comparator = "<"
constraints.append(
VersionConstraint(
comparator=comparator, version=cls.version_class(str(upper_bound))
)
)
return cls(constraints=constraints)
@classmethod
def from_natives(cls, strings):
if isinstance(strings, str):
return cls.from_native(strings)
constraints = []
for rel in strings:
constraints.extend(cls.from_native(rel).constraints)
return cls(constraints=constraints)
class NugetVersionRange(MavenVersionRange):
"""
NuGet range as in:[3.10.1,4)
"""
scheme = "nuget"
version_class = versions.NugetVersion
class ComposerVersionRange(VersionRange):
# TODO composer may need its own scheme see https//github.com/nexB/univers/issues/5
# and https//getcomposer.org/doc/articles/versions.md
scheme = "composer"
version_class = versions.ComposerVersion
vers_by_native_comparators = {
"==": "=",
"<=": "<=",
">=": ">=",
"<": "<",
">": ">",
"=": "=", # This is not a native composer-semver comparator, but is used in the gitlab version range for composer packages.
}
class RpmVersionRange(VersionRange):
# http://ftp.rpm.org/api/4.4.2.2/dependencies.html
# http://ftp.rpm.org/max-rpm/s1-rpm-depend-manual-dependencies.html
scheme = "rpm"
version_class = versions.RpmVersion
vers_by_native_comparators = {
"=": "=",
"<=": "<=",
">=": ">=",
"<": "<",
">": ">",
# seen in RPM code but never seen in the doc or in the wild so far
"<>": "!=",
# seen in a specfile parser code
"!=": "!=",
"==": "=",
}
@classmethod
def build_constraint_from_string(cls, string):
"""
Return a VersionConstraint built from a single RPM version
relationship ``string``.
>>> vr = RpmVersionRange.build_constraint_from_string("= 5.0")
>>> assert str(vr) == "5.0", str(vr)
>>> vr = RpmVersionRange.build_constraint_from_string("> 2.23,")
>>> assert str(vr) == ">2.23", str(vr)
>>> vr = RpmVersionRange.build_constraint_from_string("<= 2.24")
>>> assert str(vr) == "<=2.24", str(vr)
"""
comparator, version = split_req(
string=string,
comparators=cls.vers_by_native_comparators,
strip=",",
)
version = cls.version_class(version)
return VersionConstraint(comparator=comparator, version=version)
@classmethod
def from_native(cls, string):
"""
Return a VersionRange built from a ``string`` single RPM
version requirement string.
For example::
>>> vr = RpmVersionRange.from_native("= 3.5.6")
>>> assert str(vr) == "vers:rpm/3.5.6", str(vr)
"""
return cls(constraints=[cls.build_constraint_from_string(string)])
@classmethod
def from_natives(cls, strings):
"""
Return a VersionRange built from a ``strings`` list of RPM
version requirements or a single requirement string.
For example::
>>> vr = RpmVersionRange.from_natives("= 3.5.6")
>>> assert str(vr) == "vers:rpm/3.5.6", str(vr)
>>> reqs = [">= 2.8.16"]
>>> vr = RpmVersionRange.from_natives(reqs)
>>> assert str(vr) == "vers:rpm/>=2.8.16", str(vr)
>>> reqs = [">= 1:1.1.4", ">= 2.8.16", "<= 2.8.16-z"]
>>> vr = RpmVersionRange.from_natives(reqs)
>>> assert str(vr) == "vers:rpm/>=2.8.16|<=2.8.16-z|>=1:1.1.4", str(vr)
>>> reqs = ["= 5.0", "> 2.23,", "< 2.24"]
>>> vr = RpmVersionRange.from_natives(reqs)
>>> assert str(vr) == "vers:rpm/>2.23|<2.24|5.0", str(vr)
"""
if isinstance(strings, str):
return cls.from_native(strings)
constraints = [cls.build_constraint_from_string(rel) for rel in strings]
return cls(constraints=constraints)
class GolangVersionRange(VersionRange):
"""
Go modules use strict semver with pseudo numbering for Git repos
https://go.dev/doc/modules/version-numbers
"""
scheme = "golang"
version_class = versions.GolangVersion
vers_by_native_comparators = {
"==": "=",
"<=": "<=",
">=": ">=",
"<": "<",
">": ">",
"=": "=", # This is not a native golang-semver comparator, but is used in the gitlab version range for go packages.
}
class GenericVersionRange(VersionRange):
scheme = "generic"
version_class = versions.SemverVersion
class ApacheVersionRange(VersionRange):
# apache is not semver at large. And in particular we may have schemes that
# are package name-specific
scheme = "apache"
version_class = versions.SemverVersion
class HexVersionRange(VersionRange):
scheme = "hex"
version_class = versions.SemverVersion
class CargoVersionRange(VersionRange):
scheme = "cargo"
version_class = versions.SemverVersion
class MozillaVersionRange(VersionRange):
scheme = "mozilla"
version_class = versions.SemverVersion
class GitHubVersionRange(VersionRange):
scheme = "github"
version_class = versions.SemverVersion
class EbuildVersionRange(VersionRange):
scheme = "ebuild"
version_class = versions.GentooVersion
class AlpineLinuxVersionRange(VersionRange):
scheme = "alpine"
version_class = versions.AlpineLinuxVersion
class ArchLinuxVersionRange(VersionRange):
scheme = "alpm"
version_class = versions.ArchLinuxVersion
class NginxVersionRange(VersionRange):
"""
Nginx versioning is semver for version and their own syntax for ranges as
used in their security advisories.
The documentation on these ranges is minimal. See these for details:
- https://mailman.nginx.org/pipermail/nginx/2021-September/061039.html
- https://nginx.org/en/security_advisories.html
- https://serverfault.com/questions/715049/what-s-the-difference-between-the-mainline-and-stable-branches-of-nginx
In particular for versions:
- the versions are semver.
- versions can be in the one "mainline" branch or one of many "stable" branches.
- for versions in the "mainline" branch, (e.g., development) the minor
segment is an odd number.
- versions in the "stable" branch, (e.g., a release branch) the minor
segment is an even number. Installation are typically made from branch and
its versions.
For example: in 0.6.18 the 6 e.g., semver "minor" segment is either odd or even
- odd (as with "7") means this is the "mainline" branch
- even (as with "4") means this is in a "stable" branch
And for ranges, we have these notations:
- dash ranges: 0.6.18-1.20.0 where start and end are included in the range
- comma ranges: 1.21.0+, 1.20.1+ where any of the condition applies
- plus suffixes: 1.21.0+ where this or any later version in the branch applies
Therefore:
- 1.21.0+ would expand to >=1.21.0 because 21 is odd and this is the
mainline branch
- 1.22.0+ would expand to >=1.22.0,<1.23.0 because 22 is even and this is
one of the stable branches
There are two special version range values:
- "all" means all versions.
- "none" means no version and therefore no version range. It is used only
in one advisory for CVE-2009-4487 and triggers an error.