1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
|
"""
module to get version from tag of SCM repository.
Adapted from setuptools-scm. Currently only support git and hg.
"""
from __future__ import annotations
import os
import re
import shlex
import shutil
import subprocess
import warnings
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import TYPE_CHECKING, NamedTuple
from packaging.version import Version
if TYPE_CHECKING:
from _typeshed import StrPath
DEFAULT_TAG_REGEX = re.compile(
r"^(?:[\w-]+-)?(?P<version>[vV]?\d+(?:\.\d+){0,2}[^\+]*)(?:\+.*)?$"
)
@dataclass(frozen=True)
class Config:
tag_regex: re.Pattern
tag_filter: str | None
def _subprocess_call(
cmd: str | list[str],
cwd: StrPath | None = None,
extra_env: dict[str, str] | None = None,
) -> tuple[int, str, str]:
# adapted from pre-commit
# Too many bugs dealing with environment variables and GIT:
# https://github.com/pre-commit/pre-commit/issues/300
env = {
k: v
for k, v in os.environ.items()
if not k.startswith("GIT_")
or k in ("GIT_EXEC_PATH", "GIT_SSH", "GIT_SSH_COMMAND")
}
env.update({"LC_ALL": "C", "LANG": "", "HGPLAIN": "1"})
if extra_env:
env.update(extra_env)
if isinstance(cmd, str):
cmd = shlex.split(cmd)
try:
proc = subprocess.Popen(
cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
out, err = proc.communicate()
except NotADirectoryError as e:
if hasattr(e, "winerror") and e.winerror == 267:
# https://github.com/pdm-project/pdm-backend/issues/197
# More helpful diagnostic.
import textwrap
err_msg = f"""\
The above error is most likely caused by an unsupported
MSYS2 git binary at {cmd[0]}. Please point your PATH to
a different git binary such as Git For Windows.
"""
raise subprocess.SubprocessError(textwrap.dedent(err_msg)) from e
else:
raise e
return (
proc.returncode,
out.decode("utf-8", "surrogateescape").strip(),
err.decode("utf-8", "surrogateescape").strip(),
)
class SCMVersion(NamedTuple):
version: Version
distance: int | None
dirty: bool
node: str | None
branch: str | None
def meta(
config: Config,
tag: str | Version,
distance: int | None = None,
dirty: bool = False,
node: str | None = None,
branch: str | None = None,
) -> SCMVersion:
if isinstance(tag, str):
tag = tag_to_version(config, tag)
return SCMVersion(tag, distance, dirty, node, branch)
def _git_get_branch(root: StrPath) -> str | None:
ret, out, _ = _subprocess_call("git rev-parse --abbrev-ref HEAD", root)
if not ret:
return out
return None
def _git_is_dirty(root: StrPath) -> bool:
_, out, _ = _subprocess_call("git status --porcelain --untracked-files=no", root)
return bool(out)
def _git_get_node(root: StrPath) -> str | None:
ret, out, _ = _subprocess_call("git rev-parse --verify --quiet HEAD", root)
if not ret:
return out[:7]
return None
def _git_count_all_nodes(root: StrPath) -> int:
_, out, _ = _subprocess_call("git rev-list HEAD", root)
return out.count("\n") + 1
def _git_parse_describe(describe_output: str) -> tuple[str, int, str, bool]:
# 'describe_output' looks e.g. like 'v1.5.0-0-g4060507' or
# 'v1.15.1rc1-37-g9bd1298-dirty'.
if describe_output.endswith("-dirty"):
dirty = True
describe_output = describe_output[:-6]
else:
dirty = False
tag, number, node = describe_output.rsplit("-", 2)
return tag, int(number), node, dirty
class _ParseResult(NamedTuple):
version: str
prefix: str
suffix: str
def _parse_version_tag(config: Config, tag: str) -> _ParseResult | None:
tagstring = tag if not isinstance(tag, str) else str(tag)
match = config.tag_regex.match(tagstring)
result = None
if match:
if len(match.groups()) == 1:
key: int | str = 1
else:
key = "version"
result = _ParseResult(
match.group(key),
match.group(0)[: match.start(key)],
match.group(0)[match.end(key) :],
)
return result
def tag_to_version(config: Config, tag: str) -> Version:
"""
take a tag that might be prefixed with a keyword and return only the version part
:param config: optional configuration object
"""
tagdict = _parse_version_tag(config, tag)
if not tagdict or not tagdict.version:
warnings.warn(f"tag {tag!r} no version found")
return Version("0.0.0")
version = tagdict.version
if tagdict.suffix:
warnings.warn(f"tag {tag!r} will be stripped of its suffix {tagdict.suffix!r}")
return Version(version)
def git_parse_version(root: StrPath, config: Config) -> SCMVersion | None:
git = shutil.which("git")
if not git:
return None
ret, repo, _ = _subprocess_call([git, "rev-parse", "--show-toplevel"], root)
if ret or not repo:
return None
if os.path.isfile(os.path.join(repo, ".git/shallow")):
warnings.warn(f"{repo!r} is shallow and may cause errors")
describe_cmd = [
git,
"-c",
"core.abbrev=auto",
"describe",
"--dirty",
"--tags",
"--long",
"--match",
config.tag_filter or "*.*",
]
ret, output, _ = _subprocess_call(describe_cmd, repo)
branch = _git_get_branch(repo)
if ret:
rev_node = _git_get_node(repo)
dirty = _git_is_dirty(repo)
if rev_node is None:
return meta(config, "0.0", 0, dirty)
return meta(
config, "0.0", _git_count_all_nodes(repo), dirty, f"g{rev_node}", branch
)
else:
tag, number, node, dirty = _git_parse_describe(output)
return meta(config, tag, number or None, dirty, node, branch)
def get_distance_revset(tag: str | None) -> str:
return (
"(branch(.)" # look for revisions in this branch only
" and {rev}::." # after the last tag
# ignore commits that only modify .hgtags and nothing else:
" and (merge() or file('re:^(?!\\.hgtags).*$'))"
" and not {rev})" # ignore the tagged commit itself
).format(rev=f"tag({tag!r})" if tag is not None else "null")
def hg_get_graph_distance(root: StrPath, tag: str | None) -> int:
cmd = ["hg", "log", "-q", "-r", get_distance_revset(tag)]
_, out, _ = _subprocess_call(cmd, root)
return len(out.strip().splitlines())
def _hg_tagdist_normalize_tagcommit(
config: Config,
tag: str,
dist: int,
node: str,
branch: str,
dirty: bool,
) -> SCMVersion:
return meta(
config, tag, distance=dist or None, node=node, dirty=dirty, branch=branch
)
def guess_next_version(tag_version: Version) -> str:
version = _strip_local(str(tag_version))
return _bump_dev(version) or _bump_regex(version)
def _strip_local(version_string: str) -> str:
public, _, _ = version_string.partition("+")
return public
def _bump_dev(version: str) -> str:
if ".dev" not in version:
return ""
prefix, tail = version.rsplit(".dev", 1)
assert tail == "0", "own dev numbers are unsupported"
return prefix
def _bump_regex(version: str) -> str:
match = re.match(r"(.*?)(\d+)$", version)
assert match is not None
prefix, tail = match.groups()
return f"{prefix}{int(tail) + 1}"
def hg_parse_version(root: StrPath, config: Config) -> SCMVersion | None:
hg = shutil.which("hg")
if not hg:
return None
tag_filter = config.tag_filter or "\\."
_, output, _ = _subprocess_call(
[
hg,
"log",
"-r",
".",
"--template",
f"{{latesttag(r're:{tag_filter}')}}-{{node|short}}-{{branch}}",
],
root,
)
tag: str | None
try:
tag, node, branch = output.rsplit("-", 2)
except ValueError:
return None # unpacking failed, unexpected hg repo
# If no tag exists passes the tag filter.
if tag == "null":
tag = None
_, id_output, _ = _subprocess_call(
[hg, "id", "-i"],
root,
)
dirty = id_output.endswith("+")
try:
dist = hg_get_graph_distance(root, tag)
if tag is None:
tag = "0.0"
return _hg_tagdist_normalize_tagcommit(
config, tag, dist, node, branch, dirty=dirty
)
except ValueError:
return None # unpacking failed, old hg
def default_version_formatter(version: SCMVersion) -> str:
if version.distance is None:
main_version = str(version.version)
else:
guessed = guess_next_version(version.version)
main_version = f"{guessed}.dev{version.distance}"
if version.distance is None or version.node is None:
clean_format = ""
dirty_format = "+d{time:%Y%m%d}"
else:
clean_format = "+{node}"
dirty_format = "+{node}.d{time:%Y%m%d}"
fmt = dirty_format if version.dirty else clean_format
local_version = fmt.format(node=version.node, time=datetime.now(tz=timezone.utc))
return main_version + local_version
def get_version_from_scm(
root: str | Path, *, tag_regex: str | None = None, tag_filter: str | None = None
) -> SCMVersion | None:
config = Config(
tag_regex=re.compile(tag_regex) if tag_regex else DEFAULT_TAG_REGEX,
tag_filter=tag_filter,
)
for func in (git_parse_version, hg_parse_version):
version = func(root, config)
if version:
return version
return None
|