Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

version.py 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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 Any, 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: 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>(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. _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. _epoch: int = self._version.epoch
  217. return _epoch
  218. @property
  219. def release(self) -> Tuple[int, ...]:
  220. """The components of the "release" segment of the version.
  221. >>> Version("1.2.3").release
  222. (1, 2, 3)
  223. >>> Version("2.0.0").release
  224. (2, 0, 0)
  225. >>> Version("1!2.0.0.post0").release
  226. (2, 0, 0)
  227. Includes trailing zeroes but not the epoch or any pre-release / development /
  228. post-release suffixes.
  229. """
  230. _release: Tuple[int, ...] = self._version.release
  231. return _release
  232. @property
  233. def pre(self) -> Optional[Tuple[str, int]]:
  234. """The pre-release segment of the version.
  235. >>> print(Version("1.2.3").pre)
  236. None
  237. >>> Version("1.2.3a1").pre
  238. ('a', 1)
  239. >>> Version("1.2.3b1").pre
  240. ('b', 1)
  241. >>> Version("1.2.3rc1").pre
  242. ('rc', 1)
  243. """
  244. _pre: Optional[Tuple[str, int]] = self._version.pre
  245. return _pre
  246. @property
  247. def post(self) -> Optional[int]:
  248. """The post-release number of the version.
  249. >>> print(Version("1.2.3").post)
  250. None
  251. >>> Version("1.2.3.post1").post
  252. 1
  253. """
  254. return self._version.post[1] if self._version.post else None
  255. @property
  256. def dev(self) -> Optional[int]:
  257. """The development number of the version.
  258. >>> print(Version("1.2.3").dev)
  259. None
  260. >>> Version("1.2.3.dev1").dev
  261. 1
  262. """
  263. return self._version.dev[1] if self._version.dev else None
  264. @property
  265. def local(self) -> Optional[str]:
  266. """The local version segment of the version.
  267. >>> print(Version("1.2.3").local)
  268. None
  269. >>> Version("1.2.3+abc").local
  270. 'abc'
  271. """
  272. if self._version.local:
  273. return ".".join(str(x) for x in self._version.local)
  274. else:
  275. return None
  276. @property
  277. def public(self) -> str:
  278. """The public portion of the version.
  279. >>> Version("1.2.3").public
  280. '1.2.3'
  281. >>> Version("1.2.3+abc").public
  282. '1.2.3'
  283. >>> Version("1.2.3+abc.dev1").public
  284. '1.2.3'
  285. """
  286. return str(self).split("+", 1)[0]
  287. @property
  288. def base_version(self) -> str:
  289. """The "base version" of the version.
  290. >>> Version("1.2.3").base_version
  291. '1.2.3'
  292. >>> Version("1.2.3+abc").base_version
  293. '1.2.3'
  294. >>> Version("1!1.2.3+abc.dev1").base_version
  295. '1!1.2.3'
  296. The "base version" is the public version of the project without any pre or post
  297. release markers.
  298. """
  299. parts = []
  300. # Epoch
  301. if self.epoch != 0:
  302. parts.append(f"{self.epoch}!")
  303. # Release segment
  304. parts.append(".".join(str(x) for x in self.release))
  305. return "".join(parts)
  306. @property
  307. def is_prerelease(self) -> bool:
  308. """Whether this version is a pre-release.
  309. >>> Version("1.2.3").is_prerelease
  310. False
  311. >>> Version("1.2.3a1").is_prerelease
  312. True
  313. >>> Version("1.2.3b1").is_prerelease
  314. True
  315. >>> Version("1.2.3rc1").is_prerelease
  316. True
  317. >>> Version("1.2.3dev1").is_prerelease
  318. True
  319. """
  320. return self.dev is not None or self.pre is not None
  321. @property
  322. def is_postrelease(self) -> bool:
  323. """Whether this version is a post-release.
  324. >>> Version("1.2.3").is_postrelease
  325. False
  326. >>> Version("1.2.3.post1").is_postrelease
  327. True
  328. """
  329. return self.post is not None
  330. @property
  331. def is_devrelease(self) -> bool:
  332. """Whether this version is a development release.
  333. >>> Version("1.2.3").is_devrelease
  334. False
  335. >>> Version("1.2.3.dev1").is_devrelease
  336. True
  337. """
  338. return self.dev is not None
  339. @property
  340. def major(self) -> int:
  341. """The first item of :attr:`release` or ``0`` if unavailable.
  342. >>> Version("1.2.3").major
  343. 1
  344. """
  345. return self.release[0] if len(self.release) >= 1 else 0
  346. @property
  347. def minor(self) -> int:
  348. """The second item of :attr:`release` or ``0`` if unavailable.
  349. >>> Version("1.2.3").minor
  350. 2
  351. >>> Version("1").minor
  352. 0
  353. """
  354. return self.release[1] if len(self.release) >= 2 else 0
  355. @property
  356. def micro(self) -> int:
  357. """The third item of :attr:`release` or ``0`` if unavailable.
  358. >>> Version("1.2.3").micro
  359. 3
  360. >>> Version("1").micro
  361. 0
  362. """
  363. return self.release[2] if len(self.release) >= 3 else 0
  364. def _parse_letter_version(
  365. letter: str, number: Union[str, bytes, SupportsInt]
  366. ) -> Optional[Tuple[str, int]]:
  367. if letter:
  368. # We consider there to be an implicit 0 in a pre-release if there is
  369. # not a numeral associated with it.
  370. if number is None:
  371. number = 0
  372. # We normalize any letters to their lower case form
  373. letter = letter.lower()
  374. # We consider some words to be alternate spellings of other words and
  375. # in those cases we want to normalize the spellings to our preferred
  376. # spelling.
  377. if letter == "alpha":
  378. letter = "a"
  379. elif letter == "beta":
  380. letter = "b"
  381. elif letter in ["c", "pre", "preview"]:
  382. letter = "rc"
  383. elif letter in ["rev", "r"]:
  384. letter = "post"
  385. return letter, int(number)
  386. if not letter and number:
  387. # We assume if we are given a number, but we are not given a letter
  388. # then this is using the implicit post release syntax (e.g. 1.0-1)
  389. letter = "post"
  390. return letter, int(number)
  391. return None
  392. _local_version_separators = re.compile(r"[\._-]")
  393. def _parse_local_version(local: str) -> Optional[LocalType]:
  394. """
  395. Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
  396. """
  397. if local is not None:
  398. return tuple(
  399. part.lower() if not part.isdigit() else int(part)
  400. for part in _local_version_separators.split(local)
  401. )
  402. return None
  403. def _cmpkey(
  404. epoch: int,
  405. release: Tuple[int, ...],
  406. pre: Optional[Tuple[str, int]],
  407. post: Optional[Tuple[str, int]],
  408. dev: Optional[Tuple[str, int]],
  409. local: Optional[Tuple[SubLocalType]],
  410. ) -> CmpKey:
  411. # When we compare a release version, we want to compare it with all of the
  412. # trailing zeros removed. So we'll use a reverse the list, drop all the now
  413. # leading zeros until we come to something non zero, then take the rest
  414. # re-reverse it back into the correct order and make it a tuple and use
  415. # that for our sorting key.
  416. _release = tuple(
  417. reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
  418. )
  419. # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
  420. # We'll do this by abusing the pre segment, but we _only_ want to do this
  421. # if there is not a pre or a post segment. If we have one of those then
  422. # the normal sorting rules will handle this case correctly.
  423. if pre is None and post is None and dev is not None:
  424. _pre: PrePostDevType = NegativeInfinity
  425. # Versions without a pre-release (except as noted above) should sort after
  426. # those with one.
  427. elif pre is None:
  428. _pre = Infinity
  429. else:
  430. _pre = pre
  431. # Versions without a post segment should sort before those with one.
  432. if post is None:
  433. _post: PrePostDevType = NegativeInfinity
  434. else:
  435. _post = post
  436. # Versions without a development segment should sort after those with one.
  437. if dev is None:
  438. _dev: PrePostDevType = Infinity
  439. else:
  440. _dev = dev
  441. if local is None:
  442. # Versions without a local segment should sort before those with one.
  443. _local: LocalType = NegativeInfinity
  444. else:
  445. # Versions with a local segment need that segment parsed to implement
  446. # the sorting rules in PEP440.
  447. # - Alpha numeric segments sort before numeric segments
  448. # - Alpha numeric segments sort lexicographically
  449. # - Numeric segments sort numerically
  450. # - Shorter versions sort before longer versions when the prefixes
  451. # match exactly
  452. _local = tuple(
  453. (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
  454. )
  455. return epoch, _release, _pre, _post, _dev, _local