versioneer.py 78 KB

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