versionpredicate.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. """Module for parsing and testing package version predicate strings."""
  2. import operator
  3. import re
  4. from . import version
  5. re_validPackage = re.compile(r"(?i)^\s*([a-z_]\w*(?:\.[a-z_]\w*)*)(.*)", re.ASCII)
  6. # (package) (rest)
  7. re_paren = re.compile(r"^\s*\((.*)\)\s*$") # (list) inside of parentheses
  8. re_splitComparison = re.compile(r"^\s*(<=|>=|<|>|!=|==)\s*([^\s,]+)\s*$")
  9. # (comp) (version)
  10. def splitUp(pred):
  11. """Parse a single version comparison.
  12. Return (comparison string, StrictVersion)
  13. """
  14. res = re_splitComparison.match(pred)
  15. if not res:
  16. raise ValueError(f"bad package restriction syntax: {pred!r}")
  17. comp, verStr = res.groups()
  18. with version.suppress_known_deprecation():
  19. other = version.StrictVersion(verStr)
  20. return (comp, other)
  21. compmap = {
  22. "<": operator.lt,
  23. "<=": operator.le,
  24. "==": operator.eq,
  25. ">": operator.gt,
  26. ">=": operator.ge,
  27. "!=": operator.ne,
  28. }
  29. class VersionPredicate:
  30. """Parse and test package version predicates.
  31. >>> v = VersionPredicate('pyepat.abc (>1.0, <3333.3a1, !=1555.1b3)')
  32. The `name` attribute provides the full dotted name that is given::
  33. >>> v.name
  34. 'pyepat.abc'
  35. The str() of a `VersionPredicate` provides a normalized
  36. human-readable version of the expression::
  37. >>> print(v)
  38. pyepat.abc (> 1.0, < 3333.3a1, != 1555.1b3)
  39. The `satisfied_by()` method can be used to determine with a given
  40. version number is included in the set described by the version
  41. restrictions::
  42. >>> v.satisfied_by('1.1')
  43. True
  44. >>> v.satisfied_by('1.4')
  45. True
  46. >>> v.satisfied_by('1.0')
  47. False
  48. >>> v.satisfied_by('4444.4')
  49. False
  50. >>> v.satisfied_by('1555.1b3')
  51. False
  52. `VersionPredicate` is flexible in accepting extra whitespace::
  53. >>> v = VersionPredicate(' pat( == 0.1 ) ')
  54. >>> v.name
  55. 'pat'
  56. >>> v.satisfied_by('0.1')
  57. True
  58. >>> v.satisfied_by('0.2')
  59. False
  60. If any version numbers passed in do not conform to the
  61. restrictions of `StrictVersion`, a `ValueError` is raised::
  62. >>> v = VersionPredicate('p1.p2.p3.p4(>=1.0, <=1.3a1, !=1.2zb3)')
  63. Traceback (most recent call last):
  64. ...
  65. ValueError: invalid version number '1.2zb3'
  66. It the module or package name given does not conform to what's
  67. allowed as a legal module or package name, `ValueError` is
  68. raised::
  69. >>> v = VersionPredicate('foo-bar')
  70. Traceback (most recent call last):
  71. ...
  72. ValueError: expected parenthesized list: '-bar'
  73. >>> v = VersionPredicate('foo bar (12.21)')
  74. Traceback (most recent call last):
  75. ...
  76. ValueError: expected parenthesized list: 'bar (12.21)'
  77. """
  78. def __init__(self, versionPredicateStr):
  79. """Parse a version predicate string."""
  80. # Fields:
  81. # name: package name
  82. # pred: list of (comparison string, StrictVersion)
  83. versionPredicateStr = versionPredicateStr.strip()
  84. if not versionPredicateStr:
  85. raise ValueError("empty package restriction")
  86. match = re_validPackage.match(versionPredicateStr)
  87. if not match:
  88. raise ValueError(f"bad package name in {versionPredicateStr!r}")
  89. self.name, paren = match.groups()
  90. paren = paren.strip()
  91. if paren:
  92. match = re_paren.match(paren)
  93. if not match:
  94. raise ValueError(f"expected parenthesized list: {paren!r}")
  95. str = match.groups()[0]
  96. self.pred = [splitUp(aPred) for aPred in str.split(",")]
  97. if not self.pred:
  98. raise ValueError(f"empty parenthesized list in {versionPredicateStr!r}")
  99. else:
  100. self.pred = []
  101. def __str__(self):
  102. if self.pred:
  103. seq = [cond + " " + str(ver) for cond, ver in self.pred]
  104. return self.name + " (" + ", ".join(seq) + ")"
  105. else:
  106. return self.name
  107. def satisfied_by(self, version):
  108. """True if version is compatible with all the predicates in self.
  109. The parameter version must be acceptable to the StrictVersion
  110. constructor. It may be either a string or StrictVersion.
  111. """
  112. for cond, ver in self.pred:
  113. if not compmap[cond](version, ver):
  114. return False
  115. return True
  116. _provision_rx = None
  117. def split_provision(value):
  118. """Return the name and optional version number of a provision.
  119. The version number, if given, will be returned as a `StrictVersion`
  120. instance, otherwise it will be `None`.
  121. >>> split_provision('mypkg')
  122. ('mypkg', None)
  123. >>> split_provision(' mypkg( 1.2 ) ')
  124. ('mypkg', StrictVersion ('1.2'))
  125. """
  126. global _provision_rx
  127. if _provision_rx is None:
  128. _provision_rx = re.compile(
  129. r"([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)(?:\s*\(\s*([^)\s]+)\s*\))?$", re.ASCII
  130. )
  131. value = value.strip()
  132. m = _provision_rx.match(value)
  133. if not m:
  134. raise ValueError(f"illegal provides specification: {value!r}")
  135. ver = m.group(2) or None
  136. if ver:
  137. with version.suppress_known_deprecation():
  138. ver = version.StrictVersion(ver)
  139. return m.group(1), ver