-
Notifications
You must be signed in to change notification settings - Fork 74
/
base.py
1456 lines (1207 loc) · 47.3 KB
/
base.py
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
# -*- coding: utf-8 -*-
# Copyright (c) The python-semanticversion project
# This code is distributed under the two-clause BSD License.
import functools
import re
import warnings
def _has_leading_zero(value):
return (value
and value[0] == '0'
and value.isdigit()
and value != '0')
class MaxIdentifier(object):
__slots__ = []
def __repr__(self):
return 'MaxIdentifier()'
def __eq__(self, other):
return isinstance(other, self.__class__)
@functools.total_ordering
class NumericIdentifier(object):
__slots__ = ['value']
def __init__(self, value):
self.value = int(value)
def __repr__(self):
return 'NumericIdentifier(%r)' % self.value
def __eq__(self, other):
if isinstance(other, NumericIdentifier):
return self.value == other.value
return NotImplemented
def __lt__(self, other):
if isinstance(other, MaxIdentifier):
return True
elif isinstance(other, AlphaIdentifier):
return True
elif isinstance(other, NumericIdentifier):
return self.value < other.value
else:
return NotImplemented
@functools.total_ordering
class AlphaIdentifier(object):
__slots__ = ['value']
def __init__(self, value):
self.value = value.encode('ascii')
def __repr__(self):
return 'AlphaIdentifier(%r)' % self.value
def __eq__(self, other):
if isinstance(other, AlphaIdentifier):
return self.value == other.value
return NotImplemented
def __lt__(self, other):
if isinstance(other, MaxIdentifier):
return True
elif isinstance(other, NumericIdentifier):
return False
elif isinstance(other, AlphaIdentifier):
return self.value < other.value
else:
return NotImplemented
class Version(object):
version_re = re.compile(r'^(\d+)\.(\d+)\.(\d+)(?:-([0-9a-zA-Z.-]+))?(?:\+([0-9a-zA-Z.-]+))?$')
partial_version_re = re.compile(r'^(\d+)(?:\.(\d+)(?:\.(\d+))?)?(?:-([0-9a-zA-Z.-]*))?(?:\+([0-9a-zA-Z.-]*))?$')
def __init__(
self,
version_string=None,
major=None,
minor=None,
patch=None,
prerelease=None,
build=None,
partial=False):
if partial:
warnings.warn(
"Partial versions will be removed in 3.0; use SimpleSpec('1.x.x') instead.",
DeprecationWarning,
stacklevel=2,
)
has_text = version_string is not None
has_parts = not (major is minor is patch is prerelease is build is None)
if not has_text ^ has_parts:
raise ValueError("Call either Version('1.2.3') or Version(major=1, ...).")
if has_text:
major, minor, patch, prerelease, build = self.parse(version_string, partial)
else:
# Convenience: allow to omit prerelease/build.
prerelease = tuple(prerelease or ())
if not partial:
build = tuple(build or ())
self._validate_kwargs(major, minor, patch, prerelease, build, partial)
self.major = major
self.minor = minor
self.patch = patch
self.prerelease = prerelease
self.build = build
self.partial = partial
# Cached precedence keys
# _cmp_precedence_key is used for semver-precedence comparison
self._cmp_precedence_key = self._build_precedence_key(with_build=False)
# _sort_precedence_key is used for self.precedence_key, esp. for sorted(...)
self._sort_precedence_key = self._build_precedence_key(with_build=True)
@classmethod
def _coerce(cls, value, allow_none=False):
if value is None and allow_none:
return value
return int(value)
def next_major(self):
if self.prerelease and self.minor == self.patch == 0:
return self.__class__(
major=self.major,
minor=0,
patch=0,
partial=self.partial,
)
else:
return self.__class__(
major=self.major + 1,
minor=0,
patch=0,
partial=self.partial,
)
def next_minor(self):
if self.prerelease and self.patch == 0:
return self.__class__(
major=self.major,
minor=self.minor,
patch=0,
partial=self.partial,
)
else:
return self.__class__(
major=self.major,
minor=self.minor + 1,
patch=0,
partial=self.partial,
)
def next_patch(self):
if self.prerelease:
return self.__class__(
major=self.major,
minor=self.minor,
patch=self.patch,
partial=self.partial,
)
else:
return self.__class__(
major=self.major,
minor=self.minor,
patch=self.patch + 1,
partial=self.partial,
)
def truncate(self, level='patch'):
"""Return a new Version object, truncated up to the selected level."""
if level == 'build':
return self.__class__(
major=self.major,
minor=self.minor,
patch=self.patch,
prerelease=self.prerelease,
build=self.build,
partial=self.partial,
)
elif level == 'prerelease':
return self.__class__(
major=self.major,
minor=self.minor,
patch=self.patch,
prerelease=self.prerelease,
partial=self.partial,
)
elif level == 'patch':
return self.__class__(
major=self.major,
minor=self.minor,
patch=self.patch,
partial=self.partial,
)
elif level == 'minor':
return self.__class__(
major=self.major,
minor=self.minor,
patch=None if self.partial else 0,
partial=self.partial,
)
elif level == 'major':
return self.__class__(
major=self.major,
minor=None if self.partial else 0,
patch=None if self.partial else 0,
partial=self.partial,
)
else:
raise ValueError("Invalid truncation level `%s`." % level)
@classmethod
def coerce(cls, version_string, partial=False):
"""Coerce an arbitrary version string into a semver-compatible one.
The rule is:
- If not enough components, fill minor/patch with zeroes; unless
partial=True
- If more than 3 dot-separated components, extra components are "build"
data. If some "build" data already appeared, append it to the
extra components
Examples:
>>> Version.coerce('0.1')
Version(0, 1, 0)
>>> Version.coerce('0.1.2.3')
Version(0, 1, 2, (), ('3',))
>>> Version.coerce('0.1.2.3+4')
Version(0, 1, 2, (), ('3', '4'))
>>> Version.coerce('0.1+2-3+4_5')
Version(0, 1, 0, (), ('2-3', '4-5'))
"""
base_re = re.compile(r'^\d+(?:\.\d+(?:\.\d+)?)?')
match = base_re.match(version_string)
if not match:
raise ValueError(
"Version string lacks a numerical component: %r"
% version_string
)
version = version_string[:match.end()]
if not partial:
# We need a not-partial version.
while version.count('.') < 2:
version += '.0'
# Strip leading zeros in components
# Version is of the form nn, nn.pp or nn.pp.qq
version = '.'.join(
# If the part was '0', we end up with an empty string.
part.lstrip('0') or '0'
for part in version.split('.')
)
if match.end() == len(version_string):
return cls(version, partial=partial)
rest = version_string[match.end():]
# Cleanup the 'rest'
rest = re.sub(r'[^a-zA-Z0-9+.-]', '-', rest)
if rest[0] == '+':
# A 'build' component
prerelease = ''
build = rest[1:]
elif rest[0] == '.':
# An extra version component, probably 'build'
prerelease = ''
build = rest[1:]
elif rest[0] == '-':
rest = rest[1:]
if '+' in rest:
prerelease, build = rest.split('+', 1)
else:
prerelease, build = rest, ''
elif '+' in rest:
prerelease, build = rest.split('+', 1)
else:
prerelease, build = rest, ''
build = build.replace('+', '.')
if prerelease:
version = '%s-%s' % (version, prerelease)
if build:
version = '%s+%s' % (version, build)
return cls(version, partial=partial)
@classmethod
def parse(cls, version_string, partial=False, coerce=False):
"""Parse a version string into a tuple of components:
(major, minor, patch, prerelease, build).
Args:
version_string (str), the version string to parse
partial (bool), whether to accept incomplete input
coerce (bool), whether to try to map the passed in string into a
valid Version.
"""
if not version_string:
raise ValueError('Invalid empty version string: %r' % version_string)
if partial:
version_re = cls.partial_version_re
else:
version_re = cls.version_re
match = version_re.match(version_string)
if not match:
raise ValueError('Invalid version string: %r' % version_string)
major, minor, patch, prerelease, build = match.groups()
if _has_leading_zero(major):
raise ValueError("Invalid leading zero in major: %r" % version_string)
if _has_leading_zero(minor):
raise ValueError("Invalid leading zero in minor: %r" % version_string)
if _has_leading_zero(patch):
raise ValueError("Invalid leading zero in patch: %r" % version_string)
major = int(major)
minor = cls._coerce(minor, partial)
patch = cls._coerce(patch, partial)
if prerelease is None:
if partial and (build is None):
# No build info, strip here
return (major, minor, patch, None, None)
else:
prerelease = ()
elif prerelease == '':
prerelease = ()
else:
prerelease = tuple(prerelease.split('.'))
cls._validate_identifiers(prerelease, allow_leading_zeroes=False)
if build is None:
if partial:
build = None
else:
build = ()
elif build == '':
build = ()
else:
build = tuple(build.split('.'))
cls._validate_identifiers(build, allow_leading_zeroes=True)
return (major, minor, patch, prerelease, build)
@classmethod
def _validate_identifiers(cls, identifiers, allow_leading_zeroes=False):
for item in identifiers:
if not item:
raise ValueError(
"Invalid empty identifier %r in %r"
% (item, '.'.join(identifiers))
)
if item[0] == '0' and item.isdigit() and item != '0' and not allow_leading_zeroes:
raise ValueError("Invalid leading zero in identifier %r" % item)
@classmethod
def _validate_kwargs(cls, major, minor, patch, prerelease, build, partial):
if (
major != int(major)
or minor != cls._coerce(minor, partial)
or patch != cls._coerce(patch, partial)
or prerelease is None and not partial
or build is None and not partial
):
raise ValueError(
"Invalid kwargs to Version(major=%r, minor=%r, patch=%r, "
"prerelease=%r, build=%r, partial=%r" % (
major, minor, patch, prerelease, build, partial
))
if prerelease is not None:
cls._validate_identifiers(prerelease, allow_leading_zeroes=False)
if build is not None:
cls._validate_identifiers(build, allow_leading_zeroes=True)
def __iter__(self):
return iter((self.major, self.minor, self.patch, self.prerelease, self.build))
def __str__(self):
version = '%d' % self.major
if self.minor is not None:
version = '%s.%d' % (version, self.minor)
if self.patch is not None:
version = '%s.%d' % (version, self.patch)
if self.prerelease or (self.partial and self.prerelease == () and self.build is None):
version = '%s-%s' % (version, '.'.join(self.prerelease))
if self.build or (self.partial and self.build == ()):
version = '%s+%s' % (version, '.'.join(self.build))
return version
def __repr__(self):
return '%s(%r%s)' % (
self.__class__.__name__,
str(self),
', partial=True' if self.partial else '',
)
def __hash__(self):
# We don't include 'partial', since this is strictly equivalent to having
# at least a field being `None`.
return hash((self.major, self.minor, self.patch, self.prerelease, self.build))
def _build_precedence_key(self, with_build=False):
"""Build a precedence key.
The "build" component should only be used when sorting an iterable
of versions.
"""
if self.prerelease:
prerelease_key = tuple(
NumericIdentifier(part) if part.isdigit() else AlphaIdentifier(part)
for part in self.prerelease
)
else:
prerelease_key = (
MaxIdentifier(),
)
if not with_build:
return (
self.major,
self.minor,
self.patch,
prerelease_key,
)
build_key = tuple(
NumericIdentifier(part) if part.isdigit() else AlphaIdentifier(part)
for part in self.build or ()
)
return (
self.major,
self.minor,
self.patch,
prerelease_key,
build_key,
)
@property
def precedence_key(self):
return self._sort_precedence_key
def __cmp__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
if self < other:
return -1
elif self > other:
return 1
elif self == other:
return 0
else:
return NotImplemented
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return (
self.major == other.major
and self.minor == other.minor
and self.patch == other.patch
and (self.prerelease or ()) == (other.prerelease or ())
and (self.build or ()) == (other.build or ())
)
def __ne__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return tuple(self) != tuple(other)
def __lt__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self._cmp_precedence_key < other._cmp_precedence_key
def __le__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self._cmp_precedence_key <= other._cmp_precedence_key
def __gt__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self._cmp_precedence_key > other._cmp_precedence_key
def __ge__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self._cmp_precedence_key >= other._cmp_precedence_key
class SpecItem(object):
"""A requirement specification."""
KIND_ANY = '*'
KIND_LT = '<'
KIND_LTE = '<='
KIND_EQUAL = '=='
KIND_SHORTEQ = '='
KIND_EMPTY = ''
KIND_GTE = '>='
KIND_GT = '>'
KIND_NEQ = '!='
KIND_CARET = '^'
KIND_TILDE = '~'
KIND_COMPATIBLE = '~='
# Map a kind alias to its full version
KIND_ALIASES = {
KIND_SHORTEQ: KIND_EQUAL,
KIND_EMPTY: KIND_EQUAL,
}
re_spec = re.compile(r'^(<|<=||=|==|>=|>|!=|\^|~|~=)(\d.*)$')
def __init__(self, requirement_string, _warn=True):
if _warn:
warnings.warn(
"The `SpecItem` class will be removed in 3.0.",
DeprecationWarning,
stacklevel=2,
)
kind, spec = self.parse(requirement_string)
self.kind = kind
self.spec = spec
self._clause = Spec(requirement_string).clause
@classmethod
def parse(cls, requirement_string):
if not requirement_string:
raise ValueError("Invalid empty requirement specification: %r" % requirement_string)
# Special case: the 'any' version spec.
if requirement_string == '*':
return (cls.KIND_ANY, '')
match = cls.re_spec.match(requirement_string)
if not match:
raise ValueError("Invalid requirement specification: %r" % requirement_string)
kind, version = match.groups()
if kind in cls.KIND_ALIASES:
kind = cls.KIND_ALIASES[kind]
spec = Version(version, partial=True)
if spec.build is not None and kind not in (cls.KIND_EQUAL, cls.KIND_NEQ):
raise ValueError(
"Invalid requirement specification %r: build numbers have no ordering."
% requirement_string
)
return (kind, spec)
@classmethod
def from_matcher(cls, matcher):
if matcher == Always():
return cls('*', _warn=False)
elif matcher == Never():
return cls('<0.0.0-', _warn=False)
elif isinstance(matcher, Range):
return cls('%s%s' % (matcher.operator, matcher.target), _warn=False)
def match(self, version):
return self._clause.match(version)
def __str__(self):
return '%s%s' % (self.kind, self.spec)
def __repr__(self):
return '<SpecItem: %s %r>' % (self.kind, self.spec)
def __eq__(self, other):
if not isinstance(other, SpecItem):
return NotImplemented
return self.kind == other.kind and self.spec == other.spec
def __hash__(self):
return hash((self.kind, self.spec))
def compare(v1, v2):
return Version(v1).__cmp__(Version(v2))
def match(spec, version):
return Spec(spec).match(Version(version))
def validate(version_string):
"""Validates a version string againt the SemVer specification."""
try:
Version.parse(version_string)
return True
except ValueError:
return False
DEFAULT_SYNTAX = 'simple'
class BaseSpec(object):
"""A specification of compatible versions.
Usage:
>>> Spec('>=1.0.0', syntax='npm')
A version matches a specification if it matches any
of the clauses of that specification.
Internally, a Spec is AnyOf(
AllOf(Matcher, Matcher, Matcher),
AllOf(...),
)
"""
SYNTAXES = {}
@classmethod
def register_syntax(cls, subclass):
syntax = subclass.SYNTAX
if syntax is None:
raise ValueError("A Spec needs its SYNTAX field to be set.")
elif syntax in cls.SYNTAXES:
raise ValueError(
"Duplicate syntax for %s: %r, %r"
% (syntax, cls.SYNTAXES[syntax], subclass)
)
cls.SYNTAXES[syntax] = subclass
return subclass
def __init__(self, expression):
super(BaseSpec, self).__init__()
self.expression = expression
self.clause = self._parse_to_clause(expression)
@classmethod
def parse(cls, expression, syntax=DEFAULT_SYNTAX):
"""Convert a syntax-specific expression into a BaseSpec instance."""
return cls.SYNTAXES[syntax](expression)
@classmethod
def _parse_to_clause(cls, expression):
"""Converts an expression to a clause."""
raise NotImplementedError()
def filter(self, versions):
"""Filter an iterable of versions satisfying the Spec."""
for version in versions:
if self.match(version):
yield version
def match(self, version):
"""Check whether a Version satisfies the Spec."""
return self.clause.match(version)
def select(self, versions):
"""Select the best compatible version among an iterable of options."""
options = list(self.filter(versions))
if options:
return max(options)
return None
def __contains__(self, version):
"""Whether `version in self`."""
if isinstance(version, Version):
return self.match(version)
return False
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self.clause == other.clause
def __hash__(self):
return hash(self.clause)
def __str__(self):
return self.expression
def __repr__(self):
return '<%s: %r>' % (self.__class__.__name__, self.expression)
class Clause(object):
__slots__ = []
def match(self, version):
raise NotImplementedError()
def __and__(self, other):
raise NotImplementedError()
def __or__(self, other):
raise NotImplementedError()
def __eq__(self, other):
raise NotImplementedError()
def prettyprint(self, indent='\t'):
"""Pretty-print the clause.
"""
return '\n'.join(self._pretty()).replace('\t', indent)
def _pretty(self):
"""Actual pretty-printing logic.
Yields:
A list of string. Indentation is performed with \t.
"""
yield repr(self)
def __ne__(self, other):
return not self == other
def simplify(self):
return self
class AnyOf(Clause):
__slots__ = ['clauses']
def __init__(self, *clauses):
super(AnyOf, self).__init__()
self.clauses = frozenset(clauses)
def match(self, version):
return any(c.match(version) for c in self.clauses)
def simplify(self):
subclauses = set()
for clause in self.clauses:
simplified = clause.simplify()
if isinstance(simplified, AnyOf):
subclauses |= simplified.clauses
elif simplified == Never():
continue
else:
subclauses.add(simplified)
if len(subclauses) == 1:
return subclauses.pop()
return AnyOf(*subclauses)
def __hash__(self):
return hash((AnyOf, self.clauses))
def __iter__(self):
return iter(self.clauses)
def __eq__(self, other):
return isinstance(other, self.__class__) and self.clauses == other.clauses
def __and__(self, other):
if isinstance(other, AllOf):
return other & self
elif isinstance(other, Matcher) or isinstance(other, AnyOf):
return AllOf(self, other)
else:
return NotImplemented
def __or__(self, other):
if isinstance(other, AnyOf):
clauses = list(self.clauses | other.clauses)
elif isinstance(other, Matcher) or isinstance(other, AllOf):
clauses = list(self.clauses | set([other]))
else:
return NotImplemented
return AnyOf(*clauses)
def __repr__(self):
return 'AnyOf(%s)' % ', '.join(sorted(repr(c) for c in self.clauses))
def _pretty(self):
yield 'AnyOF('
for clause in self.clauses:
lines = list(clause._pretty())
for line in lines[:-1]:
yield '\t' + line
yield '\t' + lines[-1] + ','
yield ')'
class AllOf(Clause):
__slots__ = ['clauses']
def __init__(self, *clauses):
super(AllOf, self).__init__()
self.clauses = frozenset(clauses)
def match(self, version):
return all(clause.match(version) for clause in self.clauses)
def simplify(self):
subclauses = set()
for clause in self.clauses:
simplified = clause.simplify()
if isinstance(simplified, AllOf):
subclauses |= simplified.clauses
elif simplified == Always():
continue
else:
subclauses.add(simplified)
if len(subclauses) == 1:
return subclauses.pop()
return AllOf(*subclauses)
def __hash__(self):
return hash((AllOf, self.clauses))
def __iter__(self):
return iter(self.clauses)
def __eq__(self, other):
return isinstance(other, self.__class__) and self.clauses == other.clauses
def __and__(self, other):
if isinstance(other, Matcher) or isinstance(other, AnyOf):
clauses = list(self.clauses | set([other]))
elif isinstance(other, AllOf):
clauses = list(self.clauses | other.clauses)
else:
return NotImplemented
return AllOf(*clauses)
def __or__(self, other):
if isinstance(other, AnyOf):
return other | self
elif isinstance(other, Matcher):
return AnyOf(self, AllOf(other))
elif isinstance(other, AllOf):
return AnyOf(self, other)
else:
return NotImplemented
def __repr__(self):
return 'AllOf(%s)' % ', '.join(sorted(repr(c) for c in self.clauses))
def _pretty(self):
yield 'AllOF('
for clause in self.clauses:
lines = list(clause._pretty())
for line in lines[:-1]:
yield '\t' + line
yield '\t' + lines[-1] + ','
yield ')'
class Matcher(Clause):
__slots__ = []
def __and__(self, other):
if isinstance(other, AllOf):
return other & self
elif isinstance(other, Matcher) or isinstance(other, AnyOf):
return AllOf(self, other)
else:
return NotImplemented
def __or__(self, other):
if isinstance(other, AnyOf):
return other | self
elif isinstance(other, Matcher) or isinstance(other, AllOf):
return AnyOf(self, other)
else:
return NotImplemented
class Never(Matcher):
__slots__ = []
def match(self, version):
return False
def __hash__(self):
return hash((Never,))
def __eq__(self, other):
return isinstance(other, self.__class__)
def __and__(self, other):
return self
def __or__(self, other):
return other
def __repr__(self):
return 'Never()'
class Always(Matcher):
__slots__ = []
def match(self, version):
return True
def __hash__(self):
return hash((Always,))
def __eq__(self, other):
return isinstance(other, self.__class__)
def __and__(self, other):
return other
def __or__(self, other):
return self
def __repr__(self):
return 'Always()'
class Range(Matcher):
OP_EQ = '=='
OP_GT = '>'
OP_GTE = '>='
OP_LT = '<'
OP_LTE = '<='
OP_NEQ = '!='
# <1.2.3 matches 1.2.3-a1
PRERELEASE_ALWAYS = 'always'
# <1.2.3 does not match 1.2.3-a1
PRERELEASE_NATURAL = 'natural'
# 1.2.3-a1 is only considered if target == 1.2.3-xxx
PRERELEASE_SAMEPATCH = 'same-patch'
# 1.2.3 matches 1.2.3+*
BUILD_IMPLICIT = 'implicit'
# 1.2.3 matches only 1.2.3, not 1.2.3+4
BUILD_STRICT = 'strict'
__slots__ = ['operator', 'target', 'prerelease_policy', 'build_policy']
def __init__(self, operator, target, prerelease_policy=PRERELEASE_NATURAL, build_policy=BUILD_IMPLICIT):
super(Range, self).__init__()
if target.build and operator not in (self.OP_EQ, self.OP_NEQ):
raise ValueError(
"Invalid range %s%s: build numbers have no ordering."
% (operator, target))
self.operator = operator
self.target = target
self.prerelease_policy = prerelease_policy
self.build_policy = self.BUILD_STRICT if target.build else build_policy
def match(self, version):
if self.build_policy != self.BUILD_STRICT:
version = version.truncate('prerelease')
if version.prerelease:
same_patch = self.target.truncate() == version.truncate()
if self.prerelease_policy == self.PRERELEASE_SAMEPATCH and not same_patch:
return False
if self.operator == self.OP_EQ:
if self.build_policy == self.BUILD_STRICT:
return (
self.target.truncate('prerelease') == version.truncate('prerelease')
and version.build == self.target.build
)
return version == self.target
elif self.operator == self.OP_GT:
return version > self.target
elif self.operator == self.OP_GTE:
return version >= self.target
elif self.operator == self.OP_LT:
if (
version.prerelease
and self.prerelease_policy == self.PRERELEASE_NATURAL
and version.truncate() == self.target.truncate()
and not self.target.prerelease
):
return False
return version < self.target
elif self.operator == self.OP_LTE:
return version <= self.target
else:
assert self.operator == self.OP_NEQ
if self.build_policy == self.BUILD_STRICT:
return not (