PageRenderTime 53ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/pip/_vendor/packaging/version.py

https://github.com/pombredanne/pip
Python | 376 lines | 299 code | 44 blank | 33 comment | 15 complexity | e2c4f787b7ee736372b54ab2f59beca6 MD5 | raw file
  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 local(self):
  72. return None
  73. @property
  74. def is_prerelease(self):
  75. return False
  76. _legacy_version_component_re = re.compile(
  77. r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE,
  78. )
  79. _legacy_version_replacement_map = {
  80. "pre": "c", "preview": "c", "-": "final-", "rc": "c", "dev": "@",
  81. }
  82. def _parse_version_parts(s):
  83. for part in _legacy_version_component_re.split(s):
  84. part = _legacy_version_replacement_map.get(part, part)
  85. if not part or part == ".":
  86. continue
  87. if part[:1] in "0123456789":
  88. # pad for numeric comparison
  89. yield part.zfill(8)
  90. else:
  91. yield "*" + part
  92. # ensure that alpha/beta/candidate are before final
  93. yield "*final"
  94. def _legacy_cmpkey(version):
  95. # We hardcode an epoch of -1 here. A PEP 440 version can only have a epoch
  96. # greater than or equal to 0. This will effectively put the LegacyVersion,
  97. # which uses the defacto standard originally implemented by setuptools,
  98. # as before all PEP 440 versions.
  99. epoch = -1
  100. # This scheme is taken from pkg_resources.parse_version setuptools prior to
  101. # it's adoption of the packaging library.
  102. parts = []
  103. for part in _parse_version_parts(version.lower()):
  104. if part.startswith("*"):
  105. # remove "-" before a prerelease tag
  106. if part < "*final":
  107. while parts and parts[-1] == "*final-":
  108. parts.pop()
  109. # remove trailing zeros from each series of numeric parts
  110. while parts and parts[-1] == "00000000":
  111. parts.pop()
  112. parts.append(part)
  113. parts = tuple(parts)
  114. return epoch, parts
  115. # Deliberately not anchored to the start and end of the string, to make it
  116. # easier for 3rd party code to reuse
  117. VERSION_PATTERN = r"""
  118. v?
  119. (?:
  120. (?:(?P<epoch>[0-9]+)!)? # epoch
  121. (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
  122. (?P<pre> # pre-release
  123. [-_\.]?
  124. (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
  125. [-_\.]?
  126. (?P<pre_n>[0-9]+)?
  127. )?
  128. (?P<post> # post release
  129. (?:-(?P<post_n1>[0-9]+))
  130. |
  131. (?:
  132. [-_\.]?
  133. (?P<post_l>post|rev|r)
  134. [-_\.]?
  135. (?P<post_n2>[0-9]+)?
  136. )
  137. )?
  138. (?P<dev> # dev release
  139. [-_\.]?
  140. (?P<dev_l>dev)
  141. [-_\.]?
  142. (?P<dev_n>[0-9]+)?
  143. )?
  144. )
  145. (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
  146. """
  147. class Version(_BaseVersion):
  148. _regex = re.compile(
  149. r"^\s*" + VERSION_PATTERN + r"\s*$",
  150. re.VERBOSE | re.IGNORECASE,
  151. )
  152. def __init__(self, version):
  153. # Validate the version and parse it into pieces
  154. match = self._regex.search(version)
  155. if not match:
  156. raise InvalidVersion("Invalid version: '{0}'".format(version))
  157. # Store the parsed out pieces of the version
  158. self._version = _Version(
  159. epoch=int(match.group("epoch")) if match.group("epoch") else 0,
  160. release=tuple(int(i) for i in match.group("release").split(".")),
  161. pre=_parse_letter_version(
  162. match.group("pre_l"),
  163. match.group("pre_n"),
  164. ),
  165. post=_parse_letter_version(
  166. match.group("post_l"),
  167. match.group("post_n1") or match.group("post_n2"),
  168. ),
  169. dev=_parse_letter_version(
  170. match.group("dev_l"),
  171. match.group("dev_n"),
  172. ),
  173. local=_parse_local_version(match.group("local")),
  174. )
  175. # Generate a key which will be used for sorting
  176. self._key = _cmpkey(
  177. self._version.epoch,
  178. self._version.release,
  179. self._version.pre,
  180. self._version.post,
  181. self._version.dev,
  182. self._version.local,
  183. )
  184. def __repr__(self):
  185. return "<Version({0})>".format(repr(str(self)))
  186. def __str__(self):
  187. parts = []
  188. # Epoch
  189. if self._version.epoch != 0:
  190. parts.append("{0}!".format(self._version.epoch))
  191. # Release segment
  192. parts.append(".".join(str(x) for x in self._version.release))
  193. # Pre-release
  194. if self._version.pre is not None:
  195. parts.append("".join(str(x) for x in self._version.pre))
  196. # Post-release
  197. if self._version.post is not None:
  198. parts.append(".post{0}".format(self._version.post[1]))
  199. # Development release
  200. if self._version.dev is not None:
  201. parts.append(".dev{0}".format(self._version.dev[1]))
  202. # Local version segment
  203. if self._version.local is not None:
  204. parts.append(
  205. "+{0}".format(".".join(str(x) for x in self._version.local))
  206. )
  207. return "".join(parts)
  208. @property
  209. def public(self):
  210. return str(self).split("+", 1)[0]
  211. @property
  212. def local(self):
  213. version_string = str(self)
  214. if "+" in version_string:
  215. return version_string.split("+", 1)[1]
  216. @property
  217. def is_prerelease(self):
  218. return bool(self._version.dev or self._version.pre)
  219. def _parse_letter_version(letter, number):
  220. if letter:
  221. # We consider there to be an implicit 0 in a pre-release if there is
  222. # not a numeral associated with it.
  223. if number is None:
  224. number = 0
  225. # We normalize any letters to their lower case form
  226. letter = letter.lower()
  227. # We consider some words to be alternate spellings of other words and
  228. # in those cases we want to normalize the spellings to our preferred
  229. # spelling.
  230. if letter == "alpha":
  231. letter = "a"
  232. elif letter == "beta":
  233. letter = "b"
  234. elif letter in ["c", "pre", "preview"]:
  235. letter = "rc"
  236. return letter, int(number)
  237. if not letter and number:
  238. # We assume if we are given a number, but we are not given a letter
  239. # then this is using the implicit post release syntax (e.g. 1.0-1)
  240. letter = "post"
  241. return letter, int(number)
  242. _local_version_seperators = re.compile(r"[\._-]")
  243. def _parse_local_version(local):
  244. """
  245. Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
  246. """
  247. if local is not None:
  248. return tuple(
  249. part.lower() if not part.isdigit() else int(part)
  250. for part in _local_version_seperators.split(local)
  251. )
  252. def _cmpkey(epoch, release, pre, post, dev, local):
  253. # When we compare a release version, we want to compare it with all of the
  254. # trailing zeros removed. So we'll use a reverse the list, drop all the now
  255. # leading zeros until we come to something non zero, then take the rest
  256. # re-reverse it back into the correct order and make it a tuple and use
  257. # that for our sorting key.
  258. release = tuple(
  259. reversed(list(
  260. itertools.dropwhile(
  261. lambda x: x == 0,
  262. reversed(release),
  263. )
  264. ))
  265. )
  266. # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
  267. # We'll do this by abusing the pre segment, but we _only_ want to do this
  268. # if there is not a pre or a post segment. If we have one of those then
  269. # the normal sorting rules will handle this case correctly.
  270. if pre is None and post is None and dev is not None:
  271. pre = -Infinity
  272. # Versions without a pre-release (except as noted above) should sort after
  273. # those with one.
  274. elif pre is None:
  275. pre = Infinity
  276. # Versions without a post segment should sort before those with one.
  277. if post is None:
  278. post = -Infinity
  279. # Versions without a development segment should sort after those with one.
  280. if dev is None:
  281. dev = Infinity
  282. if local is None:
  283. # Versions without a local segment should sort before those with one.
  284. local = -Infinity
  285. else:
  286. # Versions with a local segment need that segment parsed to implement
  287. # the sorting rules in PEP440.
  288. # - Alpha numeric segments sort before numeric segments
  289. # - Alpha numeric segments sort lexicographically
  290. # - Numeric segments sort numerically
  291. # - Shorter versions sort before longer versions when the prefixes
  292. # match exactly
  293. local = tuple(
  294. (i, "") if isinstance(i, int) else (-Infinity, i)
  295. for i in local
  296. )
  297. return epoch, release, pre, post, dev, local