提交 e2ae99e1 authored 作者: Maxim Kochurov's avatar Maxim Kochurov 提交者: Maxim Kochurov

run isort and black on _version.py

上级 2a5bfc68
# 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 @@ ...@@ -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 Callable, Dict from typing import Callable, Dict
import functools
def get_keywords(): def get_keywords():
...@@ -61,17 +60,18 @@ HANDLERS: Dict[str, Dict[str, Callable]] = {} ...@@ -61,17 +60,18 @@ HANDLERS: Dict[str, Dict[str, Callable]] = {}
def register_vcs_handler(vcs, method): # decorator def register_vcs_handler(vcs, method): # 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): def decorate(f):
"""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
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None):
env=None):
"""Call the given command(s).""" """Call the given command(s)."""
assert isinstance(commands, list) assert isinstance(commands, list)
process = None process = None
...@@ -87,10 +87,14 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, ...@@ -87,10 +87,14 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
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: except OSError:
e = sys.exc_info()[1] e = sys.exc_info()[1]
...@@ -125,15 +129,21 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): ...@@ -125,15 +129,21 @@ def versions_from_parentdir(parentdir_prefix, root, verbose):
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")
...@@ -192,7 +202,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): ...@@ -192,7 +202,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
# 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
...@@ -201,7 +211,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): ...@@ -201,7 +211,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
# 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:
...@@ -209,24 +219,31 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): ...@@ -209,24 +219,31 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
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")
...@@ -248,8 +265,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): ...@@ -248,8 +265,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
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)
...@@ -257,10 +273,19 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): ...@@ -257,10 +273,19 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
# 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")
...@@ -275,8 +300,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): ...@@ -275,8 +300,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
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")
...@@ -316,17 +340,16 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): ...@@ -316,17 +340,16 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
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
...@@ -335,10 +358,12 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): ...@@ -335,10 +358,12 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
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))
...@@ -387,8 +412,7 @@ def render_pep440(pieces): ...@@ -387,8 +412,7 @@ def render_pep440(pieces):
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
...@@ -417,8 +441,7 @@ def render_pep440_branch(pieces): ...@@ -417,8 +441,7 @@ def render_pep440_branch(pieces):
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
...@@ -579,11 +602,13 @@ def render_git_describe_long(pieces): ...@@ -579,11 +602,13 @@ def render_git_describe_long(pieces):
def render(pieces, style): def render(pieces, style):
"""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
...@@ -607,9 +632,13 @@ def render(pieces, style): ...@@ -607,9 +632,13 @@ def render(pieces, style):
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(): def get_versions():
...@@ -623,8 +652,7 @@ def get_versions(): ...@@ -623,8 +652,7 @@ def get_versions():
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
...@@ -633,13 +661,16 @@ def get_versions(): ...@@ -633,13 +661,16 @@ def get_versions():
# 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)
...@@ -653,6 +684,10 @@ def get_versions(): ...@@ -653,6 +684,10 @@ def get_versions():
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,
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论