PageRenderTime 1915ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/setuptools/_distutils/version.py

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