version.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. #
  2. # distutils/version.py
  3. #
  4. # Implements multiple version numbering conventions for the
  5. # Python Module Distribution Utilities.
  6. #
  7. # $Id$
  8. #
  9. """Provides classes to represent module version numbers (one class for
  10. each style of version numbering). There are currently two such classes
  11. implemented: StrictVersion and LooseVersion.
  12. Every version number class implements the following interface:
  13. * the 'parse' method takes a string and parses it to some internal
  14. representation; if the string is an invalid version number,
  15. 'parse' raises a ValueError exception
  16. * the class constructor takes an optional string argument which,
  17. if supplied, is passed to 'parse'
  18. * __str__ reconstructs the string that was passed to 'parse' (or
  19. an equivalent string -- ie. one that will generate an equivalent
  20. version number instance)
  21. * __repr__ generates Python code to recreate the version number instance
  22. * _cmp compares the current instance with either another instance
  23. of the same class or a string (which will be parsed to an instance
  24. of the same class, thus must follow the same rules)
  25. """
  26. import contextlib
  27. import re
  28. import warnings
  29. @contextlib.contextmanager
  30. def suppress_known_deprecation():
  31. with warnings.catch_warnings(record=True) as ctx:
  32. warnings.filterwarnings(
  33. action='default',
  34. category=DeprecationWarning,
  35. message="distutils Version classes are deprecated.",
  36. )
  37. yield ctx
  38. class Version:
  39. """Abstract base class for version numbering classes. Just provides
  40. constructor (__init__) and reproducer (__repr__), because those
  41. seem to be the same for all version numbering classes; and route
  42. rich comparisons to _cmp.
  43. """
  44. def __init__(self, vstring=None):
  45. if vstring:
  46. self.parse(vstring)
  47. warnings.warn(
  48. "distutils Version classes are deprecated. Use packaging.version instead.",
  49. DeprecationWarning,
  50. stacklevel=2,
  51. )
  52. def __repr__(self):
  53. return f"{self.__class__.__name__} ('{self}')"
  54. def __eq__(self, other):
  55. c = self._cmp(other)
  56. if c is NotImplemented:
  57. return c
  58. return c == 0
  59. def __lt__(self, other):
  60. c = self._cmp(other)
  61. if c is NotImplemented:
  62. return c
  63. return c < 0
  64. def __le__(self, other):
  65. c = self._cmp(other)
  66. if c is NotImplemented:
  67. return c
  68. return c <= 0
  69. def __gt__(self, other):
  70. c = self._cmp(other)
  71. if c is NotImplemented:
  72. return c
  73. return c > 0
  74. def __ge__(self, other):
  75. c = self._cmp(other)
  76. if c is NotImplemented:
  77. return c
  78. return c >= 0
  79. # Interface for version-number classes -- must be implemented
  80. # by the following classes (the concrete ones -- Version should
  81. # be treated as an abstract class).
  82. # __init__ (string) - create and take same action as 'parse'
  83. # (string parameter is optional)
  84. # parse (string) - convert a string representation to whatever
  85. # internal representation is appropriate for
  86. # this style of version numbering
  87. # __str__ (self) - convert back to a string; should be very similar
  88. # (if not identical to) the string supplied to parse
  89. # __repr__ (self) - generate Python code to recreate
  90. # the instance
  91. # _cmp (self, other) - compare two version numbers ('other' may
  92. # be an unparsed version string, or another
  93. # instance of your version class)
  94. class StrictVersion(Version):
  95. """Version numbering for anal retentives and software idealists.
  96. Implements the standard interface for version number classes as
  97. described above. A version number consists of two or three
  98. dot-separated numeric components, with an optional "pre-release" tag
  99. on the end. The pre-release tag consists of the letter 'a' or 'b'
  100. followed by a number. If the numeric components of two version
  101. numbers are equal, then one with a pre-release tag will always
  102. be deemed earlier (lesser) than one without.
  103. The following are valid version numbers (shown in the order that
  104. would be obtained by sorting according to the supplied cmp function):
  105. 0.4 0.4.0 (these two are equivalent)
  106. 0.4.1
  107. 0.5a1
  108. 0.5b3
  109. 0.5
  110. 0.9.6
  111. 1.0
  112. 1.0.4a3
  113. 1.0.4b1
  114. 1.0.4
  115. The following are examples of invalid version numbers:
  116. 1
  117. 2.7.2.2
  118. 1.3.a4
  119. 1.3pl1
  120. 1.3c4
  121. The rationale for this version numbering system will be explained
  122. in the distutils documentation.
  123. """
  124. version_re = re.compile(
  125. r'^(\d+) \. (\d+) (\. (\d+))? ([ab](\d+))?$', re.VERBOSE | re.ASCII
  126. )
  127. def parse(self, vstring):
  128. match = self.version_re.match(vstring)
  129. if not match:
  130. raise ValueError(f"invalid version number '{vstring}'")
  131. (major, minor, patch, prerelease, prerelease_num) = match.group(1, 2, 4, 5, 6)
  132. if patch:
  133. self.version = tuple(map(int, [major, minor, patch]))
  134. else:
  135. self.version = tuple(map(int, [major, minor])) + (0,)
  136. if prerelease:
  137. self.prerelease = (prerelease[0], int(prerelease_num))
  138. else:
  139. self.prerelease = None
  140. def __str__(self):
  141. if self.version[2] == 0:
  142. vstring = '.'.join(map(str, self.version[0:2]))
  143. else:
  144. vstring = '.'.join(map(str, self.version))
  145. if self.prerelease:
  146. vstring = vstring + self.prerelease[0] + str(self.prerelease[1])
  147. return vstring
  148. def _cmp(self, other):
  149. if isinstance(other, str):
  150. with suppress_known_deprecation():
  151. other = StrictVersion(other)
  152. elif not isinstance(other, StrictVersion):
  153. return NotImplemented
  154. if self.version == other.version:
  155. # versions match; pre-release drives the comparison
  156. return self._cmp_prerelease(other)
  157. return -1 if self.version < other.version else 1
  158. def _cmp_prerelease(self, other):
  159. """
  160. case 1: self has prerelease, other doesn't; other is greater
  161. case 2: self doesn't have prerelease, other does: self is greater
  162. case 3: both or neither have prerelease: compare them!
  163. """
  164. if self.prerelease and not other.prerelease:
  165. return -1
  166. elif not self.prerelease and other.prerelease:
  167. return 1
  168. if self.prerelease == other.prerelease:
  169. return 0
  170. elif self.prerelease < other.prerelease:
  171. return -1
  172. else:
  173. return 1
  174. # end class StrictVersion
  175. # The rules according to Greg Stein:
  176. # 1) a version number has 1 or more numbers separated by a period or by
  177. # sequences of letters. If only periods, then these are compared
  178. # left-to-right to determine an ordering.
  179. # 2) sequences of letters are part of the tuple for comparison and are
  180. # compared lexicographically
  181. # 3) recognize the numeric components may have leading zeroes
  182. #
  183. # The LooseVersion class below implements these rules: a version number
  184. # string is split up into a tuple of integer and string components, and
  185. # comparison is a simple tuple comparison. This means that version
  186. # numbers behave in a predictable and obvious way, but a way that might
  187. # not necessarily be how people *want* version numbers to behave. There
  188. # wouldn't be a problem if people could stick to purely numeric version
  189. # numbers: just split on period and compare the numbers as tuples.
  190. # However, people insist on putting letters into their version numbers;
  191. # the most common purpose seems to be:
  192. # - indicating a "pre-release" version
  193. # ('alpha', 'beta', 'a', 'b', 'pre', 'p')
  194. # - indicating a post-release patch ('p', 'pl', 'patch')
  195. # but of course this can't cover all version number schemes, and there's
  196. # no way to know what a programmer means without asking him.
  197. #
  198. # The problem is what to do with letters (and other non-numeric
  199. # characters) in a version number. The current implementation does the
  200. # obvious and predictable thing: keep them as strings and compare
  201. # lexically within a tuple comparison. This has the desired effect if
  202. # an appended letter sequence implies something "post-release":
  203. # eg. "0.99" < "0.99pl14" < "1.0", and "5.001" < "5.001m" < "5.002".
  204. #
  205. # However, if letters in a version number imply a pre-release version,
  206. # the "obvious" thing isn't correct. Eg. you would expect that
  207. # "1.5.1" < "1.5.2a2" < "1.5.2", but under the tuple/lexical comparison
  208. # implemented here, this just isn't so.
  209. #
  210. # Two possible solutions come to mind. The first is to tie the
  211. # comparison algorithm to a particular set of semantic rules, as has
  212. # been done in the StrictVersion class above. This works great as long
  213. # as everyone can go along with bondage and discipline. Hopefully a
  214. # (large) subset of Python module programmers will agree that the
  215. # particular flavour of bondage and discipline provided by StrictVersion
  216. # provides enough benefit to be worth using, and will submit their
  217. # version numbering scheme to its domination. The free-thinking
  218. # anarchists in the lot will never give in, though, and something needs
  219. # to be done to accommodate them.
  220. #
  221. # Perhaps a "moderately strict" version class could be implemented that
  222. # lets almost anything slide (syntactically), and makes some heuristic
  223. # assumptions about non-digits in version number strings. This could
  224. # sink into special-case-hell, though; if I was as talented and
  225. # idiosyncratic as Larry Wall, I'd go ahead and implement a class that
  226. # somehow knows that "1.2.1" < "1.2.2a2" < "1.2.2" < "1.2.2pl3", and is
  227. # just as happy dealing with things like "2g6" and "1.13++". I don't
  228. # think I'm smart enough to do it right though.
  229. #
  230. # In any case, I've coded the test suite for this module (see
  231. # ../test/test_version.py) specifically to fail on things like comparing
  232. # "1.2a2" and "1.2". That's not because the *code* is doing anything
  233. # wrong, it's because the simple, obvious design doesn't match my
  234. # complicated, hairy expectations for real-world version numbers. It
  235. # would be a snap to fix the test suite to say, "Yep, LooseVersion does
  236. # the Right Thing" (ie. the code matches the conception). But I'd rather
  237. # have a conception that matches common notions about version numbers.
  238. class LooseVersion(Version):
  239. """Version numbering for anarchists and software realists.
  240. Implements the standard interface for version number classes as
  241. described above. A version number consists of a series of numbers,
  242. separated by either periods or strings of letters. When comparing
  243. version numbers, the numeric components will be compared
  244. numerically, and the alphabetic components lexically. The following
  245. are all valid version numbers, in no particular order:
  246. 1.5.1
  247. 1.5.2b2
  248. 161
  249. 3.10a
  250. 8.02
  251. 3.4j
  252. 1996.07.12
  253. 3.2.pl0
  254. 3.1.1.6
  255. 2g6
  256. 11g
  257. 0.960923
  258. 2.2beta29
  259. 1.13++
  260. 5.5.kw
  261. 2.0b1pl0
  262. In fact, there is no such thing as an invalid version number under
  263. this scheme; the rules for comparison are simple and predictable,
  264. but may not always give the results you want (for some definition
  265. of "want").
  266. """
  267. component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE)
  268. def parse(self, vstring):
  269. # I've given up on thinking I can reconstruct the version string
  270. # from the parsed tuple -- so I just store the string here for
  271. # use by __str__
  272. self.vstring = vstring
  273. components = [x for x in self.component_re.split(vstring) if x and x != '.']
  274. for i, obj in enumerate(components):
  275. try:
  276. components[i] = int(obj)
  277. except ValueError:
  278. pass
  279. self.version = components
  280. def __str__(self):
  281. return self.vstring
  282. def __repr__(self):
  283. return f"LooseVersion ('{self}')"
  284. def _cmp(self, other):
  285. if isinstance(other, str):
  286. other = LooseVersion(other)
  287. elif not isinstance(other, LooseVersion):
  288. return NotImplemented
  289. if self.version == other.version:
  290. return 0
  291. if self.version < other.version:
  292. return -1
  293. if self.version > other.version:
  294. return 1
  295. # end class LooseVersion