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 itertools
  9. import re
  10. from typing import Any, Callable, NamedTuple, Optional, SupportsInt, Tuple, Union
  11. from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType
  12. __all__ = ["VERSION_PATTERN", "parse", "Version", "InvalidVersion"]
  13. LocalType = Tuple[Union[int, str], ...]
  14. CmpPrePostDevType = Union[InfinityType, NegativeInfinityType, Tuple[str, int]]
  15. CmpLocalType = Union[
  16. NegativeInfinityType,
  17. Tuple[Union[Tuple[int, str], Tuple[NegativeInfinityType, Union[int, str]]], ...],
  18. ]
  19. CmpKey = Tuple[
  20. int,
  21. Tuple[int, ...],
  22. CmpPrePostDevType,
  23. CmpPrePostDevType,
  24. CmpPrePostDevType,
  25. CmpLocalType,
  26. ]
  27. VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool]
  28. class _Version(NamedTuple):
  29. epoch: int
  30. release: Tuple[int, ...]
  31. dev: Optional[Tuple[str, int]]
  32. pre: Optional[Tuple[str, int]]
  33. post: Optional[Tuple[str, int]]
  34. local: Optional[LocalType]
  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: Tuple[Any, ...]
  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>alpha|a|beta|b|preview|pre|c|rc)
  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. _key: CmpKey
  145. def __init__(self, version: str) -> None:
  146. """Initialize a Version object.
  147. :param version:
  148. The string representation of a version which will be parsed and normalized
  149. before use.
  150. :raises InvalidVersion:
  151. If the ``version`` does not conform to PEP 440 in any way then this
  152. exception will be raised.
  153. """
  154. # Validate the version and parse it into pieces
  155. match = self._regex.search(version)
  156. if not match:
  157. raise InvalidVersion(f"Invalid version: '{version}'")
  158. # Store the parsed out pieces of the version
  159. self._version = _Version(
  160. epoch=int(match.group("epoch")) if match.group("epoch") else 0,
  161. release=tuple(int(i) for i in match.group("release").split(".")),
  162. pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")),
  163. post=_parse_letter_version(
  164. match.group("post_l"), match.group("post_n1") or match.group("post_n2")
  165. ),
  166. dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),
  167. local=_parse_local_version(match.group("local")),
  168. )
  169. # Generate a key which will be used for sorting
  170. self._key = _cmpkey(
  171. self._version.epoch,
  172. self._version.release,
  173. self._version.pre,
  174. self._version.post,
  175. self._version.dev,
  176. self._version.local,
  177. )
  178. def __repr__(self) -> str:
  179. """A representation of the Version that shows all internal state.
  180. >>> Version('1.0.0')
  181. <Version('1.0.0')>
  182. """
  183. return f"<Version('{self}')>"
  184. def __str__(self) -> str:
  185. """A string representation of the version that can be rounded-tripped.
  186. >>> str(Version("1.0a5"))
  187. '1.0a5'
  188. """
  189. parts = []
  190. # Epoch
  191. if self.epoch != 0:
  192. parts.append(f"{self.epoch}!")
  193. # Release segment
  194. parts.append(".".join(str(x) for x in self.release))
  195. # Pre-release
  196. if self.pre is not None:
  197. parts.append("".join(str(x) for x in self.pre))
  198. # Post-release
  199. if self.post is not None:
  200. parts.append(f".post{self.post}")
  201. # Development release
  202. if self.dev is not None:
  203. parts.append(f".dev{self.dev}")
  204. # Local version segment
  205. if self.local is not None:
  206. parts.append(f"+{self.local}")
  207. return "".join(parts)
  208. @property
  209. def epoch(self) -> int:
  210. """The epoch of the version.
  211. >>> Version("2.0.0").epoch
  212. 0
  213. >>> Version("1!2.0.0").epoch
  214. 1
  215. """
  216. return self._version.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. return self._version.release
  230. @property
  231. def pre(self) -> Optional[Tuple[str, int]]:
  232. """The pre-release segment of the version.
  233. >>> print(Version("1.2.3").pre)
  234. None
  235. >>> Version("1.2.3a1").pre
  236. ('a', 1)
  237. >>> Version("1.2.3b1").pre
  238. ('b', 1)
  239. >>> Version("1.2.3rc1").pre
  240. ('rc', 1)
  241. """
  242. return self._version.pre
  243. @property
  244. def post(self) -> Optional[int]:
  245. """The post-release number of the version.
  246. >>> print(Version("1.2.3").post)
  247. None
  248. >>> Version("1.2.3.post1").post
  249. 1
  250. """
  251. return self._version.post[1] if self._version.post else None
  252. @property
  253. def dev(self) -> Optional[int]:
  254. """The development number of the version.
  255. >>> print(Version("1.2.3").dev)
  256. None
  257. >>> Version("1.2.3.dev1").dev
  258. 1
  259. """
  260. return self._version.dev[1] if self._version.dev else None
  261. @property
  262. def local(self) -> Optional[str]:
  263. """The local version segment of the version.
  264. >>> print(Version("1.2.3").local)
  265. None
  266. >>> Version("1.2.3+abc").local
  267. 'abc'
  268. """
  269. if self._version.local:
  270. return ".".join(str(x) for x in self._version.local)
  271. else:
  272. return None
  273. @property
  274. def public(self) -> str:
  275. """The public portion of the version.
  276. >>> Version("1.2.3").public
  277. '1.2.3'
  278. >>> Version("1.2.3+abc").public
  279. '1.2.3'
  280. >>> Version("1.2.3+abc.dev1").public
  281. '1.2.3'
  282. """
  283. return str(self).split("+", 1)[0]
  284. @property
  285. def base_version(self) -> str:
  286. """The "base version" of the version.
  287. >>> Version("1.2.3").base_version
  288. '1.2.3'
  289. >>> Version("1.2.3+abc").base_version
  290. '1.2.3'
  291. >>> Version("1!1.2.3+abc.dev1").base_version
  292. '1!1.2.3'
  293. The "base version" is the public version of the project without any pre or post
  294. release markers.
  295. """
  296. parts = []
  297. # Epoch
  298. if self.epoch != 0:
  299. parts.append(f"{self.epoch}!")
  300. # Release segment
  301. parts.append(".".join(str(x) for x in self.release))
  302. return "".join(parts)
  303. @property
  304. def is_prerelease(self) -> bool:
  305. """Whether this version is a pre-release.
  306. >>> Version("1.2.3").is_prerelease
  307. False
  308. >>> Version("1.2.3a1").is_prerelease
  309. True
  310. >>> Version("1.2.3b1").is_prerelease
  311. True
  312. >>> Version("1.2.3rc1").is_prerelease
  313. True
  314. >>> Version("1.2.3dev1").is_prerelease
  315. True
  316. """
  317. return self.dev is not None or self.pre is not None
  318. @property
  319. def is_postrelease(self) -> bool:
  320. """Whether this version is a post-release.
  321. >>> Version("1.2.3").is_postrelease
  322. False
  323. >>> Version("1.2.3.post1").is_postrelease
  324. True
  325. """
  326. return self.post is not None
  327. @property
  328. def is_devrelease(self) -> bool:
  329. """Whether this version is a development release.
  330. >>> Version("1.2.3").is_devrelease
  331. False
  332. >>> Version("1.2.3.dev1").is_devrelease
  333. True
  334. """
  335. return self.dev is not None
  336. @property
  337. def major(self) -> int:
  338. """The first item of :attr:`release` or ``0`` if unavailable.
  339. >>> Version("1.2.3").major
  340. 1
  341. """
  342. return self.release[0] if len(self.release) >= 1 else 0
  343. @property
  344. def minor(self) -> int:
  345. """The second item of :attr:`release` or ``0`` if unavailable.
  346. >>> Version("1.2.3").minor
  347. 2
  348. >>> Version("1").minor
  349. 0
  350. """
  351. return self.release[1] if len(self.release) >= 2 else 0
  352. @property
  353. def micro(self) -> int:
  354. """The third item of :attr:`release` or ``0`` if unavailable.
  355. >>> Version("1.2.3").micro
  356. 3
  357. >>> Version("1").micro
  358. 0
  359. """
  360. return self.release[2] if len(self.release) >= 3 else 0
  361. def _parse_letter_version(
  362. letter: Optional[str], number: Union[str, bytes, SupportsInt, None]
  363. ) -> Optional[Tuple[str, int]]:
  364. if letter:
  365. # We consider there to be an implicit 0 in a pre-release if there is
  366. # not a numeral associated with it.
  367. if number is None:
  368. number = 0
  369. # We normalize any letters to their lower case form
  370. letter = letter.lower()
  371. # We consider some words to be alternate spellings of other words and
  372. # in those cases we want to normalize the spellings to our preferred
  373. # spelling.
  374. if letter == "alpha":
  375. letter = "a"
  376. elif letter == "beta":
  377. letter = "b"
  378. elif letter in ["c", "pre", "preview"]:
  379. letter = "rc"
  380. elif letter in ["rev", "r"]:
  381. letter = "post"
  382. return letter, int(number)
  383. if not letter and number:
  384. # We assume if we are given a number, but we are not given a letter
  385. # then this is using the implicit post release syntax (e.g. 1.0-1)
  386. letter = "post"
  387. return letter, int(number)
  388. return None
  389. _local_version_separators = re.compile(r"[\._-]")
  390. def _parse_local_version(local: Optional[str]) -> Optional[LocalType]:
  391. """
  392. Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
  393. """
  394. if local is not None:
  395. return tuple(
  396. part.lower() if not part.isdigit() else int(part)
  397. for part in _local_version_separators.split(local)
  398. )
  399. return None
  400. def _cmpkey(
  401. epoch: int,
  402. release: Tuple[int, ...],
  403. pre: Optional[Tuple[str, int]],
  404. post: Optional[Tuple[str, int]],
  405. dev: Optional[Tuple[str, int]],
  406. local: Optional[LocalType],
  407. ) -> CmpKey:
  408. # When we compare a release version, we want to compare it with all of the
  409. # trailing zeros removed. So we'll use a reverse the list, drop all the now
  410. # leading zeros until we come to something non zero, then take the rest
  411. # re-reverse it back into the correct order and make it a tuple and use
  412. # that for our sorting key.
  413. _release = tuple(
  414. reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
  415. )
  416. # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
  417. # We'll do this by abusing the pre segment, but we _only_ want to do this
  418. # if there is not a pre or a post segment. If we have one of those then
  419. # the normal sorting rules will handle this case correctly.
  420. if pre is None and post is None and dev is not None:
  421. _pre: CmpPrePostDevType = NegativeInfinity
  422. # Versions without a pre-release (except as noted above) should sort after
  423. # those with one.
  424. elif pre is None:
  425. _pre = Infinity
  426. else:
  427. _pre = pre
  428. # Versions without a post segment should sort before those with one.
  429. if post is None:
  430. _post: CmpPrePostDevType = NegativeInfinity
  431. else:
  432. _post = post
  433. # Versions without a development segment should sort after those with one.
  434. if dev is None:
  435. _dev: CmpPrePostDevType = Infinity
  436. else:
  437. _dev = dev
  438. if local is None:
  439. # Versions without a local segment should sort before those with one.
  440. _local: CmpLocalType = NegativeInfinity
  441. else:
  442. # Versions with a local segment need that segment parsed to implement
  443. # the sorting rules in PEP440.
  444. # - Alpha numeric segments sort before numeric segments
  445. # - Alpha numeric segments sort lexicographically
  446. # - Numeric segments sort numerically
  447. # - Shorter versions sort before longer versions when the prefixes
  448. # match exactly
  449. _local = tuple(
  450. (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
  451. )
  452. return epoch, _release, _pre, _post, _dev, _local