pull/1329/head
Timo Rothenpieler 2024-01-28 15:02:03 +01:00
rodzic 2eac520042
commit fa8394b09b
3 zmienionych plików z 291 dodań i 202 usunięć

Wyświetl plik

@ -3,7 +3,7 @@ from ._version import get_versions
__version__ = get_versions()["version"] __version__ = get_versions()["version"]
del get_versions del get_versions
from . import _version
from .app import Repo2Docker from .app import Repo2Docker
from . import _version __version__ = _version.get_versions()["version"]
__version__ = _version.get_versions()['version']

Wyświetl plik

@ -1,4 +1,3 @@
# This file helps to compute a version number in source trees obtained from # This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag # git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build # feature). Distribution tarballs (built by setup.py sdist) and build
@ -12,12 +11,12 @@
"""Git implementation of _version.py.""" """Git implementation of _version.py."""
import errno import errno
import functools
import os import os
import re import re
import subprocess import subprocess
import sys import sys
from typing import Any, Callable, Dict, List, Optional, Tuple from typing import Any, Callable, Dict, List, Optional, Tuple
import functools
def get_keywords() -> Dict[str, str]: def get_keywords() -> Dict[str, str]:
@ -68,12 +67,14 @@ HANDLERS: Dict[str, Dict[str, Callable]] = {}
def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator
"""Create decorator to mark a method as the handler of a VCS.""" """Create decorator to mark a method as the handler of a VCS."""
def decorate(f: Callable) -> Callable: def decorate(f: Callable) -> Callable:
"""Store f in HANDLERS[vcs][method].""" """Store f in HANDLERS[vcs][method]."""
if vcs not in HANDLERS: if vcs not in HANDLERS:
HANDLERS[vcs] = {} HANDLERS[vcs] = {}
HANDLERS[vcs][method] = f HANDLERS[vcs][method] = f
return f return f
return decorate return decorate
@ -100,10 +101,14 @@ def run_command(
try: try:
dispcmd = str([command] + args) dispcmd = str([command] + args)
# remember shell=False, so use git.cmd on windows, not just git # remember shell=False, so use git.cmd on windows, not just git
process = subprocess.Popen([command] + args, cwd=cwd, env=env, process = subprocess.Popen(
stdout=subprocess.PIPE, [command] + args,
stderr=(subprocess.PIPE if hide_stderr cwd=cwd,
else None), **popen_kwargs) env=env,
stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr else None),
**popen_kwargs,
)
break break
except OSError as e: except OSError as e:
if e.errno == errno.ENOENT: if e.errno == errno.ENOENT:
@ -114,7 +119,7 @@ def run_command(
return None, None return None, None
else: else:
if verbose: if verbose:
print("unable to find command, tried %s" % (commands,)) print("unable to find command, tried {}".format(commands))
return None, None return None, None
stdout = process.communicate()[0].strip().decode() stdout = process.communicate()[0].strip().decode()
if process.returncode != 0: if process.returncode != 0:
@ -141,15 +146,21 @@ def versions_from_parentdir(
for _ in range(3): for _ in range(3):
dirname = os.path.basename(root) dirname = os.path.basename(root)
if dirname.startswith(parentdir_prefix): if dirname.startswith(parentdir_prefix):
return {"version": dirname[len(parentdir_prefix):], return {
"full-revisionid": None, "version": dirname[len(parentdir_prefix) :],
"dirty": False, "error": None, "date": None} "full-revisionid": None,
"dirty": False,
"error": None,
"date": None,
}
rootdirs.append(root) rootdirs.append(root)
root = os.path.dirname(root) # up a level root = os.path.dirname(root) # up a level
if verbose: if verbose:
print("Tried directories %s but none started with prefix %s" % print(
(str(rootdirs), parentdir_prefix)) "Tried directories %s but none started with prefix %s"
% (str(rootdirs), parentdir_prefix)
)
raise NotThisMethod("rootdir doesn't start with parentdir_prefix") raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
@ -162,7 +173,7 @@ def git_get_keywords(versionfile_abs: str) -> Dict[str, str]:
# _version.py. # _version.py.
keywords: Dict[str, str] = {} keywords: Dict[str, str] = {}
try: try:
with open(versionfile_abs, "r") as fobj: with open(versionfile_abs) as fobj:
for line in fobj: for line in fobj:
if line.strip().startswith("git_refnames ="): if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line) mo = re.search(r'=\s*"(.*)"', line)
@ -212,7 +223,7 @@ def git_versions_from_keywords(
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
# just "foo-1.0". If we see a "tag: " prefix, prefer those. # just "foo-1.0". If we see a "tag: " prefix, prefer those.
TAG = "tag: " TAG = "tag: "
tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)}
if not tags: if not tags:
# Either we're using git < 1.8.3, or there really are no tags. We use # Either we're using git < 1.8.3, or there really are no tags. We use
# a heuristic: assume all version tags have a digit. The old git %d # a heuristic: assume all version tags have a digit. The old git %d
@ -221,7 +232,7 @@ def git_versions_from_keywords(
# between branches and tags. By ignoring refnames without digits, we # between branches and tags. By ignoring refnames without digits, we
# filter out many common branch names like "release" and # filter out many common branch names like "release" and
# "stabilization", as well as "HEAD" and "master". # "stabilization", as well as "HEAD" and "master".
tags = {r for r in refs if re.search(r'\d', r)} tags = {r for r in refs if re.search(r"\d", r)}
if verbose: if verbose:
print("discarding '%s', no digits" % ",".join(refs - tags)) print("discarding '%s', no digits" % ",".join(refs - tags))
if verbose: if verbose:
@ -229,32 +240,36 @@ def git_versions_from_keywords(
for ref in sorted(tags): for ref in sorted(tags):
# sorting will prefer e.g. "2.0" over "2.0rc1" # sorting will prefer e.g. "2.0" over "2.0rc1"
if ref.startswith(tag_prefix): if ref.startswith(tag_prefix):
r = ref[len(tag_prefix):] r = ref[len(tag_prefix) :]
# Filter out refs that exactly match prefix or that don't start # Filter out refs that exactly match prefix or that don't start
# with a number once the prefix is stripped (mostly a concern # with a number once the prefix is stripped (mostly a concern
# when prefix is '') # when prefix is '')
if not re.match(r'\d', r): if not re.match(r"\d", r):
continue continue
if verbose: if verbose:
print("picking %s" % r) print("picking %s" % r)
return {"version": r, return {
"full-revisionid": keywords["full"].strip(), "version": r,
"dirty": False, "error": None, "full-revisionid": keywords["full"].strip(),
"date": date} "dirty": False,
"error": None,
"date": date,
}
# no suitable tags, so version is "0+unknown", but full hex is still there # no suitable tags, so version is "0+unknown", but full hex is still there
if verbose: if verbose:
print("no suitable tags, using unknown + full revision id") print("no suitable tags, using unknown + full revision id")
return {"version": "0+unknown", return {
"full-revisionid": keywords["full"].strip(), "version": "0+unknown",
"dirty": False, "error": "no suitable tags", "date": None} "full-revisionid": keywords["full"].strip(),
"dirty": False,
"error": "no suitable tags",
"date": None,
}
@register_vcs_handler("git", "pieces_from_vcs") @register_vcs_handler("git", "pieces_from_vcs")
def git_pieces_from_vcs( def git_pieces_from_vcs(
tag_prefix: str, tag_prefix: str, root: str, verbose: bool, runner: Callable = run_command
root: str,
verbose: bool,
runner: Callable = run_command
) -> Dict[str, Any]: ) -> Dict[str, Any]:
"""Get version from 'git describe' in the root of the source tree. """Get version from 'git describe' in the root of the source tree.
@ -273,8 +288,7 @@ def git_pieces_from_vcs(
env.pop("GIT_DIR", None) env.pop("GIT_DIR", None)
runner = functools.partial(runner, env=env) runner = functools.partial(runner, env=env)
_, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=not verbose)
hide_stderr=not verbose)
if rc != 0: if rc != 0:
if verbose: if verbose:
print("Directory %s not under git control" % root) print("Directory %s not under git control" % root)
@ -282,10 +296,19 @@ def git_pieces_from_vcs(
# if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
# if there isn't one, this yields HEX[-dirty] (no NUM) # if there isn't one, this yields HEX[-dirty] (no NUM)
describe_out, rc = runner(GITS, [ describe_out, rc = runner(
"describe", "--tags", "--dirty", "--always", "--long", GITS,
"--match", f"{tag_prefix}[[:digit:]]*" [
], cwd=root) "describe",
"--tags",
"--dirty",
"--always",
"--long",
"--match",
f"{tag_prefix}[[:digit:]]*",
],
cwd=root,
)
# --long was added in git-1.5.5 # --long was added in git-1.5.5
if describe_out is None: if describe_out is None:
raise NotThisMethod("'git describe' failed") raise NotThisMethod("'git describe' failed")
@ -300,8 +323,7 @@ def git_pieces_from_vcs(
pieces["short"] = full_out[:7] # maybe improved later pieces["short"] = full_out[:7] # maybe improved later
pieces["error"] = None pieces["error"] = None
branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
cwd=root)
# --abbrev-ref was added in git-1.6.3 # --abbrev-ref was added in git-1.6.3
if rc != 0 or branch_name is None: if rc != 0 or branch_name is None:
raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") raise NotThisMethod("'git rev-parse --abbrev-ref' returned error")
@ -341,17 +363,16 @@ def git_pieces_from_vcs(
dirty = git_describe.endswith("-dirty") dirty = git_describe.endswith("-dirty")
pieces["dirty"] = dirty pieces["dirty"] = dirty
if dirty: if dirty:
git_describe = git_describe[:git_describe.rindex("-dirty")] git_describe = git_describe[: git_describe.rindex("-dirty")]
# now we have TAG-NUM-gHEX or HEX # now we have TAG-NUM-gHEX or HEX
if "-" in git_describe: if "-" in git_describe:
# TAG-NUM-gHEX # TAG-NUM-gHEX
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe)
if not mo: if not mo:
# unparsable. Maybe git-describe is misbehaving? # unparsable. Maybe git-describe is misbehaving?
pieces["error"] = ("unable to parse git-describe output: '%s'" pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out
% describe_out)
return pieces return pieces
# tag # tag
@ -360,10 +381,12 @@ def git_pieces_from_vcs(
if verbose: if verbose:
fmt = "tag '%s' doesn't start with prefix '%s'" fmt = "tag '%s' doesn't start with prefix '%s'"
print(fmt % (full_tag, tag_prefix)) print(fmt % (full_tag, tag_prefix))
pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
% (full_tag, tag_prefix)) full_tag,
tag_prefix,
)
return pieces return pieces
pieces["closest-tag"] = full_tag[len(tag_prefix):] pieces["closest-tag"] = full_tag[len(tag_prefix) :]
# distance: number of commits since tag # distance: number of commits since tag
pieces["distance"] = int(mo.group(2)) pieces["distance"] = int(mo.group(2))
@ -412,8 +435,7 @@ def render_pep440(pieces: Dict[str, Any]) -> str:
rendered += ".dirty" rendered += ".dirty"
else: else:
# exception #1 # exception #1
rendered = "0+untagged.%d.g%s" % (pieces["distance"], rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
pieces["short"])
if pieces["dirty"]: if pieces["dirty"]:
rendered += ".dirty" rendered += ".dirty"
return rendered return rendered
@ -442,8 +464,7 @@ def render_pep440_branch(pieces: Dict[str, Any]) -> str:
rendered = "0" rendered = "0"
if pieces["branch"] != "master": if pieces["branch"] != "master":
rendered += ".dev0" rendered += ".dev0"
rendered += "+untagged.%d.g%s" % (pieces["distance"], rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
pieces["short"])
if pieces["dirty"]: if pieces["dirty"]:
rendered += ".dirty" rendered += ".dirty"
return rendered return rendered
@ -604,11 +625,13 @@ def render_git_describe_long(pieces: Dict[str, Any]) -> str:
def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]:
"""Render the given version pieces into the requested style.""" """Render the given version pieces into the requested style."""
if pieces["error"]: if pieces["error"]:
return {"version": "unknown", return {
"full-revisionid": pieces.get("long"), "version": "unknown",
"dirty": None, "full-revisionid": pieces.get("long"),
"error": pieces["error"], "dirty": None,
"date": None} "error": pieces["error"],
"date": None,
}
if not style or style == "default": if not style or style == "default":
style = "pep440" # the default style = "pep440" # the default
@ -632,9 +655,13 @@ def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]:
else: else:
raise ValueError("unknown style '%s'" % style) raise ValueError("unknown style '%s'" % style)
return {"version": rendered, "full-revisionid": pieces["long"], return {
"dirty": pieces["dirty"], "error": None, "version": rendered,
"date": pieces.get("date")} "full-revisionid": pieces["long"],
"dirty": pieces["dirty"],
"error": None,
"date": pieces.get("date"),
}
def get_versions() -> Dict[str, Any]: def get_versions() -> Dict[str, Any]:
@ -648,8 +675,7 @@ def get_versions() -> Dict[str, Any]:
verbose = cfg.verbose verbose = cfg.verbose
try: try:
return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose)
verbose)
except NotThisMethod: except NotThisMethod:
pass pass
@ -658,13 +684,16 @@ def get_versions() -> Dict[str, Any]:
# versionfile_source is the relative path from the top of the source # versionfile_source is the relative path from the top of the source
# tree (where the .git directory might live) to this file. Invert # tree (where the .git directory might live) to this file. Invert
# this to find the root from __file__. # this to find the root from __file__.
for _ in cfg.versionfile_source.split('/'): for _ in cfg.versionfile_source.split("/"):
root = os.path.dirname(root) root = os.path.dirname(root)
except NameError: except NameError:
return {"version": "0+unknown", "full-revisionid": None, return {
"dirty": None, "version": "0+unknown",
"error": "unable to find root of source tree", "full-revisionid": None,
"date": None} "dirty": None,
"error": "unable to find root of source tree",
"date": None,
}
try: try:
pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
@ -678,6 +707,10 @@ def get_versions() -> Dict[str, Any]:
except NotThisMethod: except NotThisMethod:
pass pass
return {"version": "0+unknown", "full-revisionid": None, return {
"dirty": None, "version": "0+unknown",
"error": "unable to compute version", "date": None} "full-revisionid": None,
"dirty": None,
"error": "unable to compute version",
"date": None,
}

Wyświetl plik

@ -1,4 +1,3 @@
# Version: 0.29 # Version: 0.29
"""The Versioneer - like a rocketeer, but for versions. """The Versioneer - like a rocketeer, but for versions.
@ -310,15 +309,14 @@ https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg
import configparser import configparser
import errno import errno
import functools
import json import json
import os import os
import re import re
import subprocess import subprocess
import sys import sys
from pathlib import Path from pathlib import Path
from typing import Any, Callable, cast, Dict, List, Optional, Tuple, Union from typing import Any, Callable, Dict, List, NoReturn, Optional, Tuple, Union, cast
from typing import NoReturn
import functools
have_tomllib = True have_tomllib = True
if sys.version_info >= (3, 11): if sys.version_info >= (3, 11):
@ -367,11 +365,13 @@ def get_root() -> str:
or os.path.exists(pyproject_toml) or os.path.exists(pyproject_toml)
or os.path.exists(versioneer_py) or os.path.exists(versioneer_py)
): ):
err = ("Versioneer was unable to run the project root directory. " err = (
"Versioneer requires setup.py to be executed from " "Versioneer was unable to run the project root directory. "
"its immediate directory (like 'python setup.py COMMAND'), " "Versioneer requires setup.py to be executed from "
"or in a way that lets it use sys.argv[0] to find the root " "its immediate directory (like 'python setup.py COMMAND'), "
"(like 'python path/to/setup.py COMMAND').") "or in a way that lets it use sys.argv[0] to find the root "
"(like 'python path/to/setup.py COMMAND')."
)
raise VersioneerBadRootError(err) raise VersioneerBadRootError(err)
try: try:
# Certain runtime workflows (setup.py install/develop in a setuptools # Certain runtime workflows (setup.py install/develop in a setuptools
@ -384,8 +384,10 @@ def get_root() -> str:
me_dir = os.path.normcase(os.path.splitext(my_path)[0]) me_dir = os.path.normcase(os.path.splitext(my_path)[0])
vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0])
if me_dir != vsr_dir and "VERSIONEER_PEP518" not in globals(): if me_dir != vsr_dir and "VERSIONEER_PEP518" not in globals():
print("Warning: build in %s is using versioneer.py from %s" print(
% (os.path.dirname(my_path), versioneer_py)) "Warning: build in %s is using versioneer.py from %s"
% (os.path.dirname(my_path), versioneer_py)
)
except NameError: except NameError:
pass pass
return root return root
@ -403,9 +405,9 @@ def get_config_from_root(root: str) -> VersioneerConfig:
section: Union[Dict[str, Any], configparser.SectionProxy, None] = None section: Union[Dict[str, Any], configparser.SectionProxy, None] = None
if pyproject_toml.exists() and have_tomllib: if pyproject_toml.exists() and have_tomllib:
try: try:
with open(pyproject_toml, 'rb') as fobj: with open(pyproject_toml, "rb") as fobj:
pp = tomllib.load(fobj) pp = tomllib.load(fobj)
section = pp['tool']['versioneer'] section = pp["tool"]["versioneer"]
except (tomllib.TOMLDecodeError, KeyError) as e: except (tomllib.TOMLDecodeError, KeyError) as e:
print(f"Failed to load config from {pyproject_toml}: {e}") print(f"Failed to load config from {pyproject_toml}: {e}")
print("Try to load it from setup.cfg") print("Try to load it from setup.cfg")
@ -422,7 +424,7 @@ def get_config_from_root(root: str) -> VersioneerConfig:
# `None` values elsewhere where it matters # `None` values elsewhere where it matters
cfg = VersioneerConfig() cfg = VersioneerConfig()
cfg.VCS = section['VCS'] cfg.VCS = section["VCS"]
cfg.style = section.get("style", "") cfg.style = section.get("style", "")
cfg.versionfile_source = cast(str, section.get("versionfile_source")) cfg.versionfile_source = cast(str, section.get("versionfile_source"))
cfg.versionfile_build = section.get("versionfile_build") cfg.versionfile_build = section.get("versionfile_build")
@ -450,10 +452,12 @@ HANDLERS: Dict[str, Dict[str, Callable]] = {}
def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator
"""Create decorator to mark a method as the handler of a VCS.""" """Create decorator to mark a method as the handler of a VCS."""
def decorate(f: Callable) -> Callable: def decorate(f: Callable) -> Callable:
"""Store f in HANDLERS[vcs][method].""" """Store f in HANDLERS[vcs][method]."""
HANDLERS.setdefault(vcs, {})[method] = f HANDLERS.setdefault(vcs, {})[method] = f
return f return f
return decorate return decorate
@ -480,10 +484,14 @@ def run_command(
try: try:
dispcmd = str([command] + args) dispcmd = str([command] + args)
# remember shell=False, so use git.cmd on windows, not just git # remember shell=False, so use git.cmd on windows, not just git
process = subprocess.Popen([command] + args, cwd=cwd, env=env, process = subprocess.Popen(
stdout=subprocess.PIPE, [command] + args,
stderr=(subprocess.PIPE if hide_stderr cwd=cwd,
else None), **popen_kwargs) env=env,
stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr else None),
**popen_kwargs,
)
break break
except OSError as e: except OSError as e:
if e.errno == errno.ENOENT: if e.errno == errno.ENOENT:
@ -494,7 +502,7 @@ def run_command(
return None, None return None, None
else: else:
if verbose: if verbose:
print("unable to find command, tried %s" % (commands,)) print("unable to find command, tried {}".format(commands))
return None, None return None, None
stdout = process.communicate()[0].strip().decode() stdout = process.communicate()[0].strip().decode()
if process.returncode != 0: if process.returncode != 0:
@ -505,7 +513,9 @@ def run_command(
return stdout, process.returncode return stdout, process.returncode
LONG_VERSION_PY['git'] = r''' LONG_VERSION_PY[
"git"
] = r'''
# This file helps to compute a version number in source trees obtained from # This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag # git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build # feature). Distribution tarballs (built by setup.py sdist) and build
@ -1200,7 +1210,7 @@ def git_get_keywords(versionfile_abs: str) -> Dict[str, str]:
# _version.py. # _version.py.
keywords: Dict[str, str] = {} keywords: Dict[str, str] = {}
try: try:
with open(versionfile_abs, "r") as fobj: with open(versionfile_abs) as fobj:
for line in fobj: for line in fobj:
if line.strip().startswith("git_refnames ="): if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line) mo = re.search(r'=\s*"(.*)"', line)
@ -1250,7 +1260,7 @@ def git_versions_from_keywords(
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
# just "foo-1.0". If we see a "tag: " prefix, prefer those. # just "foo-1.0". If we see a "tag: " prefix, prefer those.
TAG = "tag: " TAG = "tag: "
tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)}
if not tags: if not tags:
# Either we're using git < 1.8.3, or there really are no tags. We use # Either we're using git < 1.8.3, or there really are no tags. We use
# a heuristic: assume all version tags have a digit. The old git %d # a heuristic: assume all version tags have a digit. The old git %d
@ -1259,7 +1269,7 @@ def git_versions_from_keywords(
# between branches and tags. By ignoring refnames without digits, we # between branches and tags. By ignoring refnames without digits, we
# filter out many common branch names like "release" and # filter out many common branch names like "release" and
# "stabilization", as well as "HEAD" and "master". # "stabilization", as well as "HEAD" and "master".
tags = {r for r in refs if re.search(r'\d', r)} tags = {r for r in refs if re.search(r"\d", r)}
if verbose: if verbose:
print("discarding '%s', no digits" % ",".join(refs - tags)) print("discarding '%s', no digits" % ",".join(refs - tags))
if verbose: if verbose:
@ -1267,32 +1277,36 @@ def git_versions_from_keywords(
for ref in sorted(tags): for ref in sorted(tags):
# sorting will prefer e.g. "2.0" over "2.0rc1" # sorting will prefer e.g. "2.0" over "2.0rc1"
if ref.startswith(tag_prefix): if ref.startswith(tag_prefix):
r = ref[len(tag_prefix):] r = ref[len(tag_prefix) :]
# Filter out refs that exactly match prefix or that don't start # Filter out refs that exactly match prefix or that don't start
# with a number once the prefix is stripped (mostly a concern # with a number once the prefix is stripped (mostly a concern
# when prefix is '') # when prefix is '')
if not re.match(r'\d', r): if not re.match(r"\d", r):
continue continue
if verbose: if verbose:
print("picking %s" % r) print("picking %s" % r)
return {"version": r, return {
"full-revisionid": keywords["full"].strip(), "version": r,
"dirty": False, "error": None, "full-revisionid": keywords["full"].strip(),
"date": date} "dirty": False,
"error": None,
"date": date,
}
# no suitable tags, so version is "0+unknown", but full hex is still there # no suitable tags, so version is "0+unknown", but full hex is still there
if verbose: if verbose:
print("no suitable tags, using unknown + full revision id") print("no suitable tags, using unknown + full revision id")
return {"version": "0+unknown", return {
"full-revisionid": keywords["full"].strip(), "version": "0+unknown",
"dirty": False, "error": "no suitable tags", "date": None} "full-revisionid": keywords["full"].strip(),
"dirty": False,
"error": "no suitable tags",
"date": None,
}
@register_vcs_handler("git", "pieces_from_vcs") @register_vcs_handler("git", "pieces_from_vcs")
def git_pieces_from_vcs( def git_pieces_from_vcs(
tag_prefix: str, tag_prefix: str, root: str, verbose: bool, runner: Callable = run_command
root: str,
verbose: bool,
runner: Callable = run_command
) -> Dict[str, Any]: ) -> Dict[str, Any]:
"""Get version from 'git describe' in the root of the source tree. """Get version from 'git describe' in the root of the source tree.
@ -1311,8 +1325,7 @@ def git_pieces_from_vcs(
env.pop("GIT_DIR", None) env.pop("GIT_DIR", None)
runner = functools.partial(runner, env=env) runner = functools.partial(runner, env=env)
_, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=not verbose)
hide_stderr=not verbose)
if rc != 0: if rc != 0:
if verbose: if verbose:
print("Directory %s not under git control" % root) print("Directory %s not under git control" % root)
@ -1320,10 +1333,19 @@ def git_pieces_from_vcs(
# if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
# if there isn't one, this yields HEX[-dirty] (no NUM) # if there isn't one, this yields HEX[-dirty] (no NUM)
describe_out, rc = runner(GITS, [ describe_out, rc = runner(
"describe", "--tags", "--dirty", "--always", "--long", GITS,
"--match", f"{tag_prefix}[[:digit:]]*" [
], cwd=root) "describe",
"--tags",
"--dirty",
"--always",
"--long",
"--match",
f"{tag_prefix}[[:digit:]]*",
],
cwd=root,
)
# --long was added in git-1.5.5 # --long was added in git-1.5.5
if describe_out is None: if describe_out is None:
raise NotThisMethod("'git describe' failed") raise NotThisMethod("'git describe' failed")
@ -1338,8 +1360,7 @@ def git_pieces_from_vcs(
pieces["short"] = full_out[:7] # maybe improved later pieces["short"] = full_out[:7] # maybe improved later
pieces["error"] = None pieces["error"] = None
branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
cwd=root)
# --abbrev-ref was added in git-1.6.3 # --abbrev-ref was added in git-1.6.3
if rc != 0 or branch_name is None: if rc != 0 or branch_name is None:
raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") raise NotThisMethod("'git rev-parse --abbrev-ref' returned error")
@ -1379,17 +1400,16 @@ def git_pieces_from_vcs(
dirty = git_describe.endswith("-dirty") dirty = git_describe.endswith("-dirty")
pieces["dirty"] = dirty pieces["dirty"] = dirty
if dirty: if dirty:
git_describe = git_describe[:git_describe.rindex("-dirty")] git_describe = git_describe[: git_describe.rindex("-dirty")]
# now we have TAG-NUM-gHEX or HEX # now we have TAG-NUM-gHEX or HEX
if "-" in git_describe: if "-" in git_describe:
# TAG-NUM-gHEX # TAG-NUM-gHEX
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe)
if not mo: if not mo:
# unparsable. Maybe git-describe is misbehaving? # unparsable. Maybe git-describe is misbehaving?
pieces["error"] = ("unable to parse git-describe output: '%s'" pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out
% describe_out)
return pieces return pieces
# tag # tag
@ -1398,10 +1418,12 @@ def git_pieces_from_vcs(
if verbose: if verbose:
fmt = "tag '%s' doesn't start with prefix '%s'" fmt = "tag '%s' doesn't start with prefix '%s'"
print(fmt % (full_tag, tag_prefix)) print(fmt % (full_tag, tag_prefix))
pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
% (full_tag, tag_prefix)) full_tag,
tag_prefix,
)
return pieces return pieces
pieces["closest-tag"] = full_tag[len(tag_prefix):] pieces["closest-tag"] = full_tag[len(tag_prefix) :]
# distance: number of commits since tag # distance: number of commits since tag
pieces["distance"] = int(mo.group(2)) pieces["distance"] = int(mo.group(2))
@ -1448,7 +1470,7 @@ def do_vcs_install(versionfile_source: str, ipy: Optional[str]) -> None:
files.append(versioneer_file) files.append(versioneer_file)
present = False present = False
try: try:
with open(".gitattributes", "r") as fobj: with open(".gitattributes") as fobj:
for line in fobj: for line in fobj:
if line.strip().startswith(versionfile_source): if line.strip().startswith(versionfile_source):
if "export-subst" in line.strip().split()[1:]: if "export-subst" in line.strip().split()[1:]:
@ -1479,15 +1501,21 @@ def versions_from_parentdir(
for _ in range(3): for _ in range(3):
dirname = os.path.basename(root) dirname = os.path.basename(root)
if dirname.startswith(parentdir_prefix): if dirname.startswith(parentdir_prefix):
return {"version": dirname[len(parentdir_prefix):], return {
"full-revisionid": None, "version": dirname[len(parentdir_prefix) :],
"dirty": False, "error": None, "date": None} "full-revisionid": None,
"dirty": False,
"error": None,
"date": None,
}
rootdirs.append(root) rootdirs.append(root)
root = os.path.dirname(root) # up a level root = os.path.dirname(root) # up a level
if verbose: if verbose:
print("Tried directories %s but none started with prefix %s" % print(
(str(rootdirs), parentdir_prefix)) "Tried directories %s but none started with prefix %s"
% (str(rootdirs), parentdir_prefix)
)
raise NotThisMethod("rootdir doesn't start with parentdir_prefix") raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
@ -1516,11 +1544,13 @@ def versions_from_file(filename: str) -> Dict[str, Any]:
contents = f.read() contents = f.read()
except OSError: except OSError:
raise NotThisMethod("unable to read _version.py") raise NotThisMethod("unable to read _version.py")
mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", mo = re.search(
contents, re.M | re.S) r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S
)
if not mo: if not mo:
mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", mo = re.search(
contents, re.M | re.S) r"version_json = '''\r\n(.*)''' # END VERSION_JSON", contents, re.M | re.S
)
if not mo: if not mo:
raise NotThisMethod("no version_json in _version.py") raise NotThisMethod("no version_json in _version.py")
return json.loads(mo.group(1)) return json.loads(mo.group(1))
@ -1528,12 +1558,11 @@ def versions_from_file(filename: str) -> Dict[str, Any]:
def write_to_version_file(filename: str, versions: Dict[str, Any]) -> None: def write_to_version_file(filename: str, versions: Dict[str, Any]) -> None:
"""Write the given version number to the given _version.py file.""" """Write the given version number to the given _version.py file."""
contents = json.dumps(versions, sort_keys=True, contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": "))
indent=1, separators=(",", ": "))
with open(filename, "w") as f: with open(filename, "w") as f:
f.write(SHORT_VERSION_PY % contents) f.write(SHORT_VERSION_PY % contents)
print("set %s to '%s'" % (filename, versions["version"])) print("set {} to '{}'".format(filename, versions["version"]))
def plus_or_dot(pieces: Dict[str, Any]) -> str: def plus_or_dot(pieces: Dict[str, Any]) -> str:
@ -1561,8 +1590,7 @@ def render_pep440(pieces: Dict[str, Any]) -> str:
rendered += ".dirty" rendered += ".dirty"
else: else:
# exception #1 # exception #1
rendered = "0+untagged.%d.g%s" % (pieces["distance"], rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
pieces["short"])
if pieces["dirty"]: if pieces["dirty"]:
rendered += ".dirty" rendered += ".dirty"
return rendered return rendered
@ -1591,8 +1619,7 @@ def render_pep440_branch(pieces: Dict[str, Any]) -> str:
rendered = "0" rendered = "0"
if pieces["branch"] != "master": if pieces["branch"] != "master":
rendered += ".dev0" rendered += ".dev0"
rendered += "+untagged.%d.g%s" % (pieces["distance"], rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
pieces["short"])
if pieces["dirty"]: if pieces["dirty"]:
rendered += ".dirty" rendered += ".dirty"
return rendered return rendered
@ -1753,11 +1780,13 @@ def render_git_describe_long(pieces: Dict[str, Any]) -> str:
def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]:
"""Render the given version pieces into the requested style.""" """Render the given version pieces into the requested style."""
if pieces["error"]: if pieces["error"]:
return {"version": "unknown", return {
"full-revisionid": pieces.get("long"), "version": "unknown",
"dirty": None, "full-revisionid": pieces.get("long"),
"error": pieces["error"], "dirty": None,
"date": None} "error": pieces["error"],
"date": None,
}
if not style or style == "default": if not style or style == "default":
style = "pep440" # the default style = "pep440" # the default
@ -1781,9 +1810,13 @@ def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]:
else: else:
raise ValueError("unknown style '%s'" % style) raise ValueError("unknown style '%s'" % style)
return {"version": rendered, "full-revisionid": pieces["long"], return {
"dirty": pieces["dirty"], "error": None, "version": rendered,
"date": pieces.get("date")} "full-revisionid": pieces["long"],
"dirty": pieces["dirty"],
"error": None,
"date": pieces.get("date"),
}
class VersioneerBadRootError(Exception): class VersioneerBadRootError(Exception):
@ -1806,8 +1839,9 @@ def get_versions(verbose: bool = False) -> Dict[str, Any]:
handlers = HANDLERS.get(cfg.VCS) handlers = HANDLERS.get(cfg.VCS)
assert handlers, "unrecognized VCS '%s'" % cfg.VCS assert handlers, "unrecognized VCS '%s'" % cfg.VCS
verbose = verbose or bool(cfg.verbose) # `bool()` used to avoid `None` verbose = verbose or bool(cfg.verbose) # `bool()` used to avoid `None`
assert cfg.versionfile_source is not None, \ assert (
"please set versioneer.versionfile_source" cfg.versionfile_source is not None
), "please set versioneer.versionfile_source"
assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix"
versionfile_abs = os.path.join(root, cfg.versionfile_source) versionfile_abs = os.path.join(root, cfg.versionfile_source)
@ -1833,7 +1867,7 @@ def get_versions(verbose: bool = False) -> Dict[str, Any]:
try: try:
ver = versions_from_file(versionfile_abs) ver = versions_from_file(versionfile_abs)
if verbose: if verbose:
print("got version from file %s %s" % (versionfile_abs, ver)) print("got version from file {} {}".format(versionfile_abs, ver))
return ver return ver
except NotThisMethod: except NotThisMethod:
pass pass
@ -1861,9 +1895,13 @@ def get_versions(verbose: bool = False) -> Dict[str, Any]:
if verbose: if verbose:
print("unable to compute version") print("unable to compute version")
return {"version": "0+unknown", "full-revisionid": None, return {
"dirty": None, "error": "unable to compute version", "version": "0+unknown",
"date": None} "full-revisionid": None,
"dirty": None,
"error": "unable to compute version",
"date": None,
}
def get_version() -> str: def get_version() -> str:
@ -1916,6 +1954,7 @@ def get_cmdclass(cmdclass: Optional[Dict[str, Any]] = None):
print(" date: %s" % vers.get("date")) print(" date: %s" % vers.get("date"))
if vers["error"]: if vers["error"]:
print(" error: %s" % vers["error"]) print(" error: %s" % vers["error"])
cmds["version"] = cmd_version cmds["version"] = cmd_version
# we override "build_py" in setuptools # we override "build_py" in setuptools
@ -1937,8 +1976,8 @@ def get_cmdclass(cmdclass: Optional[Dict[str, Any]] = None):
# but the build_py command is not expected to copy any files. # but the build_py command is not expected to copy any files.
# we override different "build_py" commands for both environments # we override different "build_py" commands for both environments
if 'build_py' in cmds: if "build_py" in cmds:
_build_py: Any = cmds['build_py'] _build_py: Any = cmds["build_py"]
else: else:
from setuptools.command.build_py import build_py as _build_py from setuptools.command.build_py import build_py as _build_py
@ -1955,14 +1994,14 @@ def get_cmdclass(cmdclass: Optional[Dict[str, Any]] = None):
# now locate _version.py in the new build/ directory and replace # now locate _version.py in the new build/ directory and replace
# it with an updated value # it with an updated value
if cfg.versionfile_build: if cfg.versionfile_build:
target_versionfile = os.path.join(self.build_lib, target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build)
cfg.versionfile_build)
print("UPDATING %s" % target_versionfile) print("UPDATING %s" % target_versionfile)
write_to_version_file(target_versionfile, versions) write_to_version_file(target_versionfile, versions)
cmds["build_py"] = cmd_build_py cmds["build_py"] = cmd_build_py
if 'build_ext' in cmds: if "build_ext" in cmds:
_build_ext: Any = cmds['build_ext'] _build_ext: Any = cmds["build_ext"]
else: else:
from setuptools.command.build_ext import build_ext as _build_ext from setuptools.command.build_ext import build_ext as _build_ext
@ -1982,19 +2021,22 @@ def get_cmdclass(cmdclass: Optional[Dict[str, Any]] = None):
# it with an updated value # it with an updated value
if not cfg.versionfile_build: if not cfg.versionfile_build:
return return
target_versionfile = os.path.join(self.build_lib, target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build)
cfg.versionfile_build)
if not os.path.exists(target_versionfile): if not os.path.exists(target_versionfile):
print(f"Warning: {target_versionfile} does not exist, skipping " print(
"version update. This can happen if you are running build_ext " f"Warning: {target_versionfile} does not exist, skipping "
"without first running build_py.") "version update. This can happen if you are running build_ext "
"without first running build_py."
)
return return
print("UPDATING %s" % target_versionfile) print("UPDATING %s" % target_versionfile)
write_to_version_file(target_versionfile, versions) write_to_version_file(target_versionfile, versions)
cmds["build_ext"] = cmd_build_ext cmds["build_ext"] = cmd_build_ext
if "cx_Freeze" in sys.modules: # cx_freeze enabled? if "cx_Freeze" in sys.modules: # cx_freeze enabled?
from cx_Freeze.dist import build_exe as _build_exe # type: ignore from cx_Freeze.dist import build_exe as _build_exe # type: ignore
# nczeczulin reports that py2exe won't like the pep440-style string # nczeczulin reports that py2exe won't like the pep440-style string
# as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g.
# setup(console=[{ # setup(console=[{
@ -2015,17 +2057,21 @@ def get_cmdclass(cmdclass: Optional[Dict[str, Any]] = None):
os.unlink(target_versionfile) os.unlink(target_versionfile)
with open(cfg.versionfile_source, "w") as f: with open(cfg.versionfile_source, "w") as f:
LONG = LONG_VERSION_PY[cfg.VCS] LONG = LONG_VERSION_PY[cfg.VCS]
f.write(LONG % f.write(
{"DOLLAR": "$", LONG
"STYLE": cfg.style, % {
"TAG_PREFIX": cfg.tag_prefix, "DOLLAR": "$",
"PARENTDIR_PREFIX": cfg.parentdir_prefix, "STYLE": cfg.style,
"VERSIONFILE_SOURCE": cfg.versionfile_source, "TAG_PREFIX": cfg.tag_prefix,
}) "PARENTDIR_PREFIX": cfg.parentdir_prefix,
"VERSIONFILE_SOURCE": cfg.versionfile_source,
}
)
cmds["build_exe"] = cmd_build_exe cmds["build_exe"] = cmd_build_exe
del cmds["build_py"] del cmds["build_py"]
if 'py2exe' in sys.modules: # py2exe enabled? if "py2exe" in sys.modules: # py2exe enabled?
try: try:
from py2exe.setuptools_buildexe import py2exe as _py2exe # type: ignore from py2exe.setuptools_buildexe import py2exe as _py2exe # type: ignore
except ImportError: except ImportError:
@ -2044,18 +2090,22 @@ def get_cmdclass(cmdclass: Optional[Dict[str, Any]] = None):
os.unlink(target_versionfile) os.unlink(target_versionfile)
with open(cfg.versionfile_source, "w") as f: with open(cfg.versionfile_source, "w") as f:
LONG = LONG_VERSION_PY[cfg.VCS] LONG = LONG_VERSION_PY[cfg.VCS]
f.write(LONG % f.write(
{"DOLLAR": "$", LONG
"STYLE": cfg.style, % {
"TAG_PREFIX": cfg.tag_prefix, "DOLLAR": "$",
"PARENTDIR_PREFIX": cfg.parentdir_prefix, "STYLE": cfg.style,
"VERSIONFILE_SOURCE": cfg.versionfile_source, "TAG_PREFIX": cfg.tag_prefix,
}) "PARENTDIR_PREFIX": cfg.parentdir_prefix,
"VERSIONFILE_SOURCE": cfg.versionfile_source,
}
)
cmds["py2exe"] = cmd_py2exe cmds["py2exe"] = cmd_py2exe
# sdist farms its file list building out to egg_info # sdist farms its file list building out to egg_info
if 'egg_info' in cmds: if "egg_info" in cmds:
_egg_info: Any = cmds['egg_info'] _egg_info: Any = cmds["egg_info"]
else: else:
from setuptools.command.egg_info import egg_info as _egg_info from setuptools.command.egg_info import egg_info as _egg_info
@ -2068,7 +2118,7 @@ def get_cmdclass(cmdclass: Optional[Dict[str, Any]] = None):
# Modify the filelist and normalize it # Modify the filelist and normalize it
root = get_root() root = get_root()
cfg = get_config_from_root(root) cfg = get_config_from_root(root)
self.filelist.append('versioneer.py') self.filelist.append("versioneer.py")
if cfg.versionfile_source: if cfg.versionfile_source:
# There are rare cases where versionfile_source might not be # There are rare cases where versionfile_source might not be
# included by default, so we must be explicit # included by default, so we must be explicit
@ -2081,18 +2131,21 @@ def get_cmdclass(cmdclass: Optional[Dict[str, Any]] = None):
# We will instead replicate their final normalization (to unicode, # We will instead replicate their final normalization (to unicode,
# and POSIX-style paths) # and POSIX-style paths)
from setuptools import unicode_utils from setuptools import unicode_utils
normalized = [unicode_utils.filesys_decode(f).replace(os.sep, '/')
for f in self.filelist.files]
manifest_filename = os.path.join(self.egg_info, 'SOURCES.txt') normalized = [
with open(manifest_filename, 'w') as fobj: unicode_utils.filesys_decode(f).replace(os.sep, "/")
fobj.write('\n'.join(normalized)) for f in self.filelist.files
]
cmds['egg_info'] = cmd_egg_info manifest_filename = os.path.join(self.egg_info, "SOURCES.txt")
with open(manifest_filename, "w") as fobj:
fobj.write("\n".join(normalized))
cmds["egg_info"] = cmd_egg_info
# we override different "sdist" commands for both environments # we override different "sdist" commands for both environments
if 'sdist' in cmds: if "sdist" in cmds:
_sdist: Any = cmds['sdist'] _sdist: Any = cmds["sdist"]
else: else:
from setuptools.command.sdist import sdist as _sdist from setuptools.command.sdist import sdist as _sdist
@ -2114,8 +2167,10 @@ def get_cmdclass(cmdclass: Optional[Dict[str, Any]] = None):
# updated value # updated value
target_versionfile = os.path.join(base_dir, cfg.versionfile_source) target_versionfile = os.path.join(base_dir, cfg.versionfile_source)
print("UPDATING %s" % target_versionfile) print("UPDATING %s" % target_versionfile)
write_to_version_file(target_versionfile, write_to_version_file(
self._versioneer_generated_versions) target_versionfile, self._versioneer_generated_versions
)
cmds["sdist"] = cmd_sdist cmds["sdist"] = cmd_sdist
return cmds return cmds
@ -2175,11 +2230,9 @@ def do_setup() -> int:
root = get_root() root = get_root()
try: try:
cfg = get_config_from_root(root) cfg = get_config_from_root(root)
except (OSError, configparser.NoSectionError, except (OSError, configparser.NoSectionError, configparser.NoOptionError) as e:
configparser.NoOptionError) as e:
if isinstance(e, (OSError, configparser.NoSectionError)): if isinstance(e, (OSError, configparser.NoSectionError)):
print("Adding sample versioneer config to setup.cfg", print("Adding sample versioneer config to setup.cfg", file=sys.stderr)
file=sys.stderr)
with open(os.path.join(root, "setup.cfg"), "a") as f: with open(os.path.join(root, "setup.cfg"), "a") as f:
f.write(SAMPLE_CONFIG) f.write(SAMPLE_CONFIG)
print(CONFIG_ERROR, file=sys.stderr) print(CONFIG_ERROR, file=sys.stderr)
@ -2188,19 +2241,22 @@ def do_setup() -> int:
print(" creating %s" % cfg.versionfile_source) print(" creating %s" % cfg.versionfile_source)
with open(cfg.versionfile_source, "w") as f: with open(cfg.versionfile_source, "w") as f:
LONG = LONG_VERSION_PY[cfg.VCS] LONG = LONG_VERSION_PY[cfg.VCS]
f.write(LONG % {"DOLLAR": "$", f.write(
"STYLE": cfg.style, LONG
"TAG_PREFIX": cfg.tag_prefix, % {
"PARENTDIR_PREFIX": cfg.parentdir_prefix, "DOLLAR": "$",
"VERSIONFILE_SOURCE": cfg.versionfile_source, "STYLE": cfg.style,
}) "TAG_PREFIX": cfg.tag_prefix,
"PARENTDIR_PREFIX": cfg.parentdir_prefix,
"VERSIONFILE_SOURCE": cfg.versionfile_source,
}
)
ipy = os.path.join(os.path.dirname(cfg.versionfile_source), ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py")
"__init__.py")
maybe_ipy: Optional[str] = ipy maybe_ipy: Optional[str] = ipy
if os.path.exists(ipy): if os.path.exists(ipy):
try: try:
with open(ipy, "r") as f: with open(ipy) as f:
old = f.read() old = f.read()
except OSError: except OSError:
old = "" old = ""
@ -2232,7 +2288,7 @@ def scan_setup_py() -> int:
found = set() found = set()
setters = False setters = False
errors = 0 errors = 0
with open("setup.py", "r") as f: with open("setup.py") as f:
for line in f.readlines(): for line in f.readlines():
if "import versioneer" in line: if "import versioneer" in line:
found.add("import") found.add("import")