You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

1823 lines
67 KiB

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