0001-Update-versioneer-to-0.29.patch 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194
  1. From 5b5436f11d01e66505bb4c148304c2eb49346529 Mon Sep 17 00:00:00 2001
  2. From: Adam Duskett <adam.duskett@amarulasolutions.com>
  3. Date: Tue, 24 Oct 2023 09:56:57 +0200
  4. Subject: [PATCH] Update versioneer to 0.29
  5. Fixes builds against Python 3.12.0
  6. Upstream: https://github.com/warner/python-spake2/pull/15
  7. Signed-off-by: Adam Duskett <adam.duskett@amarulasolutions.com>
  8. ---
  9. versioneer.py | 1350 ++++++++++++++++++++++++++++++++++---------------
  10. 1 file changed, 931 insertions(+), 419 deletions(-)
  11. diff --git a/versioneer.py b/versioneer.py
  12. index 64fea1c..de97d90 100644
  13. --- a/versioneer.py
  14. +++ b/versioneer.py
  15. @@ -1,5 +1,4 @@
  16. -
  17. -# Version: 0.18
  18. +# Version: 0.29
  19. """The Versioneer - like a rocketeer, but for versions.
  20. @@ -7,18 +6,14 @@ The Versioneer
  21. ==============
  22. * like a rocketeer, but for versions!
  23. -* https://github.com/warner/python-versioneer
  24. +* https://github.com/python-versioneer/python-versioneer
  25. * Brian Warner
  26. -* License: Public Domain
  27. -* Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6, and pypy
  28. -* [![Latest Version]
  29. -(https://pypip.in/version/versioneer/badge.svg?style=flat)
  30. -](https://pypi.python.org/pypi/versioneer/)
  31. -* [![Build Status]
  32. -(https://travis-ci.org/warner/python-versioneer.png?branch=master)
  33. -](https://travis-ci.org/warner/python-versioneer)
  34. -
  35. -This is a tool for managing a recorded version number in distutils-based
  36. +* License: Public Domain (Unlicense)
  37. +* Compatible with: Python 3.7, 3.8, 3.9, 3.10, 3.11 and pypy3
  38. +* [![Latest Version][pypi-image]][pypi-url]
  39. +* [![Build Status][travis-image]][travis-url]
  40. +
  41. +This is a tool for managing a recorded version number in setuptools-based
  42. python projects. The goal is to remove the tedious and error-prone "update
  43. the embedded version string" step from your release process. Making a new
  44. release should be as easy as recording a new tag in your version-control
  45. @@ -27,9 +22,38 @@ system, and maybe making new tarballs.
  46. ## Quick Install
  47. -* `pip install versioneer` to somewhere to your $PATH
  48. -* add a `[versioneer]` section to your setup.cfg (see below)
  49. -* run `versioneer install` in your source tree, commit the results
  50. +Versioneer provides two installation modes. The "classic" vendored mode installs
  51. +a copy of versioneer into your repository. The experimental build-time dependency mode
  52. +is intended to allow you to skip this step and simplify the process of upgrading.
  53. +
  54. +### Vendored mode
  55. +
  56. +* `pip install versioneer` to somewhere in your $PATH
  57. + * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is
  58. + available, so you can also use `conda install -c conda-forge versioneer`
  59. +* add a `[tool.versioneer]` section to your `pyproject.toml` or a
  60. + `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md))
  61. + * Note that you will need to add `tomli; python_version < "3.11"` to your
  62. + build-time dependencies if you use `pyproject.toml`
  63. +* run `versioneer install --vendor` in your source tree, commit the results
  64. +* verify version information with `python setup.py version`
  65. +
  66. +### Build-time dependency mode
  67. +
  68. +* `pip install versioneer` to somewhere in your $PATH
  69. + * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is
  70. + available, so you can also use `conda install -c conda-forge versioneer`
  71. +* add a `[tool.versioneer]` section to your `pyproject.toml` or a
  72. + `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md))
  73. +* add `versioneer` (with `[toml]` extra, if configuring in `pyproject.toml`)
  74. + to the `requires` key of the `build-system` table in `pyproject.toml`:
  75. + ```toml
  76. + [build-system]
  77. + requires = ["setuptools", "versioneer[toml]"]
  78. + build-backend = "setuptools.build_meta"
  79. + ```
  80. +* run `versioneer install --no-vendor` in your source tree, commit the results
  81. +* verify version information with `python setup.py version`
  82. ## Version Identifiers
  83. @@ -61,7 +85,7 @@ version 1.3). Many VCS systems can report a description that captures this,
  84. for example `git describe --tags --dirty --always` reports things like
  85. "0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the
  86. 0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has
  87. -uncommitted changes.
  88. +uncommitted changes).
  89. The version identifier is used for multiple purposes:
  90. @@ -166,7 +190,7 @@ which may help identify what went wrong).
  91. Some situations are known to cause problems for Versioneer. This details the
  92. most significant ones. More can be found on Github
  93. -[issues page](https://github.com/warner/python-versioneer/issues).
  94. +[issues page](https://github.com/python-versioneer/python-versioneer/issues).
  95. ### Subprojects
  96. @@ -180,7 +204,7 @@ two common reasons why `setup.py` might not be in the root:
  97. `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI
  98. distributions (and upload multiple independently-installable tarballs).
  99. * Source trees whose main purpose is to contain a C library, but which also
  100. - provide bindings to Python (and perhaps other langauges) in subdirectories.
  101. + provide bindings to Python (and perhaps other languages) in subdirectories.
  102. Versioneer will look for `.git` in parent directories, and most operations
  103. should get the right version string. However `pip` and `setuptools` have bugs
  104. @@ -194,9 +218,9 @@ work too.
  105. Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in
  106. some later version.
  107. -[Bug #38](https://github.com/warner/python-versioneer/issues/38) is tracking
  108. +[Bug #38](https://github.com/python-versioneer/python-versioneer/issues/38) is tracking
  109. this issue. The discussion in
  110. -[PR #61](https://github.com/warner/python-versioneer/pull/61) describes the
  111. +[PR #61](https://github.com/python-versioneer/python-versioneer/pull/61) describes the
  112. issue from the Versioneer side in more detail.
  113. [pip PR#3176](https://github.com/pypa/pip/pull/3176) and
  114. [pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve
  115. @@ -224,31 +248,20 @@ regenerated while a different version is checked out. Many setup.py commands
  116. cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into
  117. a different virtualenv), so this can be surprising.
  118. -[Bug #83](https://github.com/warner/python-versioneer/issues/83) describes
  119. +[Bug #83](https://github.com/python-versioneer/python-versioneer/issues/83) describes
  120. this one, but upgrading to a newer version of setuptools should probably
  121. resolve it.
  122. -### Unicode version strings
  123. -
  124. -While Versioneer works (and is continually tested) with both Python 2 and
  125. -Python 3, it is not entirely consistent with bytes-vs-unicode distinctions.
  126. -Newer releases probably generate unicode version strings on py2. It's not
  127. -clear that this is wrong, but it may be surprising for applications when then
  128. -write these strings to a network connection or include them in bytes-oriented
  129. -APIs like cryptographic checksums.
  130. -
  131. -[Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates
  132. -this question.
  133. -
  134. ## Updating Versioneer
  135. To upgrade your project to a new release of Versioneer, do the following:
  136. * install the new Versioneer (`pip install -U versioneer` or equivalent)
  137. -* edit `setup.cfg`, if necessary, to include any new configuration settings
  138. - indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details.
  139. -* re-run `versioneer install` in your source tree, to replace
  140. +* edit `setup.cfg` and `pyproject.toml`, if necessary,
  141. + to include any new configuration settings indicated by the release notes.
  142. + See [UPGRADING](./UPGRADING.md) for details.
  143. +* re-run `versioneer install --[no-]vendor` in your source tree, to replace
  144. `SRC/_version.py`
  145. * commit any changed files
  146. @@ -265,35 +278,70 @@ installation by editing setup.py . Alternatively, it might go the other
  147. direction and include code from all supported VCS systems, reducing the
  148. number of intermediate scripts.
  149. +## Similar projects
  150. +
  151. +* [setuptools_scm](https://github.com/pypa/setuptools_scm/) - a non-vendored build-time
  152. + dependency
  153. +* [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of
  154. + versioneer
  155. +* [versioningit](https://github.com/jwodder/versioningit) - a PEP 518-based setuptools
  156. + plugin
  157. ## License
  158. To make Versioneer easier to embed, all its code is dedicated to the public
  159. domain. The `_version.py` that it creates is also in the public domain.
  160. -Specifically, both are released under the Creative Commons "Public Domain
  161. -Dedication" license (CC0-1.0), as described in
  162. -https://creativecommons.org/publicdomain/zero/1.0/ .
  163. +Specifically, both are released under the "Unlicense", as described in
  164. +https://unlicense.org/.
  165. +
  166. +[pypi-image]: https://img.shields.io/pypi/v/versioneer.svg
  167. +[pypi-url]: https://pypi.python.org/pypi/versioneer/
  168. +[travis-image]:
  169. +https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg
  170. +[travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer
  171. """
  172. +# pylint:disable=invalid-name,import-outside-toplevel,missing-function-docstring
  173. +# pylint:disable=missing-class-docstring,too-many-branches,too-many-statements
  174. +# pylint:disable=raise-missing-from,too-many-lines,too-many-locals,import-error
  175. +# pylint:disable=too-few-public-methods,redefined-outer-name,consider-using-with
  176. +# pylint:disable=attribute-defined-outside-init,too-many-arguments
  177. -from __future__ import print_function
  178. -try:
  179. - import configparser
  180. -except ImportError:
  181. - import ConfigParser as configparser
  182. +import configparser
  183. import errno
  184. import json
  185. import os
  186. import re
  187. import subprocess
  188. import sys
  189. +from pathlib import Path
  190. +from typing import Any, Callable, cast, Dict, List, Optional, Tuple, Union
  191. +from typing import NoReturn
  192. +import functools
  193. +
  194. +have_tomllib = True
  195. +if sys.version_info >= (3, 11):
  196. + import tomllib
  197. +else:
  198. + try:
  199. + import tomli as tomllib
  200. + except ImportError:
  201. + have_tomllib = False
  202. class VersioneerConfig:
  203. """Container for Versioneer configuration parameters."""
  204. + VCS: str
  205. + style: str
  206. + tag_prefix: str
  207. + versionfile_source: str
  208. + versionfile_build: Optional[str]
  209. + parentdir_prefix: Optional[str]
  210. + verbose: Optional[bool]
  211. +
  212. -def get_root():
  213. +def get_root() -> str:
  214. """Get the project root directory.
  215. We require that all commands are run from the project root, i.e. the
  216. @@ -301,18 +349,30 @@ def get_root():
  217. """
  218. root = os.path.realpath(os.path.abspath(os.getcwd()))
  219. setup_py = os.path.join(root, "setup.py")
  220. + pyproject_toml = os.path.join(root, "pyproject.toml")
  221. versioneer_py = os.path.join(root, "versioneer.py")
  222. - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):
  223. + if not (
  224. + os.path.exists(setup_py)
  225. + or os.path.exists(pyproject_toml)
  226. + or os.path.exists(versioneer_py)
  227. + ):
  228. # allow 'python path/to/setup.py COMMAND'
  229. root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0])))
  230. setup_py = os.path.join(root, "setup.py")
  231. + pyproject_toml = os.path.join(root, "pyproject.toml")
  232. versioneer_py = os.path.join(root, "versioneer.py")
  233. - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):
  234. - err = ("Versioneer was unable to run the project root directory. "
  235. - "Versioneer requires setup.py to be executed from "
  236. - "its immediate directory (like 'python setup.py COMMAND'), "
  237. - "or in a way that lets it use sys.argv[0] to find the root "
  238. - "(like 'python path/to/setup.py COMMAND').")
  239. + if not (
  240. + os.path.exists(setup_py)
  241. + or os.path.exists(pyproject_toml)
  242. + or os.path.exists(versioneer_py)
  243. + ):
  244. + err = (
  245. + "Versioneer was unable to run the project root directory. "
  246. + "Versioneer requires setup.py to be executed from "
  247. + "its immediate directory (like 'python setup.py COMMAND'), "
  248. + "or in a way that lets it use sys.argv[0] to find the root "
  249. + "(like 'python path/to/setup.py COMMAND')."
  250. + )
  251. raise VersioneerBadRootError(err)
  252. try:
  253. # Certain runtime workflows (setup.py install/develop in a setuptools
  254. @@ -321,43 +381,64 @@ def get_root():
  255. # module-import table will cache the first one. So we can't use
  256. # os.path.dirname(__file__), as that will find whichever
  257. # versioneer.py was first imported, even in later projects.
  258. - me = os.path.realpath(os.path.abspath(__file__))
  259. - me_dir = os.path.normcase(os.path.splitext(me)[0])
  260. + my_path = os.path.realpath(os.path.abspath(__file__))
  261. + me_dir = os.path.normcase(os.path.splitext(my_path)[0])
  262. vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0])
  263. - if me_dir != vsr_dir:
  264. - print("Warning: build in %s is using versioneer.py from %s"
  265. - % (os.path.dirname(me), versioneer_py))
  266. + if me_dir != vsr_dir and "VERSIONEER_PEP518" not in globals():
  267. + print(
  268. + "Warning: build in %s is using versioneer.py from %s"
  269. + % (os.path.dirname(my_path), versioneer_py)
  270. + )
  271. except NameError:
  272. pass
  273. return root
  274. -def get_config_from_root(root):
  275. +def get_config_from_root(root: str) -> VersioneerConfig:
  276. """Read the project setup.cfg file to determine Versioneer config."""
  277. - # This might raise EnvironmentError (if setup.cfg is missing), or
  278. + # This might raise OSError (if setup.cfg is missing), or
  279. # configparser.NoSectionError (if it lacks a [versioneer] section), or
  280. # configparser.NoOptionError (if it lacks "VCS="). See the docstring at
  281. # the top of versioneer.py for instructions on writing your setup.cfg .
  282. - setup_cfg = os.path.join(root, "setup.cfg")
  283. - parser = configparser.SafeConfigParser()
  284. - with open(setup_cfg, "r") as f:
  285. - parser.readfp(f)
  286. - VCS = parser.get("versioneer", "VCS") # mandatory
  287. -
  288. - def get(parser, name):
  289. - if parser.has_option("versioneer", name):
  290. - return parser.get("versioneer", name)
  291. - return None
  292. + root_pth = Path(root)
  293. + pyproject_toml = root_pth / "pyproject.toml"
  294. + setup_cfg = root_pth / "setup.cfg"
  295. + section: Union[Dict[str, Any], configparser.SectionProxy, None] = None
  296. + if pyproject_toml.exists() and have_tomllib:
  297. + try:
  298. + with open(pyproject_toml, "rb") as fobj:
  299. + pp = tomllib.load(fobj)
  300. + section = pp["tool"]["versioneer"]
  301. + except (tomllib.TOMLDecodeError, KeyError) as e:
  302. + print(f"Failed to load config from {pyproject_toml}: {e}")
  303. + print("Try to load it from setup.cfg")
  304. + if not section:
  305. + parser = configparser.ConfigParser()
  306. + with open(setup_cfg) as cfg_file:
  307. + parser.read_file(cfg_file)
  308. + parser.get("versioneer", "VCS") # raise error if missing
  309. +
  310. + section = parser["versioneer"]
  311. +
  312. + # `cast`` really shouldn't be used, but its simplest for the
  313. + # common VersioneerConfig users at the moment. We verify against
  314. + # `None` values elsewhere where it matters
  315. +
  316. cfg = VersioneerConfig()
  317. - cfg.VCS = VCS
  318. - cfg.style = get(parser, "style") or ""
  319. - cfg.versionfile_source = get(parser, "versionfile_source")
  320. - cfg.versionfile_build = get(parser, "versionfile_build")
  321. - cfg.tag_prefix = get(parser, "tag_prefix")
  322. - if cfg.tag_prefix in ("''", '""'):
  323. + cfg.VCS = section["VCS"]
  324. + cfg.style = section.get("style", "")
  325. + cfg.versionfile_source = cast(str, section.get("versionfile_source"))
  326. + cfg.versionfile_build = section.get("versionfile_build")
  327. + cfg.tag_prefix = cast(str, section.get("tag_prefix"))
  328. + if cfg.tag_prefix in ("''", '""', None):
  329. cfg.tag_prefix = ""
  330. - cfg.parentdir_prefix = get(parser, "parentdir_prefix")
  331. - cfg.verbose = get(parser, "verbose")
  332. + cfg.parentdir_prefix = section.get("parentdir_prefix")
  333. + if isinstance(section, configparser.SectionProxy):
  334. + # Make sure configparser translates to bool
  335. + cfg.verbose = section.getboolean("verbose")
  336. + else:
  337. + cfg.verbose = section.get("verbose")
  338. +
  339. return cfg
  340. @@ -366,37 +447,54 @@ class NotThisMethod(Exception):
  341. # these dictionaries contain VCS-specific tools
  342. -LONG_VERSION_PY = {}
  343. -HANDLERS = {}
  344. +LONG_VERSION_PY: Dict[str, str] = {}
  345. +HANDLERS: Dict[str, Dict[str, Callable]] = {}
  346. -def register_vcs_handler(vcs, method): # decorator
  347. - """Decorator to mark a method as the handler for a particular VCS."""
  348. - def decorate(f):
  349. +def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator
  350. + """Create decorator to mark a method as the handler of a VCS."""
  351. +
  352. + def decorate(f: Callable) -> Callable:
  353. """Store f in HANDLERS[vcs][method]."""
  354. - if vcs not in HANDLERS:
  355. - HANDLERS[vcs] = {}
  356. - HANDLERS[vcs][method] = f
  357. + HANDLERS.setdefault(vcs, {})[method] = f
  358. return f
  359. +
  360. return decorate
  361. -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
  362. - env=None):
  363. +def run_command(
  364. + commands: List[str],
  365. + args: List[str],
  366. + cwd: Optional[str] = None,
  367. + verbose: bool = False,
  368. + hide_stderr: bool = False,
  369. + env: Optional[Dict[str, str]] = None,
  370. +) -> Tuple[Optional[str], Optional[int]]:
  371. """Call the given command(s)."""
  372. assert isinstance(commands, list)
  373. - p = None
  374. - for c in commands:
  375. + process = None
  376. +
  377. + popen_kwargs: Dict[str, Any] = {}
  378. + if sys.platform == "win32":
  379. + # This hides the console window if pythonw.exe is used
  380. + startupinfo = subprocess.STARTUPINFO()
  381. + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  382. + popen_kwargs["startupinfo"] = startupinfo
  383. +
  384. + for command in commands:
  385. try:
  386. - dispcmd = str([c] + args)
  387. + dispcmd = str([command] + args)
  388. # remember shell=False, so use git.cmd on windows, not just git
  389. - p = subprocess.Popen([c] + args, cwd=cwd, env=env,
  390. - stdout=subprocess.PIPE,
  391. - stderr=(subprocess.PIPE if hide_stderr
  392. - else None))
  393. + process = subprocess.Popen(
  394. + [command] + args,
  395. + cwd=cwd,
  396. + env=env,
  397. + stdout=subprocess.PIPE,
  398. + stderr=(subprocess.PIPE if hide_stderr else None),
  399. + **popen_kwargs,
  400. + )
  401. break
  402. - except EnvironmentError:
  403. - e = sys.exc_info()[1]
  404. + except OSError as e:
  405. if e.errno == errno.ENOENT:
  406. continue
  407. if verbose:
  408. @@ -407,26 +505,27 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
  409. if verbose:
  410. print("unable to find command, tried %s" % (commands,))
  411. return None, None
  412. - stdout = p.communicate()[0].strip()
  413. - if sys.version_info[0] >= 3:
  414. - stdout = stdout.decode()
  415. - if p.returncode != 0:
  416. + stdout = process.communicate()[0].strip().decode()
  417. + if process.returncode != 0:
  418. if verbose:
  419. print("unable to run %s (error)" % dispcmd)
  420. print("stdout was %s" % stdout)
  421. - return None, p.returncode
  422. - return stdout, p.returncode
  423. + return None, process.returncode
  424. + return stdout, process.returncode
  425. -LONG_VERSION_PY['git'] = '''
  426. +LONG_VERSION_PY[
  427. + "git"
  428. +] = r'''
  429. # This file helps to compute a version number in source trees obtained from
  430. # git-archive tarball (such as those provided by githubs download-from-tag
  431. # feature). Distribution tarballs (built by setup.py sdist) and build
  432. # directories (produced by setup.py build) will contain a much shorter file
  433. # that just contains the computed version number.
  434. -# This file is released into the public domain. Generated by
  435. -# versioneer-0.18 (https://github.com/warner/python-versioneer)
  436. +# This file is released into the public domain.
  437. +# Generated by versioneer-0.29
  438. +# https://github.com/python-versioneer/python-versioneer
  439. """Git implementation of _version.py."""
  440. @@ -435,9 +534,11 @@ import os
  441. import re
  442. import subprocess
  443. import sys
  444. +from typing import Any, Callable, Dict, List, Optional, Tuple
  445. +import functools
  446. -def get_keywords():
  447. +def get_keywords() -> Dict[str, str]:
  448. """Get the keywords needed to look up the version information."""
  449. # these strings will be replaced by git during git-archive.
  450. # setup.py/versioneer.py will grep for the variable names, so they must
  451. @@ -453,8 +554,15 @@ def get_keywords():
  452. class VersioneerConfig:
  453. """Container for Versioneer configuration parameters."""
  454. + VCS: str
  455. + style: str
  456. + tag_prefix: str
  457. + parentdir_prefix: str
  458. + versionfile_source: str
  459. + verbose: bool
  460. +
  461. -def get_config():
  462. +def get_config() -> VersioneerConfig:
  463. """Create, populate and return the VersioneerConfig() object."""
  464. # these strings are filled in when 'setup.py versioneer' creates
  465. # _version.py
  466. @@ -472,13 +580,13 @@ class NotThisMethod(Exception):
  467. """Exception raised if a method is not valid for the current scenario."""
  468. -LONG_VERSION_PY = {}
  469. -HANDLERS = {}
  470. +LONG_VERSION_PY: Dict[str, str] = {}
  471. +HANDLERS: Dict[str, Dict[str, Callable]] = {}
  472. -def register_vcs_handler(vcs, method): # decorator
  473. - """Decorator to mark a method as the handler for a particular VCS."""
  474. - def decorate(f):
  475. +def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator
  476. + """Create decorator to mark a method as the handler of a VCS."""
  477. + def decorate(f: Callable) -> Callable:
  478. """Store f in HANDLERS[vcs][method]."""
  479. if vcs not in HANDLERS:
  480. HANDLERS[vcs] = {}
  481. @@ -487,22 +595,35 @@ def register_vcs_handler(vcs, method): # decorator
  482. return decorate
  483. -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
  484. - env=None):
  485. +def run_command(
  486. + commands: List[str],
  487. + args: List[str],
  488. + cwd: Optional[str] = None,
  489. + verbose: bool = False,
  490. + hide_stderr: bool = False,
  491. + env: Optional[Dict[str, str]] = None,
  492. +) -> Tuple[Optional[str], Optional[int]]:
  493. """Call the given command(s)."""
  494. assert isinstance(commands, list)
  495. - p = None
  496. - for c in commands:
  497. + process = None
  498. +
  499. + popen_kwargs: Dict[str, Any] = {}
  500. + if sys.platform == "win32":
  501. + # This hides the console window if pythonw.exe is used
  502. + startupinfo = subprocess.STARTUPINFO()
  503. + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  504. + popen_kwargs["startupinfo"] = startupinfo
  505. +
  506. + for command in commands:
  507. try:
  508. - dispcmd = str([c] + args)
  509. + dispcmd = str([command] + args)
  510. # remember shell=False, so use git.cmd on windows, not just git
  511. - p = subprocess.Popen([c] + args, cwd=cwd, env=env,
  512. - stdout=subprocess.PIPE,
  513. - stderr=(subprocess.PIPE if hide_stderr
  514. - else None))
  515. + process = subprocess.Popen([command] + args, cwd=cwd, env=env,
  516. + stdout=subprocess.PIPE,
  517. + stderr=(subprocess.PIPE if hide_stderr
  518. + else None), **popen_kwargs)
  519. break
  520. - except EnvironmentError:
  521. - e = sys.exc_info()[1]
  522. + except OSError as e:
  523. if e.errno == errno.ENOENT:
  524. continue
  525. if verbose:
  526. @@ -513,18 +634,20 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
  527. if verbose:
  528. print("unable to find command, tried %%s" %% (commands,))
  529. return None, None
  530. - stdout = p.communicate()[0].strip()
  531. - if sys.version_info[0] >= 3:
  532. - stdout = stdout.decode()
  533. - if p.returncode != 0:
  534. + stdout = process.communicate()[0].strip().decode()
  535. + if process.returncode != 0:
  536. if verbose:
  537. print("unable to run %%s (error)" %% dispcmd)
  538. print("stdout was %%s" %% stdout)
  539. - return None, p.returncode
  540. - return stdout, p.returncode
  541. + return None, process.returncode
  542. + return stdout, process.returncode
  543. -def versions_from_parentdir(parentdir_prefix, root, verbose):
  544. +def versions_from_parentdir(
  545. + parentdir_prefix: str,
  546. + root: str,
  547. + verbose: bool,
  548. +) -> Dict[str, Any]:
  549. """Try to determine the version from the parent directory name.
  550. Source tarballs conventionally unpack into a directory that includes both
  551. @@ -533,15 +656,14 @@ def versions_from_parentdir(parentdir_prefix, root, verbose):
  552. """
  553. rootdirs = []
  554. - for i in range(3):
  555. + for _ in range(3):
  556. dirname = os.path.basename(root)
  557. if dirname.startswith(parentdir_prefix):
  558. return {"version": dirname[len(parentdir_prefix):],
  559. "full-revisionid": None,
  560. "dirty": False, "error": None, "date": None}
  561. - else:
  562. - rootdirs.append(root)
  563. - root = os.path.dirname(root) # up a level
  564. + rootdirs.append(root)
  565. + root = os.path.dirname(root) # up a level
  566. if verbose:
  567. print("Tried directories %%s but none started with prefix %%s" %%
  568. @@ -550,41 +672,48 @@ def versions_from_parentdir(parentdir_prefix, root, verbose):
  569. @register_vcs_handler("git", "get_keywords")
  570. -def git_get_keywords(versionfile_abs):
  571. +def git_get_keywords(versionfile_abs: str) -> Dict[str, str]:
  572. """Extract version information from the given file."""
  573. # the code embedded in _version.py can just fetch the value of these
  574. # keywords. When used from setup.py, we don't want to import _version.py,
  575. # so we do it with a regexp instead. This function is not used from
  576. # _version.py.
  577. - keywords = {}
  578. + keywords: Dict[str, str] = {}
  579. try:
  580. - f = open(versionfile_abs, "r")
  581. - for line in f.readlines():
  582. - if line.strip().startswith("git_refnames ="):
  583. - mo = re.search(r'=\s*"(.*)"', line)
  584. - if mo:
  585. - keywords["refnames"] = mo.group(1)
  586. - if line.strip().startswith("git_full ="):
  587. - mo = re.search(r'=\s*"(.*)"', line)
  588. - if mo:
  589. - keywords["full"] = mo.group(1)
  590. - if line.strip().startswith("git_date ="):
  591. - mo = re.search(r'=\s*"(.*)"', line)
  592. - if mo:
  593. - keywords["date"] = mo.group(1)
  594. - f.close()
  595. - except EnvironmentError:
  596. + with open(versionfile_abs, "r") as fobj:
  597. + for line in fobj:
  598. + if line.strip().startswith("git_refnames ="):
  599. + mo = re.search(r'=\s*"(.*)"', line)
  600. + if mo:
  601. + keywords["refnames"] = mo.group(1)
  602. + if line.strip().startswith("git_full ="):
  603. + mo = re.search(r'=\s*"(.*)"', line)
  604. + if mo:
  605. + keywords["full"] = mo.group(1)
  606. + if line.strip().startswith("git_date ="):
  607. + mo = re.search(r'=\s*"(.*)"', line)
  608. + if mo:
  609. + keywords["date"] = mo.group(1)
  610. + except OSError:
  611. pass
  612. return keywords
  613. @register_vcs_handler("git", "keywords")
  614. -def git_versions_from_keywords(keywords, tag_prefix, verbose):
  615. +def git_versions_from_keywords(
  616. + keywords: Dict[str, str],
  617. + tag_prefix: str,
  618. + verbose: bool,
  619. +) -> Dict[str, Any]:
  620. """Get version information from git keywords."""
  621. - if not keywords:
  622. - raise NotThisMethod("no keywords at all, weird")
  623. + if "refnames" not in keywords:
  624. + raise NotThisMethod("Short version file found")
  625. date = keywords.get("date")
  626. if date is not None:
  627. + # Use only the last line. Previous lines may contain GPG signature
  628. + # information.
  629. + date = date.splitlines()[-1]
  630. +
  631. # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant
  632. # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601
  633. # -like" string, which we must then edit to make compliant), because
  634. @@ -597,11 +726,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
  635. if verbose:
  636. print("keywords are unexpanded, not using")
  637. raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
  638. - refs = set([r.strip() for r in refnames.strip("()").split(",")])
  639. + refs = {r.strip() for r in refnames.strip("()").split(",")}
  640. # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
  641. # just "foo-1.0". If we see a "tag: " prefix, prefer those.
  642. TAG = "tag: "
  643. - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
  644. + tags = {r[len(TAG):] for r in refs if r.startswith(TAG)}
  645. if not tags:
  646. # Either we're using git < 1.8.3, or there really are no tags. We use
  647. # a heuristic: assume all version tags have a digit. The old git %%d
  648. @@ -610,7 +739,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
  649. # between branches and tags. By ignoring refnames without digits, we
  650. # filter out many common branch names like "release" and
  651. # "stabilization", as well as "HEAD" and "master".
  652. - tags = set([r for r in refs if re.search(r'\d', r)])
  653. + tags = {r for r in refs if re.search(r'\d', r)}
  654. if verbose:
  655. print("discarding '%%s', no digits" %% ",".join(refs - tags))
  656. if verbose:
  657. @@ -619,6 +748,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
  658. # sorting will prefer e.g. "2.0" over "2.0rc1"
  659. if ref.startswith(tag_prefix):
  660. r = ref[len(tag_prefix):]
  661. + # Filter out refs that exactly match prefix or that don't start
  662. + # with a number once the prefix is stripped (mostly a concern
  663. + # when prefix is '')
  664. + if not re.match(r'\d', r):
  665. + continue
  666. if verbose:
  667. print("picking %%s" %% r)
  668. return {"version": r,
  669. @@ -634,7 +768,12 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
  670. @register_vcs_handler("git", "pieces_from_vcs")
  671. -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
  672. +def git_pieces_from_vcs(
  673. + tag_prefix: str,
  674. + root: str,
  675. + verbose: bool,
  676. + runner: Callable = run_command
  677. +) -> Dict[str, Any]:
  678. """Get version from 'git describe' in the root of the source tree.
  679. This only gets called if the git-archive 'subst' keywords were *not*
  680. @@ -645,8 +784,15 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
  681. if sys.platform == "win32":
  682. GITS = ["git.cmd", "git.exe"]
  683. - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root,
  684. - hide_stderr=True)
  685. + # GIT_DIR can interfere with correct operation of Versioneer.
  686. + # It may be intended to be passed to the Versioneer-versioned project,
  687. + # but that should not change where we get our version from.
  688. + env = os.environ.copy()
  689. + env.pop("GIT_DIR", None)
  690. + runner = functools.partial(runner, env=env)
  691. +
  692. + _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root,
  693. + hide_stderr=not verbose)
  694. if rc != 0:
  695. if verbose:
  696. print("Directory %%s not under git control" %% root)
  697. @@ -654,24 +800,57 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
  698. # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
  699. # if there isn't one, this yields HEX[-dirty] (no NUM)
  700. - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty",
  701. - "--always", "--long",
  702. - "--match", "%%s*" %% tag_prefix],
  703. - cwd=root)
  704. + describe_out, rc = runner(GITS, [
  705. + "describe", "--tags", "--dirty", "--always", "--long",
  706. + "--match", f"{tag_prefix}[[:digit:]]*"
  707. + ], cwd=root)
  708. # --long was added in git-1.5.5
  709. if describe_out is None:
  710. raise NotThisMethod("'git describe' failed")
  711. describe_out = describe_out.strip()
  712. - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
  713. + full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root)
  714. if full_out is None:
  715. raise NotThisMethod("'git rev-parse' failed")
  716. full_out = full_out.strip()
  717. - pieces = {}
  718. + pieces: Dict[str, Any] = {}
  719. pieces["long"] = full_out
  720. pieces["short"] = full_out[:7] # maybe improved later
  721. pieces["error"] = None
  722. + branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
  723. + cwd=root)
  724. + # --abbrev-ref was added in git-1.6.3
  725. + if rc != 0 or branch_name is None:
  726. + raise NotThisMethod("'git rev-parse --abbrev-ref' returned error")
  727. + branch_name = branch_name.strip()
  728. +
  729. + if branch_name == "HEAD":
  730. + # If we aren't exactly on a branch, pick a branch which represents
  731. + # the current commit. If all else fails, we are on a branchless
  732. + # commit.
  733. + branches, rc = runner(GITS, ["branch", "--contains"], cwd=root)
  734. + # --contains was added in git-1.5.4
  735. + if rc != 0 or branches is None:
  736. + raise NotThisMethod("'git branch --contains' returned error")
  737. + branches = branches.split("\n")
  738. +
  739. + # Remove the first line if we're running detached
  740. + if "(" in branches[0]:
  741. + branches.pop(0)
  742. +
  743. + # Strip off the leading "* " from the list of branches.
  744. + branches = [branch[2:] for branch in branches]
  745. + if "master" in branches:
  746. + branch_name = "master"
  747. + elif not branches:
  748. + branch_name = None
  749. + else:
  750. + # Pick the first branch that is returned. Good or bad.
  751. + branch_name = branches[0]
  752. +
  753. + pieces["branch"] = branch_name
  754. +
  755. # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
  756. # TAG might have hyphens.
  757. git_describe = describe_out
  758. @@ -688,7 +867,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
  759. # TAG-NUM-gHEX
  760. mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
  761. if not mo:
  762. - # unparseable. Maybe git-describe is misbehaving?
  763. + # unparsable. Maybe git-describe is misbehaving?
  764. pieces["error"] = ("unable to parse git-describe output: '%%s'"
  765. %% describe_out)
  766. return pieces
  767. @@ -713,26 +892,27 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
  768. else:
  769. # HEX: no tags
  770. pieces["closest-tag"] = None
  771. - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"],
  772. - cwd=root)
  773. - pieces["distance"] = int(count_out) # total number of commits
  774. + out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root)
  775. + pieces["distance"] = len(out.split()) # total number of commits
  776. # commit date: see ISO-8601 comment in git_versions_from_keywords()
  777. - date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"],
  778. - cwd=root)[0].strip()
  779. + date = runner(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip()
  780. + # Use only the last line. Previous lines may contain GPG signature
  781. + # information.
  782. + date = date.splitlines()[-1]
  783. pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
  784. return pieces
  785. -def plus_or_dot(pieces):
  786. +def plus_or_dot(pieces: Dict[str, Any]) -> str:
  787. """Return a + if we don't already have one, else return a ."""
  788. if "+" in pieces.get("closest-tag", ""):
  789. return "."
  790. return "+"
  791. -def render_pep440(pieces):
  792. +def render_pep440(pieces: Dict[str, Any]) -> str:
  793. """Build up version string, with post-release "local version identifier".
  794. Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
  795. @@ -757,23 +937,71 @@ def render_pep440(pieces):
  796. return rendered
  797. -def render_pep440_pre(pieces):
  798. - """TAG[.post.devDISTANCE] -- No -dirty.
  799. +def render_pep440_branch(pieces: Dict[str, Any]) -> str:
  800. + """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] .
  801. +
  802. + The ".dev0" means not master branch. Note that .dev0 sorts backwards
  803. + (a feature branch will appear "older" than the master branch).
  804. Exceptions:
  805. - 1: no tags. 0.post.devDISTANCE
  806. + 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty]
  807. """
  808. if pieces["closest-tag"]:
  809. rendered = pieces["closest-tag"]
  810. + if pieces["distance"] or pieces["dirty"]:
  811. + if pieces["branch"] != "master":
  812. + rendered += ".dev0"
  813. + rendered += plus_or_dot(pieces)
  814. + rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"])
  815. + if pieces["dirty"]:
  816. + rendered += ".dirty"
  817. + else:
  818. + # exception #1
  819. + rendered = "0"
  820. + if pieces["branch"] != "master":
  821. + rendered += ".dev0"
  822. + rendered += "+untagged.%%d.g%%s" %% (pieces["distance"],
  823. + pieces["short"])
  824. + if pieces["dirty"]:
  825. + rendered += ".dirty"
  826. + return rendered
  827. +
  828. +
  829. +def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]:
  830. + """Split pep440 version string at the post-release segment.
  831. +
  832. + Returns the release segments before the post-release and the
  833. + post-release version number (or -1 if no post-release segment is present).
  834. + """
  835. + vc = str.split(ver, ".post")
  836. + return vc[0], int(vc[1] or 0) if len(vc) == 2 else None
  837. +
  838. +
  839. +def render_pep440_pre(pieces: Dict[str, Any]) -> str:
  840. + """TAG[.postN.devDISTANCE] -- No -dirty.
  841. +
  842. + Exceptions:
  843. + 1: no tags. 0.post0.devDISTANCE
  844. + """
  845. + if pieces["closest-tag"]:
  846. if pieces["distance"]:
  847. - rendered += ".post.dev%%d" %% pieces["distance"]
  848. + # update the post release segment
  849. + tag_version, post_version = pep440_split_post(pieces["closest-tag"])
  850. + rendered = tag_version
  851. + if post_version is not None:
  852. + rendered += ".post%%d.dev%%d" %% (post_version + 1, pieces["distance"])
  853. + else:
  854. + rendered += ".post0.dev%%d" %% (pieces["distance"])
  855. + else:
  856. + # no commits, use the tag as the version
  857. + rendered = pieces["closest-tag"]
  858. else:
  859. # exception #1
  860. - rendered = "0.post.dev%%d" %% pieces["distance"]
  861. + rendered = "0.post0.dev%%d" %% pieces["distance"]
  862. return rendered
  863. -def render_pep440_post(pieces):
  864. +def render_pep440_post(pieces: Dict[str, Any]) -> str:
  865. """TAG[.postDISTANCE[.dev0]+gHEX] .
  866. The ".dev0" means dirty. Note that .dev0 sorts backwards
  867. @@ -800,12 +1028,41 @@ def render_pep440_post(pieces):
  868. return rendered
  869. -def render_pep440_old(pieces):
  870. +def render_pep440_post_branch(pieces: Dict[str, Any]) -> str:
  871. + """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] .
  872. +
  873. + The ".dev0" means not master branch.
  874. +
  875. + Exceptions:
  876. + 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty]
  877. + """
  878. + if pieces["closest-tag"]:
  879. + rendered = pieces["closest-tag"]
  880. + if pieces["distance"] or pieces["dirty"]:
  881. + rendered += ".post%%d" %% pieces["distance"]
  882. + if pieces["branch"] != "master":
  883. + rendered += ".dev0"
  884. + rendered += plus_or_dot(pieces)
  885. + rendered += "g%%s" %% pieces["short"]
  886. + if pieces["dirty"]:
  887. + rendered += ".dirty"
  888. + else:
  889. + # exception #1
  890. + rendered = "0.post%%d" %% pieces["distance"]
  891. + if pieces["branch"] != "master":
  892. + rendered += ".dev0"
  893. + rendered += "+g%%s" %% pieces["short"]
  894. + if pieces["dirty"]:
  895. + rendered += ".dirty"
  896. + return rendered
  897. +
  898. +
  899. +def render_pep440_old(pieces: Dict[str, Any]) -> str:
  900. """TAG[.postDISTANCE[.dev0]] .
  901. The ".dev0" means dirty.
  902. - Eexceptions:
  903. + Exceptions:
  904. 1: no tags. 0.postDISTANCE[.dev0]
  905. """
  906. if pieces["closest-tag"]:
  907. @@ -822,7 +1079,7 @@ def render_pep440_old(pieces):
  908. return rendered
  909. -def render_git_describe(pieces):
  910. +def render_git_describe(pieces: Dict[str, Any]) -> str:
  911. """TAG[-DISTANCE-gHEX][-dirty].
  912. Like 'git describe --tags --dirty --always'.
  913. @@ -842,7 +1099,7 @@ def render_git_describe(pieces):
  914. return rendered
  915. -def render_git_describe_long(pieces):
  916. +def render_git_describe_long(pieces: Dict[str, Any]) -> str:
  917. """TAG-DISTANCE-gHEX[-dirty].
  918. Like 'git describe --tags --dirty --always -long'.
  919. @@ -862,7 +1119,7 @@ def render_git_describe_long(pieces):
  920. return rendered
  921. -def render(pieces, style):
  922. +def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]:
  923. """Render the given version pieces into the requested style."""
  924. if pieces["error"]:
  925. return {"version": "unknown",
  926. @@ -876,10 +1133,14 @@ def render(pieces, style):
  927. if style == "pep440":
  928. rendered = render_pep440(pieces)
  929. + elif style == "pep440-branch":
  930. + rendered = render_pep440_branch(pieces)
  931. elif style == "pep440-pre":
  932. rendered = render_pep440_pre(pieces)
  933. elif style == "pep440-post":
  934. rendered = render_pep440_post(pieces)
  935. + elif style == "pep440-post-branch":
  936. + rendered = render_pep440_post_branch(pieces)
  937. elif style == "pep440-old":
  938. rendered = render_pep440_old(pieces)
  939. elif style == "git-describe":
  940. @@ -894,7 +1155,7 @@ def render(pieces, style):
  941. "date": pieces.get("date")}
  942. -def get_versions():
  943. +def get_versions() -> Dict[str, Any]:
  944. """Get version information or return default if unable to do so."""
  945. # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
  946. # __file__, we can work backwards from there to the root. Some
  947. @@ -915,7 +1176,7 @@ def get_versions():
  948. # versionfile_source is the relative path from the top of the source
  949. # tree (where the .git directory might live) to this file. Invert
  950. # this to find the root from __file__.
  951. - for i in cfg.versionfile_source.split('/'):
  952. + for _ in cfg.versionfile_source.split('/'):
  953. root = os.path.dirname(root)
  954. except NameError:
  955. return {"version": "0+unknown", "full-revisionid": None,
  956. @@ -942,41 +1203,48 @@ def get_versions():
  957. @register_vcs_handler("git", "get_keywords")
  958. -def git_get_keywords(versionfile_abs):
  959. +def git_get_keywords(versionfile_abs: str) -> Dict[str, str]:
  960. """Extract version information from the given file."""
  961. # the code embedded in _version.py can just fetch the value of these
  962. # keywords. When used from setup.py, we don't want to import _version.py,
  963. # so we do it with a regexp instead. This function is not used from
  964. # _version.py.
  965. - keywords = {}
  966. + keywords: Dict[str, str] = {}
  967. try:
  968. - f = open(versionfile_abs, "r")
  969. - for line in f.readlines():
  970. - if line.strip().startswith("git_refnames ="):
  971. - mo = re.search(r'=\s*"(.*)"', line)
  972. - if mo:
  973. - keywords["refnames"] = mo.group(1)
  974. - if line.strip().startswith("git_full ="):
  975. - mo = re.search(r'=\s*"(.*)"', line)
  976. - if mo:
  977. - keywords["full"] = mo.group(1)
  978. - if line.strip().startswith("git_date ="):
  979. - mo = re.search(r'=\s*"(.*)"', line)
  980. - if mo:
  981. - keywords["date"] = mo.group(1)
  982. - f.close()
  983. - except EnvironmentError:
  984. + with open(versionfile_abs, "r") as fobj:
  985. + for line in fobj:
  986. + if line.strip().startswith("git_refnames ="):
  987. + mo = re.search(r'=\s*"(.*)"', line)
  988. + if mo:
  989. + keywords["refnames"] = mo.group(1)
  990. + if line.strip().startswith("git_full ="):
  991. + mo = re.search(r'=\s*"(.*)"', line)
  992. + if mo:
  993. + keywords["full"] = mo.group(1)
  994. + if line.strip().startswith("git_date ="):
  995. + mo = re.search(r'=\s*"(.*)"', line)
  996. + if mo:
  997. + keywords["date"] = mo.group(1)
  998. + except OSError:
  999. pass
  1000. return keywords
  1001. @register_vcs_handler("git", "keywords")
  1002. -def git_versions_from_keywords(keywords, tag_prefix, verbose):
  1003. +def git_versions_from_keywords(
  1004. + keywords: Dict[str, str],
  1005. + tag_prefix: str,
  1006. + verbose: bool,
  1007. +) -> Dict[str, Any]:
  1008. """Get version information from git keywords."""
  1009. - if not keywords:
  1010. - raise NotThisMethod("no keywords at all, weird")
  1011. + if "refnames" not in keywords:
  1012. + raise NotThisMethod("Short version file found")
  1013. date = keywords.get("date")
  1014. if date is not None:
  1015. + # Use only the last line. Previous lines may contain GPG signature
  1016. + # information.
  1017. + date = date.splitlines()[-1]
  1018. +
  1019. # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
  1020. # datestamp. However we prefer "%ci" (which expands to an "ISO-8601
  1021. # -like" string, which we must then edit to make compliant), because
  1022. @@ -989,11 +1257,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
  1023. if verbose:
  1024. print("keywords are unexpanded, not using")
  1025. raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
  1026. - refs = set([r.strip() for r in refnames.strip("()").split(",")])
  1027. + refs = {r.strip() for r in refnames.strip("()").split(",")}
  1028. # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
  1029. # just "foo-1.0". If we see a "tag: " prefix, prefer those.
  1030. TAG = "tag: "
  1031. - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
  1032. + tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)}
  1033. if not tags:
  1034. # Either we're using git < 1.8.3, or there really are no tags. We use
  1035. # a heuristic: assume all version tags have a digit. The old git %d
  1036. @@ -1002,7 +1270,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
  1037. # between branches and tags. By ignoring refnames without digits, we
  1038. # filter out many common branch names like "release" and
  1039. # "stabilization", as well as "HEAD" and "master".
  1040. - tags = set([r for r in refs if re.search(r'\d', r)])
  1041. + tags = {r for r in refs if re.search(r"\d", r)}
  1042. if verbose:
  1043. print("discarding '%s', no digits" % ",".join(refs - tags))
  1044. if verbose:
  1045. @@ -1010,23 +1278,37 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
  1046. for ref in sorted(tags):
  1047. # sorting will prefer e.g. "2.0" over "2.0rc1"
  1048. if ref.startswith(tag_prefix):
  1049. - r = ref[len(tag_prefix):]
  1050. + r = ref[len(tag_prefix) :]
  1051. + # Filter out refs that exactly match prefix or that don't start
  1052. + # with a number once the prefix is stripped (mostly a concern
  1053. + # when prefix is '')
  1054. + if not re.match(r"\d", r):
  1055. + continue
  1056. if verbose:
  1057. print("picking %s" % r)
  1058. - return {"version": r,
  1059. - "full-revisionid": keywords["full"].strip(),
  1060. - "dirty": False, "error": None,
  1061. - "date": date}
  1062. + return {
  1063. + "version": r,
  1064. + "full-revisionid": keywords["full"].strip(),
  1065. + "dirty": False,
  1066. + "error": None,
  1067. + "date": date,
  1068. + }
  1069. # no suitable tags, so version is "0+unknown", but full hex is still there
  1070. if verbose:
  1071. print("no suitable tags, using unknown + full revision id")
  1072. - return {"version": "0+unknown",
  1073. - "full-revisionid": keywords["full"].strip(),
  1074. - "dirty": False, "error": "no suitable tags", "date": None}
  1075. + return {
  1076. + "version": "0+unknown",
  1077. + "full-revisionid": keywords["full"].strip(),
  1078. + "dirty": False,
  1079. + "error": "no suitable tags",
  1080. + "date": None,
  1081. + }
  1082. @register_vcs_handler("git", "pieces_from_vcs")
  1083. -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
  1084. +def git_pieces_from_vcs(
  1085. + tag_prefix: str, root: str, verbose: bool, runner: Callable = run_command
  1086. +) -> Dict[str, Any]:
  1087. """Get version from 'git describe' in the root of the source tree.
  1088. This only gets called if the git-archive 'subst' keywords were *not*
  1089. @@ -1037,8 +1319,14 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
  1090. if sys.platform == "win32":
  1091. GITS = ["git.cmd", "git.exe"]
  1092. - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root,
  1093. - hide_stderr=True)
  1094. + # GIT_DIR can interfere with correct operation of Versioneer.
  1095. + # It may be intended to be passed to the Versioneer-versioned project,
  1096. + # but that should not change where we get our version from.
  1097. + env = os.environ.copy()
  1098. + env.pop("GIT_DIR", None)
  1099. + runner = functools.partial(runner, env=env)
  1100. +
  1101. + _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=not verbose)
  1102. if rc != 0:
  1103. if verbose:
  1104. print("Directory %s not under git control" % root)
  1105. @@ -1046,24 +1334,65 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
  1106. # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
  1107. # if there isn't one, this yields HEX[-dirty] (no NUM)
  1108. - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty",
  1109. - "--always", "--long",
  1110. - "--match", "%s*" % tag_prefix],
  1111. - cwd=root)
  1112. + describe_out, rc = runner(
  1113. + GITS,
  1114. + [
  1115. + "describe",
  1116. + "--tags",
  1117. + "--dirty",
  1118. + "--always",
  1119. + "--long",
  1120. + "--match",
  1121. + f"{tag_prefix}[[:digit:]]*",
  1122. + ],
  1123. + cwd=root,
  1124. + )
  1125. # --long was added in git-1.5.5
  1126. if describe_out is None:
  1127. raise NotThisMethod("'git describe' failed")
  1128. describe_out = describe_out.strip()
  1129. - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
  1130. + full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root)
  1131. if full_out is None:
  1132. raise NotThisMethod("'git rev-parse' failed")
  1133. full_out = full_out.strip()
  1134. - pieces = {}
  1135. + pieces: Dict[str, Any] = {}
  1136. pieces["long"] = full_out
  1137. pieces["short"] = full_out[:7] # maybe improved later
  1138. pieces["error"] = None
  1139. + branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
  1140. + # --abbrev-ref was added in git-1.6.3
  1141. + if rc != 0 or branch_name is None:
  1142. + raise NotThisMethod("'git rev-parse --abbrev-ref' returned error")
  1143. + branch_name = branch_name.strip()
  1144. +
  1145. + if branch_name == "HEAD":
  1146. + # If we aren't exactly on a branch, pick a branch which represents
  1147. + # the current commit. If all else fails, we are on a branchless
  1148. + # commit.
  1149. + branches, rc = runner(GITS, ["branch", "--contains"], cwd=root)
  1150. + # --contains was added in git-1.5.4
  1151. + if rc != 0 or branches is None:
  1152. + raise NotThisMethod("'git branch --contains' returned error")
  1153. + branches = branches.split("\n")
  1154. +
  1155. + # Remove the first line if we're running detached
  1156. + if "(" in branches[0]:
  1157. + branches.pop(0)
  1158. +
  1159. + # Strip off the leading "* " from the list of branches.
  1160. + branches = [branch[2:] for branch in branches]
  1161. + if "master" in branches:
  1162. + branch_name = "master"
  1163. + elif not branches:
  1164. + branch_name = None
  1165. + else:
  1166. + # Pick the first branch that is returned. Good or bad.
  1167. + branch_name = branches[0]
  1168. +
  1169. + pieces["branch"] = branch_name
  1170. +
  1171. # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
  1172. # TAG might have hyphens.
  1173. git_describe = describe_out
  1174. @@ -1072,17 +1401,16 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
  1175. dirty = git_describe.endswith("-dirty")
  1176. pieces["dirty"] = dirty
  1177. if dirty:
  1178. - git_describe = git_describe[:git_describe.rindex("-dirty")]
  1179. + git_describe = git_describe[: git_describe.rindex("-dirty")]
  1180. # now we have TAG-NUM-gHEX or HEX
  1181. if "-" in git_describe:
  1182. # TAG-NUM-gHEX
  1183. - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
  1184. + mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe)
  1185. if not mo:
  1186. - # unparseable. Maybe git-describe is misbehaving?
  1187. - pieces["error"] = ("unable to parse git-describe output: '%s'"
  1188. - % describe_out)
  1189. + # unparsable. Maybe git-describe is misbehaving?
  1190. + pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out
  1191. return pieces
  1192. # tag
  1193. @@ -1091,10 +1419,12 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
  1194. if verbose:
  1195. fmt = "tag '%s' doesn't start with prefix '%s'"
  1196. print(fmt % (full_tag, tag_prefix))
  1197. - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
  1198. - % (full_tag, tag_prefix))
  1199. + pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
  1200. + full_tag,
  1201. + tag_prefix,
  1202. + )
  1203. return pieces
  1204. - pieces["closest-tag"] = full_tag[len(tag_prefix):]
  1205. + pieces["closest-tag"] = full_tag[len(tag_prefix) :]
  1206. # distance: number of commits since tag
  1207. pieces["distance"] = int(mo.group(2))
  1208. @@ -1105,19 +1435,20 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
  1209. else:
  1210. # HEX: no tags
  1211. pieces["closest-tag"] = None
  1212. - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"],
  1213. - cwd=root)
  1214. - pieces["distance"] = int(count_out) # total number of commits
  1215. + out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root)
  1216. + pieces["distance"] = len(out.split()) # total number of commits
  1217. # commit date: see ISO-8601 comment in git_versions_from_keywords()
  1218. - date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"],
  1219. - cwd=root)[0].strip()
  1220. + date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip()
  1221. + # Use only the last line. Previous lines may contain GPG signature
  1222. + # information.
  1223. + date = date.splitlines()[-1]
  1224. pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
  1225. return pieces
  1226. -def do_vcs_install(manifest_in, versionfile_source, ipy):
  1227. +def do_vcs_install(versionfile_source: str, ipy: Optional[str]) -> None:
  1228. """Git-specific installation logic for Versioneer.
  1229. For Git, this means creating/changing .gitattributes to mark _version.py
  1230. @@ -1126,36 +1457,40 @@ def do_vcs_install(manifest_in, versionfile_source, ipy):
  1231. GITS = ["git"]
  1232. if sys.platform == "win32":
  1233. GITS = ["git.cmd", "git.exe"]
  1234. - files = [manifest_in, versionfile_source]
  1235. + files = [versionfile_source]
  1236. if ipy:
  1237. files.append(ipy)
  1238. - try:
  1239. - me = __file__
  1240. - if me.endswith(".pyc") or me.endswith(".pyo"):
  1241. - me = os.path.splitext(me)[0] + ".py"
  1242. - versioneer_file = os.path.relpath(me)
  1243. - except NameError:
  1244. - versioneer_file = "versioneer.py"
  1245. - files.append(versioneer_file)
  1246. + if "VERSIONEER_PEP518" not in globals():
  1247. + try:
  1248. + my_path = __file__
  1249. + if my_path.endswith((".pyc", ".pyo")):
  1250. + my_path = os.path.splitext(my_path)[0] + ".py"
  1251. + versioneer_file = os.path.relpath(my_path)
  1252. + except NameError:
  1253. + versioneer_file = "versioneer.py"
  1254. + files.append(versioneer_file)
  1255. present = False
  1256. try:
  1257. - f = open(".gitattributes", "r")
  1258. - for line in f.readlines():
  1259. - if line.strip().startswith(versionfile_source):
  1260. - if "export-subst" in line.strip().split()[1:]:
  1261. - present = True
  1262. - f.close()
  1263. - except EnvironmentError:
  1264. + with open(".gitattributes", "r") as fobj:
  1265. + for line in fobj:
  1266. + if line.strip().startswith(versionfile_source):
  1267. + if "export-subst" in line.strip().split()[1:]:
  1268. + present = True
  1269. + break
  1270. + except OSError:
  1271. pass
  1272. if not present:
  1273. - f = open(".gitattributes", "a+")
  1274. - f.write("%s export-subst\n" % versionfile_source)
  1275. - f.close()
  1276. + with open(".gitattributes", "a+") as fobj:
  1277. + fobj.write(f"{versionfile_source} export-subst\n")
  1278. files.append(".gitattributes")
  1279. run_command(GITS, ["add", "--"] + files)
  1280. -def versions_from_parentdir(parentdir_prefix, root, verbose):
  1281. +def versions_from_parentdir(
  1282. + parentdir_prefix: str,
  1283. + root: str,
  1284. + verbose: bool,
  1285. +) -> Dict[str, Any]:
  1286. """Try to determine the version from the parent directory name.
  1287. Source tarballs conventionally unpack into a directory that includes both
  1288. @@ -1164,24 +1499,29 @@ def versions_from_parentdir(parentdir_prefix, root, verbose):
  1289. """
  1290. rootdirs = []
  1291. - for i in range(3):
  1292. + for _ in range(3):
  1293. dirname = os.path.basename(root)
  1294. if dirname.startswith(parentdir_prefix):
  1295. - return {"version": dirname[len(parentdir_prefix):],
  1296. - "full-revisionid": None,
  1297. - "dirty": False, "error": None, "date": None}
  1298. - else:
  1299. - rootdirs.append(root)
  1300. - root = os.path.dirname(root) # up a level
  1301. + return {
  1302. + "version": dirname[len(parentdir_prefix) :],
  1303. + "full-revisionid": None,
  1304. + "dirty": False,
  1305. + "error": None,
  1306. + "date": None,
  1307. + }
  1308. + rootdirs.append(root)
  1309. + root = os.path.dirname(root) # up a level
  1310. if verbose:
  1311. - print("Tried directories %s but none started with prefix %s" %
  1312. - (str(rootdirs), parentdir_prefix))
  1313. + print(
  1314. + "Tried directories %s but none started with prefix %s"
  1315. + % (str(rootdirs), parentdir_prefix)
  1316. + )
  1317. raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
  1318. SHORT_VERSION_PY = """
  1319. -# This file was generated by 'versioneer.py' (0.18) from
  1320. +# This file was generated by 'versioneer.py' (0.29) from
  1321. # revision-control system data, or from the parent directory name of an
  1322. # unpacked source archive. Distribution tarballs contain a pre-generated copy
  1323. # of this file.
  1324. @@ -1198,42 +1538,42 @@ def get_versions():
  1325. """
  1326. -def versions_from_file(filename):
  1327. +def versions_from_file(filename: str) -> Dict[str, Any]:
  1328. """Try to determine the version from _version.py if present."""
  1329. try:
  1330. with open(filename) as f:
  1331. contents = f.read()
  1332. - except EnvironmentError:
  1333. + except OSError:
  1334. raise NotThisMethod("unable to read _version.py")
  1335. - mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON",
  1336. - contents, re.M | re.S)
  1337. + mo = re.search(
  1338. + r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S
  1339. + )
  1340. if not mo:
  1341. - mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON",
  1342. - contents, re.M | re.S)
  1343. + mo = re.search(
  1344. + r"version_json = '''\r\n(.*)''' # END VERSION_JSON", contents, re.M | re.S
  1345. + )
  1346. if not mo:
  1347. raise NotThisMethod("no version_json in _version.py")
  1348. return json.loads(mo.group(1))
  1349. -def write_to_version_file(filename, versions):
  1350. +def write_to_version_file(filename: str, versions: Dict[str, Any]) -> None:
  1351. """Write the given version number to the given _version.py file."""
  1352. - os.unlink(filename)
  1353. - contents = json.dumps(versions, sort_keys=True,
  1354. - indent=1, separators=(",", ": "))
  1355. + contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": "))
  1356. with open(filename, "w") as f:
  1357. f.write(SHORT_VERSION_PY % contents)
  1358. print("set %s to '%s'" % (filename, versions["version"]))
  1359. -def plus_or_dot(pieces):
  1360. +def plus_or_dot(pieces: Dict[str, Any]) -> str:
  1361. """Return a + if we don't already have one, else return a ."""
  1362. if "+" in pieces.get("closest-tag", ""):
  1363. return "."
  1364. return "+"
  1365. -def render_pep440(pieces):
  1366. +def render_pep440(pieces: Dict[str, Any]) -> str:
  1367. """Build up version string, with post-release "local version identifier".
  1368. Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
  1369. @@ -1251,30 +1591,76 @@ def render_pep440(pieces):
  1370. rendered += ".dirty"
  1371. else:
  1372. # exception #1
  1373. - rendered = "0+untagged.%d.g%s" % (pieces["distance"],
  1374. - pieces["short"])
  1375. + rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
  1376. if pieces["dirty"]:
  1377. rendered += ".dirty"
  1378. return rendered
  1379. -def render_pep440_pre(pieces):
  1380. - """TAG[.post.devDISTANCE] -- No -dirty.
  1381. +def render_pep440_branch(pieces: Dict[str, Any]) -> str:
  1382. + """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] .
  1383. +
  1384. + The ".dev0" means not master branch. Note that .dev0 sorts backwards
  1385. + (a feature branch will appear "older" than the master branch).
  1386. Exceptions:
  1387. - 1: no tags. 0.post.devDISTANCE
  1388. + 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty]
  1389. """
  1390. if pieces["closest-tag"]:
  1391. rendered = pieces["closest-tag"]
  1392. + if pieces["distance"] or pieces["dirty"]:
  1393. + if pieces["branch"] != "master":
  1394. + rendered += ".dev0"
  1395. + rendered += plus_or_dot(pieces)
  1396. + rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
  1397. + if pieces["dirty"]:
  1398. + rendered += ".dirty"
  1399. + else:
  1400. + # exception #1
  1401. + rendered = "0"
  1402. + if pieces["branch"] != "master":
  1403. + rendered += ".dev0"
  1404. + rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
  1405. + if pieces["dirty"]:
  1406. + rendered += ".dirty"
  1407. + return rendered
  1408. +
  1409. +
  1410. +def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]:
  1411. + """Split pep440 version string at the post-release segment.
  1412. +
  1413. + Returns the release segments before the post-release and the
  1414. + post-release version number (or -1 if no post-release segment is present).
  1415. + """
  1416. + vc = str.split(ver, ".post")
  1417. + return vc[0], int(vc[1] or 0) if len(vc) == 2 else None
  1418. +
  1419. +
  1420. +def render_pep440_pre(pieces: Dict[str, Any]) -> str:
  1421. + """TAG[.postN.devDISTANCE] -- No -dirty.
  1422. +
  1423. + Exceptions:
  1424. + 1: no tags. 0.post0.devDISTANCE
  1425. + """
  1426. + if pieces["closest-tag"]:
  1427. if pieces["distance"]:
  1428. - rendered += ".post.dev%d" % pieces["distance"]
  1429. + # update the post release segment
  1430. + tag_version, post_version = pep440_split_post(pieces["closest-tag"])
  1431. + rendered = tag_version
  1432. + if post_version is not None:
  1433. + rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"])
  1434. + else:
  1435. + rendered += ".post0.dev%d" % (pieces["distance"])
  1436. + else:
  1437. + # no commits, use the tag as the version
  1438. + rendered = pieces["closest-tag"]
  1439. else:
  1440. # exception #1
  1441. - rendered = "0.post.dev%d" % pieces["distance"]
  1442. + rendered = "0.post0.dev%d" % pieces["distance"]
  1443. return rendered
  1444. -def render_pep440_post(pieces):
  1445. +def render_pep440_post(pieces: Dict[str, Any]) -> str:
  1446. """TAG[.postDISTANCE[.dev0]+gHEX] .
  1447. The ".dev0" means dirty. Note that .dev0 sorts backwards
  1448. @@ -1301,12 +1687,41 @@ def render_pep440_post(pieces):
  1449. return rendered
  1450. -def render_pep440_old(pieces):
  1451. +def render_pep440_post_branch(pieces: Dict[str, Any]) -> str:
  1452. + """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] .
  1453. +
  1454. + The ".dev0" means not master branch.
  1455. +
  1456. + Exceptions:
  1457. + 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty]
  1458. + """
  1459. + if pieces["closest-tag"]:
  1460. + rendered = pieces["closest-tag"]
  1461. + if pieces["distance"] or pieces["dirty"]:
  1462. + rendered += ".post%d" % pieces["distance"]
  1463. + if pieces["branch"] != "master":
  1464. + rendered += ".dev0"
  1465. + rendered += plus_or_dot(pieces)
  1466. + rendered += "g%s" % pieces["short"]
  1467. + if pieces["dirty"]:
  1468. + rendered += ".dirty"
  1469. + else:
  1470. + # exception #1
  1471. + rendered = "0.post%d" % pieces["distance"]
  1472. + if pieces["branch"] != "master":
  1473. + rendered += ".dev0"
  1474. + rendered += "+g%s" % pieces["short"]
  1475. + if pieces["dirty"]:
  1476. + rendered += ".dirty"
  1477. + return rendered
  1478. +
  1479. +
  1480. +def render_pep440_old(pieces: Dict[str, Any]) -> str:
  1481. """TAG[.postDISTANCE[.dev0]] .
  1482. The ".dev0" means dirty.
  1483. - Eexceptions:
  1484. + Exceptions:
  1485. 1: no tags. 0.postDISTANCE[.dev0]
  1486. """
  1487. if pieces["closest-tag"]:
  1488. @@ -1323,7 +1738,7 @@ def render_pep440_old(pieces):
  1489. return rendered
  1490. -def render_git_describe(pieces):
  1491. +def render_git_describe(pieces: Dict[str, Any]) -> str:
  1492. """TAG[-DISTANCE-gHEX][-dirty].
  1493. Like 'git describe --tags --dirty --always'.
  1494. @@ -1343,7 +1758,7 @@ def render_git_describe(pieces):
  1495. return rendered
  1496. -def render_git_describe_long(pieces):
  1497. +def render_git_describe_long(pieces: Dict[str, Any]) -> str:
  1498. """TAG-DISTANCE-gHEX[-dirty].
  1499. Like 'git describe --tags --dirty --always -long'.
  1500. @@ -1363,24 +1778,30 @@ def render_git_describe_long(pieces):
  1501. return rendered
  1502. -def render(pieces, style):
  1503. +def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]:
  1504. """Render the given version pieces into the requested style."""
  1505. if pieces["error"]:
  1506. - return {"version": "unknown",
  1507. - "full-revisionid": pieces.get("long"),
  1508. - "dirty": None,
  1509. - "error": pieces["error"],
  1510. - "date": None}
  1511. + return {
  1512. + "version": "unknown",
  1513. + "full-revisionid": pieces.get("long"),
  1514. + "dirty": None,
  1515. + "error": pieces["error"],
  1516. + "date": None,
  1517. + }
  1518. if not style or style == "default":
  1519. style = "pep440" # the default
  1520. if style == "pep440":
  1521. rendered = render_pep440(pieces)
  1522. + elif style == "pep440-branch":
  1523. + rendered = render_pep440_branch(pieces)
  1524. elif style == "pep440-pre":
  1525. rendered = render_pep440_pre(pieces)
  1526. elif style == "pep440-post":
  1527. rendered = render_pep440_post(pieces)
  1528. + elif style == "pep440-post-branch":
  1529. + rendered = render_pep440_post_branch(pieces)
  1530. elif style == "pep440-old":
  1531. rendered = render_pep440_old(pieces)
  1532. elif style == "git-describe":
  1533. @@ -1390,16 +1811,20 @@ def render(pieces, style):
  1534. else:
  1535. raise ValueError("unknown style '%s'" % style)
  1536. - return {"version": rendered, "full-revisionid": pieces["long"],
  1537. - "dirty": pieces["dirty"], "error": None,
  1538. - "date": pieces.get("date")}
  1539. + return {
  1540. + "version": rendered,
  1541. + "full-revisionid": pieces["long"],
  1542. + "dirty": pieces["dirty"],
  1543. + "error": None,
  1544. + "date": pieces.get("date"),
  1545. + }
  1546. class VersioneerBadRootError(Exception):
  1547. """The project root directory is unknown or missing key files."""
  1548. -def get_versions(verbose=False):
  1549. +def get_versions(verbose: bool = False) -> Dict[str, Any]:
  1550. """Get the project version from whatever source is available.
  1551. Returns dict with two keys: 'version' and 'full'.
  1552. @@ -1414,9 +1839,10 @@ def get_versions(verbose=False):
  1553. assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg"
  1554. handlers = HANDLERS.get(cfg.VCS)
  1555. assert handlers, "unrecognized VCS '%s'" % cfg.VCS
  1556. - verbose = verbose or cfg.verbose
  1557. - assert cfg.versionfile_source is not None, \
  1558. - "please set versioneer.versionfile_source"
  1559. + verbose = verbose or bool(cfg.verbose) # `bool()` used to avoid `None`
  1560. + assert (
  1561. + cfg.versionfile_source is not None
  1562. + ), "please set versioneer.versionfile_source"
  1563. assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix"
  1564. versionfile_abs = os.path.join(root, cfg.versionfile_source)
  1565. @@ -1470,18 +1896,26 @@ def get_versions(verbose=False):
  1566. if verbose:
  1567. print("unable to compute version")
  1568. - return {"version": "0+unknown", "full-revisionid": None,
  1569. - "dirty": None, "error": "unable to compute version",
  1570. - "date": None}
  1571. + return {
  1572. + "version": "0+unknown",
  1573. + "full-revisionid": None,
  1574. + "dirty": None,
  1575. + "error": "unable to compute version",
  1576. + "date": None,
  1577. + }
  1578. -def get_version():
  1579. +def get_version() -> str:
  1580. """Get the short version string for this project."""
  1581. return get_versions()["version"]
  1582. -def get_cmdclass():
  1583. - """Get the custom setuptools/distutils subclasses used by Versioneer."""
  1584. +def get_cmdclass(cmdclass: Optional[Dict[str, Any]] = None):
  1585. + """Get the custom setuptools subclasses used by Versioneer.
  1586. +
  1587. + If the package uses a different cmdclass (e.g. one from numpy), it
  1588. + should be provide as an argument.
  1589. + """
  1590. if "versioneer" in sys.modules:
  1591. del sys.modules["versioneer"]
  1592. # this fixes the "python setup.py develop" case (also 'install' and
  1593. @@ -1495,25 +1929,25 @@ def get_cmdclass():
  1594. # parent is protected against the child's "import versioneer". By
  1595. # removing ourselves from sys.modules here, before the child build
  1596. # happens, we protect the child from the parent's versioneer too.
  1597. - # Also see https://github.com/warner/python-versioneer/issues/52
  1598. + # Also see https://github.com/python-versioneer/python-versioneer/issues/52
  1599. - cmds = {}
  1600. + cmds = {} if cmdclass is None else cmdclass.copy()
  1601. - # we add "version" to both distutils and setuptools
  1602. - from distutils.core import Command
  1603. + # we add "version" to setuptools
  1604. + from setuptools import Command
  1605. class cmd_version(Command):
  1606. description = "report generated version string"
  1607. - user_options = []
  1608. - boolean_options = []
  1609. + user_options: List[Tuple[str, str, str]] = []
  1610. + boolean_options: List[str] = []
  1611. - def initialize_options(self):
  1612. + def initialize_options(self) -> None:
  1613. pass
  1614. - def finalize_options(self):
  1615. + def finalize_options(self) -> None:
  1616. pass
  1617. - def run(self):
  1618. + def run(self) -> None:
  1619. vers = get_versions(verbose=True)
  1620. print("Version: %s" % vers["version"])
  1621. print(" full-revisionid: %s" % vers.get("full-revisionid"))
  1622. @@ -1521,9 +1955,10 @@ def get_cmdclass():
  1623. print(" date: %s" % vers.get("date"))
  1624. if vers["error"]:
  1625. print(" error: %s" % vers["error"])
  1626. +
  1627. cmds["version"] = cmd_version
  1628. - # we override "build_py" in both distutils and setuptools
  1629. + # we override "build_py" in setuptools
  1630. #
  1631. # most invocation pathways end up running build_py:
  1632. # distutils/build -> build_py
  1633. @@ -1538,29 +1973,71 @@ def get_cmdclass():
  1634. # then does setup.py bdist_wheel, or sometimes setup.py install
  1635. # setup.py egg_info -> ?
  1636. + # pip install -e . and setuptool/editable_wheel will invoke build_py
  1637. + # but the build_py command is not expected to copy any files.
  1638. +
  1639. # we override different "build_py" commands for both environments
  1640. - if "setuptools" in sys.modules:
  1641. - from setuptools.command.build_py import build_py as _build_py
  1642. + if "build_py" in cmds:
  1643. + _build_py: Any = cmds["build_py"]
  1644. else:
  1645. - from distutils.command.build_py import build_py as _build_py
  1646. + from setuptools.command.build_py import build_py as _build_py
  1647. class cmd_build_py(_build_py):
  1648. - def run(self):
  1649. + def run(self) -> None:
  1650. root = get_root()
  1651. cfg = get_config_from_root(root)
  1652. versions = get_versions()
  1653. _build_py.run(self)
  1654. + if getattr(self, "editable_mode", False):
  1655. + # During editable installs `.py` and data files are
  1656. + # not copied to build_lib
  1657. + return
  1658. # now locate _version.py in the new build/ directory and replace
  1659. # it with an updated value
  1660. if cfg.versionfile_build:
  1661. - target_versionfile = os.path.join(self.build_lib,
  1662. - cfg.versionfile_build)
  1663. + target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build)
  1664. print("UPDATING %s" % target_versionfile)
  1665. write_to_version_file(target_versionfile, versions)
  1666. +
  1667. cmds["build_py"] = cmd_build_py
  1668. + if "build_ext" in cmds:
  1669. + _build_ext: Any = cmds["build_ext"]
  1670. + else:
  1671. + from setuptools.command.build_ext import build_ext as _build_ext
  1672. +
  1673. + class cmd_build_ext(_build_ext):
  1674. + def run(self) -> None:
  1675. + root = get_root()
  1676. + cfg = get_config_from_root(root)
  1677. + versions = get_versions()
  1678. + _build_ext.run(self)
  1679. + if self.inplace:
  1680. + # build_ext --inplace will only build extensions in
  1681. + # build/lib<..> dir with no _version.py to write to.
  1682. + # As in place builds will already have a _version.py
  1683. + # in the module dir, we do not need to write one.
  1684. + return
  1685. + # now locate _version.py in the new build/ directory and replace
  1686. + # it with an updated value
  1687. + if not cfg.versionfile_build:
  1688. + return
  1689. + target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build)
  1690. + if not os.path.exists(target_versionfile):
  1691. + print(
  1692. + f"Warning: {target_versionfile} does not exist, skipping "
  1693. + "version update. This can happen if you are running build_ext "
  1694. + "without first running build_py."
  1695. + )
  1696. + return
  1697. + print("UPDATING %s" % target_versionfile)
  1698. + write_to_version_file(target_versionfile, versions)
  1699. +
  1700. + cmds["build_ext"] = cmd_build_ext
  1701. +
  1702. if "cx_Freeze" in sys.modules: # cx_freeze enabled?
  1703. - from cx_Freeze.dist import build_exe as _build_exe
  1704. + from cx_Freeze.dist import build_exe as _build_exe # type: ignore
  1705. +
  1706. # nczeczulin reports that py2exe won't like the pep440-style string
  1707. # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g.
  1708. # setup(console=[{
  1709. @@ -1569,7 +2046,7 @@ def get_cmdclass():
  1710. # ...
  1711. class cmd_build_exe(_build_exe):
  1712. - def run(self):
  1713. + def run(self) -> None:
  1714. root = get_root()
  1715. cfg = get_config_from_root(root)
  1716. versions = get_versions()
  1717. @@ -1581,24 +2058,28 @@ def get_cmdclass():
  1718. os.unlink(target_versionfile)
  1719. with open(cfg.versionfile_source, "w") as f:
  1720. LONG = LONG_VERSION_PY[cfg.VCS]
  1721. - f.write(LONG %
  1722. - {"DOLLAR": "$",
  1723. - "STYLE": cfg.style,
  1724. - "TAG_PREFIX": cfg.tag_prefix,
  1725. - "PARENTDIR_PREFIX": cfg.parentdir_prefix,
  1726. - "VERSIONFILE_SOURCE": cfg.versionfile_source,
  1727. - })
  1728. + f.write(
  1729. + LONG
  1730. + % {
  1731. + "DOLLAR": "$",
  1732. + "STYLE": cfg.style,
  1733. + "TAG_PREFIX": cfg.tag_prefix,
  1734. + "PARENTDIR_PREFIX": cfg.parentdir_prefix,
  1735. + "VERSIONFILE_SOURCE": cfg.versionfile_source,
  1736. + }
  1737. + )
  1738. +
  1739. cmds["build_exe"] = cmd_build_exe
  1740. del cmds["build_py"]
  1741. - if 'py2exe' in sys.modules: # py2exe enabled?
  1742. + if "py2exe" in sys.modules: # py2exe enabled?
  1743. try:
  1744. - from py2exe.distutils_buildexe import py2exe as _py2exe # py3
  1745. + from py2exe.setuptools_buildexe import py2exe as _py2exe # type: ignore
  1746. except ImportError:
  1747. - from py2exe.build_exe import py2exe as _py2exe # py2
  1748. + from py2exe.distutils_buildexe import py2exe as _py2exe # type: ignore
  1749. class cmd_py2exe(_py2exe):
  1750. - def run(self):
  1751. + def run(self) -> None:
  1752. root = get_root()
  1753. cfg = get_config_from_root(root)
  1754. versions = get_versions()
  1755. @@ -1610,23 +2091,67 @@ def get_cmdclass():
  1756. os.unlink(target_versionfile)
  1757. with open(cfg.versionfile_source, "w") as f:
  1758. LONG = LONG_VERSION_PY[cfg.VCS]
  1759. - f.write(LONG %
  1760. - {"DOLLAR": "$",
  1761. - "STYLE": cfg.style,
  1762. - "TAG_PREFIX": cfg.tag_prefix,
  1763. - "PARENTDIR_PREFIX": cfg.parentdir_prefix,
  1764. - "VERSIONFILE_SOURCE": cfg.versionfile_source,
  1765. - })
  1766. + f.write(
  1767. + LONG
  1768. + % {
  1769. + "DOLLAR": "$",
  1770. + "STYLE": cfg.style,
  1771. + "TAG_PREFIX": cfg.tag_prefix,
  1772. + "PARENTDIR_PREFIX": cfg.parentdir_prefix,
  1773. + "VERSIONFILE_SOURCE": cfg.versionfile_source,
  1774. + }
  1775. + )
  1776. +
  1777. cmds["py2exe"] = cmd_py2exe
  1778. + # sdist farms its file list building out to egg_info
  1779. + if "egg_info" in cmds:
  1780. + _egg_info: Any = cmds["egg_info"]
  1781. + else:
  1782. + from setuptools.command.egg_info import egg_info as _egg_info
  1783. +
  1784. + class cmd_egg_info(_egg_info):
  1785. + def find_sources(self) -> None:
  1786. + # egg_info.find_sources builds the manifest list and writes it
  1787. + # in one shot
  1788. + super().find_sources()
  1789. +
  1790. + # Modify the filelist and normalize it
  1791. + root = get_root()
  1792. + cfg = get_config_from_root(root)
  1793. + self.filelist.append("versioneer.py")
  1794. + if cfg.versionfile_source:
  1795. + # There are rare cases where versionfile_source might not be
  1796. + # included by default, so we must be explicit
  1797. + self.filelist.append(cfg.versionfile_source)
  1798. + self.filelist.sort()
  1799. + self.filelist.remove_duplicates()
  1800. +
  1801. + # The write method is hidden in the manifest_maker instance that
  1802. + # generated the filelist and was thrown away
  1803. + # We will instead replicate their final normalization (to unicode,
  1804. + # and POSIX-style paths)
  1805. + from setuptools import unicode_utils
  1806. +
  1807. + normalized = [
  1808. + unicode_utils.filesys_decode(f).replace(os.sep, "/")
  1809. + for f in self.filelist.files
  1810. + ]
  1811. +
  1812. + manifest_filename = os.path.join(self.egg_info, "SOURCES.txt")
  1813. + with open(manifest_filename, "w") as fobj:
  1814. + fobj.write("\n".join(normalized))
  1815. +
  1816. + cmds["egg_info"] = cmd_egg_info
  1817. +
  1818. # we override different "sdist" commands for both environments
  1819. - if "setuptools" in sys.modules:
  1820. - from setuptools.command.sdist import sdist as _sdist
  1821. + if "sdist" in cmds:
  1822. + _sdist: Any = cmds["sdist"]
  1823. else:
  1824. - from distutils.command.sdist import sdist as _sdist
  1825. + from setuptools.command.sdist import sdist as _sdist
  1826. class cmd_sdist(_sdist):
  1827. - def run(self):
  1828. + def run(self) -> None:
  1829. versions = get_versions()
  1830. self._versioneer_generated_versions = versions
  1831. # unless we update this, the command will keep using the old
  1832. @@ -1634,7 +2159,7 @@ def get_cmdclass():
  1833. self.distribution.metadata.version = versions["version"]
  1834. return _sdist.run(self)
  1835. - def make_release_tree(self, base_dir, files):
  1836. + def make_release_tree(self, base_dir: str, files: List[str]) -> None:
  1837. root = get_root()
  1838. cfg = get_config_from_root(root)
  1839. _sdist.make_release_tree(self, base_dir, files)
  1840. @@ -1643,8 +2168,10 @@ def get_cmdclass():
  1841. # updated value
  1842. target_versionfile = os.path.join(base_dir, cfg.versionfile_source)
  1843. print("UPDATING %s" % target_versionfile)
  1844. - write_to_version_file(target_versionfile,
  1845. - self._versioneer_generated_versions)
  1846. + write_to_version_file(
  1847. + target_versionfile, self._versioneer_generated_versions
  1848. + )
  1849. +
  1850. cmds["sdist"] = cmd_sdist
  1851. return cmds
  1852. @@ -1687,23 +2214,26 @@ SAMPLE_CONFIG = """
  1853. """
  1854. -INIT_PY_SNIPPET = """
  1855. +OLD_SNIPPET = """
  1856. from ._version import get_versions
  1857. __version__ = get_versions()['version']
  1858. del get_versions
  1859. """
  1860. +INIT_PY_SNIPPET = """
  1861. +from . import {0}
  1862. +__version__ = {0}.get_versions()['version']
  1863. +"""
  1864. +
  1865. -def do_setup():
  1866. - """Main VCS-independent setup function for installing Versioneer."""
  1867. +def do_setup() -> int:
  1868. + """Do main VCS-independent setup function for installing Versioneer."""
  1869. root = get_root()
  1870. try:
  1871. cfg = get_config_from_root(root)
  1872. - except (EnvironmentError, configparser.NoSectionError,
  1873. - configparser.NoOptionError) as e:
  1874. - if isinstance(e, (EnvironmentError, configparser.NoSectionError)):
  1875. - print("Adding sample versioneer config to setup.cfg",
  1876. - file=sys.stderr)
  1877. + except (OSError, configparser.NoSectionError, configparser.NoOptionError) as e:
  1878. + if isinstance(e, (OSError, configparser.NoSectionError)):
  1879. + print("Adding sample versioneer config to setup.cfg", file=sys.stderr)
  1880. with open(os.path.join(root, "setup.cfg"), "a") as f:
  1881. f.write(SAMPLE_CONFIG)
  1882. print(CONFIG_ERROR, file=sys.stderr)
  1883. @@ -1712,71 +2242,49 @@ def do_setup():
  1884. print(" creating %s" % cfg.versionfile_source)
  1885. with open(cfg.versionfile_source, "w") as f:
  1886. LONG = LONG_VERSION_PY[cfg.VCS]
  1887. - f.write(LONG % {"DOLLAR": "$",
  1888. - "STYLE": cfg.style,
  1889. - "TAG_PREFIX": cfg.tag_prefix,
  1890. - "PARENTDIR_PREFIX": cfg.parentdir_prefix,
  1891. - "VERSIONFILE_SOURCE": cfg.versionfile_source,
  1892. - })
  1893. -
  1894. - ipy = os.path.join(os.path.dirname(cfg.versionfile_source),
  1895. - "__init__.py")
  1896. + f.write(
  1897. + LONG
  1898. + % {
  1899. + "DOLLAR": "$",
  1900. + "STYLE": cfg.style,
  1901. + "TAG_PREFIX": cfg.tag_prefix,
  1902. + "PARENTDIR_PREFIX": cfg.parentdir_prefix,
  1903. + "VERSIONFILE_SOURCE": cfg.versionfile_source,
  1904. + }
  1905. + )
  1906. +
  1907. + ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py")
  1908. + maybe_ipy: Optional[str] = ipy
  1909. if os.path.exists(ipy):
  1910. try:
  1911. with open(ipy, "r") as f:
  1912. old = f.read()
  1913. - except EnvironmentError:
  1914. + except OSError:
  1915. old = ""
  1916. - if INIT_PY_SNIPPET not in old:
  1917. + module = os.path.splitext(os.path.basename(cfg.versionfile_source))[0]
  1918. + snippet = INIT_PY_SNIPPET.format(module)
  1919. + if OLD_SNIPPET in old:
  1920. + print(" replacing boilerplate in %s" % ipy)
  1921. + with open(ipy, "w") as f:
  1922. + f.write(old.replace(OLD_SNIPPET, snippet))
  1923. + elif snippet not in old:
  1924. print(" appending to %s" % ipy)
  1925. with open(ipy, "a") as f:
  1926. - f.write(INIT_PY_SNIPPET)
  1927. + f.write(snippet)
  1928. else:
  1929. print(" %s unmodified" % ipy)
  1930. else:
  1931. print(" %s doesn't exist, ok" % ipy)
  1932. - ipy = None
  1933. -
  1934. - # Make sure both the top-level "versioneer.py" and versionfile_source
  1935. - # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so
  1936. - # they'll be copied into source distributions. Pip won't be able to
  1937. - # install the package without this.
  1938. - manifest_in = os.path.join(root, "MANIFEST.in")
  1939. - simple_includes = set()
  1940. - try:
  1941. - with open(manifest_in, "r") as f:
  1942. - for line in f:
  1943. - if line.startswith("include "):
  1944. - for include in line.split()[1:]:
  1945. - simple_includes.add(include)
  1946. - except EnvironmentError:
  1947. - pass
  1948. - # That doesn't cover everything MANIFEST.in can do
  1949. - # (http://docs.python.org/2/distutils/sourcedist.html#commands), so
  1950. - # it might give some false negatives. Appending redundant 'include'
  1951. - # lines is safe, though.
  1952. - if "versioneer.py" not in simple_includes:
  1953. - print(" appending 'versioneer.py' to MANIFEST.in")
  1954. - with open(manifest_in, "a") as f:
  1955. - f.write("include versioneer.py\n")
  1956. - else:
  1957. - print(" 'versioneer.py' already in MANIFEST.in")
  1958. - if cfg.versionfile_source not in simple_includes:
  1959. - print(" appending versionfile_source ('%s') to MANIFEST.in" %
  1960. - cfg.versionfile_source)
  1961. - with open(manifest_in, "a") as f:
  1962. - f.write("include %s\n" % cfg.versionfile_source)
  1963. - else:
  1964. - print(" versionfile_source already in MANIFEST.in")
  1965. + maybe_ipy = None
  1966. # Make VCS-specific changes. For git, this means creating/changing
  1967. # .gitattributes to mark _version.py for export-subst keyword
  1968. # substitution.
  1969. - do_vcs_install(manifest_in, cfg.versionfile_source, ipy)
  1970. + do_vcs_install(cfg.versionfile_source, maybe_ipy)
  1971. return 0
  1972. -def scan_setup_py():
  1973. +def scan_setup_py() -> int:
  1974. """Validate the contents of setup.py against Versioneer's expectations."""
  1975. found = set()
  1976. setters = False
  1977. @@ -1813,10 +2321,14 @@ def scan_setup_py():
  1978. return errors
  1979. +def setup_command() -> NoReturn:
  1980. + """Set up Versioneer and exit with appropriate error code."""
  1981. + errors = do_setup()
  1982. + errors += scan_setup_py()
  1983. + sys.exit(1 if errors else 0)
  1984. +
  1985. +
  1986. if __name__ == "__main__":
  1987. cmd = sys.argv[1]
  1988. if cmd == "setup":
  1989. - errors = do_setup()
  1990. - errors += scan_setup_py()
  1991. - if errors:
  1992. - sys.exit(1)
  1993. + setup_command()
  1994. --
  1995. 2.41.0