versionpredicate.py 5.1 KB

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