versioneer.py 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109
  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 = ("Versioneer was unable to run the project root directory. "
  241. "Versioneer requires setup.py to be executed from "
  242. "its immediate directory (like 'python setup.py COMMAND'), "
  243. "or in a way that lets it use sys.argv[0] to find the root "
  244. "(like 'python path/to/setup.py COMMAND').")
  245. raise VersioneerBadRootError(err)
  246. try:
  247. # Certain runtime workflows (setup.py install/develop in a setuptools
  248. # tree) execute all dependencies in a single python process, so
  249. # "versioneer" may be imported multiple times, and python's shared
  250. # module-import table will cache the first one. So we can't use
  251. # os.path.dirname(__file__), as that will find whichever
  252. # versioneer.py was first imported, even in later projects.
  253. my_path = os.path.realpath(os.path.abspath(__file__))
  254. me_dir = os.path.normcase(os.path.splitext(my_path)[0])
  255. vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0])
  256. if me_dir != vsr_dir:
  257. print("Warning: build in %s is using versioneer.py from %s"
  258. % (os.path.dirname(my_path), versioneer_py))
  259. except NameError:
  260. pass
  261. return root
  262. def get_config_from_root(root):
  263. """Read the project setup.cfg file to determine Versioneer config."""
  264. # This might raise OSError (if setup.cfg is missing), or
  265. # configparser.NoSectionError (if it lacks a [versioneer] section), or
  266. # configparser.NoOptionError (if it lacks "VCS="). See the docstring at
  267. # the top of versioneer.py for instructions on writing your setup.cfg .
  268. setup_cfg = os.path.join(root, "setup.cfg")
  269. parser = configparser.ConfigParser()
  270. with open(setup_cfg, "r") as cfg_file:
  271. parser.read_file(cfg_file)
  272. VCS = parser.get("versioneer", "VCS") # mandatory
  273. # Dict-like interface for non-mandatory entries
  274. section = parser["versioneer"]
  275. cfg = VersioneerConfig()
  276. cfg.VCS = VCS
  277. cfg.style = section.get("style", "")
  278. cfg.versionfile_source = section.get("versionfile_source")
  279. cfg.versionfile_build = section.get("versionfile_build")
  280. cfg.tag_prefix = section.get("tag_prefix")
  281. if cfg.tag_prefix in ("''", '""'):
  282. cfg.tag_prefix = ""
  283. cfg.parentdir_prefix = section.get("parentdir_prefix")
  284. cfg.verbose = section.get("verbose")
  285. return cfg
  286. class NotThisMethod(Exception):
  287. """Exception raised if a method is not valid for the current scenario."""
  288. # these dictionaries contain VCS-specific tools
  289. LONG_VERSION_PY: Dict[str, str] = {}
  290. HANDLERS: Dict[str, Dict[str, Callable]] = {}
  291. def register_vcs_handler(vcs, method): # decorator
  292. """Create decorator to mark a method as the handler of a VCS."""
  293. def decorate(f):
  294. """Store f in HANDLERS[vcs][method]."""
  295. HANDLERS.setdefault(vcs, {})[method] = f
  296. return f
  297. return decorate
  298. def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
  299. env=None):
  300. """Call the given command(s)."""
  301. assert isinstance(commands, list)
  302. process = None
  303. for command in commands:
  304. try:
  305. dispcmd = str([command] + args)
  306. # remember shell=False, so use git.cmd on windows, not just git
  307. process = subprocess.Popen([command] + args, cwd=cwd, env=env,
  308. stdout=subprocess.PIPE,
  309. stderr=(subprocess.PIPE if hide_stderr
  310. else None))
  311. break
  312. except OSError:
  313. e = sys.exc_info()[1]
  314. if e.errno == errno.ENOENT:
  315. continue
  316. if verbose:
  317. print("unable to run %s" % dispcmd)
  318. print(e)
  319. return None, None
  320. else:
  321. if verbose:
  322. print("unable to find command, tried %s" % (commands,))
  323. return None, None
  324. stdout = process.communicate()[0].strip().decode()
  325. if process.returncode != 0:
  326. if verbose:
  327. print("unable to run %s (error)" % dispcmd)
  328. print("stdout was %s" % stdout)
  329. return None, process.returncode
  330. return stdout, process.returncode
  331. LONG_VERSION_PY['git'] = r'''
  332. # This file helps to compute a version number in source trees obtained from
  333. # git-archive tarball (such as those provided by githubs download-from-tag
  334. # feature). Distribution tarballs (built by setup.py sdist) and build
  335. # directories (produced by setup.py build) will contain a much shorter file
  336. # that just contains the computed version number.
  337. # This file is released into the public domain. Generated by
  338. # versioneer-0.21 (https://github.com/python-versioneer/python-versioneer)
  339. """Git implementation of _version.py."""
  340. import errno
  341. import os
  342. import re
  343. import subprocess
  344. import sys
  345. from typing import Callable, Dict
  346. def get_keywords():
  347. """Get the keywords needed to look up the version information."""
  348. # these strings will be replaced by git during git-archive.
  349. # setup.py/versioneer.py will grep for the variable names, so they must
  350. # each be defined on a line of their own. _version.py will just call
  351. # get_keywords().
  352. git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s"
  353. git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s"
  354. git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s"
  355. keywords = {"refnames": git_refnames, "full": git_full, "date": git_date}
  356. return keywords
  357. class VersioneerConfig:
  358. """Container for Versioneer configuration parameters."""
  359. def get_config():
  360. """Create, populate and return the VersioneerConfig() object."""
  361. # these strings are filled in when 'setup.py versioneer' creates
  362. # _version.py
  363. cfg = VersioneerConfig()
  364. cfg.VCS = "git"
  365. cfg.style = "%(STYLE)s"
  366. cfg.tag_prefix = "%(TAG_PREFIX)s"
  367. cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s"
  368. cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s"
  369. cfg.verbose = False
  370. return cfg
  371. class NotThisMethod(Exception):
  372. """Exception raised if a method is not valid for the current scenario."""
  373. LONG_VERSION_PY: Dict[str, str] = {}
  374. HANDLERS: Dict[str, Dict[str, Callable]] = {}
  375. def register_vcs_handler(vcs, method): # decorator
  376. """Create decorator to mark a method as the handler of a VCS."""
  377. def decorate(f):
  378. """Store f in HANDLERS[vcs][method]."""
  379. if vcs not in HANDLERS:
  380. HANDLERS[vcs] = {}
  381. HANDLERS[vcs][method] = f
  382. return f
  383. return decorate
  384. def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
  385. env=None):
  386. """Call the given command(s)."""
  387. assert isinstance(commands, list)
  388. process = None
  389. for command in commands:
  390. try:
  391. dispcmd = str([command] + args)
  392. # remember shell=False, so use git.cmd on windows, not just git
  393. process = subprocess.Popen([command] + args, cwd=cwd, env=env,
  394. stdout=subprocess.PIPE,
  395. stderr=(subprocess.PIPE if hide_stderr
  396. else None))
  397. break
  398. except OSError:
  399. e = sys.exc_info()[1]
  400. if e.errno == errno.ENOENT:
  401. continue
  402. if verbose:
  403. print("unable to run %%s" %% dispcmd)
  404. print(e)
  405. return None, None
  406. else:
  407. if verbose:
  408. print("unable to find command, tried %%s" %% (commands,))
  409. return None, None
  410. stdout = process.communicate()[0].strip().decode()
  411. if process.returncode != 0:
  412. if verbose:
  413. print("unable to run %%s (error)" %% dispcmd)
  414. print("stdout was %%s" %% stdout)
  415. return None, process.returncode
  416. return stdout, process.returncode
  417. def versions_from_parentdir(parentdir_prefix, root, verbose):
  418. """Try to determine the version from the parent directory name.
  419. Source tarballs conventionally unpack into a directory that includes both
  420. the project name and a version string. We will also support searching up
  421. two directory levels for an appropriately named parent directory
  422. """
  423. rootdirs = []
  424. for _ in range(3):
  425. dirname = os.path.basename(root)
  426. if dirname.startswith(parentdir_prefix):
  427. return {"version": dirname[len(parentdir_prefix):],
  428. "full-revisionid": None,
  429. "dirty": False, "error": None, "date": None}
  430. rootdirs.append(root)
  431. root = os.path.dirname(root) # up a level
  432. if verbose:
  433. print("Tried directories %%s but none started with prefix %%s" %%
  434. (str(rootdirs), parentdir_prefix))
  435. raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
  436. @register_vcs_handler("git", "get_keywords")
  437. def git_get_keywords(versionfile_abs):
  438. """Extract version information from the given file."""
  439. # the code embedded in _version.py can just fetch the value of these
  440. # keywords. When used from setup.py, we don't want to import _version.py,
  441. # so we do it with a regexp instead. This function is not used from
  442. # _version.py.
  443. keywords = {}
  444. try:
  445. with open(versionfile_abs, "r") as fobj:
  446. for line in fobj:
  447. if line.strip().startswith("git_refnames ="):
  448. mo = re.search(r'=\s*"(.*)"', line)
  449. if mo:
  450. keywords["refnames"] = mo.group(1)
  451. if line.strip().startswith("git_full ="):
  452. mo = re.search(r'=\s*"(.*)"', line)
  453. if mo:
  454. keywords["full"] = mo.group(1)
  455. if line.strip().startswith("git_date ="):
  456. mo = re.search(r'=\s*"(.*)"', line)
  457. if mo:
  458. keywords["date"] = mo.group(1)
  459. except OSError:
  460. pass
  461. return keywords
  462. @register_vcs_handler("git", "keywords")
  463. def git_versions_from_keywords(keywords, tag_prefix, verbose):
  464. """Get version information from git keywords."""
  465. if "refnames" not in keywords:
  466. raise NotThisMethod("Short version file found")
  467. date = keywords.get("date")
  468. if date is not None:
  469. # Use only the last line. Previous lines may contain GPG signature
  470. # information.
  471. date = date.splitlines()[-1]
  472. # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant
  473. # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601
  474. # -like" string, which we must then edit to make compliant), because
  475. # it's been around since git-1.5.3, and it's too difficult to
  476. # discover which version we're using, or to work around using an
  477. # older one.
  478. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
  479. refnames = keywords["refnames"].strip()
  480. if refnames.startswith("$Format"):
  481. if verbose:
  482. print("keywords are unexpanded, not using")
  483. raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
  484. refs = {r.strip() for r in refnames.strip("()").split(",")}
  485. # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
  486. # just "foo-1.0". If we see a "tag: " prefix, prefer those.
  487. TAG = "tag: "
  488. tags = {r[len(TAG):] for r in refs if r.startswith(TAG)}
  489. if not tags:
  490. # Either we're using git < 1.8.3, or there really are no tags. We use
  491. # a heuristic: assume all version tags have a digit. The old git %%d
  492. # expansion behaves like git log --decorate=short and strips out the
  493. # refs/heads/ and refs/tags/ prefixes that would let us distinguish
  494. # between branches and tags. By ignoring refnames without digits, we
  495. # filter out many common branch names like "release" and
  496. # "stabilization", as well as "HEAD" and "master".
  497. tags = {r for r in refs if re.search(r'\d', r)}
  498. if verbose:
  499. print("discarding '%%s', no digits" %% ",".join(refs - tags))
  500. if verbose:
  501. print("likely tags: %%s" %% ",".join(sorted(tags)))
  502. for ref in sorted(tags):
  503. # sorting will prefer e.g. "2.0" over "2.0rc1"
  504. if ref.startswith(tag_prefix):
  505. r = ref[len(tag_prefix):]
  506. # Filter out refs that exactly match prefix or that don't start
  507. # with a number once the prefix is stripped (mostly a concern
  508. # when prefix is '')
  509. if not re.match(r'\d', r):
  510. continue
  511. if verbose:
  512. print("picking %%s" %% r)
  513. return {"version": r,
  514. "full-revisionid": keywords["full"].strip(),
  515. "dirty": False, "error": None,
  516. "date": date}
  517. # no suitable tags, so version is "0+unknown", but full hex is still there
  518. if verbose:
  519. print("no suitable tags, using unknown + full revision id")
  520. return {"version": "0+unknown",
  521. "full-revisionid": keywords["full"].strip(),
  522. "dirty": False, "error": "no suitable tags", "date": None}
  523. @register_vcs_handler("git", "pieces_from_vcs")
  524. def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
  525. """Get version from 'git describe' in the root of the source tree.
  526. This only gets called if the git-archive 'subst' keywords were *not*
  527. expanded, and _version.py hasn't already been rewritten with a short
  528. version string, meaning we're inside a checked out source tree.
  529. """
  530. GITS = ["git"]
  531. TAG_PREFIX_REGEX = "*"
  532. if sys.platform == "win32":
  533. GITS = ["git.cmd", "git.exe"]
  534. TAG_PREFIX_REGEX = r"\*"
  535. _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root,
  536. hide_stderr=True)
  537. if rc != 0:
  538. if verbose:
  539. print("Directory %%s not under git control" %% root)
  540. raise NotThisMethod("'git rev-parse --git-dir' returned error")
  541. # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
  542. # if there isn't one, this yields HEX[-dirty] (no NUM)
  543. describe_out, rc = runner(GITS, ["describe", "--tags", "--dirty",
  544. "--always", "--long",
  545. "--match",
  546. "%%s%%s" %% (tag_prefix, TAG_PREFIX_REGEX)],
  547. cwd=root)
  548. # --long was added in git-1.5.5
  549. if describe_out is None:
  550. raise NotThisMethod("'git describe' failed")
  551. describe_out = describe_out.strip()
  552. full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root)
  553. if full_out is None:
  554. raise NotThisMethod("'git rev-parse' failed")
  555. full_out = full_out.strip()
  556. pieces = {}
  557. pieces["long"] = full_out
  558. pieces["short"] = full_out[:7] # maybe improved later
  559. pieces["error"] = None
  560. branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
  561. cwd=root)
  562. # --abbrev-ref was added in git-1.6.3
  563. if rc != 0 or branch_name is None:
  564. raise NotThisMethod("'git rev-parse --abbrev-ref' returned error")
  565. branch_name = branch_name.strip()
  566. if branch_name == "HEAD":
  567. # If we aren't exactly on a branch, pick a branch which represents
  568. # the current commit. If all else fails, we are on a branchless
  569. # commit.
  570. branches, rc = runner(GITS, ["branch", "--contains"], cwd=root)
  571. # --contains was added in git-1.5.4
  572. if rc != 0 or branches is None:
  573. raise NotThisMethod("'git branch --contains' returned error")
  574. branches = branches.split("\n")
  575. # Remove the first line if we're running detached
  576. if "(" in branches[0]:
  577. branches.pop(0)
  578. # Strip off the leading "* " from the list of branches.
  579. branches = [branch[2:] for branch in branches]
  580. if "master" in branches:
  581. branch_name = "master"
  582. elif not branches:
  583. branch_name = None
  584. else:
  585. # Pick the first branch that is returned. Good or bad.
  586. branch_name = branches[0]
  587. pieces["branch"] = branch_name
  588. # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
  589. # TAG might have hyphens.
  590. git_describe = describe_out
  591. # look for -dirty suffix
  592. dirty = git_describe.endswith("-dirty")
  593. pieces["dirty"] = dirty
  594. if dirty:
  595. git_describe = git_describe[:git_describe.rindex("-dirty")]
  596. # now we have TAG-NUM-gHEX or HEX
  597. if "-" in git_describe:
  598. # TAG-NUM-gHEX
  599. mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
  600. if not mo:
  601. # unparsable. Maybe git-describe is misbehaving?
  602. pieces["error"] = ("unable to parse git-describe output: '%%s'"
  603. %% describe_out)
  604. return pieces
  605. # tag
  606. full_tag = mo.group(1)
  607. if not full_tag.startswith(tag_prefix):
  608. if verbose:
  609. fmt = "tag '%%s' doesn't start with prefix '%%s'"
  610. print(fmt %% (full_tag, tag_prefix))
  611. pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'"
  612. %% (full_tag, tag_prefix))
  613. return pieces
  614. pieces["closest-tag"] = full_tag[len(tag_prefix):]
  615. # distance: number of commits since tag
  616. pieces["distance"] = int(mo.group(2))
  617. # commit: short hex revision ID
  618. pieces["short"] = mo.group(3)
  619. else:
  620. # HEX: no tags
  621. pieces["closest-tag"] = None
  622. count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root)
  623. pieces["distance"] = int(count_out) # total number of commits
  624. # commit date: see ISO-8601 comment in git_versions_from_keywords()
  625. date = runner(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip()
  626. # Use only the last line. Previous lines may contain GPG signature
  627. # information.
  628. date = date.splitlines()[-1]
  629. pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
  630. return pieces
  631. def plus_or_dot(pieces):
  632. """Return a + if we don't already have one, else return a ."""
  633. if "+" in pieces.get("closest-tag", ""):
  634. return "."
  635. return "+"
  636. def render_pep440(pieces):
  637. """Build up version string, with post-release "local version identifier".
  638. Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
  639. get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
  640. Exceptions:
  641. 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
  642. """
  643. if pieces["closest-tag"]:
  644. rendered = pieces["closest-tag"]
  645. if pieces["distance"] or pieces["dirty"]:
  646. rendered += plus_or_dot(pieces)
  647. rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"])
  648. if pieces["dirty"]:
  649. rendered += ".dirty"
  650. else:
  651. # exception #1
  652. rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"],
  653. pieces["short"])
  654. if pieces["dirty"]:
  655. rendered += ".dirty"
  656. return rendered
  657. def render_pep440_branch(pieces):
  658. """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] .
  659. The ".dev0" means not master branch. Note that .dev0 sorts backwards
  660. (a feature branch will appear "older" than the master branch).
  661. Exceptions:
  662. 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty]
  663. """
  664. if pieces["closest-tag"]:
  665. rendered = pieces["closest-tag"]
  666. if pieces["distance"] or pieces["dirty"]:
  667. if pieces["branch"] != "master":
  668. rendered += ".dev0"
  669. rendered += plus_or_dot(pieces)
  670. rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"])
  671. if pieces["dirty"]:
  672. rendered += ".dirty"
  673. else:
  674. # exception #1
  675. rendered = "0"
  676. if pieces["branch"] != "master":
  677. rendered += ".dev0"
  678. rendered += "+untagged.%%d.g%%s" %% (pieces["distance"],
  679. pieces["short"])
  680. if pieces["dirty"]:
  681. rendered += ".dirty"
  682. return rendered
  683. def pep440_split_post(ver):
  684. """Split pep440 version string at the post-release segment.
  685. Returns the release segments before the post-release and the
  686. post-release version number (or -1 if no post-release segment is present).
  687. """
  688. vc = str.split(ver, ".post")
  689. return vc[0], int(vc[1] or 0) if len(vc) == 2 else None
  690. def render_pep440_pre(pieces):
  691. """TAG[.postN.devDISTANCE] -- No -dirty.
  692. Exceptions:
  693. 1: no tags. 0.post0.devDISTANCE
  694. """
  695. if pieces["closest-tag"]:
  696. if pieces["distance"]:
  697. # update the post release segment
  698. tag_version, post_version = pep440_split_post(pieces["closest-tag"])
  699. rendered = tag_version
  700. if post_version is not None:
  701. rendered += ".post%%d.dev%%d" %% (post_version+1, pieces["distance"])
  702. else:
  703. rendered += ".post0.dev%%d" %% (pieces["distance"])
  704. else:
  705. # no commits, use the tag as the version
  706. rendered = pieces["closest-tag"]
  707. else:
  708. # exception #1
  709. rendered = "0.post0.dev%%d" %% pieces["distance"]
  710. return rendered
  711. def render_pep440_post(pieces):
  712. """TAG[.postDISTANCE[.dev0]+gHEX] .
  713. The ".dev0" means dirty. Note that .dev0 sorts backwards
  714. (a dirty tree will appear "older" than the corresponding clean one),
  715. but you shouldn't be releasing software with -dirty anyways.
  716. Exceptions:
  717. 1: no tags. 0.postDISTANCE[.dev0]
  718. """
  719. if pieces["closest-tag"]:
  720. rendered = pieces["closest-tag"]
  721. if pieces["distance"] or pieces["dirty"]:
  722. rendered += ".post%%d" %% pieces["distance"]
  723. if pieces["dirty"]:
  724. rendered += ".dev0"
  725. rendered += plus_or_dot(pieces)
  726. rendered += "g%%s" %% pieces["short"]
  727. else:
  728. # exception #1
  729. rendered = "0.post%%d" %% pieces["distance"]
  730. if pieces["dirty"]:
  731. rendered += ".dev0"
  732. rendered += "+g%%s" %% pieces["short"]
  733. return rendered
  734. def render_pep440_post_branch(pieces):
  735. """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] .
  736. The ".dev0" means not master branch.
  737. Exceptions:
  738. 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty]
  739. """
  740. if pieces["closest-tag"]:
  741. rendered = pieces["closest-tag"]
  742. if pieces["distance"] or pieces["dirty"]:
  743. rendered += ".post%%d" %% pieces["distance"]
  744. if pieces["branch"] != "master":
  745. rendered += ".dev0"
  746. rendered += plus_or_dot(pieces)
  747. rendered += "g%%s" %% pieces["short"]
  748. if pieces["dirty"]:
  749. rendered += ".dirty"
  750. else:
  751. # exception #1
  752. rendered = "0.post%%d" %% pieces["distance"]
  753. if pieces["branch"] != "master":
  754. rendered += ".dev0"
  755. rendered += "+g%%s" %% pieces["short"]
  756. if pieces["dirty"]:
  757. rendered += ".dirty"
  758. return rendered
  759. def render_pep440_old(pieces):
  760. """TAG[.postDISTANCE[.dev0]] .
  761. The ".dev0" means dirty.
  762. Exceptions:
  763. 1: no tags. 0.postDISTANCE[.dev0]
  764. """
  765. if pieces["closest-tag"]:
  766. rendered = pieces["closest-tag"]
  767. if pieces["distance"] or pieces["dirty"]:
  768. rendered += ".post%%d" %% pieces["distance"]
  769. if pieces["dirty"]:
  770. rendered += ".dev0"
  771. else:
  772. # exception #1
  773. rendered = "0.post%%d" %% pieces["distance"]
  774. if pieces["dirty"]:
  775. rendered += ".dev0"
  776. return rendered
  777. def render_git_describe(pieces):
  778. """TAG[-DISTANCE-gHEX][-dirty].
  779. Like 'git describe --tags --dirty --always'.
  780. Exceptions:
  781. 1: no tags. HEX[-dirty] (note: no 'g' prefix)
  782. """
  783. if pieces["closest-tag"]:
  784. rendered = pieces["closest-tag"]
  785. if pieces["distance"]:
  786. rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"])
  787. else:
  788. # exception #1
  789. rendered = pieces["short"]
  790. if pieces["dirty"]:
  791. rendered += "-dirty"
  792. return rendered
  793. def render_git_describe_long(pieces):
  794. """TAG-DISTANCE-gHEX[-dirty].
  795. Like 'git describe --tags --dirty --always -long'.
  796. The distance/hash is unconditional.
  797. Exceptions:
  798. 1: no tags. HEX[-dirty] (note: no 'g' prefix)
  799. """
  800. if pieces["closest-tag"]:
  801. rendered = pieces["closest-tag"]
  802. rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"])
  803. else:
  804. # exception #1
  805. rendered = pieces["short"]
  806. if pieces["dirty"]:
  807. rendered += "-dirty"
  808. return rendered
  809. def render(pieces, style):
  810. """Render the given version pieces into the requested style."""
  811. if pieces["error"]:
  812. return {"version": "unknown",
  813. "full-revisionid": pieces.get("long"),
  814. "dirty": None,
  815. "error": pieces["error"],
  816. "date": None}
  817. if not style or style == "default":
  818. style = "pep440" # the default
  819. if style == "pep440":
  820. rendered = render_pep440(pieces)
  821. elif style == "pep440-branch":
  822. rendered = render_pep440_branch(pieces)
  823. elif style == "pep440-pre":
  824. rendered = render_pep440_pre(pieces)
  825. elif style == "pep440-post":
  826. rendered = render_pep440_post(pieces)
  827. elif style == "pep440-post-branch":
  828. rendered = render_pep440_post_branch(pieces)
  829. elif style == "pep440-old":
  830. rendered = render_pep440_old(pieces)
  831. elif style == "git-describe":
  832. rendered = render_git_describe(pieces)
  833. elif style == "git-describe-long":
  834. rendered = render_git_describe_long(pieces)
  835. else:
  836. raise ValueError("unknown style '%%s'" %% style)
  837. return {"version": rendered, "full-revisionid": pieces["long"],
  838. "dirty": pieces["dirty"], "error": None,
  839. "date": pieces.get("date")}
  840. def get_versions():
  841. """Get version information or return default if unable to do so."""
  842. # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
  843. # __file__, we can work backwards from there to the root. Some
  844. # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
  845. # case we can only use expanded keywords.
  846. cfg = get_config()
  847. verbose = cfg.verbose
  848. try:
  849. return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
  850. verbose)
  851. except NotThisMethod:
  852. pass
  853. try:
  854. root = os.path.realpath(__file__)
  855. # versionfile_source is the relative path from the top of the source
  856. # tree (where the .git directory might live) to this file. Invert
  857. # this to find the root from __file__.
  858. for _ in cfg.versionfile_source.split('/'):
  859. root = os.path.dirname(root)
  860. except NameError:
  861. return {"version": "0+unknown", "full-revisionid": None,
  862. "dirty": None,
  863. "error": "unable to find root of source tree",
  864. "date": None}
  865. try:
  866. pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
  867. return render(pieces, cfg.style)
  868. except NotThisMethod:
  869. pass
  870. try:
  871. if cfg.parentdir_prefix:
  872. return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
  873. except NotThisMethod:
  874. pass
  875. return {"version": "0+unknown", "full-revisionid": None,
  876. "dirty": None,
  877. "error": "unable to compute version", "date": None}
  878. '''
  879. @register_vcs_handler("git", "get_keywords")
  880. def git_get_keywords(versionfile_abs):
  881. """Extract version information from the given file."""
  882. # the code embedded in _version.py can just fetch the value of these
  883. # keywords. When used from setup.py, we don't want to import _version.py,
  884. # so we do it with a regexp instead. This function is not used from
  885. # _version.py.
  886. keywords = {}
  887. try:
  888. with open(versionfile_abs, "r") as fobj:
  889. for line in fobj:
  890. if line.strip().startswith("git_refnames ="):
  891. mo = re.search(r'=\s*"(.*)"', line)
  892. if mo:
  893. keywords["refnames"] = mo.group(1)
  894. if line.strip().startswith("git_full ="):
  895. mo = re.search(r'=\s*"(.*)"', line)
  896. if mo:
  897. keywords["full"] = mo.group(1)
  898. if line.strip().startswith("git_date ="):
  899. mo = re.search(r'=\s*"(.*)"', line)
  900. if mo:
  901. keywords["date"] = mo.group(1)
  902. except OSError:
  903. pass
  904. return keywords
  905. @register_vcs_handler("git", "keywords")
  906. def git_versions_from_keywords(keywords, tag_prefix, verbose):
  907. """Get version information from git keywords."""
  908. if "refnames" not in keywords:
  909. raise NotThisMethod("Short version file found")
  910. date = keywords.get("date")
  911. if date is not None:
  912. # Use only the last line. Previous lines may contain GPG signature
  913. # information.
  914. date = date.splitlines()[-1]
  915. # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
  916. # datestamp. However we prefer "%ci" (which expands to an "ISO-8601
  917. # -like" string, which we must then edit to make compliant), because
  918. # it's been around since git-1.5.3, and it's too difficult to
  919. # discover which version we're using, or to work around using an
  920. # older one.
  921. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
  922. refnames = keywords["refnames"].strip()
  923. if refnames.startswith("$Format"):
  924. if verbose:
  925. print("keywords are unexpanded, not using")
  926. raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
  927. refs = {r.strip() for r in refnames.strip("()").split(",")}
  928. # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
  929. # just "foo-1.0". If we see a "tag: " prefix, prefer those.
  930. TAG = "tag: "
  931. tags = {r[len(TAG):] for r in refs if r.startswith(TAG)}
  932. if not tags:
  933. # Either we're using git < 1.8.3, or there really are no tags. We use
  934. # a heuristic: assume all version tags have a digit. The old git %d
  935. # expansion behaves like git log --decorate=short and strips out the
  936. # refs/heads/ and refs/tags/ prefixes that would let us distinguish
  937. # between branches and tags. By ignoring refnames without digits, we
  938. # filter out many common branch names like "release" and
  939. # "stabilization", as well as "HEAD" and "master".
  940. tags = {r for r in refs if re.search(r'\d', r)}
  941. if verbose:
  942. print("discarding '%s', no digits" % ",".join(refs - tags))
  943. if verbose:
  944. print("likely tags: %s" % ",".join(sorted(tags)))
  945. for ref in sorted(tags):
  946. # sorting will prefer e.g. "2.0" over "2.0rc1"
  947. if ref.startswith(tag_prefix):
  948. r = ref[len(tag_prefix):]
  949. # Filter out refs that exactly match prefix or that don't start
  950. # with a number once the prefix is stripped (mostly a concern
  951. # when prefix is '')
  952. if not re.match(r'\d', r):
  953. continue
  954. if verbose:
  955. print("picking %s" % r)
  956. return {"version": r,
  957. "full-revisionid": keywords["full"].strip(),
  958. "dirty": False, "error": None,
  959. "date": date}
  960. # no suitable tags, so version is "0+unknown", but full hex is still there
  961. if verbose:
  962. print("no suitable tags, using unknown + full revision id")
  963. return {"version": "0+unknown",
  964. "full-revisionid": keywords["full"].strip(),
  965. "dirty": False, "error": "no suitable tags", "date": None}
  966. @register_vcs_handler("git", "pieces_from_vcs")
  967. def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
  968. """Get version from 'git describe' in the root of the source tree.
  969. This only gets called if the git-archive 'subst' keywords were *not*
  970. expanded, and _version.py hasn't already been rewritten with a short
  971. version string, meaning we're inside a checked out source tree.
  972. """
  973. GITS = ["git"]
  974. TAG_PREFIX_REGEX = "*"
  975. if sys.platform == "win32":
  976. GITS = ["git.cmd", "git.exe"]
  977. TAG_PREFIX_REGEX = r"\*"
  978. _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root,
  979. hide_stderr=True)
  980. if rc != 0:
  981. if verbose:
  982. print("Directory %s not under git control" % root)
  983. raise NotThisMethod("'git rev-parse --git-dir' returned error")
  984. # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
  985. # if there isn't one, this yields HEX[-dirty] (no NUM)
  986. describe_out, rc = runner(GITS, ["describe", "--tags", "--dirty",
  987. "--always", "--long",
  988. "--match",
  989. "%s%s" % (tag_prefix, TAG_PREFIX_REGEX)],
  990. cwd=root)
  991. # --long was added in git-1.5.5
  992. if describe_out is None:
  993. raise NotThisMethod("'git describe' failed")
  994. describe_out = describe_out.strip()
  995. full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root)
  996. if full_out is None:
  997. raise NotThisMethod("'git rev-parse' failed")
  998. full_out = full_out.strip()
  999. pieces = {}
  1000. pieces["long"] = full_out
  1001. pieces["short"] = full_out[:7] # maybe improved later
  1002. pieces["error"] = None
  1003. branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
  1004. cwd=root)
  1005. # --abbrev-ref was added in git-1.6.3
  1006. if rc != 0 or branch_name is None:
  1007. raise NotThisMethod("'git rev-parse --abbrev-ref' returned error")
  1008. branch_name = branch_name.strip()
  1009. if branch_name == "HEAD":
  1010. # If we aren't exactly on a branch, pick a branch which represents
  1011. # the current commit. If all else fails, we are on a branchless
  1012. # commit.
  1013. branches, rc = runner(GITS, ["branch", "--contains"], cwd=root)
  1014. # --contains was added in git-1.5.4
  1015. if rc != 0 or branches is None:
  1016. raise NotThisMethod("'git branch --contains' returned error")
  1017. branches = branches.split("\n")
  1018. # Remove the first line if we're running detached
  1019. if "(" in branches[0]:
  1020. branches.pop(0)
  1021. # Strip off the leading "* " from the list of branches.
  1022. branches = [branch[2:] for branch in branches]
  1023. if "master" in branches:
  1024. branch_name = "master"
  1025. elif not branches:
  1026. branch_name = None
  1027. else:
  1028. # Pick the first branch that is returned. Good or bad.
  1029. branch_name = branches[0]
  1030. pieces["branch"] = branch_name
  1031. # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
  1032. # TAG might have hyphens.
  1033. git_describe = describe_out
  1034. # look for -dirty suffix
  1035. dirty = git_describe.endswith("-dirty")
  1036. pieces["dirty"] = dirty
  1037. if dirty:
  1038. git_describe = git_describe[:git_describe.rindex("-dirty")]
  1039. # now we have TAG-NUM-gHEX or HEX
  1040. if "-" in git_describe:
  1041. # TAG-NUM-gHEX
  1042. mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
  1043. if not mo:
  1044. # unparsable. Maybe git-describe is misbehaving?
  1045. pieces["error"] = ("unable to parse git-describe output: '%s'"
  1046. % describe_out)
  1047. return pieces
  1048. # tag
  1049. full_tag = mo.group(1)
  1050. if not full_tag.startswith(tag_prefix):
  1051. if verbose:
  1052. fmt = "tag '%s' doesn't start with prefix '%s'"
  1053. print(fmt % (full_tag, tag_prefix))
  1054. pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
  1055. % (full_tag, tag_prefix))
  1056. return pieces
  1057. pieces["closest-tag"] = full_tag[len(tag_prefix):]
  1058. # distance: number of commits since tag
  1059. pieces["distance"] = int(mo.group(2))
  1060. # commit: short hex revision ID
  1061. pieces["short"] = mo.group(3)
  1062. else:
  1063. # HEX: no tags
  1064. pieces["closest-tag"] = None
  1065. count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root)
  1066. pieces["distance"] = int(count_out) # total number of commits
  1067. # commit date: see ISO-8601 comment in git_versions_from_keywords()
  1068. date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip()
  1069. # Use only the last line. Previous lines may contain GPG signature
  1070. # information.
  1071. date = date.splitlines()[-1]
  1072. pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
  1073. return pieces
  1074. def do_vcs_install(manifest_in, versionfile_source, ipy):
  1075. """Git-specific installation logic for Versioneer.
  1076. For Git, this means creating/changing .gitattributes to mark _version.py
  1077. for export-subst keyword substitution.
  1078. """
  1079. GITS = ["git"]
  1080. if sys.platform == "win32":
  1081. GITS = ["git.cmd", "git.exe"]
  1082. files = [manifest_in, versionfile_source]
  1083. if ipy:
  1084. files.append(ipy)
  1085. try:
  1086. my_path = __file__
  1087. if my_path.endswith(".pyc") or my_path.endswith(".pyo"):
  1088. my_path = os.path.splitext(my_path)[0] + ".py"
  1089. versioneer_file = os.path.relpath(my_path)
  1090. except NameError:
  1091. versioneer_file = "versioneer.py"
  1092. files.append(versioneer_file)
  1093. present = False
  1094. try:
  1095. with open(".gitattributes", "r") as fobj:
  1096. for line in fobj:
  1097. if line.strip().startswith(versionfile_source):
  1098. if "export-subst" in line.strip().split()[1:]:
  1099. present = True
  1100. break
  1101. except OSError:
  1102. pass
  1103. if not present:
  1104. with open(".gitattributes", "a+") as fobj:
  1105. fobj.write(f"{versionfile_source} export-subst\n")
  1106. files.append(".gitattributes")
  1107. run_command(GITS, ["add", "--"] + files)
  1108. def versions_from_parentdir(parentdir_prefix, root, verbose):
  1109. """Try to determine the version from the parent directory name.
  1110. Source tarballs conventionally unpack into a directory that includes both
  1111. the project name and a version string. We will also support searching up
  1112. two directory levels for an appropriately named parent directory
  1113. """
  1114. rootdirs = []
  1115. for _ in range(3):
  1116. dirname = os.path.basename(root)
  1117. if dirname.startswith(parentdir_prefix):
  1118. return {"version": dirname[len(parentdir_prefix):],
  1119. "full-revisionid": None,
  1120. "dirty": False, "error": None, "date": None}
  1121. rootdirs.append(root)
  1122. root = os.path.dirname(root) # up a level
  1123. if verbose:
  1124. print("Tried directories %s but none started with prefix %s" %
  1125. (str(rootdirs), parentdir_prefix))
  1126. raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
  1127. SHORT_VERSION_PY = """
  1128. # This file was generated by 'versioneer.py' (0.21) from
  1129. # revision-control system data, or from the parent directory name of an
  1130. # unpacked source archive. Distribution tarballs contain a pre-generated copy
  1131. # of this file.
  1132. import json
  1133. version_json = '''
  1134. %s
  1135. ''' # END VERSION_JSON
  1136. def get_versions():
  1137. return json.loads(version_json)
  1138. """
  1139. def versions_from_file(filename):
  1140. """Try to determine the version from _version.py if present."""
  1141. try:
  1142. with open(filename) as f:
  1143. contents = f.read()
  1144. except OSError:
  1145. raise NotThisMethod("unable to read _version.py")
  1146. mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON",
  1147. contents, re.M | re.S)
  1148. if not mo:
  1149. mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON",
  1150. contents, re.M | re.S)
  1151. if not mo:
  1152. raise NotThisMethod("no version_json in _version.py")
  1153. return json.loads(mo.group(1))
  1154. def write_to_version_file(filename, versions):
  1155. """Write the given version number to the given _version.py file."""
  1156. os.unlink(filename)
  1157. contents = json.dumps(versions, sort_keys=True,
  1158. indent=1, separators=(",", ": "))
  1159. with open(filename, "w") as f:
  1160. f.write(SHORT_VERSION_PY % contents)
  1161. print("set %s to '%s'" % (filename, versions["version"]))
  1162. def plus_or_dot(pieces):
  1163. """Return a + if we don't already have one, else return a ."""
  1164. if "+" in pieces.get("closest-tag", ""):
  1165. return "."
  1166. return "+"
  1167. def render_pep440(pieces):
  1168. """Build up version string, with post-release "local version identifier".
  1169. Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
  1170. get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
  1171. Exceptions:
  1172. 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
  1173. """
  1174. if pieces["closest-tag"]:
  1175. rendered = pieces["closest-tag"]
  1176. if pieces["distance"] or pieces["dirty"]:
  1177. rendered += plus_or_dot(pieces)
  1178. rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
  1179. if pieces["dirty"]:
  1180. rendered += ".dirty"
  1181. else:
  1182. # exception #1
  1183. rendered = "0+untagged.%d.g%s" % (pieces["distance"],
  1184. pieces["short"])
  1185. if pieces["dirty"]:
  1186. rendered += ".dirty"
  1187. return rendered
  1188. def render_pep440_branch(pieces):
  1189. """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] .
  1190. The ".dev0" means not master branch. Note that .dev0 sorts backwards
  1191. (a feature branch will appear "older" than the master branch).
  1192. Exceptions:
  1193. 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty]
  1194. """
  1195. if pieces["closest-tag"]:
  1196. rendered = pieces["closest-tag"]
  1197. if pieces["distance"] or pieces["dirty"]:
  1198. if pieces["branch"] != "master":
  1199. rendered += ".dev0"
  1200. rendered += plus_or_dot(pieces)
  1201. rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
  1202. if pieces["dirty"]:
  1203. rendered += ".dirty"
  1204. else:
  1205. # exception #1
  1206. rendered = "0"
  1207. if pieces["branch"] != "master":
  1208. rendered += ".dev0"
  1209. rendered += "+untagged.%d.g%s" % (pieces["distance"],
  1210. pieces["short"])
  1211. if pieces["dirty"]:
  1212. rendered += ".dirty"
  1213. return rendered
  1214. def pep440_split_post(ver):
  1215. """Split pep440 version string at the post-release segment.
  1216. Returns the release segments before the post-release and the
  1217. post-release version number (or -1 if no post-release segment is present).
  1218. """
  1219. vc = str.split(ver, ".post")
  1220. return vc[0], int(vc[1] or 0) if len(vc) == 2 else None
  1221. def render_pep440_pre(pieces):
  1222. """TAG[.postN.devDISTANCE] -- No -dirty.
  1223. Exceptions:
  1224. 1: no tags. 0.post0.devDISTANCE
  1225. """
  1226. if pieces["closest-tag"]:
  1227. if pieces["distance"]:
  1228. # update the post release segment
  1229. tag_version, post_version = pep440_split_post(pieces["closest-tag"])
  1230. rendered = tag_version
  1231. if post_version is not None:
  1232. rendered += ".post%d.dev%d" % (post_version+1, pieces["distance"])
  1233. else:
  1234. rendered += ".post0.dev%d" % (pieces["distance"])
  1235. else:
  1236. # no commits, use the tag as the version
  1237. rendered = pieces["closest-tag"]
  1238. else:
  1239. # exception #1
  1240. rendered = "0.post0.dev%d" % pieces["distance"]
  1241. return rendered
  1242. def render_pep440_post(pieces):
  1243. """TAG[.postDISTANCE[.dev0]+gHEX] .
  1244. The ".dev0" means dirty. Note that .dev0 sorts backwards
  1245. (a dirty tree will appear "older" than the corresponding clean one),
  1246. but you shouldn't be releasing software with -dirty anyways.
  1247. Exceptions:
  1248. 1: no tags. 0.postDISTANCE[.dev0]
  1249. """
  1250. if pieces["closest-tag"]:
  1251. rendered = pieces["closest-tag"]
  1252. if pieces["distance"] or pieces["dirty"]:
  1253. rendered += ".post%d" % pieces["distance"]
  1254. if pieces["dirty"]:
  1255. rendered += ".dev0"
  1256. rendered += plus_or_dot(pieces)
  1257. rendered += "g%s" % pieces["short"]
  1258. else:
  1259. # exception #1
  1260. rendered = "0.post%d" % pieces["distance"]
  1261. if pieces["dirty"]:
  1262. rendered += ".dev0"
  1263. rendered += "+g%s" % pieces["short"]
  1264. return rendered
  1265. def render_pep440_post_branch(pieces):
  1266. """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] .
  1267. The ".dev0" means not master branch.
  1268. Exceptions:
  1269. 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty]
  1270. """
  1271. if pieces["closest-tag"]:
  1272. rendered = pieces["closest-tag"]
  1273. if pieces["distance"] or pieces["dirty"]:
  1274. rendered += ".post%d" % pieces["distance"]
  1275. if pieces["branch"] != "master":
  1276. rendered += ".dev0"
  1277. rendered += plus_or_dot(pieces)
  1278. rendered += "g%s" % pieces["short"]
  1279. if pieces["dirty"]:
  1280. rendered += ".dirty"
  1281. else:
  1282. # exception #1
  1283. rendered = "0.post%d" % pieces["distance"]
  1284. if pieces["branch"] != "master":
  1285. rendered += ".dev0"
  1286. rendered += "+g%s" % pieces["short"]
  1287. if pieces["dirty"]:
  1288. rendered += ".dirty"
  1289. return rendered
  1290. def render_pep440_old(pieces):
  1291. """TAG[.postDISTANCE[.dev0]] .
  1292. The ".dev0" means dirty.
  1293. Exceptions:
  1294. 1: no tags. 0.postDISTANCE[.dev0]
  1295. """
  1296. if pieces["closest-tag"]:
  1297. rendered = pieces["closest-tag"]
  1298. if pieces["distance"] or pieces["dirty"]:
  1299. rendered += ".post%d" % pieces["distance"]
  1300. if pieces["dirty"]:
  1301. rendered += ".dev0"
  1302. else:
  1303. # exception #1
  1304. rendered = "0.post%d" % pieces["distance"]
  1305. if pieces["dirty"]:
  1306. rendered += ".dev0"
  1307. return rendered
  1308. def render_git_describe(pieces):
  1309. """TAG[-DISTANCE-gHEX][-dirty].
  1310. Like 'git describe --tags --dirty --always'.
  1311. Exceptions:
  1312. 1: no tags. HEX[-dirty] (note: no 'g' prefix)
  1313. """
  1314. if pieces["closest-tag"]:
  1315. rendered = pieces["closest-tag"]
  1316. if pieces["distance"]:
  1317. rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
  1318. else:
  1319. # exception #1
  1320. rendered = pieces["short"]
  1321. if pieces["dirty"]:
  1322. rendered += "-dirty"
  1323. return rendered
  1324. def render_git_describe_long(pieces):
  1325. """TAG-DISTANCE-gHEX[-dirty].
  1326. Like 'git describe --tags --dirty --always -long'.
  1327. The distance/hash is unconditional.
  1328. Exceptions:
  1329. 1: no tags. HEX[-dirty] (note: no 'g' prefix)
  1330. """
  1331. if pieces["closest-tag"]:
  1332. rendered = pieces["closest-tag"]
  1333. rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
  1334. else:
  1335. # exception #1
  1336. rendered = pieces["short"]
  1337. if pieces["dirty"]:
  1338. rendered += "-dirty"
  1339. return rendered
  1340. def render(pieces, style):
  1341. """Render the given version pieces into the requested style."""
  1342. if pieces["error"]:
  1343. return {"version": "unknown",
  1344. "full-revisionid": pieces.get("long"),
  1345. "dirty": None,
  1346. "error": pieces["error"],
  1347. "date": None}
  1348. if not style or style == "default":
  1349. style = "pep440" # the default
  1350. if style == "pep440":
  1351. rendered = render_pep440(pieces)
  1352. elif style == "pep440-branch":
  1353. rendered = render_pep440_branch(pieces)
  1354. elif style == "pep440-pre":
  1355. rendered = render_pep440_pre(pieces)
  1356. elif style == "pep440-post":
  1357. rendered = render_pep440_post(pieces)
  1358. elif style == "pep440-post-branch":
  1359. rendered = render_pep440_post_branch(pieces)
  1360. elif style == "pep440-old":
  1361. rendered = render_pep440_old(pieces)
  1362. elif style == "git-describe":
  1363. rendered = render_git_describe(pieces)
  1364. elif style == "git-describe-long":
  1365. rendered = render_git_describe_long(pieces)
  1366. else:
  1367. raise ValueError("unknown style '%s'" % style)
  1368. return {"version": rendered, "full-revisionid": pieces["long"],
  1369. "dirty": pieces["dirty"], "error": None,
  1370. "date": pieces.get("date")}
  1371. class VersioneerBadRootError(Exception):
  1372. """The project root directory is unknown or missing key files."""
  1373. def get_versions(verbose=False):
  1374. """Get the project version from whatever source is available.
  1375. Returns dict with two keys: 'version' and 'full'.
  1376. """
  1377. if "versioneer" in sys.modules:
  1378. # see the discussion in cmdclass.py:get_cmdclass()
  1379. del sys.modules["versioneer"]
  1380. root = get_root()
  1381. cfg = get_config_from_root(root)
  1382. assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg"
  1383. handlers = HANDLERS.get(cfg.VCS)
  1384. assert handlers, "unrecognized VCS '%s'" % cfg.VCS
  1385. verbose = verbose or cfg.verbose
  1386. assert cfg.versionfile_source is not None, \
  1387. "please set versioneer.versionfile_source"
  1388. assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix"
  1389. versionfile_abs = os.path.join(root, cfg.versionfile_source)
  1390. # extract version from first of: _version.py, VCS command (e.g. 'git
  1391. # describe'), parentdir. This is meant to work for developers using a
  1392. # source checkout, for users of a tarball created by 'setup.py sdist',
  1393. # and for users of a tarball/zipball created by 'git archive' or github's
  1394. # download-from-tag feature or the equivalent in other VCSes.
  1395. get_keywords_f = handlers.get("get_keywords")
  1396. from_keywords_f = handlers.get("keywords")
  1397. if get_keywords_f and from_keywords_f:
  1398. try:
  1399. keywords = get_keywords_f(versionfile_abs)
  1400. ver = from_keywords_f(keywords, cfg.tag_prefix, verbose)
  1401. if verbose:
  1402. print("got version from expanded keyword %s" % ver)
  1403. return ver
  1404. except NotThisMethod:
  1405. pass
  1406. try:
  1407. ver = versions_from_file(versionfile_abs)
  1408. if verbose:
  1409. print("got version from file %s %s" % (versionfile_abs, ver))
  1410. return ver
  1411. except NotThisMethod:
  1412. pass
  1413. from_vcs_f = handlers.get("pieces_from_vcs")
  1414. if from_vcs_f:
  1415. try:
  1416. pieces = from_vcs_f(cfg.tag_prefix, root, verbose)
  1417. ver = render(pieces, cfg.style)
  1418. if verbose:
  1419. print("got version from VCS %s" % ver)
  1420. return ver
  1421. except NotThisMethod:
  1422. pass
  1423. try:
  1424. if cfg.parentdir_prefix:
  1425. ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
  1426. if verbose:
  1427. print("got version from parentdir %s" % ver)
  1428. return ver
  1429. except NotThisMethod:
  1430. pass
  1431. if verbose:
  1432. print("unable to compute version")
  1433. return {"version": "0+unknown", "full-revisionid": None,
  1434. "dirty": None, "error": "unable to compute version",
  1435. "date": None}
  1436. def get_version():
  1437. """Get the short version string for this project."""
  1438. return get_versions()["version"]
  1439. def get_cmdclass(cmdclass=None):
  1440. """Get the custom setuptools/distutils subclasses used by Versioneer.
  1441. If the package uses a different cmdclass (e.g. one from numpy), it
  1442. should be provide as an argument.
  1443. """
  1444. if "versioneer" in sys.modules:
  1445. del sys.modules["versioneer"]
  1446. # this fixes the "python setup.py develop" case (also 'install' and
  1447. # 'easy_install .'), in which subdependencies of the main project are
  1448. # built (using setup.py bdist_egg) in the same python process. Assume
  1449. # a main project A and a dependency B, which use different versions
  1450. # of Versioneer. A's setup.py imports A's Versioneer, leaving it in
  1451. # sys.modules by the time B's setup.py is executed, causing B to run
  1452. # with the wrong versioneer. Setuptools wraps the sub-dep builds in a
  1453. # sandbox that restores sys.modules to it's pre-build state, so the
  1454. # parent is protected against the child's "import versioneer". By
  1455. # removing ourselves from sys.modules here, before the child build
  1456. # happens, we protect the child from the parent's versioneer too.
  1457. # Also see https://github.com/python-versioneer/python-versioneer/issues/52
  1458. cmds = {} if cmdclass is None else cmdclass.copy()
  1459. # we add "version" to both distutils and setuptools
  1460. from distutils.core import Command
  1461. class cmd_version(Command):
  1462. description = "report generated version string"
  1463. user_options = []
  1464. boolean_options = []
  1465. def initialize_options(self):
  1466. pass
  1467. def finalize_options(self):
  1468. pass
  1469. def run(self):
  1470. vers = get_versions(verbose=True)
  1471. print("Version: %s" % vers["version"])
  1472. print(" full-revisionid: %s" % vers.get("full-revisionid"))
  1473. print(" dirty: %s" % vers.get("dirty"))
  1474. print(" date: %s" % vers.get("date"))
  1475. if vers["error"]:
  1476. print(" error: %s" % vers["error"])
  1477. cmds["version"] = cmd_version
  1478. # we override "build_py" in both distutils and setuptools
  1479. #
  1480. # most invocation pathways end up running build_py:
  1481. # distutils/build -> build_py
  1482. # distutils/install -> distutils/build ->..
  1483. # setuptools/bdist_wheel -> distutils/install ->..
  1484. # setuptools/bdist_egg -> distutils/install_lib -> build_py
  1485. # setuptools/install -> bdist_egg ->..
  1486. # setuptools/develop -> ?
  1487. # pip install:
  1488. # copies source tree to a tempdir before running egg_info/etc
  1489. # if .git isn't copied too, 'git describe' will fail
  1490. # then does setup.py bdist_wheel, or sometimes setup.py install
  1491. # setup.py egg_info -> ?
  1492. # we override different "build_py" commands for both environments
  1493. if 'build_py' in cmds:
  1494. _build_py = cmds['build_py']
  1495. elif "setuptools" in sys.modules:
  1496. from setuptools.command.build_py import build_py as _build_py
  1497. else:
  1498. from distutils.command.build_py import build_py as _build_py
  1499. class cmd_build_py(_build_py):
  1500. def run(self):
  1501. root = get_root()
  1502. cfg = get_config_from_root(root)
  1503. versions = get_versions()
  1504. _build_py.run(self)
  1505. # now locate _version.py in the new build/ directory and replace
  1506. # it with an updated value
  1507. if cfg.versionfile_build:
  1508. target_versionfile = os.path.join(self.build_lib,
  1509. cfg.versionfile_build)
  1510. print("UPDATING %s" % target_versionfile)
  1511. write_to_version_file(target_versionfile, versions)
  1512. cmds["build_py"] = cmd_build_py
  1513. if 'build_ext' in cmds:
  1514. _build_ext = cmds['build_ext']
  1515. elif "setuptools" in sys.modules:
  1516. from setuptools.command.build_ext import build_ext as _build_ext
  1517. else:
  1518. from distutils.command.build_ext import build_ext as _build_ext
  1519. class cmd_build_ext(_build_ext):
  1520. def run(self):
  1521. root = get_root()
  1522. cfg = get_config_from_root(root)
  1523. versions = get_versions()
  1524. _build_ext.run(self)
  1525. if self.inplace:
  1526. # build_ext --inplace will only build extensions in
  1527. # build/lib<..> dir with no _version.py to write to.
  1528. # As in place builds will already have a _version.py
  1529. # in the module dir, we do not need to write one.
  1530. return
  1531. # now locate _version.py in the new build/ directory and replace
  1532. # it with an updated value
  1533. target_versionfile = os.path.join(self.build_lib,
  1534. cfg.versionfile_build)
  1535. print("UPDATING %s" % target_versionfile)
  1536. write_to_version_file(target_versionfile, versions)
  1537. cmds["build_ext"] = cmd_build_ext
  1538. if "cx_Freeze" in sys.modules: # cx_freeze enabled?
  1539. from cx_Freeze.dist import build_exe as _build_exe
  1540. # nczeczulin reports that py2exe won't like the pep440-style string
  1541. # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g.
  1542. # setup(console=[{
  1543. # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION
  1544. # "product_version": versioneer.get_version(),
  1545. # ...
  1546. class cmd_build_exe(_build_exe):
  1547. def run(self):
  1548. root = get_root()
  1549. cfg = get_config_from_root(root)
  1550. versions = get_versions()
  1551. target_versionfile = cfg.versionfile_source
  1552. print("UPDATING %s" % target_versionfile)
  1553. write_to_version_file(target_versionfile, versions)
  1554. _build_exe.run(self)
  1555. os.unlink(target_versionfile)
  1556. with open(cfg.versionfile_source, "w") as f:
  1557. LONG = LONG_VERSION_PY[cfg.VCS]
  1558. f.write(LONG %
  1559. {"DOLLAR": "$",
  1560. "STYLE": cfg.style,
  1561. "TAG_PREFIX": cfg.tag_prefix,
  1562. "PARENTDIR_PREFIX": cfg.parentdir_prefix,
  1563. "VERSIONFILE_SOURCE": cfg.versionfile_source,
  1564. })
  1565. cmds["build_exe"] = cmd_build_exe
  1566. del cmds["build_py"]
  1567. if 'py2exe' in sys.modules: # py2exe enabled?
  1568. from py2exe.distutils_buildexe import py2exe as _py2exe
  1569. class cmd_py2exe(_py2exe):
  1570. def run(self):
  1571. root = get_root()
  1572. cfg = get_config_from_root(root)
  1573. versions = get_versions()
  1574. target_versionfile = cfg.versionfile_source
  1575. print("UPDATING %s" % target_versionfile)
  1576. write_to_version_file(target_versionfile, versions)
  1577. _py2exe.run(self)
  1578. os.unlink(target_versionfile)
  1579. with open(cfg.versionfile_source, "w") as f:
  1580. LONG = LONG_VERSION_PY[cfg.VCS]
  1581. f.write(LONG %
  1582. {"DOLLAR": "$",
  1583. "STYLE": cfg.style,
  1584. "TAG_PREFIX": cfg.tag_prefix,
  1585. "PARENTDIR_PREFIX": cfg.parentdir_prefix,
  1586. "VERSIONFILE_SOURCE": cfg.versionfile_source,
  1587. })
  1588. cmds["py2exe"] = cmd_py2exe
  1589. # we override different "sdist" commands for both environments
  1590. if 'sdist' in cmds:
  1591. _sdist = cmds['sdist']
  1592. elif "setuptools" in sys.modules:
  1593. from setuptools.command.sdist import sdist as _sdist
  1594. else:
  1595. from distutils.command.sdist import sdist as _sdist
  1596. class cmd_sdist(_sdist):
  1597. def run(self):
  1598. versions = get_versions()
  1599. self._versioneer_generated_versions = versions
  1600. # unless we update this, the command will keep using the old
  1601. # version
  1602. self.distribution.metadata.version = versions["version"]
  1603. return _sdist.run(self)
  1604. def make_release_tree(self, base_dir, files):
  1605. root = get_root()
  1606. cfg = get_config_from_root(root)
  1607. _sdist.make_release_tree(self, base_dir, files)
  1608. # now locate _version.py in the new base_dir directory
  1609. # (remembering that it may be a hardlink) and replace it with an
  1610. # updated value
  1611. target_versionfile = os.path.join(base_dir, cfg.versionfile_source)
  1612. print("UPDATING %s" % target_versionfile)
  1613. write_to_version_file(target_versionfile,
  1614. self._versioneer_generated_versions)
  1615. cmds["sdist"] = cmd_sdist
  1616. return cmds
  1617. CONFIG_ERROR = """
  1618. setup.cfg is missing the necessary Versioneer configuration. You need
  1619. a section like:
  1620. [versioneer]
  1621. VCS = git
  1622. style = pep440
  1623. versionfile_source = src/myproject/_version.py
  1624. versionfile_build = myproject/_version.py
  1625. tag_prefix =
  1626. parentdir_prefix = myproject-
  1627. You will also need to edit your setup.py to use the results:
  1628. import versioneer
  1629. setup(version=versioneer.get_version(),
  1630. cmdclass=versioneer.get_cmdclass(), ...)
  1631. Please read the docstring in ./versioneer.py for configuration instructions,
  1632. edit setup.cfg, and re-run the installer or 'python versioneer.py setup'.
  1633. """
  1634. SAMPLE_CONFIG = """
  1635. # See the docstring in versioneer.py for instructions. Note that you must
  1636. # re-run 'versioneer.py setup' after changing this section, and commit the
  1637. # resulting files.
  1638. [versioneer]
  1639. #VCS = git
  1640. #style = pep440
  1641. #versionfile_source =
  1642. #versionfile_build =
  1643. #tag_prefix =
  1644. #parentdir_prefix =
  1645. """
  1646. OLD_SNIPPET = """
  1647. from ._version import get_versions
  1648. __version__ = get_versions()['version']
  1649. del get_versions
  1650. """
  1651. INIT_PY_SNIPPET = """
  1652. from . import {0}
  1653. __version__ = {0}.get_versions()['version']
  1654. """
  1655. def do_setup():
  1656. """Do main VCS-independent setup function for installing Versioneer."""
  1657. root = get_root()
  1658. try:
  1659. cfg = get_config_from_root(root)
  1660. except (OSError, configparser.NoSectionError,
  1661. configparser.NoOptionError) as e:
  1662. if isinstance(e, (OSError, configparser.NoSectionError)):
  1663. print("Adding sample versioneer config to setup.cfg",
  1664. file=sys.stderr)
  1665. with open(os.path.join(root, "setup.cfg"), "a") as f:
  1666. f.write(SAMPLE_CONFIG)
  1667. print(CONFIG_ERROR, file=sys.stderr)
  1668. return 1
  1669. print(" creating %s" % cfg.versionfile_source)
  1670. with open(cfg.versionfile_source, "w") as f:
  1671. LONG = LONG_VERSION_PY[cfg.VCS]
  1672. f.write(LONG % {"DOLLAR": "$",
  1673. "STYLE": cfg.style,
  1674. "TAG_PREFIX": cfg.tag_prefix,
  1675. "PARENTDIR_PREFIX": cfg.parentdir_prefix,
  1676. "VERSIONFILE_SOURCE": cfg.versionfile_source,
  1677. })
  1678. ipy = os.path.join(os.path.dirname(cfg.versionfile_source),
  1679. "__init__.py")
  1680. if os.path.exists(ipy):
  1681. try:
  1682. with open(ipy, "r") as f:
  1683. old = f.read()
  1684. except OSError:
  1685. old = ""
  1686. module = os.path.splitext(os.path.basename(cfg.versionfile_source))[0]
  1687. snippet = INIT_PY_SNIPPET.format(module)
  1688. if OLD_SNIPPET in old:
  1689. print(" replacing boilerplate in %s" % ipy)
  1690. with open(ipy, "w") as f:
  1691. f.write(old.replace(OLD_SNIPPET, snippet))
  1692. elif snippet not in old:
  1693. print(" appending to %s" % ipy)
  1694. with open(ipy, "a") as f:
  1695. f.write(snippet)
  1696. else:
  1697. print(" %s unmodified" % ipy)
  1698. else:
  1699. print(" %s doesn't exist, ok" % ipy)
  1700. ipy = None
  1701. # Make sure both the top-level "versioneer.py" and versionfile_source
  1702. # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so
  1703. # they'll be copied into source distributions. Pip won't be able to
  1704. # install the package without this.
  1705. manifest_in = os.path.join(root, "MANIFEST.in")
  1706. simple_includes = set()
  1707. try:
  1708. with open(manifest_in, "r") as f:
  1709. for line in f:
  1710. if line.startswith("include "):
  1711. for include in line.split()[1:]:
  1712. simple_includes.add(include)
  1713. except OSError:
  1714. pass
  1715. # That doesn't cover everything MANIFEST.in can do
  1716. # (http://docs.python.org/2/distutils/sourcedist.html#commands), so
  1717. # it might give some false negatives. Appending redundant 'include'
  1718. # lines is safe, though.
  1719. if "versioneer.py" not in simple_includes:
  1720. print(" appending 'versioneer.py' to MANIFEST.in")
  1721. with open(manifest_in, "a") as f:
  1722. f.write("include versioneer.py\n")
  1723. else:
  1724. print(" 'versioneer.py' already in MANIFEST.in")
  1725. if cfg.versionfile_source not in simple_includes:
  1726. print(" appending versionfile_source ('%s') to MANIFEST.in" %
  1727. cfg.versionfile_source)
  1728. with open(manifest_in, "a") as f:
  1729. f.write("include %s\n" % cfg.versionfile_source)
  1730. else:
  1731. print(" versionfile_source already in MANIFEST.in")
  1732. # Make VCS-specific changes. For git, this means creating/changing
  1733. # .gitattributes to mark _version.py for export-subst keyword
  1734. # substitution.
  1735. do_vcs_install(manifest_in, cfg.versionfile_source, ipy)
  1736. return 0
  1737. def scan_setup_py():
  1738. """Validate the contents of setup.py against Versioneer's expectations."""
  1739. found = set()
  1740. setters = False
  1741. errors = 0
  1742. with open("setup.py", "r") as f:
  1743. for line in f.readlines():
  1744. if "import versioneer" in line:
  1745. found.add("import")
  1746. if "versioneer.get_cmdclass()" in line:
  1747. found.add("cmdclass")
  1748. if "versioneer.get_version()" in line:
  1749. found.add("get_version")
  1750. if "versioneer.VCS" in line:
  1751. setters = True
  1752. if "versioneer.versionfile_source" in line:
  1753. setters = True
  1754. if len(found) != 3:
  1755. print("")
  1756. print("Your setup.py appears to be missing some important items")
  1757. print("(but I might be wrong). Please make sure it has something")
  1758. print("roughly like the following:")
  1759. print("")
  1760. print(" import versioneer")
  1761. print(" setup( version=versioneer.get_version(),")
  1762. print(" cmdclass=versioneer.get_cmdclass(), ...)")
  1763. print("")
  1764. errors += 1
  1765. if setters:
  1766. print("You should remove lines like 'versioneer.VCS = ' and")
  1767. print("'versioneer.versionfile_source = ' . This configuration")
  1768. print("now lives in setup.cfg, and should be removed from setup.py")
  1769. print("")
  1770. errors += 1
  1771. return errors
  1772. if __name__ == "__main__":
  1773. cmd = sys.argv[1]
  1774. if cmd == "setup":
  1775. errors = do_setup()
  1776. errors += scan_setup_py()
  1777. if errors:
  1778. sys.exit(1)