versioneer.py 76 KB

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