version.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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. """
  5. .. testsetup::
  6. from packaging.version import parse, Version
  7. """
  8. import collections
  9. import itertools
  10. import re
  11. from typing import Callable, Optional, SupportsInt, Tuple, Union
  12. from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType
  13. __all__ = ["VERSION_PATTERN", "parse", "Version", "InvalidVersion"]
  14. InfiniteTypes = Union[InfinityType, NegativeInfinityType]
  15. PrePostDevType = Union[InfiniteTypes, Tuple[str, int]]
  16. SubLocalType = Union[InfiniteTypes, int, str]
  17. LocalType = Union[
  18. NegativeInfinityType,
  19. Tuple[
  20. Union[
  21. SubLocalType,
  22. Tuple[SubLocalType, str],
  23. Tuple[NegativeInfinityType, SubLocalType],
  24. ],
  25. ...,
  26. ],
  27. ]
  28. CmpKey = Tuple[
  29. int, Tuple[int, ...], PrePostDevType, PrePostDevType, PrePostDevType, LocalType
  30. ]
  31. VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool]
  32. _Version = collections.namedtuple(
  33. "_Version", ["epoch", "release", "dev", "pre", "post", "local"]
  34. )
  35. def parse(version: str) -> "Version":
  36. """Parse the given version string.
  37. >>> parse('1.0.dev1')
  38. <Version('1.0.dev1')>
  39. :param version: The version string to parse.
  40. :raises InvalidVersion: When the version string is not a valid version.
  41. """
  42. return Version(version)
  43. class InvalidVersion(ValueError):
  44. """Raised when a version string is not a valid version.
  45. >>> Version("invalid")
  46. Traceback (most recent call last):
  47. ...
  48. packaging.version.InvalidVersion: Invalid version: 'invalid'
  49. """
  50. class _BaseVersion:
  51. _key: CmpKey
  52. def __hash__(self) -> int:
  53. return hash(self._key)
  54. # Please keep the duplicated `isinstance` check
  55. # in the six comparisons hereunder
  56. # unless you find a way to avoid adding overhead function calls.
  57. def __lt__(self, other: "_BaseVersion") -> bool:
  58. if not isinstance(other, _BaseVersion):
  59. return NotImplemented
  60. return self._key < other._key
  61. def __le__(self, other: "_BaseVersion") -> bool:
  62. if not isinstance(other, _BaseVersion):
  63. return NotImplemented
  64. return self._key <= other._key
  65. def __eq__(self, other: object) -> bool:
  66. if not isinstance(other, _BaseVersion):
  67. return NotImplemented
  68. return self._key == other._key
  69. def __ge__(self, other: "_BaseVersion") -> bool:
  70. if not isinstance(other, _BaseVersion):
  71. return NotImplemented
  72. return self._key >= other._key
  73. def __gt__(self, other: "_BaseVersion") -> bool:
  74. if not isinstance(other, _BaseVersion):
  75. return NotImplemented
  76. return self._key > other._key
  77. def __ne__(self, other: object) -> bool:
  78. if not isinstance(other, _BaseVersion):
  79. return NotImplemented
  80. return self._key != other._key
  81. # Deliberately not anchored to the start and end of the string, to make it
  82. # easier for 3rd party code to reuse
  83. _VERSION_PATTERN = r"""
  84. v?
  85. (?:
  86. (?:(?P<epoch>[0-9]+)!)? # epoch
  87. (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
  88. (?P<pre> # pre-release
  89. [-_\.]?
  90. (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
  91. [-_\.]?
  92. (?P<pre_n>[0-9]+)?
  93. )?
  94. (?P<post> # post release
  95. (?:-(?P<post_n1>[0-9]+))
  96. |
  97. (?:
  98. [-_\.]?
  99. (?P<post_l>post|rev|r)
  100. [-_\.]?
  101. (?P<post_n2>[0-9]+)?
  102. )
  103. )?
  104. (?P<dev> # dev release
  105. [-_\.]?
  106. (?P<dev_l>dev)
  107. [-_\.]?
  108. (?P<dev_n>[0-9]+)?
  109. )?
  110. )
  111. (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
  112. """
  113. VERSION_PATTERN = _VERSION_PATTERN
  114. """
  115. A string containing the regular expression used to match a valid version.
  116. The pattern is not anchored at either end, and is intended for embedding in larger
  117. expressions (for example, matching a version number as part of a file name). The
  118. regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
  119. flags set.
  120. :meta hide-value:
  121. """
  122. class Version(_BaseVersion):
  123. """This class abstracts handling of a project's versions.
  124. A :class:`Version` instance is comparison aware and can be compared and
  125. sorted using the standard Python interfaces.
  126. >>> v1 = Version("1.0a5")
  127. >>> v2 = Version("1.0")
  128. >>> v1
  129. <Version('1.0a5')>
  130. >>> v2
  131. <Version('1.0')>
  132. >>> v1 < v2
  133. True
  134. >>> v1 == v2
  135. False
  136. >>> v1 > v2
  137. False
  138. >>> v1 >= v2
  139. False
  140. >>> v1 <= v2
  141. True
  142. """
  143. _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
  144. def __init__(self, version: str) -> None:
  145. """Initialize a Version object.
  146. :param version:
  147. The string representation of a version which will be parsed and normalized
  148. before use.
  149. :raises InvalidVersion:
  150. If the ``version`` does not conform to PEP 440 in any way then this
  151. exception will be raised.
  152. """
  153. # Validate the version and parse it into pieces
  154. match = self._regex.search(version)
  155. if not match:
  156. raise InvalidVersion(f"Invalid version: '{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(match.group("pre_l"), match.group("pre_n")),
  162. post=_parse_letter_version(
  163. match.group("post_l"), match.group("post_n1") or match.group("post_n2")
  164. ),
  165. dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),
  166. local=_parse_local_version(match.group("local")),
  167. )
  168. # Generate a key which will be used for sorting
  169. self._key = _cmpkey(
  170. self._version.epoch,
  171. self._version.release,
  172. self._version.pre,
  173. self._version.post,
  174. self._version.dev,
  175. self._version.local,
  176. )
  177. def __repr__(self) -> str:
  178. """A representation of the Version that shows all internal state.
  179. >>> Version('1.0.0')
  180. <Version('1.0.0')>
  181. """
  182. return f"<Version('{self}')>"
  183. def __str__(self) -> str:
  184. """A string representation of the version that can be rounded-tripped.
  185. >>> str(Version("1.0a5"))
  186. '1.0a5'
  187. """
  188. parts = []
  189. # Epoch
  190. if self.epoch != 0:
  191. parts.append(f"{self.epoch}!")
  192. # Release segment
  193. parts.append(".".join(str(x) for x in self.release))
  194. # Pre-release
  195. if self.pre is not None:
  196. parts.append("".join(str(x) for x in self.pre))
  197. # Post-release
  198. if self.post is not None:
  199. parts.append(f".post{self.post}")
  200. # Development release
  201. if self.dev is not None:
  202. parts.append(f".dev{self.dev}")
  203. # Local version segment
  204. if self.local is not None:
  205. parts.append(f"+{self.local}")
  206. return "".join(parts)
  207. @property
  208. def epoch(self) -> int:
  209. """The epoch of the version.
  210. >>> Version("2.0.0").epoch
  211. 0
  212. >>> Version("1!2.0.0").epoch
  213. 1
  214. """
  215. _epoch: int = self._version.epoch
  216. return _epoch
  217. @property
  218. def release(self) -> Tuple[int, ...]:
  219. """The components of the "release" segment of the version.
  220. >>> Version("1.2.3").release
  221. (1, 2, 3)
  222. >>> Version("2.0.0").release
  223. (2, 0, 0)
  224. >>> Version("1!2.0.0.post0").release
  225. (2, 0, 0)
  226. Includes trailing zeroes but not the epoch or any pre-release / development /
  227. post-release suffixes.
  228. """
  229. _release: Tuple[int, ...] = self._version.release
  230. return _release
  231. @property
  232. def pre(self) -> Optional[Tuple[str, int]]:
  233. """The pre-release segment of the version.
  234. >>> print(Version("1.2.3").pre)
  235. None
  236. >>> Version("1.2.3a1").pre
  237. ('a', 1)
  238. >>> Version("1.2.3b1").pre
  239. ('b', 1)
  240. >>> Version("1.2.3rc1").pre
  241. ('rc', 1)
  242. """
  243. _pre: Optional[Tuple[str, int]] = self._version.pre
  244. return _pre
  245. @property
  246. def post(self) -> Optional[int]:
  247. """The post-release number of the version.
  248. >>> print(Version("1.2.3").post)
  249. None
  250. >>> Version("1.2.3.post1").post
  251. 1
  252. """
  253. return self._version.post[1] if self._version.post else None
  254. @property
  255. def dev(self) -> Optional[int]:
  256. """The development number of the version.
  257. >>> print(Version("1.2.3").dev)
  258. None
  259. >>> Version("1.2.3.dev1").dev
  260. 1
  261. """
  262. return self._version.dev[1] if self._version.dev else None
  263. @property
  264. def local(self) -> Optional[str]:
  265. """The local version segment of the version.
  266. >>> print(Version("1.2.3").local)
  267. None
  268. >>> Version("1.2.3+abc").local
  269. 'abc'
  270. """
  271. if self._version.local:
  272. return ".".join(str(x) for x in self._version.local)
  273. else:
  274. return None
  275. @property
  276. def public(self) -> str:
  277. """The public portion of the version.
  278. >>> Version("1.2.3").public
  279. '1.2.3'
  280. >>> Version("1.2.3+abc").public
  281. '1.2.3'
  282. >>> Version("1.2.3+abc.dev1").public
  283. '1.2.3'
  284. """
  285. return str(self).split("+", 1)[0]
  286. @property
  287. def base_version(self) -> str:
  288. """The "base version" of the version.
  289. >>> Version("1.2.3").base_version
  290. '1.2.3'
  291. >>> Version("1.2.3+abc").base_version
  292. '1.2.3'
  293. >>> Version("1!1.2.3+abc.dev1").base_version
  294. '1!1.2.3'
  295. The "base version" is the public version of the project without any pre or post
  296. release markers.
  297. """
  298. parts = []
  299. # Epoch
  300. if self.epoch != 0:
  301. parts.append(f"{self.epoch}!")
  302. # Release segment
  303. parts.append(".".join(str(x) for x in self.release))
  304. return "".join(parts)
  305. @property
  306. def is_prerelease(self) -> bool:
  307. """Whether this version is a pre-release.
  308. >>> Version("1.2.3").is_prerelease
  309. False
  310. >>> Version("1.2.3a1").is_prerelease
  311. True
  312. >>> Version("1.2.3b1").is_prerelease
  313. True
  314. >>> Version("1.2.3rc1").is_prerelease
  315. True
  316. >>> Version("1.2.3dev1").is_prerelease
  317. True
  318. """
  319. return self.dev is not None or self.pre is not None
  320. @property
  321. def is_postrelease(self) -> bool:
  322. """Whether this version is a post-release.
  323. >>> Version("1.2.3").is_postrelease
  324. False
  325. >>> Version("1.2.3.post1").is_postrelease
  326. True
  327. """
  328. return self.post is not None
  329. @property
  330. def is_devrelease(self) -> bool:
  331. """Whether this version is a development release.
  332. >>> Version("1.2.3").is_devrelease
  333. False
  334. >>> Version("1.2.3.dev1").is_devrelease
  335. True
  336. """
  337. return self.dev is not None
  338. @property
  339. def major(self) -> int:
  340. """The first item of :attr:`release` or ``0`` if unavailable.
  341. >>> Version("1.2.3").major
  342. 1
  343. """
  344. return self.release[0] if len(self.release) >= 1 else 0
  345. @property
  346. def minor(self) -> int:
  347. """The second item of :attr:`release` or ``0`` if unavailable.
  348. >>> Version("1.2.3").minor
  349. 2
  350. >>> Version("1").minor
  351. 0
  352. """
  353. return self.release[1] if len(self.release) >= 2 else 0
  354. @property
  355. def micro(self) -> int:
  356. """The third item of :attr:`release` or ``0`` if unavailable.
  357. >>> Version("1.2.3").micro
  358. 3
  359. >>> Version("1").micro
  360. 0
  361. """
  362. return self.release[2] if len(self.release) >= 3 else 0
  363. def _parse_letter_version(
  364. letter: str, number: Union[str, bytes, SupportsInt]
  365. ) -> Optional[Tuple[str, int]]:
  366. if letter:
  367. # We consider there to be an implicit 0 in a pre-release if there is
  368. # not a numeral associated with it.
  369. if number is None:
  370. number = 0
  371. # We normalize any letters to their lower case form
  372. letter = letter.lower()
  373. # We consider some words to be alternate spellings of other words and
  374. # in those cases we want to normalize the spellings to our preferred
  375. # spelling.
  376. if letter == "alpha":
  377. letter = "a"
  378. elif letter == "beta":
  379. letter = "b"
  380. elif letter in ["c", "pre", "preview"]:
  381. letter = "rc"
  382. elif letter in ["rev", "r"]:
  383. letter = "post"
  384. return letter, int(number)
  385. if not letter and number:
  386. # We assume if we are given a number, but we are not given a letter
  387. # then this is using the implicit post release syntax (e.g. 1.0-1)
  388. letter = "post"
  389. return letter, int(number)
  390. return None
  391. _local_version_separators = re.compile(r"[\._-]")
  392. def _parse_local_version(local: str) -> Optional[LocalType]:
  393. """
  394. Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
  395. """
  396. if local is not None:
  397. return tuple(
  398. part.lower() if not part.isdigit() else int(part)
  399. for part in _local_version_separators.split(local)
  400. )
  401. return None
  402. def _cmpkey(
  403. epoch: int,
  404. release: Tuple[int, ...],
  405. pre: Optional[Tuple[str, int]],
  406. post: Optional[Tuple[str, int]],
  407. dev: Optional[Tuple[str, int]],
  408. local: Optional[Tuple[SubLocalType]],
  409. ) -> CmpKey:
  410. # When we compare a release version, we want to compare it with all of the
  411. # trailing zeros removed. So we'll use a reverse the list, drop all the now
  412. # leading zeros until we come to something non zero, then take the rest
  413. # re-reverse it back into the correct order and make it a tuple and use
  414. # that for our sorting key.
  415. _release = tuple(
  416. reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
  417. )
  418. # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
  419. # We'll do this by abusing the pre segment, but we _only_ want to do this
  420. # if there is not a pre or a post segment. If we have one of those then
  421. # the normal sorting rules will handle this case correctly.
  422. if pre is None and post is None and dev is not None:
  423. _pre: PrePostDevType = NegativeInfinity
  424. # Versions without a pre-release (except as noted above) should sort after
  425. # those with one.
  426. elif pre is None:
  427. _pre = Infinity
  428. else:
  429. _pre = pre
  430. # Versions without a post segment should sort before those with one.
  431. if post is None:
  432. _post: PrePostDevType = NegativeInfinity
  433. else:
  434. _post = post
  435. # Versions without a development segment should sort after those with one.
  436. if dev is None:
  437. _dev: PrePostDevType = Infinity
  438. else:
  439. _dev = dev
  440. if local is None:
  441. # Versions without a local segment should sort before those with one.
  442. _local: LocalType = NegativeInfinity
  443. else:
  444. # Versions with a local segment need that segment parsed to implement
  445. # the sorting rules in PEP440.
  446. # - Alpha numeric segments sort before numeric segments
  447. # - Alpha numeric segments sort lexicographically
  448. # - Numeric segments sort numerically
  449. # - Shorter versions sort before longer versions when the prefixes
  450. # match exactly
  451. _local = tuple(
  452. (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
  453. )
  454. return epoch, _release, _pre, _post, _dev, _local