version.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. # Copyright 2014 Donald Stufft
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import absolute_import, division, print_function
  15. import collections
  16. import itertools
  17. import re
  18. from ._structures import Infinity
  19. __all__ = [
  20. "parse", "Version", "LegacyVersion", "InvalidVersion", "VERSION_PATTERN"
  21. ]
  22. _Version = collections.namedtuple(
  23. "_Version",
  24. ["epoch", "release", "dev", "pre", "post", "local"],
  25. )
  26. def parse(version):
  27. """
  28. Parse the given version string and return either a :class:`Version` object
  29. or a :class:`LegacyVersion` object depending on if the given version is
  30. a valid PEP 440 version or a legacy version.
  31. """
  32. try:
  33. return Version(version)
  34. except InvalidVersion:
  35. return LegacyVersion(version)
  36. class InvalidVersion(ValueError):
  37. """
  38. An invalid version was found, users should refer to PEP 440.
  39. """
  40. class _BaseVersion(object):
  41. def __hash__(self):
  42. return hash(self._key)
  43. def __lt__(self, other):
  44. return self._compare(other, lambda s, o: s < o)
  45. def __le__(self, other):
  46. return self._compare(other, lambda s, o: s <= o)
  47. def __eq__(self, other):
  48. return self._compare(other, lambda s, o: s == o)
  49. def __ge__(self, other):
  50. return self._compare(other, lambda s, o: s >= o)
  51. def __gt__(self, other):
  52. return self._compare(other, lambda s, o: s > o)
  53. def __ne__(self, other):
  54. return self._compare(other, lambda s, o: s != o)
  55. def _compare(self, other, method):
  56. if not isinstance(other, _BaseVersion):
  57. return NotImplemented
  58. return method(self._key, other._key)
  59. class LegacyVersion(_BaseVersion):
  60. def __init__(self, version):
  61. self._version = str(version)
  62. self._key = _legacy_cmpkey(self._version)
  63. def __str__(self):
  64. return self._version
  65. def __repr__(self):
  66. return "<LegacyVersion({0})>".format(repr(str(self)))
  67. @property
  68. def public(self):
  69. return self._version
  70. @property
  71. def base_version(self):
  72. return self._version
  73. @property
  74. def local(self):
  75. return None
  76. @property
  77. def is_prerelease(self):
  78. return False
  79. @property
  80. def is_postrelease(self):
  81. return False
  82. _legacy_version_component_re = re.compile(
  83. r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE,
  84. )
  85. _legacy_version_replacement_map = {
  86. "pre": "c", "preview": "c", "-": "final-", "rc": "c", "dev": "@",
  87. }
  88. def _parse_version_parts(s):
  89. for part in _legacy_version_component_re.split(s):
  90. part = _legacy_version_replacement_map.get(part, part)
  91. if not part or part == ".":
  92. continue
  93. if part[:1] in "0123456789":
  94. # pad for numeric comparison
  95. yield part.zfill(8)
  96. else:
  97. yield "*" + part
  98. # ensure that alpha/beta/candidate are before final
  99. yield "*final"
  100. def _legacy_cmpkey(version):
  101. # We hardcode an epoch of -1 here. A PEP 440 version can only have a epoch
  102. # greater than or equal to 0. This will effectively put the LegacyVersion,
  103. # which uses the defacto standard originally implemented by setuptools,
  104. # as before all PEP 440 versions.
  105. epoch = -1
  106. # This scheme is taken from pkg_resources.parse_version setuptools prior to
  107. # it's adoption of the packaging library.
  108. parts = []
  109. for part in _parse_version_parts(version.lower()):
  110. if part.startswith("*"):
  111. # remove "-" before a prerelease tag
  112. if part < "*final":
  113. while parts and parts[-1] == "*final-":
  114. parts.pop()
  115. # remove trailing zeros from each series of numeric parts
  116. while parts and parts[-1] == "00000000":
  117. parts.pop()
  118. parts.append(part)
  119. parts = tuple(parts)
  120. return epoch, parts
  121. # Deliberately not anchored to the start and end of the string, to make it
  122. # easier for 3rd party code to reuse
  123. VERSION_PATTERN = r"""
  124. v?
  125. (?:
  126. (?:(?P<epoch>[0-9]+)!)? # epoch
  127. (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
  128. (?P<pre> # pre-release
  129. [-_\.]?
  130. (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
  131. [-_\.]?
  132. (?P<pre_n>[0-9]+)?
  133. )?
  134. (?P<post> # post release
  135. (?:-(?P<post_n1>[0-9]+))
  136. |
  137. (?:
  138. [-_\.]?
  139. (?P<post_l>post|rev|r)
  140. [-_\.]?
  141. (?P<post_n2>[0-9]+)?
  142. )
  143. )?
  144. (?P<dev> # dev release
  145. [-_\.]?
  146. (?P<dev_l>dev)
  147. [-_\.]?
  148. (?P<dev_n>[0-9]+)?
  149. )?
  150. )
  151. (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
  152. """
  153. class Version(_BaseVersion):
  154. _regex = re.compile(
  155. r"^\s*" + VERSION_PATTERN + r"\s*$",
  156. re.VERBOSE | re.IGNORECASE,
  157. )
  158. def __init__(self, version):
  159. # Validate the version and parse it into pieces
  160. match = self._regex.search(version)
  161. if not match:
  162. raise InvalidVersion("Invalid version: '{0}'".format(version))
  163. # Store the parsed out pieces of the version
  164. self._version = _Version(
  165. epoch=int(match.group("epoch")) if match.group("epoch") else 0,
  166. release=tuple(int(i) for i in match.group("release").split(".")),
  167. pre=_parse_letter_version(
  168. match.group("pre_l"),
  169. match.group("pre_n"),
  170. ),
  171. post=_parse_letter_version(
  172. match.group("post_l"),
  173. match.group("post_n1") or match.group("post_n2"),
  174. ),
  175. dev=_parse_letter_version(
  176. match.group("dev_l"),
  177. match.group("dev_n"),
  178. ),
  179. local=_parse_local_version(match.group("local")),
  180. )
  181. # Generate a key which will be used for sorting
  182. self._key = _cmpkey(
  183. self._version.epoch,
  184. self._version.release,
  185. self._version.pre,
  186. self._version.post,
  187. self._version.dev,
  188. self._version.local,
  189. )
  190. def __repr__(self):
  191. return "<Version({0})>".format(repr(str(self)))
  192. def __str__(self):
  193. parts = []
  194. # Epoch
  195. if self._version.epoch != 0:
  196. parts.append("{0}!".format(self._version.epoch))
  197. # Release segment
  198. parts.append(".".join(str(x) for x in self._version.release))
  199. # Pre-release
  200. if self._version.pre is not None:
  201. parts.append("".join(str(x) for x in self._version.pre))
  202. # Post-release
  203. if self._version.post is not None:
  204. parts.append(".post{0}".format(self._version.post[1]))
  205. # Development release
  206. if self._version.dev is not None:
  207. parts.append(".dev{0}".format(self._version.dev[1]))
  208. # Local version segment
  209. if self._version.local is not None:
  210. parts.append(
  211. "+{0}".format(".".join(str(x) for x in self._version.local))
  212. )
  213. return "".join(parts)
  214. @property
  215. def public(self):
  216. return str(self).split("+", 1)[0]
  217. @property
  218. def base_version(self):
  219. parts = []
  220. # Epoch
  221. if self._version.epoch != 0:
  222. parts.append("{0}!".format(self._version.epoch))
  223. # Release segment
  224. parts.append(".".join(str(x) for x in self._version.release))
  225. return "".join(parts)
  226. @property
  227. def local(self):
  228. version_string = str(self)
  229. if "+" in version_string:
  230. return version_string.split("+", 1)[1]
  231. @property
  232. def is_prerelease(self):
  233. return bool(self._version.dev or self._version.pre)
  234. @property
  235. def is_postrelease(self):
  236. return bool(self._version.post)
  237. def _parse_letter_version(letter, number):
  238. if letter:
  239. # We consider there to be an implicit 0 in a pre-release if there is
  240. # not a numeral associated with it.
  241. if number is None:
  242. number = 0
  243. # We normalize any letters to their lower case form
  244. letter = letter.lower()
  245. # We consider some words to be alternate spellings of other words and
  246. # in those cases we want to normalize the spellings to our preferred
  247. # spelling.
  248. if letter == "alpha":
  249. letter = "a"
  250. elif letter == "beta":
  251. letter = "b"
  252. elif letter in ["c", "pre", "preview"]:
  253. letter = "rc"
  254. return letter, int(number)
  255. if not letter and number:
  256. # We assume if we are given a number, but we are not given a letter
  257. # then this is using the implicit post release syntax (e.g. 1.0-1)
  258. letter = "post"
  259. return letter, int(number)
  260. _local_version_seperators = re.compile(r"[\._-]")
  261. def _parse_local_version(local):
  262. """
  263. Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
  264. """
  265. if local is not None:
  266. return tuple(
  267. part.lower() if not part.isdigit() else int(part)
  268. for part in _local_version_seperators.split(local)
  269. )
  270. def _cmpkey(epoch, release, pre, post, dev, local):
  271. # When we compare a release version, we want to compare it with all of the
  272. # trailing zeros removed. So we'll use a reverse the list, drop all the now
  273. # leading zeros until we come to something non zero, then take the rest
  274. # re-reverse it back into the correct order and make it a tuple and use
  275. # that for our sorting key.
  276. release = tuple(
  277. reversed(list(
  278. itertools.dropwhile(
  279. lambda x: x == 0,
  280. reversed(release),
  281. )
  282. ))
  283. )
  284. # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
  285. # We'll do this by abusing the pre segment, but we _only_ want to do this
  286. # if there is not a pre or a post segment. If we have one of those then
  287. # the normal sorting rules will handle this case correctly.
  288. if pre is None and post is None and dev is not None:
  289. pre = -Infinity
  290. # Versions without a pre-release (except as noted above) should sort after
  291. # those with one.
  292. elif pre is None:
  293. pre = Infinity
  294. # Versions without a post segment should sort before those with one.
  295. if post is None:
  296. post = -Infinity
  297. # Versions without a development segment should sort after those with one.
  298. if dev is None:
  299. dev = Infinity
  300. if local is None:
  301. # Versions without a local segment should sort before those with one.
  302. local = -Infinity
  303. else:
  304. # Versions with a local segment need that segment parsed to implement
  305. # the sorting rules in PEP440.
  306. # - Alpha numeric segments sort before numeric segments
  307. # - Alpha numeric segments sort lexicographically
  308. # - Numeric segments sort numerically
  309. # - Shorter versions sort before longer versions when the prefixes
  310. # match exactly
  311. local = tuple(
  312. (i, "") if isinstance(i, int) else (-Infinity, i)
  313. for i in local
  314. )
  315. return epoch, release, pre, post, dev, local