versionpredicate.py 5.2 KB

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