pep562.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. """
  2. Backport of PEP 562.
  3. https://pypi.org/search/?q=pep562
  4. Licensed under MIT
  5. Copyright (c) 2018 Isaac Muse <isaacmuse@gmail.com>
  6. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  7. documentation files (the "Software"), to deal in the Software without restriction, including without limitation
  8. the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
  9. and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all copies or substantial portions
  11. of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  13. TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  14. THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  15. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  16. IN THE SOFTWARE.
  17. """
  18. import sys
  19. from collections import namedtuple
  20. import re
  21. __all__ = ('Pep562',)
  22. RE_VER = re.compile(
  23. r'''(?x)
  24. (?P<major>\d+)(?:\.(?P<minor>\d+))?(?:\.(?P<micro>\d+))?
  25. (?:(?P<type>a|b|rc)(?P<pre>\d+))?
  26. (?:\.post(?P<post>\d+))?
  27. (?:\.dev(?P<dev>\d+))?
  28. '''
  29. )
  30. REL_MAP = {
  31. ".dev": "",
  32. ".dev-alpha": "a",
  33. ".dev-beta": "b",
  34. ".dev-candidate": "rc",
  35. "alpha": "a",
  36. "beta": "b",
  37. "candidate": "rc",
  38. "final": ""
  39. }
  40. DEV_STATUS = {
  41. ".dev": "2 - Pre-Alpha",
  42. ".dev-alpha": "2 - Pre-Alpha",
  43. ".dev-beta": "2 - Pre-Alpha",
  44. ".dev-candidate": "2 - Pre-Alpha",
  45. "alpha": "3 - Alpha",
  46. "beta": "4 - Beta",
  47. "candidate": "4 - Beta",
  48. "final": "5 - Production/Stable"
  49. }
  50. PRE_REL_MAP = {"a": 'alpha', "b": 'beta', "rc": 'candidate'}
  51. class Version(namedtuple("Version", ["major", "minor", "micro", "release", "pre", "post", "dev"])):
  52. """
  53. Get the version (PEP 440).
  54. A biased approach to the PEP 440 semantic version.
  55. Provides a tuple structure which is sorted for comparisons `v1 > v2` etc.
  56. (major, minor, micro, release type, pre-release build, post-release build, development release build)
  57. Release types are named in is such a way they are comparable with ease.
  58. Accessors to check if a development, pre-release, or post-release build. Also provides accessor to get
  59. development status for setup files.
  60. How it works (currently):
  61. - You must specify a release type as either `final`, `alpha`, `beta`, or `candidate`.
  62. - To define a development release, you can use either `.dev`, `.dev-alpha`, `.dev-beta`, or `.dev-candidate`.
  63. The dot is used to ensure all development specifiers are sorted before `alpha`.
  64. You can specify a `dev` number for development builds, but do not have to as implicit development releases
  65. are allowed.
  66. - You must specify a `pre` value greater than zero if using a prerelease as this project (not PEP 440) does not
  67. allow implicit prereleases.
  68. - You can optionally set `post` to a value greater than zero to make the build a post release. While post releases
  69. are technically allowed in prereleases, it is strongly discouraged, so we are rejecting them. It should be
  70. noted that we do not allow `post0` even though PEP 440 does not restrict this. This project specifically
  71. does not allow implicit post releases.
  72. - It should be noted that we do not support epochs `1!` or local versions `+some-custom.version-1`.
  73. Acceptable version releases:
  74. ```
  75. Version(1, 0, 0, "final") 1.0
  76. Version(1, 2, 0, "final") 1.2
  77. Version(1, 2, 3, "final") 1.2.3
  78. Version(1, 2, 0, ".dev-alpha", pre=4) 1.2a4
  79. Version(1, 2, 0, ".dev-beta", pre=4) 1.2b4
  80. Version(1, 2, 0, ".dev-candidate", pre=4) 1.2rc4
  81. Version(1, 2, 0, "final", post=1) 1.2.post1
  82. Version(1, 2, 3, ".dev") 1.2.3.dev0
  83. Version(1, 2, 3, ".dev", dev=1) 1.2.3.dev1
  84. ```
  85. """
  86. def __new__(cls, major, minor, micro, release="final", pre=0, post=0, dev=0):
  87. """Validate version info."""
  88. # Ensure all parts are positive integers.
  89. for value in (major, minor, micro, pre, post):
  90. if not (isinstance(value, int) and value >= 0):
  91. raise ValueError("All version parts except 'release' should be integers.")
  92. if release not in REL_MAP:
  93. raise ValueError("'{}' is not a valid release type.".format(release))
  94. # Ensure valid pre-release (we do not allow implicit pre-releases).
  95. if ".dev-candidate" < release < "final":
  96. if pre == 0:
  97. raise ValueError("Implicit pre-releases not allowed.")
  98. elif dev:
  99. raise ValueError("Version is not a development release.")
  100. elif post:
  101. raise ValueError("Post-releases are not allowed with pre-releases.")
  102. # Ensure valid development or development/pre release
  103. elif release < "alpha":
  104. if release > ".dev" and pre == 0:
  105. raise ValueError("Implicit pre-release not allowed.")
  106. elif post:
  107. raise ValueError("Post-releases are not allowed with pre-releases.")
  108. # Ensure a valid normal release
  109. else:
  110. if pre:
  111. raise ValueError("Version is not a pre-release.")
  112. elif dev:
  113. raise ValueError("Version is not a development release.")
  114. return super().__new__(cls, major, minor, micro, release, pre, post, dev)
  115. def _is_pre(self):
  116. """Is prerelease."""
  117. return self.pre > 0
  118. def _is_dev(self):
  119. """Is development."""
  120. return bool(self.release < "alpha")
  121. def _is_post(self):
  122. """Is post."""
  123. return self.post > 0
  124. def _get_dev_status(self): # pragma: no cover
  125. """Get development status string."""
  126. return DEV_STATUS[self.release]
  127. def _get_canonical(self):
  128. """Get the canonical output string."""
  129. # Assemble major, minor, micro version and append `pre`, `post`, or `dev` if needed..
  130. if self.micro == 0:
  131. ver = "{}.{}".format(self.major, self.minor)
  132. else:
  133. ver = "{}.{}.{}".format(self.major, self.minor, self.micro)
  134. if self._is_pre():
  135. ver += '{}{}'.format(REL_MAP[self.release], self.pre)
  136. if self._is_post():
  137. ver += ".post{}".format(self.post)
  138. if self._is_dev():
  139. ver += ".dev{}".format(self.dev)
  140. return ver
  141. def parse_version(ver, pre=False):
  142. """Parse version into a comparable Version tuple."""
  143. m = RE_VER.match(ver)
  144. # Handle major, minor, micro
  145. major = int(m.group('major'))
  146. minor = int(m.group('minor')) if m.group('minor') else 0
  147. micro = int(m.group('micro')) if m.group('micro') else 0
  148. # Handle pre releases
  149. if m.group('type'):
  150. release = PRE_REL_MAP[m.group('type')]
  151. pre = int(m.group('pre'))
  152. else:
  153. release = "final"
  154. pre = 0
  155. # Handle development releases
  156. dev = m.group('dev') if m.group('dev') else 0
  157. if m.group('dev'):
  158. dev = int(m.group('dev'))
  159. release = '.dev-' + release if pre else '.dev'
  160. else:
  161. dev = 0
  162. # Handle post
  163. post = int(m.group('post')) if m.group('post') else 0
  164. return Version(major, minor, micro, release, pre, post, dev)
  165. class Pep562:
  166. """
  167. Backport of PEP 562 <https://pypi.org/search/?q=pep562>.
  168. Wraps the module in a class that exposes the mechanics to override `__dir__` and `__getattr__`.
  169. The given module will be searched for overrides of `__dir__` and `__getattr__` and use them when needed.
  170. """
  171. def __init__(self, name):
  172. """Acquire `__getattr__` and `__dir__`, but only replace module for versions less than Python 3.7."""
  173. self._module = sys.modules[name]
  174. self._get_attr = getattr(self._module, '__getattr__', None)
  175. self._get_dir = getattr(self._module, '__dir__', None)
  176. sys.modules[name] = self
  177. def __dir__(self):
  178. """Return the overridden `dir` if one was provided, else apply `dir` to the module."""
  179. return self._get_dir() if self._get_dir else dir(self._module)
  180. def __getattr__(self, name):
  181. """Attempt to retrieve the attribute from the module, and if missing, use the overridden function if present."""
  182. try:
  183. return getattr(self._module, name)
  184. except AttributeError:
  185. if self._get_attr:
  186. return self._get_attr(name)
  187. raise
  188. __version_info__ = Version(1, 0, 0, "final")
  189. __version__ = __version_info__._get_canonical()