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