You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

441 lines
12 KiB

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