| 1 |
__all__ = [ |
| 2 |
"bump_version", |
| 3 |
"check_version", |
| 4 |
"get_version", |
| 5 |
"serialize_pep440", |
| 6 |
"serialize_pvp", |
| 7 |
"serialize_semver", |
| 8 |
"Style", |
| 9 |
"Vcs", |
| 10 |
"Version", |
| 11 |
] |
| 12 |
|
| 13 |
import copy |
| 14 |
import datetime as dt |
| 15 |
import inspect |
| 16 |
import json |
| 17 |
import os |
| 18 |
import re |
| 19 |
import shlex |
| 20 |
import shutil |
| 21 |
import subprocess |
| 22 |
import sys |
| 23 |
from collections import OrderedDict |
| 24 |
from enum import Enum |
| 25 |
from functools import total_ordering |
| 26 |
from pathlib import Path |
| 27 |
from typing import ( |
| 28 |
Any, |
| 29 |
Callable, |
| 30 |
List, |
| 31 |
Mapping, |
| 32 |
NamedTuple, |
| 33 |
Optional, |
| 34 |
Sequence, |
| 35 |
Set, |
| 36 |
Tuple, |
| 37 |
TypeVar, |
| 38 |
Union, |
| 39 |
) |
| 40 |
from xml.etree import ElementTree |
| 41 |
|
| 42 |
VERSION_SOURCE_PATTERN = r""" |
| 43 |
(?x) (?# ignore whitespace) |
| 44 |
^v((?P<epoch>\d+)!)?(?P<base>\d+(\.\d+)*) (?# v1.2.3 or v1!2000.1.2) |
| 45 |
([-._]?((?P<stage>[a-zA-Z]+)[-._]?(?P<revision>\d+)?))? (?# b0) |
| 46 |
(\+(?P<tagged_metadata>.+))?$ (?# +linux) |
| 47 |
""".strip() |
| 48 |
|
| 49 |
# Preserve old/private name for now in case it exists in the wild |
| 50 |
_VERSION_PATTERN = VERSION_SOURCE_PATTERN |
| 51 |
|
| 52 |
_VALID_PEP440 = r""" |
| 53 |
(?x) |
| 54 |
^(\d+!)? |
| 55 |
\d+(\.\d+)* |
| 56 |
((a|b|rc)\d+)? |
| 57 |
(\.post\d+)? |
| 58 |
(\.dev\d+)? |
| 59 |
(\+([a-zA-Z0-9]|[a-zA-Z0-9]{2}|[a-zA-Z0-9][a-zA-Z0-9.]+[a-zA-Z0-9]))?$ |
| 60 |
""".strip() |
| 61 |
_VALID_SEMVER = r""" |
| 62 |
(?x) |
| 63 |
^\d+\.\d+\.\d+ |
| 64 |
(\-[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]+)*)? |
| 65 |
(\+[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]+)*)?$ |
| 66 |
""".strip() |
| 67 |
_VALID_PVP = r"^\d+(\.\d+)*(-[a-zA-Z0-9]+)*$" |
| 68 |
|
| 69 |
_TIMESTAMP_GENERIC = "%Y-%m-%dT%H:%M:%S.%f%z" |
| 70 |
_TIMESTAMP_GENERIC_SPACE = "%Y-%m-%d %H:%M:%S.%f%z" |
| 71 |
_TIMESTAMP_GIT_ISO_STRICT = "%Y-%m-%dT%H:%M:%S%z" |
| 72 |
_TIMESTAMP_GIT_ISO = "%Y-%m-%d %H:%M:%S %z" |
| 73 |
|
| 74 |
_T = TypeVar("_T") |
| 75 |
|
| 76 |
|
| 77 |
class Style(Enum): |
| 78 |
""" |
| 79 |
Standard styles for serializing a version. |
| 80 |
""" |
| 81 |
|
| 82 |
Pep440 = "pep440" |
| 83 |
"""PEP 440""" |
| 84 |
SemVer = "semver" |
| 85 |
"""Semantic Versioning""" |
| 86 |
Pvp = "pvp" |
| 87 |
"""Haskell Package Versioning Policy""" |
| 88 |
|
| 89 |
|
| 90 |
class Vcs(Enum): |
| 91 |
""" |
| 92 |
Version control systems. |
| 93 |
""" |
| 94 |
|
| 95 |
Any = "any" |
| 96 |
"""Automatically determine the VCS.""" |
| 97 |
Git = "git" |
| 98 |
"""Git""" |
| 99 |
Mercurial = "mercurial" |
| 100 |
"""Mercurial""" |
| 101 |
Darcs = "darcs" |
| 102 |
"""Darcs""" |
| 103 |
Subversion = "subversion" |
| 104 |
"""Subversion""" |
| 105 |
Bazaar = "bazaar" |
| 106 |
"""Bazaar""" |
| 107 |
Fossil = "fossil" |
| 108 |
"""Fossil""" |
| 109 |
Pijul = "pijul" |
| 110 |
"""Pijul""" |
| 111 |
|
| 112 |
|
| 113 |
class Pattern(Enum): |
| 114 |
""" |
| 115 |
Regular expressions used to parse tags as versions. |
| 116 |
""" |
| 117 |
|
| 118 |
Default = "default" |
| 119 |
"""Default pattern, including `v` prefix.""" |
| 120 |
DefaultUnprefixed = "default-unprefixed" |
| 121 |
"""Default pattern, but without `v` prefix.""" |
| 122 |
|
| 123 |
def regex(self, prefix: Optional[str] = None) -> str: |
| 124 |
""" |
| 125 |
Get the regular expression for this preset pattern. |
| 126 |
|
| 127 |
:param prefix: Insert this after the pattern's start anchor (`^`). |
| 128 |
:returns: Regular expression. |
| 129 |
""" |
| 130 |
variants = { |
| 131 |
Pattern.Default: VERSION_SOURCE_PATTERN, |
| 132 |
Pattern.DefaultUnprefixed: VERSION_SOURCE_PATTERN.replace("^v", "^v?", 1), |
| 133 |
} |
| 134 |
|
| 135 |
out = variants[self] |
| 136 |
if prefix: |
| 137 |
out = out.replace("^", "^{}".format(prefix), 1) |
| 138 |
|
| 139 |
return out |
| 140 |
|
| 141 |
@staticmethod |
| 142 |
def parse(pattern: Union[str, "Pattern"], prefix: Optional[str] = None) -> str: |
| 143 |
""" |
| 144 |
Parse a pattern string into a regular expression. |
| 145 |
|
| 146 |
If the pattern contains the capture group `?P<base>`, then it is |
| 147 |
returned as-is. Otherwise, it is interpreted as a variant of the |
| 148 |
`Pattern` enum. |
| 149 |
|
| 150 |
:param pattern: Pattern to parse. |
| 151 |
:param prefix: Insert this after the pattern's start anchor (`^`). |
| 152 |
:returns: Regular expression. |
| 153 |
""" |
| 154 |
if isinstance(pattern, str) and "?P<base>" in pattern: |
| 155 |
if prefix: |
| 156 |
return pattern.replace("^", "^{}".format(prefix), 1) |
| 157 |
else: |
| 158 |
return pattern |
| 159 |
|
| 160 |
try: |
| 161 |
pattern = Pattern(pattern) |
| 162 |
except ValueError: |
| 163 |
raise ValueError( |
| 164 |
_pattern_error( |
| 165 |
( |
| 166 |
"The pattern does not contain the capture group '?P<base>'" |
| 167 |
" and is not a known preset like '{}'".format(Pattern.Default.value) |
| 168 |
), |
| 169 |
pattern, |
| 170 |
) |
| 171 |
) |
| 172 |
return pattern.regex(prefix) |
| 173 |
|
| 174 |
|
| 175 |
class Concern(Enum): |
| 176 |
""" |
| 177 |
A concern/warning discovered while producing the version. |
| 178 |
""" |
| 179 |
|
| 180 |
ShallowRepository = "shallow-repository" |
| 181 |
"""Repository does not contain full history""" |
| 182 |
|
| 183 |
def message(self) -> str: |
| 184 |
""" |
| 185 |
Produce a human-readable description of the concern. |
| 186 |
|
| 187 |
:returns: Concern description. |
| 188 |
""" |
| 189 |
|
| 190 |
if self == Concern.ShallowRepository: |
| 191 |
return "This is a shallow repository, so Dunamai may not produce the correct version." |
| 192 |
else: |
| 193 |
return "" |
| 194 |
|
| 195 |
|
| 196 |
def _pattern_error(primary: str, pattern: Union[str, Pattern], tags: Optional[Sequence[str]] = None) -> str: |
| 197 |
parts = [primary, "Pattern:\n{}".format(pattern)] |
| 198 |
|
| 199 |
if tags is not None: |
| 200 |
parts.append("Tags:\n{}".format(tags)) |
| 201 |
|
| 202 |
return "\n\n".join(parts) |
| 203 |
|
| 204 |
|
| 205 |
def _run_cmd( |
| 206 |
command: str, |
| 207 |
where: Optional[Path], |
| 208 |
codes: Sequence[int] = (0,), |
| 209 |
shell: bool = False, |
| 210 |
env: Optional[dict] = None, |
| 211 |
stderr: bool = True, |
| 212 |
) -> Tuple[int, str]: |
| 213 |
result = subprocess.run( |
| 214 |
shlex.split(command), |
| 215 |
stdout=subprocess.PIPE, |
| 216 |
stderr=subprocess.STDOUT if stderr else subprocess.DEVNULL, |
| 217 |
cwd=str(where) if where is not None else None, |
| 218 |
shell=shell, |
| 219 |
env=env, |
| 220 |
) |
| 221 |
output = result.stdout.decode().strip() |
| 222 |
if codes and result.returncode not in codes: |
| 223 |
raise RuntimeError("The command '{}' returned code {}. Output:\n{}".format(command, result.returncode, output)) |
| 224 |
return (result.returncode, output) |
| 225 |
|
| 226 |
|
| 227 |
_MatchedVersionPattern = NamedTuple( |
| 228 |
"_MatchedVersionPattern", |
| 229 |
[ |
| 230 |
("matched_tag", str), |
| 231 |
("base", str), |
| 232 |
("stage_revision", Optional[Tuple[str, Optional[int]]]), |
| 233 |
("newer_tags", Sequence[str]), |
| 234 |
("tagged_metadata", Optional[str]), |
| 235 |
("epoch", Optional[int]), |
| 236 |
], |
| 237 |
) |
| 238 |
|
| 239 |
|
| 240 |
def _match_version_pattern( |
| 241 |
pattern: Union[str, Pattern], |
| 242 |
sources: Sequence[str], |
| 243 |
latest_source: bool, |
| 244 |
highest_source: bool, |
| 245 |
strict: bool, |
| 246 |
pattern_prefix: Optional[str], |
| 247 |
) -> Optional[_MatchedVersionPattern]: |
| 248 |
""" |
| 249 |
:returns: Tuple of: |
| 250 |
* matched tag |
| 251 |
* base segment |
| 252 |
* tuple of: |
| 253 |
* stage |
| 254 |
* revision |
| 255 |
* any newer unmatched tags |
| 256 |
* tagged_metadata matched section |
| 257 |
""" |
| 258 |
pattern_match = None |
| 259 |
base = None |
| 260 |
stage_revision = None |
| 261 |
newer_unmatched_tags = [] |
| 262 |
tagged_metadata = None |
| 263 |
epoch = None # type: Optional[Union[str, int]] |
| 264 |
|
| 265 |
pattern = Pattern.parse(pattern, pattern_prefix) |
| 266 |
|
| 267 |
if latest_source: |
| 268 |
relevant_sources = sources[:1] |
| 269 |
elif highest_source: |
| 270 |
selected_source = None |
| 271 |
selected_parsed = None |
| 272 |
for source in sources: |
| 273 |
parsed = Version.parse(source, pattern) |
| 274 |
try: |
| 275 |
if selected_parsed is None or parsed > selected_parsed: |
| 276 |
selected_source = source |
| 277 |
selected_parsed = parsed |
| 278 |
except Exception: |
| 279 |
continue |
| 280 |
relevant_sources = [selected_source] if selected_source is not None else [] |
| 281 |
else: |
| 282 |
relevant_sources = sources |
| 283 |
|
| 284 |
for source in relevant_sources: |
| 285 |
try: |
| 286 |
pattern_match = re.search(pattern, source) |
| 287 |
except re.error as e: |
| 288 |
raise re.error( |
| 289 |
_pattern_error( |
| 290 |
"The pattern is an invalid regular expression: {}".format(e.msg), # type: ignore |
| 291 |
pattern, |
| 292 |
), |
| 293 |
e.pattern, # type: ignore |
| 294 |
e.pos, # type: ignore |
| 295 |
) |
| 296 |
if pattern_match is None: |
| 297 |
newer_unmatched_tags.append(source) |
| 298 |
continue |
| 299 |
try: |
| 300 |
base = pattern_match.group("base") |
| 301 |
if base is not None: |
| 302 |
break |
| 303 |
except IndexError: |
| 304 |
raise ValueError(_pattern_error("The pattern did not include required capture group 'base'", pattern)) |
| 305 |
if pattern_match is None or base is None: |
| 306 |
if latest_source: |
| 307 |
raise ValueError( |
| 308 |
_pattern_error( |
| 309 |
"The pattern did not match the latest tag '{}'".format(sources[0]), |
| 310 |
pattern, |
| 311 |
sources, |
| 312 |
) |
| 313 |
) |
| 314 |
elif strict: |
| 315 |
raise ValueError(_pattern_error("The pattern did not match any tags", pattern, sources)) |
| 316 |
else: |
| 317 |
return None |
| 318 |
|
| 319 |
stage = pattern_match.groupdict().get("stage") |
| 320 |
revision = pattern_match.groupdict().get("revision") |
| 321 |
tagged_metadata = pattern_match.groupdict().get("tagged_metadata") |
| 322 |
epoch = pattern_match.groupdict().get("epoch") |
| 323 |
if stage is not None: |
| 324 |
try: |
| 325 |
stage_revision = (stage, None if revision is None else int(revision)) |
| 326 |
except ValueError: |
| 327 |
raise ValueError("Revision '{}' is not a valid number".format(revision)) |
| 328 |
if epoch is not None: |
| 329 |
try: |
| 330 |
epoch = int(epoch) |
| 331 |
except ValueError: |
| 332 |
raise ValueError("Epoch '{}' is not a valid number".format(epoch)) |
| 333 |
|
| 334 |
return _MatchedVersionPattern(source, base, stage_revision, newer_unmatched_tags, tagged_metadata, epoch) |
| 335 |
|
| 336 |
|
| 337 |
def _blank(value: Optional[_T], default: _T) -> _T: |
| 338 |
return value if value is not None else default |
| 339 |
|
| 340 |
|
| 341 |
def _escape_branch(value: str, replacement: str) -> str: |
| 342 |
return re.sub(r"[^a-zA-Z0-9]", replacement, value) |
| 343 |
|
| 344 |
|
| 345 |
def _equal_if_set(x: _T, y: Optional[_T], unset: Sequence[Any] = (None,)) -> bool: |
| 346 |
if y in unset: |
| 347 |
return True |
| 348 |
return x == y |
| 349 |
|
| 350 |
|
| 351 |
def _get_git_version() -> List[int]: |
| 352 |
_, msg = _run_cmd("git version", where=None) |
| 353 |
result = re.search(r"git version (\d+(\.\d+)*)", msg.strip()) |
| 354 |
if result is not None: |
| 355 |
parts = result.group(1).split(".") |
| 356 |
return [int(x) for x in parts] |
| 357 |
return [] |
| 358 |
|
| 359 |
|
| 360 |
def _git_log(git_version: List[int]) -> str: |
| 361 |
if git_version < [2, 10]: |
| 362 |
return "git log" |
| 363 |
else: |
| 364 |
return "git -c log.showsignature=false log" |
| 365 |
|
| 366 |
|
| 367 |
def _detect_vcs(expected_vcs: Optional[Vcs], path: Optional[Path]) -> Vcs: |
| 368 |
checks = OrderedDict( |
| 369 |
[ |
| 370 |
(Vcs.Git, "git status"), |
| 371 |
(Vcs.Mercurial, "hg status"), |
| 372 |
(Vcs.Darcs, "darcs log"), |
| 373 |
(Vcs.Subversion, "svn log"), |
| 374 |
(Vcs.Bazaar, "bzr status"), |
| 375 |
(Vcs.Fossil, "fossil status"), |
| 376 |
(Vcs.Pijul, "pijul log"), |
| 377 |
] |
| 378 |
) |
| 379 |
|
| 380 |
dubious_ownership_flag = "detected dubious ownership" |
| 381 |
dubious_ownership_error = "Detected Git repository, but failed because of dubious ownership" |
| 382 |
|
| 383 |
if expected_vcs: |
| 384 |
command = checks[expected_vcs] |
| 385 |
program = command.split()[0] |
| 386 |
if not shutil.which(program): |
| 387 |
raise RuntimeError("Unable to find '{}' program".format(program)) |
| 388 |
code, msg = _run_cmd(command, path, codes=[]) |
| 389 |
if code != 0: |
| 390 |
if expected_vcs == Vcs.Git and dubious_ownership_flag in msg: |
| 391 |
raise RuntimeError(dubious_ownership_error) |
| 392 |
raise RuntimeError("This does not appear to be a {} project".format(expected_vcs.value.title())) |
| 393 |
return expected_vcs |
| 394 |
else: |
| 395 |
disproven = [] |
| 396 |
unavailable = [] |
| 397 |
for vcs, command in checks.items(): |
| 398 |
if shutil.which(command.split()[0]): |
| 399 |
code, msg = _run_cmd(command, path, codes=[]) |
| 400 |
if code == 0: |
| 401 |
return vcs |
| 402 |
elif vcs == Vcs.Git and dubious_ownership_flag in msg: |
| 403 |
raise RuntimeError(dubious_ownership_error) |
| 404 |
disproven.append(vcs.name) |
| 405 |
else: |
| 406 |
unavailable.append(vcs.name) |
| 407 |
|
| 408 |
error_parts = ["Unable to detect version control system."] |
| 409 |
if disproven: |
| 410 |
error_parts.append("Checked: {}.".format(", ".join(disproven))) |
| 411 |
if unavailable: |
| 412 |
error_parts.append("Not installed: {}.".format(", ".join(unavailable))) |
| 413 |
raise RuntimeError(" ".join(error_parts)) |
| 414 |
|
| 415 |
|
| 416 |
def _detect_vcs_from_archival(path: Optional[Path]) -> Optional[Vcs]: |
| 417 |
archival = _find_higher_file(".git_archival.json", path, ".git") |
| 418 |
if archival is not None: |
| 419 |
content = archival.read_text("utf8") |
| 420 |
if "$Format:" not in content: |
| 421 |
return Vcs.Git |
| 422 |
|
| 423 |
archival = _find_higher_file(".hg_archival.txt", path, ".hg") |
| 424 |
if archival is not None: |
| 425 |
return Vcs.Mercurial |
| 426 |
|
| 427 |
return None |
| 428 |
|
| 429 |
|
| 430 |
def _find_higher_file(name: str, start: Optional[Path], limit: Optional[str] = None) -> Optional[Path]: |
| 431 |
""" |
| 432 |
:param name: Bare name of a file we'd like to find. |
| 433 |
:param limit: Give up if we find a file/folder with this name. |
| 434 |
:param start: Begin recursing from this folder (default: `.`). |
| 435 |
""" |
| 436 |
|
| 437 |
if start is None: |
| 438 |
start = Path.cwd() |
| 439 |
for level in [start, *start.parents]: |
| 440 |
if (level / name).is_file(): |
| 441 |
return level / name |
| 442 |
if limit is not None and (level / limit).exists(): |
| 443 |
return None |
| 444 |
return None |
| 445 |
|
| 446 |
|
| 447 |
class _GitRefInfo: |
| 448 |
""" |
| 449 |
This assumes Git 2.7+. |
| 450 |
""" |
| 451 |
|
| 452 |
def __init__(self, ref: str, commit: str, creatordate: str, committerdate: str, taggerdate: str): |
| 453 |
self.fullref = ref |
| 454 |
self.commit = commit |
| 455 |
self.creatordate = self.normalize_git_dt(creatordate) |
| 456 |
self.committerdate = self.normalize_git_dt(committerdate) |
| 457 |
self.taggerdate = self.normalize_git_dt(taggerdate) |
| 458 |
self.tag_topo_lookup = {} # type: Mapping[str, int] |
| 459 |
|
| 460 |
def with_tag_topo_lookup(self, lookup: Mapping[str, int]) -> "_GitRefInfo": |
| 461 |
self.tag_topo_lookup = lookup |
| 462 |
return self |
| 463 |
|
| 464 |
@staticmethod |
| 465 |
def normalize_git_dt(timestamp: str) -> Optional[dt.datetime]: |
| 466 |
if timestamp == "": |
| 467 |
return None |
| 468 |
else: |
| 469 |
return _parse_git_timestamp_iso_strict(timestamp) |
| 470 |
|
| 471 |
def __repr__(self): |
| 472 |
return ("_GitRefInfo(ref={!r}, commit={!r}, creatordate={!r}, committerdate={!r}, taggerdate={!r})").format( |
| 473 |
self.fullref, self.commit_offset, self.creatordate, self.committerdate, self.taggerdate |
| 474 |
) |
| 475 |
|
| 476 |
def best_date(self) -> Optional[dt.datetime]: |
| 477 |
if self.taggerdate is not None: |
| 478 |
return self.taggerdate |
| 479 |
elif self.committerdate is not None: |
| 480 |
return self.committerdate |
| 481 |
else: |
| 482 |
return self.creatordate |
| 483 |
|
| 484 |
def commit_offset(self) -> int: |
| 485 |
try: |
| 486 |
return self.tag_topo_lookup[self.fullref] |
| 487 |
except KeyError: |
| 488 |
# This can happen when the initial commit is both tagged and empty. |
| 489 |
return sys.maxsize |
| 490 |
|
| 491 |
def sort_key(self) -> Tuple[int, Optional[dt.datetime]]: |
| 492 |
return (-self.commit_offset(), self.best_date()) |
| 493 |
|
| 494 |
def ref(self) -> str: |
| 495 |
return self.fullref.replace("refs/tags/", "") |
| 496 |
|
| 497 |
@staticmethod |
| 498 |
def normalize_tag_ref(ref: str) -> str: |
| 499 |
if ref.startswith("refs/tags/"): |
| 500 |
return ref |
| 501 |
else: |
| 502 |
return "refs/tags/{}".format(ref) |
| 503 |
|
| 504 |
@staticmethod |
| 505 |
def from_git_tag_topo_order(tag_branch: str, git_version: List[int], path: Optional[Path]) -> Mapping[str, int]: |
| 506 |
cmd = ('{} --simplify-by-decoration --topo-order --decorate=full {} "--format=%H%d"').format( |
| 507 |
_git_log(git_version), tag_branch |
| 508 |
) |
| 509 |
if git_version >= [2, 16]: |
| 510 |
cmd += " --decorate-refs=refs/tags/" |
| 511 |
code, logmsg = _run_cmd(cmd, path) |
| 512 |
|
| 513 |
filtered_lines = [x for x in logmsg.strip().splitlines(keepends=False) if " (" not in x or "tag: " in x] |
| 514 |
|
| 515 |
tag_lookup = {} |
| 516 |
for tag_offset, line in enumerate(filtered_lines): |
| 517 |
# lines have the pattern |
| 518 |
# <gitsha1> (tag: refs/tags/v1.2.0b1, tag: refs/tags/v1.2.0) |
| 519 |
commit, _, tags = line.partition("(") |
| 520 |
commit = commit.strip() |
| 521 |
if tags: |
| 522 |
# remove trailing ')' |
| 523 |
tags = tags[:-1] |
| 524 |
taglist = [tag.strip() for tag in tags.split(", ") if tag.strip().startswith("tag: ")] |
| 525 |
taglist = [tag.split()[-1] for tag in taglist] |
| 526 |
taglist = [_GitRefInfo.normalize_tag_ref(tag) for tag in taglist] |
| 527 |
for tag in taglist: |
| 528 |
tag_lookup[tag] = tag_offset |
| 529 |
return tag_lookup |
| 530 |
|
| 531 |
|
| 532 |
@total_ordering |
| 533 |
class Version: |
| 534 |
""" |
| 535 |
A dynamic version. |
| 536 |
|
| 537 |
:ivar base: Release segment. |
| 538 |
:vartype base: str |
| 539 |
:ivar stage: Alphabetical part of prerelease segment. |
| 540 |
:vartype stage: Optional[str] |
| 541 |
:ivar revision: Numerical part of prerelease segment. |
| 542 |
:vartype revision: Optional[int] |
| 543 |
:ivar distance: Number of commits since the last tag. |
| 544 |
:vartype distance: int |
| 545 |
:ivar commit: Commit ID. |
| 546 |
:vartype commit: Optional[str] |
| 547 |
:ivar dirty: Whether there are uncommitted changes. |
| 548 |
:vartype dirty: Optional[bool] |
| 549 |
:ivar tagged_metadata: Any metadata segment from the tag itself. |
| 550 |
:vartype tagged_metadata: Optional[str] |
| 551 |
:ivar epoch: Optional PEP 440 epoch. |
| 552 |
:vartype epoch: Optional[int] |
| 553 |
:ivar branch: Name of the current branch. |
| 554 |
:vartype branch: Optional[str] |
| 555 |
:ivar timestamp: Timestamp of the current commit. |
| 556 |
:vartype timestamp: Optional[dt.datetime] |
| 557 |
:ivar concerns: Any concerns regarding the version. |
| 558 |
:vartype concerns: Optional[Set[Concern]] |
| 559 |
:ivar vcs: Version control system from which the version was detected. |
| 560 |
:vartype vcs: Vcs |
| 561 |
""" |
| 562 |
|
| 563 |
def __init__( |
| 564 |
self, |
| 565 |
base: str, |
| 566 |
*, |
| 567 |
stage: Optional[Tuple[str, Optional[int]]] = None, |
| 568 |
distance: int = 0, |
| 569 |
commit: Optional[str] = None, |
| 570 |
dirty: Optional[bool] = None, |
| 571 |
tagged_metadata: Optional[str] = None, |
| 572 |
epoch: Optional[int] = None, |
| 573 |
branch: Optional[str] = None, |
| 574 |
timestamp: Optional[dt.datetime] = None, |
| 575 |
concerns: Optional[Set[Concern]] = None, |
| 576 |
# fmt: off |
| 577 |
vcs: Vcs = Vcs.Any |
| 578 |
# fmt: on |
| 579 |
) -> None: |
| 580 |
""" |
| 581 |
:param base: Release segment, such as 0.1.0. |
| 582 |
:param stage: Pair of release stage (e.g., "a", "alpha", "b", "rc") |
| 583 |
and an optional revision number. |
| 584 |
:param distance: Number of commits since the last tag. |
| 585 |
:param commit: Commit hash/identifier. |
| 586 |
:param dirty: True if the working directory does not match the commit. |
| 587 |
:param epoch: Optional PEP 440 epoch. |
| 588 |
:param branch: Name of the current branch. |
| 589 |
:param timestamp: Timestamp of the current commit. |
| 590 |
:param concerns: Any concerns regarding the version. |
| 591 |
""" |
| 592 |
self.base = base |
| 593 |
self.stage = None |
| 594 |
self.revision = None |
| 595 |
if stage is not None: |
| 596 |
self.stage, self.revision = stage |
| 597 |
self.distance = distance |
| 598 |
self.commit = commit |
| 599 |
self.dirty = dirty |
| 600 |
self.tagged_metadata = tagged_metadata |
| 601 |
self.epoch = epoch |
| 602 |
self.branch = branch |
| 603 |
try: |
| 604 |
self.timestamp = timestamp.astimezone(dt.timezone.utc) if timestamp else None |
| 605 |
except ValueError: |
| 606 |
# Will fail for naive timestamps before Python 3.6. |
| 607 |
self.timestamp = timestamp |
| 608 |
self.concerns = concerns or set() |
| 609 |
self.vcs = vcs |
| 610 |
|
| 611 |
self._matched_tag = None # type: Optional[str] |
| 612 |
self._newer_unmatched_tags = None # type: Optional[Sequence[str]] |
| 613 |
self._smart_bumped = False |
| 614 |
|
| 615 |
def __str__(self) -> str: |
| 616 |
return self.serialize() |
| 617 |
|
| 618 |
def __repr__(self) -> str: |
| 619 |
return ( |
| 620 |
"Version(base={!r}, stage={!r}, revision={!r}, distance={!r}, commit={!r}," |
| 621 |
" dirty={!r}, tagged_metadata={!r}, epoch={!r}, branch={!r}, timestamp={!r})" |
| 622 |
).format( |
| 623 |
self.base, |
| 624 |
self.stage, |
| 625 |
self.revision, |
| 626 |
self.distance, |
| 627 |
self.commit, |
| 628 |
self.dirty, |
| 629 |
self.tagged_metadata, |
| 630 |
self.epoch, |
| 631 |
self.branch, |
| 632 |
self.timestamp, |
| 633 |
) |
| 634 |
|
| 635 |
def __eq__(self, other: Any) -> bool: |
| 636 |
if not isinstance(other, Version): |
| 637 |
raise TypeError("Cannot compare Version with type {}".format(other.__class__.__qualname__)) |
| 638 |
return ( |
| 639 |
self.base == other.base |
| 640 |
and self.stage == other.stage |
| 641 |
and self.revision == other.revision |
| 642 |
and self.distance == other.distance |
| 643 |
and self.commit == other.commit |
| 644 |
and self.dirty == other.dirty |
| 645 |
and self.tagged_metadata == other.tagged_metadata |
| 646 |
and self.epoch == other.epoch |
| 647 |
and self.branch == other.branch |
| 648 |
and self.timestamp == other.timestamp |
| 649 |
) |
| 650 |
|
| 651 |
def _matches_partial(self, other: "Version") -> bool: |
| 652 |
""" |
| 653 |
Compare this version to another version, but ignore None values in the other version. |
| 654 |
Distance is also ignored when `other.distance == 0`. |
| 655 |
|
| 656 |
:param other: The version to compare to. |
| 657 |
:returns: True if this version equals the other version. |
| 658 |
""" |
| 659 |
return ( |
| 660 |
_equal_if_set(self.base, other.base) |
| 661 |
and _equal_if_set(self.stage, other.stage) |
| 662 |
and _equal_if_set(self.revision, other.revision) |
| 663 |
and _equal_if_set(self.distance, other.distance, unset=[None, 0]) |
| 664 |
and _equal_if_set(self.commit, other.commit) |
| 665 |
and _equal_if_set(self.dirty, other.dirty) |
| 666 |
and _equal_if_set(self.tagged_metadata, other.tagged_metadata) |
| 667 |
and _equal_if_set(self.epoch, other.epoch) |
| 668 |
and _equal_if_set(self.branch, other.branch) |
| 669 |
and _equal_if_set(self.timestamp, other.timestamp) |
| 670 |
) |
| 671 |
|
| 672 |
def __lt__(self, other: Any) -> bool: |
| 673 |
if not isinstance(other, Version): |
| 674 |
raise TypeError("Cannot compare Version with type {}".format(other.__class__.__qualname__)) |
| 675 |
|
| 676 |
import packaging.version as pv |
| 677 |
|
| 678 |
parsable = True |
| 679 |
try: |
| 680 |
us = pv.Version(self.serialize(metadata=False)) |
| 681 |
them = pv.Version(other.serialize(metadata=False)) |
| 682 |
if us < them: |
| 683 |
return True |
| 684 |
elif us > them: |
| 685 |
return False |
| 686 |
except Exception: |
| 687 |
parsable = False |
| 688 |
|
| 689 |
common_pairs = [ |
| 690 |
(_blank(self.distance, 0), _blank(other.distance, 0)), |
| 691 |
(_blank(self.commit, ""), _blank(other.commit, "")), |
| 692 |
(bool(self.dirty), bool(other.dirty)), |
| 693 |
(_blank(self.tagged_metadata, ""), _blank(other.tagged_metadata, "")), |
| 694 |
(_blank(self.branch, ""), _blank(other.branch, "")), |
| 695 |
( |
| 696 |
_blank(self.timestamp, dt.datetime(1, 1, 1, 0, 0, 0)), |
| 697 |
_blank(other.timestamp, dt.datetime(1, 1, 1, 0, 0, 0)), |
| 698 |
), |
| 699 |
] |
| 700 |
|
| 701 |
if parsable: |
| 702 |
pairs = common_pairs |
| 703 |
else: |
| 704 |
pairs = [ |
| 705 |
(_blank(self.epoch, 0), _blank(other.epoch, 0)), |
| 706 |
(pv.Version(self.base), pv.Version(other.base)), |
| 707 |
(_blank(self.stage, ""), _blank(other.stage, "")), |
| 708 |
(_blank(self.revision, 0), _blank(other.revision, 0)), |
| 709 |
*common_pairs, |
| 710 |
] |
| 711 |
|
| 712 |
for (a, b) in pairs: |
| 713 |
if a < b: # type: ignore |
| 714 |
return True |
| 715 |
elif a > b: # type: ignore |
| 716 |
return False |
| 717 |
|
| 718 |
return False |
| 719 |
|
| 720 |
def serialize( |
| 721 |
self, |
| 722 |
metadata: Optional[bool] = None, |
| 723 |
dirty: bool = False, |
| 724 |
format: Optional[Union[str, Callable[["Version"], str]]] = None, |
| 725 |
style: Optional[Style] = None, |
| 726 |
bump: bool = False, |
| 727 |
tagged_metadata: bool = False, |
| 728 |
commit_prefix: Optional[str] = None, |
| 729 |
escape_with: Optional[str] = None, |
| 730 |
) -> str: |
| 731 |
""" |
| 732 |
Create a string from the version info. |
| 733 |
|
| 734 |
:param metadata: Metadata (commit ID, dirty flag) is normally included |
| 735 |
in the metadata/local version part only if the distance is nonzero. |
| 736 |
Set this to True to always include metadata even with no distance, |
| 737 |
or set it to False to always exclude it. |
| 738 |
This is ignored when `format` is used. |
| 739 |
:param dirty: Set this to True to include a dirty flag in the |
| 740 |
metadata if applicable. Inert when metadata=False. |
| 741 |
This is ignored when `format` is used. |
| 742 |
:param format: Custom output format. It is either a formatted string or a |
| 743 |
callback. In the string you can use substitutions, such as "v{base}" |
| 744 |
to get "v0.1.0". Available substitutions: |
| 745 |
|
| 746 |
* {base} |
| 747 |
* {stage} |
| 748 |
* {revision} |
| 749 |
* {distance} |
| 750 |
* {commit} |
| 751 |
* {dirty} which expands to either "dirty" or "clean" |
| 752 |
* {tagged_metadata} |
| 753 |
* {epoch} |
| 754 |
* {branch} |
| 755 |
* {branch_escaped} which omits any non-letter/number characters (or replaces via `escape_with`) |
| 756 |
* {timestamp} which expands to YYYYmmddHHMMSS as UTC |
| 757 |
* {major} (first part of `base` split on `.`, or 0) |
| 758 |
* {minor} (second part of `base` split on `.`, or 0) |
| 759 |
* {patch} (third part of `base` split on `.`, or 0) |
| 760 |
:param style: Built-in output formats. Will default to PEP 440 if not |
| 761 |
set and no custom format given. If you specify both a style and a |
| 762 |
custom format, then the format will be validated against the |
| 763 |
style's rules. |
| 764 |
:param bump: If true, increment the last part of the `base` by 1, |
| 765 |
unless `stage` is set, in which case either increment `revision` |
| 766 |
by 1 or set it to a default of 2 if there was no revision. |
| 767 |
Does nothing when on a commit with a version tag. |
| 768 |
:param tagged_metadata: If true, insert the `tagged_metadata` in the |
| 769 |
version as the first part of the metadata segment. |
| 770 |
This is ignored when `format` is used. |
| 771 |
:param commit_prefix: Add this prefix to the commit ID. |
| 772 |
This can be helpful when an all-numeric commit would be misinterpreted. |
| 773 |
For example, "g" is a common prefix for Git commits. |
| 774 |
:param escape_with: When escaping, replace with this substitution. |
| 775 |
The default is simply to remove invalid characters. |
| 776 |
:returns: Serialized version. |
| 777 |
""" |
| 778 |
base = self.base |
| 779 |
revision = self.revision |
| 780 |
if bump: |
| 781 |
bumped = self.bump(smart=True) |
| 782 |
base = bumped.base |
| 783 |
revision = bumped.revision |
| 784 |
|
| 785 |
commit = self.commit |
| 786 |
if commit is not None and commit_prefix is not None: |
| 787 |
commit = "{}{}".format(commit_prefix, commit) |
| 788 |
|
| 789 |
if format is not None: |
| 790 |
if callable(format): |
| 791 |
new_version = copy.deepcopy(self) |
| 792 |
new_version.base = base |
| 793 |
new_version.revision = revision |
| 794 |
out = format(new_version) |
| 795 |
else: |
| 796 |
try: |
| 797 |
base_parts = base.split(".") |
| 798 |
|
| 799 |
out = format.format( |
| 800 |
base=base, |
| 801 |
stage=_blank(self.stage, ""), |
| 802 |
revision=_blank(revision, ""), |
| 803 |
distance=_blank(self.distance, ""), |
| 804 |
commit=_blank(commit, ""), |
| 805 |
tagged_metadata=_blank(self.tagged_metadata, ""), |
| 806 |
dirty="dirty" if self.dirty else "clean", |
| 807 |
epoch=_blank(self.epoch, ""), |
| 808 |
branch=_blank(self.branch, ""), |
| 809 |
branch_escaped=_escape_branch(_blank(self.branch, ""), escape_with or ""), |
| 810 |
timestamp=self.timestamp.strftime("%Y%m%d%H%M%S") if self.timestamp else "", |
| 811 |
major=base_parts[0] if len(base_parts) > 0 else "0", |
| 812 |
minor=base_parts[1] if len(base_parts) > 1 else "0", |
| 813 |
patch=base_parts[2] if len(base_parts) > 2 else "0", |
| 814 |
) |
| 815 |
except KeyError as e: |
| 816 |
raise KeyError("Format contains invalid placeholder: {}".format(e)) |
| 817 |
except ValueError as e: |
| 818 |
raise ValueError("Format is invalid: {}".format(e)) |
| 819 |
if style is not None: |
| 820 |
check_version(out, style) |
| 821 |
return out |
| 822 |
|
| 823 |
if style is None: |
| 824 |
style = Style.Pep440 |
| 825 |
out = "" |
| 826 |
|
| 827 |
meta_parts = [] |
| 828 |
if metadata is not False: |
| 829 |
if tagged_metadata and self.tagged_metadata: |
| 830 |
meta_parts.append(self.tagged_metadata) |
| 831 |
if (metadata or self.distance > 0) and commit is not None: |
| 832 |
meta_parts.append(commit) |
| 833 |
if dirty and self.dirty: |
| 834 |
meta_parts.append("dirty") |
| 835 |
|
| 836 |
pre_parts = [] |
| 837 |
if self.stage is not None: |
| 838 |
pre_parts.append(self.stage) |
| 839 |
if revision is not None: |
| 840 |
pre_parts.append(str(revision)) |
| 841 |
if self.distance > 0: |
| 842 |
pre_parts.append("pre" if bump or self._smart_bumped else "post") |
| 843 |
pre_parts.append(str(self.distance)) |
| 844 |
|
| 845 |
if style == Style.Pep440: |
| 846 |
stage = self.stage |
| 847 |
post = None |
| 848 |
dev = None |
| 849 |
if stage == "post": |
| 850 |
stage = None |
| 851 |
post = revision |
| 852 |
elif stage == "dev": |
| 853 |
stage = None |
| 854 |
dev = revision |
| 855 |
if self.distance > 0: |
| 856 |
if bump or self._smart_bumped: |
| 857 |
if dev is None: |
| 858 |
dev = self.distance |
| 859 |
else: |
| 860 |
dev += self.distance |
| 861 |
else: |
| 862 |
if post is None and dev is None: |
| 863 |
post = self.distance |
| 864 |
dev = 0 |
| 865 |
elif dev is None: |
| 866 |
dev = self.distance |
| 867 |
else: |
| 868 |
dev += self.distance |
| 869 |
|
| 870 |
out = serialize_pep440( |
| 871 |
base, |
| 872 |
stage=stage, |
| 873 |
revision=revision, |
| 874 |
post=post, |
| 875 |
dev=dev, |
| 876 |
metadata=meta_parts, |
| 877 |
epoch=self.epoch, |
| 878 |
) |
| 879 |
elif style == Style.SemVer: |
| 880 |
out = serialize_semver(base, pre=pre_parts, metadata=meta_parts) |
| 881 |
elif style == Style.Pvp: |
| 882 |
out = serialize_pvp(base, metadata=[*pre_parts, *meta_parts]) |
| 883 |
|
| 884 |
check_version(out, style) |
| 885 |
return out |
| 886 |
|
| 887 |
@classmethod |
| 888 |
def parse(cls, version: str, pattern: Union[str, Pattern] = Pattern.Default) -> "Version": |
| 889 |
""" |
| 890 |
Attempt to parse a string into a Version instance. |
| 891 |
|
| 892 |
This uses inexact heuristics, so its output may vary slightly between |
| 893 |
releases. Consider this a "best effort" conversion. |
| 894 |
|
| 895 |
:param version: Full version, such as 0.3.0a3+d7.gb6a9020.dirty. |
| 896 |
:param pattern: Regular expression matched against the version. |
| 897 |
Refer to `from_any_vcs` for more info. |
| 898 |
:returns: Parsed version. |
| 899 |
""" |
| 900 |
normalized = version |
| 901 |
if not version.startswith("v") and pattern in [VERSION_SOURCE_PATTERN, Pattern.Default]: |
| 902 |
normalized = "v{}".format(version) |
| 903 |
|
| 904 |
failed = False |
| 905 |
try: |
| 906 |
matched_pattern = _match_version_pattern( |
| 907 |
pattern, [normalized], True, False, strict=True, pattern_prefix=None |
| 908 |
) |
| 909 |
except ValueError: |
| 910 |
failed = True |
| 911 |
|
| 912 |
if failed or matched_pattern is None: |
| 913 |
replaced = re.sub(r"(\.post(\d+)\.dev\d+)", r".dev\2", version, count=1) |
| 914 |
if replaced != version: |
| 915 |
alt = Version.parse(replaced, pattern) |
| 916 |
if alt.base != replaced: |
| 917 |
return alt |
| 918 |
|
| 919 |
return cls(version) |
| 920 |
|
| 921 |
base = matched_pattern.base |
| 922 |
stage = matched_pattern.stage_revision |
| 923 |
distance = None |
| 924 |
commit = None |
| 925 |
dirty = None |
| 926 |
tagged_metadata = matched_pattern.tagged_metadata |
| 927 |
epoch = matched_pattern.epoch |
| 928 |
|
| 929 |
if tagged_metadata: |
| 930 |
pop = [] # type: list |
| 931 |
parts = tagged_metadata.split(".") |
| 932 |
|
| 933 |
for i, value in enumerate(parts): |
| 934 |
if dirty is None: |
| 935 |
if value == "dirty": |
| 936 |
dirty = True |
| 937 |
pop.append(i) |
| 938 |
continue |
| 939 |
elif value == "clean": |
| 940 |
dirty = False |
| 941 |
pop.append(i) |
| 942 |
continue |
| 943 |
if distance is None: |
| 944 |
match = re.match(r"d?(\d+)", value) |
| 945 |
if match: |
| 946 |
distance = int(match.group(1)) |
| 947 |
pop.append(i) |
| 948 |
continue |
| 949 |
if commit is None: |
| 950 |
match = re.match(r"g?([\da-z]+)", value) |
| 951 |
if match: |
| 952 |
commit = match.group(1) |
| 953 |
pop.append(i) |
| 954 |
continue |
| 955 |
|
| 956 |
for i in reversed(sorted(pop)): |
| 957 |
parts.pop(i) |
| 958 |
|
| 959 |
tagged_metadata = ".".join(parts) |
| 960 |
|
| 961 |
if distance is None: |
| 962 |
distance = 0 |
| 963 |
if tagged_metadata is not None and tagged_metadata.strip() == "": |
| 964 |
tagged_metadata = None |
| 965 |
|
| 966 |
if stage is not None and stage[0] == "dev" and stage[1] is not None: |
| 967 |
distance += stage[1] |
| 968 |
stage = None |
| 969 |
|
| 970 |
return cls( |
| 971 |
base, |
| 972 |
stage=stage, |
| 973 |
distance=distance, |
| 974 |
commit=commit, |
| 975 |
dirty=dirty, |
| 976 |
tagged_metadata=tagged_metadata, |
| 977 |
epoch=epoch, |
| 978 |
) |
| 979 |
|
| 980 |
def bump(self, index: int = -1, increment: int = 1, smart: bool = False) -> "Version": |
| 981 |
""" |
| 982 |
Increment the version. |
| 983 |
|
| 984 |
The base is bumped unless there is a stage defined, in which case, |
| 985 |
the revision is bumped instead. |
| 986 |
|
| 987 |
:param index: Numerical position to increment in the base. |
| 988 |
This follows Python indexing rules, so positive numbers start from |
| 989 |
the left side and count up from 0, while negative numbers start from |
| 990 |
the right side and count down from -1. |
| 991 |
Only has an effect when the base is bumped. |
| 992 |
:param increment: By how much to increment the relevant position. |
| 993 |
:param smart: If true, only bump when distance is not 0. |
| 994 |
This will also make `Version.serialize()` use pre-release formatting automatically, |
| 995 |
like calling `Version.serialize(bump=True)`. |
| 996 |
:returns: Bumped version. |
| 997 |
""" |
| 998 |
bumped = copy.deepcopy(self) |
| 999 |
|
| 1000 |
if smart: |
| 1001 |
if bumped.distance == 0: |
| 1002 |
return bumped |
| 1003 |
bumped._smart_bumped = True |
| 1004 |
|
| 1005 |
if bumped.stage is None: |
| 1006 |
bumped.base = bump_version(bumped.base, index, increment) |
| 1007 |
else: |
| 1008 |
if bumped.revision is None: |
| 1009 |
bumped.revision = 2 |
| 1010 |
else: |
| 1011 |
bumped.revision += increment |
| 1012 |
return bumped |
| 1013 |
|
| 1014 |
@classmethod |
| 1015 |
def _fallback( |
| 1016 |
cls, |
| 1017 |
strict: bool, |
| 1018 |
*, |
| 1019 |
stage: Optional[Tuple[str, Optional[int]]] = None, |
| 1020 |
distance: int = 0, |
| 1021 |
commit: Optional[str] = None, |
| 1022 |
dirty: Optional[bool] = None, |
| 1023 |
tagged_metadata: Optional[str] = None, |
| 1024 |
epoch: Optional[int] = None, |
| 1025 |
branch: Optional[str] = None, |
| 1026 |
timestamp: Optional[dt.datetime] = None, |
| 1027 |
concerns: Optional[Set[Concern]] = None, |
| 1028 |
# fmt: off |
| 1029 |
vcs: Vcs = Vcs.Any |
| 1030 |
# fmt: on |
| 1031 |
): |
| 1032 |
if strict: |
| 1033 |
raise RuntimeError("No tags available and fallbacks disabled by strict mode") |
| 1034 |
return cls( |
| 1035 |
"0.0.0", |
| 1036 |
stage=stage, |
| 1037 |
distance=distance, |
| 1038 |
commit=commit, |
| 1039 |
dirty=dirty, |
| 1040 |
tagged_metadata=tagged_metadata, |
| 1041 |
epoch=epoch, |
| 1042 |
branch=branch, |
| 1043 |
timestamp=timestamp, |
| 1044 |
concerns=concerns, |
| 1045 |
vcs=vcs, |
| 1046 |
) |
| 1047 |
|
| 1048 |
@classmethod |
| 1049 |
def from_git( |
| 1050 |
cls, |
| 1051 |
pattern: Union[str, Pattern] = Pattern.Default, |
| 1052 |
latest_tag: bool = False, |
| 1053 |
tag_branch: Optional[str] = None, |
| 1054 |
full_commit: bool = False, |
| 1055 |
strict: bool = False, |
| 1056 |
path: Optional[Path] = None, |
| 1057 |
pattern_prefix: Optional[str] = None, |
| 1058 |
ignore_untracked: bool = False, |
| 1059 |
commit_length: Optional[int] = None, |
| 1060 |
highest_tag: bool = False, |
| 1061 |
) -> "Version": |
| 1062 |
r""" |
| 1063 |
Determine a version based on Git tags. |
| 1064 |
|
| 1065 |
:param pattern: Regular expression matched against the version source. |
| 1066 |
Refer to `from_any_vcs` for more info. |
| 1067 |
:param latest_tag: If true, only inspect the latest tag on the latest |
| 1068 |
tagged commit for a pattern match. If false, keep looking at tags |
| 1069 |
until there is a match. |
| 1070 |
:param tag_branch: Branch on which to find tags, if different than the |
| 1071 |
current branch. |
| 1072 |
:param full_commit: Get the full commit hash instead of the short form. |
| 1073 |
:param strict: Elevate warnings to errors. |
| 1074 |
When there are no tags, fail instead of falling back to 0.0.0. |
| 1075 |
:param path: Directory to inspect, if not the current working directory. |
| 1076 |
:param pattern_prefix: Insert this after the pattern's start anchor (`^`). |
| 1077 |
:param ignore_untracked: |
| 1078 |
Ignore untracked files when determining whether the repository is dirty. |
| 1079 |
:param commit_length: |
| 1080 |
Use this many characters from the start of the full commit hash. |
| 1081 |
:param highest_tag: |
| 1082 |
Only inspect the numerically highest tag across all tagged commits for a pattern match. |
| 1083 |
:returns: Detected version. |
| 1084 |
""" |
| 1085 |
vcs = Vcs.Git |
| 1086 |
full_commit = full_commit or commit_length is not None |
| 1087 |
env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_TRACE")} |
| 1088 |
|
| 1089 |
archival = _find_higher_file(".git_archival.json", path, ".git") |
| 1090 |
if archival is not None: |
| 1091 |
content = archival.read_text("utf8") |
| 1092 |
if "$Format:" not in content: |
| 1093 |
data = json.loads(content) |
| 1094 |
|
| 1095 |
if full_commit: |
| 1096 |
commit = data.get("hash-full") |
| 1097 |
else: |
| 1098 |
commit = data.get("hash-short") |
| 1099 |
|
| 1100 |
if commit is not None: |
| 1101 |
commit = commit[:commit_length] |
| 1102 |
|
| 1103 |
timestamp = None |
| 1104 |
raw_timestamp = data.get("timestamp") |
| 1105 |
if raw_timestamp: |
| 1106 |
timestamp = _parse_git_timestamp_iso_strict(raw_timestamp) |
| 1107 |
|
| 1108 |
branch = None |
| 1109 |
refs = data.get("refs") |
| 1110 |
if refs: |
| 1111 |
parts = refs.split(" -> ") |
| 1112 |
if len(parts) == 2: |
| 1113 |
branch = parts[1].split(", ")[0] |
| 1114 |
|
| 1115 |
tag = None |
| 1116 |
distance = 0 |
| 1117 |
dirty = None |
| 1118 |
describe = data.get("describe") |
| 1119 |
if describe: |
| 1120 |
if describe.endswith("-dirty"): |
| 1121 |
dirty = True |
| 1122 |
describe = describe[:-6] |
| 1123 |
else: |
| 1124 |
dirty = False |
| 1125 |
parts = describe.rsplit("-", 2) |
| 1126 |
tag = parts[0] |
| 1127 |
if len(parts) > 1: |
| 1128 |
distance = int(parts[1]) |
| 1129 |
|
| 1130 |
if tag is None: |
| 1131 |
return cls._fallback( |
| 1132 |
strict, |
| 1133 |
distance=distance, |
| 1134 |
commit=commit, |
| 1135 |
dirty=dirty, |
| 1136 |
branch=branch, |
| 1137 |
timestamp=timestamp, |
| 1138 |
vcs=vcs, |
| 1139 |
) |
| 1140 |
|
| 1141 |
matched_pattern = _match_version_pattern( |
| 1142 |
pattern, [tag], latest_tag, highest_tag, strict, pattern_prefix |
| 1143 |
) |
| 1144 |
if matched_pattern is None: |
| 1145 |
return cls._fallback( |
| 1146 |
strict, |
| 1147 |
distance=distance, |
| 1148 |
commit=commit, |
| 1149 |
dirty=dirty, |
| 1150 |
branch=branch, |
| 1151 |
timestamp=timestamp, |
| 1152 |
vcs=vcs, |
| 1153 |
) |
| 1154 |
tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern |
| 1155 |
|
| 1156 |
version = cls( |
| 1157 |
base, |
| 1158 |
stage=stage, |
| 1159 |
distance=distance, |
| 1160 |
commit=commit, |
| 1161 |
dirty=dirty, |
| 1162 |
tagged_metadata=tagged_metadata, |
| 1163 |
epoch=epoch, |
| 1164 |
branch=branch, |
| 1165 |
timestamp=timestamp, |
| 1166 |
vcs=vcs, |
| 1167 |
) |
| 1168 |
version._matched_tag = tag |
| 1169 |
version._newer_unmatched_tags = unmatched |
| 1170 |
return version |
| 1171 |
|
| 1172 |
_detect_vcs(vcs, path) |
| 1173 |
concerns = set() # type: Set[Concern] |
| 1174 |
if tag_branch is None: |
| 1175 |
tag_branch = "HEAD" |
| 1176 |
|
| 1177 |
git_version = _get_git_version() |
| 1178 |
|
| 1179 |
if git_version < [2, 15]: |
| 1180 |
flag_file = _find_higher_file(".git/shallow", path) |
| 1181 |
if flag_file: |
| 1182 |
concerns.add(Concern.ShallowRepository) |
| 1183 |
else: |
| 1184 |
code, msg = _run_cmd("git rev-parse --is-shallow-repository", path, env=env) |
| 1185 |
if msg.strip() == "true": |
| 1186 |
concerns.add(Concern.ShallowRepository) |
| 1187 |
|
| 1188 |
if strict and concerns: |
| 1189 |
raise RuntimeError("\n".join(x.message() for x in concerns)) |
| 1190 |
|
| 1191 |
code, msg = _run_cmd("git symbolic-ref --short HEAD", path, codes=[0, 128], env=env) |
| 1192 |
if code == 128: |
| 1193 |
branch = None |
| 1194 |
else: |
| 1195 |
branch = msg |
| 1196 |
|
| 1197 |
code, msg = _run_cmd( |
| 1198 |
'{} -n 1 --format="format:{}"'.format(_git_log(git_version), "%H" if full_commit else "%h"), |
| 1199 |
path, |
| 1200 |
codes=[0, 128], |
| 1201 |
env=env, |
| 1202 |
) |
| 1203 |
if code == 128: |
| 1204 |
return cls._fallback(strict, distance=0, dirty=True, branch=branch, concerns=concerns, vcs=vcs) |
| 1205 |
commit = msg[:commit_length] |
| 1206 |
|
| 1207 |
timestamp = None |
| 1208 |
if git_version < [2, 2]: |
| 1209 |
code, msg = _run_cmd('{} -n 1 --pretty=format:"%ci"'.format(_git_log(git_version)), path, env=env) |
| 1210 |
timestamp = _parse_git_timestamp_iso(msg) |
| 1211 |
else: |
| 1212 |
code, msg = _run_cmd('{} -n 1 --pretty=format:"%cI"'.format(_git_log(git_version)), path, env=env) |
| 1213 |
timestamp = _parse_git_timestamp_iso_strict(msg) |
| 1214 |
|
| 1215 |
code, msg = _run_cmd("git describe --always --dirty", path, env=env) |
| 1216 |
dirty = msg.endswith("-dirty") |
| 1217 |
|
| 1218 |
if not dirty and not ignore_untracked: |
| 1219 |
code, msg = _run_cmd("git status --porcelain", path, env=env) |
| 1220 |
if msg.strip() != "": |
| 1221 |
dirty = True |
| 1222 |
|
| 1223 |
if git_version < [2, 7]: |
| 1224 |
code, msg = _run_cmd( |
| 1225 |
'git for-each-ref "refs/tags/**" --format "%(refname)" --sort -creatordate', path, env=env |
| 1226 |
) |
| 1227 |
if not msg: |
| 1228 |
try: |
| 1229 |
code, msg = _run_cmd("git rev-list --count HEAD", path, env=env) |
| 1230 |
distance = int(msg) |
| 1231 |
except Exception: |
| 1232 |
distance = 0 |
| 1233 |
return cls._fallback( |
| 1234 |
strict, |
| 1235 |
distance=distance, |
| 1236 |
commit=commit, |
| 1237 |
dirty=dirty, |
| 1238 |
branch=branch, |
| 1239 |
timestamp=timestamp, |
| 1240 |
concerns=concerns, |
| 1241 |
vcs=vcs, |
| 1242 |
) |
| 1243 |
tags = [line.replace("refs/tags/", "") for line in msg.splitlines()] |
| 1244 |
matched_pattern = _match_version_pattern(pattern, tags, latest_tag, highest_tag, strict, pattern_prefix) |
| 1245 |
else: |
| 1246 |
code, msg = _run_cmd( |
| 1247 |
'git for-each-ref "refs/tags/**" --merged {}'.format(tag_branch) + ' --format "%(refname)' |
| 1248 |
"@{%(objectname)" |
| 1249 |
"@{%(creatordate:iso-strict)" |
| 1250 |
"@{%(*committerdate:iso-strict)" |
| 1251 |
"@{%(taggerdate:iso-strict)" |
| 1252 |
'"', |
| 1253 |
path, |
| 1254 |
env=env, |
| 1255 |
) |
| 1256 |
if not msg: |
| 1257 |
try: |
| 1258 |
code, msg = _run_cmd("git rev-list --count HEAD", path, env=env) |
| 1259 |
distance = int(msg) |
| 1260 |
except Exception: |
| 1261 |
distance = 0 |
| 1262 |
return cls._fallback( |
| 1263 |
strict, |
| 1264 |
distance=distance, |
| 1265 |
commit=commit, |
| 1266 |
dirty=dirty, |
| 1267 |
branch=branch, |
| 1268 |
timestamp=timestamp, |
| 1269 |
concerns=concerns, |
| 1270 |
vcs=vcs, |
| 1271 |
) |
| 1272 |
|
| 1273 |
detailed_tags = [] # type: List[_GitRefInfo] |
| 1274 |
tag_topo_lookup = _GitRefInfo.from_git_tag_topo_order(tag_branch, git_version, path) |
| 1275 |
|
| 1276 |
for line in msg.strip().splitlines(): |
| 1277 |
parts = line.split("@{") |
| 1278 |
if len(parts) != 5: |
| 1279 |
continue |
| 1280 |
detailed_tags.append(_GitRefInfo(*parts).with_tag_topo_lookup(tag_topo_lookup)) |
| 1281 |
|
| 1282 |
tags = [t.ref() for t in sorted(detailed_tags, key=lambda x: x.sort_key(), reverse=True)] |
| 1283 |
matched_pattern = _match_version_pattern(pattern, tags, latest_tag, highest_tag, strict, pattern_prefix) |
| 1284 |
|
| 1285 |
if matched_pattern is None: |
| 1286 |
try: |
| 1287 |
code, msg = _run_cmd("git rev-list --count HEAD", path, env=env) |
| 1288 |
distance = int(msg) |
| 1289 |
except Exception: |
| 1290 |
distance = 0 |
| 1291 |
|
| 1292 |
return cls._fallback( |
| 1293 |
strict, |
| 1294 |
distance=distance, |
| 1295 |
commit=commit, |
| 1296 |
dirty=dirty, |
| 1297 |
branch=branch, |
| 1298 |
timestamp=timestamp, |
| 1299 |
concerns=concerns, |
| 1300 |
vcs=vcs, |
| 1301 |
) |
| 1302 |
tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern |
| 1303 |
|
| 1304 |
code, msg = _run_cmd("git rev-list --count refs/tags/{}..HEAD".format(tag), path, env=env) |
| 1305 |
distance = int(msg) |
| 1306 |
|
| 1307 |
version = cls( |
| 1308 |
base, |
| 1309 |
stage=stage, |
| 1310 |
distance=distance, |
| 1311 |
commit=commit, |
| 1312 |
dirty=dirty, |
| 1313 |
tagged_metadata=tagged_metadata, |
| 1314 |
epoch=epoch, |
| 1315 |
branch=branch, |
| 1316 |
timestamp=timestamp, |
| 1317 |
concerns=concerns, |
| 1318 |
vcs=vcs, |
| 1319 |
) |
| 1320 |
version._matched_tag = tag |
| 1321 |
version._newer_unmatched_tags = unmatched |
| 1322 |
return version |
| 1323 |
|
| 1324 |
@classmethod |
| 1325 |
def from_mercurial( |
| 1326 |
cls, |
| 1327 |
pattern: Union[str, Pattern] = Pattern.Default, |
| 1328 |
latest_tag: bool = False, |
| 1329 |
full_commit: bool = False, |
| 1330 |
strict: bool = False, |
| 1331 |
path: Optional[Path] = None, |
| 1332 |
pattern_prefix: Optional[str] = None, |
| 1333 |
commit_length: Optional[int] = None, |
| 1334 |
highest_tag: bool = False, |
| 1335 |
) -> "Version": |
| 1336 |
r""" |
| 1337 |
Determine a version based on Mercurial tags. |
| 1338 |
|
| 1339 |
:param pattern: Regular expression matched against the version source. |
| 1340 |
Refer to `from_any_vcs` for more info. |
| 1341 |
:param latest_tag: If true, only inspect the latest tag on the latest |
| 1342 |
tagged commit for a pattern match. If false, keep looking at tags |
| 1343 |
until there is a match. |
| 1344 |
:param full_commit: Get the full commit hash instead of the short form. |
| 1345 |
:param strict: Elevate warnings to errors. |
| 1346 |
When there are no tags, fail instead of falling back to 0.0.0. |
| 1347 |
:param path: Directory to inspect, if not the current working directory. |
| 1348 |
:param pattern_prefix: Insert this after the pattern's start anchor (`^`). |
| 1349 |
:param commit_length: |
| 1350 |
Use this many characters from the start of the full commit hash. |
| 1351 |
:param highest_tag: |
| 1352 |
Only inspect the numerically highest tag across all tagged commits for a pattern match. |
| 1353 |
:returns: Detected version. |
| 1354 |
""" |
| 1355 |
vcs = Vcs.Mercurial |
| 1356 |
full_commit = full_commit or commit_length is not None |
| 1357 |
|
| 1358 |
archival = _find_higher_file(".hg_archival.txt", path, ".hg") |
| 1359 |
if archival is not None: |
| 1360 |
content = archival.read_text("utf8") |
| 1361 |
data = {} |
| 1362 |
for line in content.splitlines(): |
| 1363 |
parts = line.split(":", 1) |
| 1364 |
if len(parts) != 2: |
| 1365 |
continue |
| 1366 |
data[parts[0].strip()] = parts[1].strip() |
| 1367 |
|
| 1368 |
tag = data.get("latesttag") |
| 1369 |
# The distance is 1 on a new repo or on a tagged commit. |
| 1370 |
distance = int(data.get("latesttagdistance", 1)) - 1 |
| 1371 |
commit = data.get("node") |
| 1372 |
if commit is not None: |
| 1373 |
commit = commit[:commit_length] |
| 1374 |
branch = data.get("branch") |
| 1375 |
|
| 1376 |
if tag is None or tag == "null": |
| 1377 |
return cls._fallback(strict, distance=distance, commit=commit, branch=branch, vcs=vcs) |
| 1378 |
|
| 1379 |
all_tags_file = _find_higher_file(".hgtags", path, ".hg") |
| 1380 |
if all_tags_file is None: |
| 1381 |
all_tags = [tag] |
| 1382 |
else: |
| 1383 |
all_tags = [] |
| 1384 |
all_tags_content = all_tags_file.read_text("utf8") |
| 1385 |
for line in reversed(all_tags_content.splitlines()): |
| 1386 |
parts = line.split(" ", 1) |
| 1387 |
if len(parts) != 2: |
| 1388 |
continue |
| 1389 |
all_tags.append(parts[1]) |
| 1390 |
|
| 1391 |
matched_pattern = _match_version_pattern(pattern, all_tags, latest_tag, highest_tag, strict, pattern_prefix) |
| 1392 |
if matched_pattern is None: |
| 1393 |
return cls._fallback( |
| 1394 |
strict, |
| 1395 |
distance=distance, |
| 1396 |
commit=commit, |
| 1397 |
branch=branch, |
| 1398 |
vcs=vcs, |
| 1399 |
) |
| 1400 |
tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern |
| 1401 |
|
| 1402 |
version = cls( |
| 1403 |
base, |
| 1404 |
stage=stage, |
| 1405 |
distance=distance, |
| 1406 |
commit=commit, |
| 1407 |
tagged_metadata=tagged_metadata, |
| 1408 |
epoch=epoch, |
| 1409 |
branch=branch, |
| 1410 |
vcs=vcs, |
| 1411 |
) |
| 1412 |
version._matched_tag = tag |
| 1413 |
version._newer_unmatched_tags = unmatched |
| 1414 |
return version |
| 1415 |
|
| 1416 |
_detect_vcs(vcs, path) |
| 1417 |
|
| 1418 |
code, msg = _run_cmd("hg summary", path) |
| 1419 |
dirty = "commit: (clean)" not in msg.splitlines() |
| 1420 |
|
| 1421 |
code, msg = _run_cmd("hg branch", path) |
| 1422 |
branch = msg |
| 1423 |
|
| 1424 |
code, msg = _run_cmd('hg id --template "{}"'.format("{id}" if full_commit else "{id|short}"), path) |
| 1425 |
commit = msg[:commit_length] if set(msg) != {"0"} else None |
| 1426 |
|
| 1427 |
code, msg = _run_cmd('hg log --limit 1 --template "{date|rfc3339date}"', path) |
| 1428 |
timestamp = _parse_git_timestamp_iso_strict(msg) if msg != "" else None |
| 1429 |
|
| 1430 |
code, msg = _run_cmd( |
| 1431 |
'hg log -r "sort(tag(){}, -rev)" --template "{{join(tags, \':\')}}\\n"'.format( |
| 1432 |
" and ancestors({})".format(commit) if commit is not None else "" |
| 1433 |
), |
| 1434 |
path, |
| 1435 |
) |
| 1436 |
if not msg: |
| 1437 |
try: |
| 1438 |
code, msg = _run_cmd("hg id --num --rev tip", path) |
| 1439 |
distance = int(msg) + 1 |
| 1440 |
except Exception: |
| 1441 |
distance = 0 |
| 1442 |
return cls._fallback( |
| 1443 |
strict, |
| 1444 |
distance=distance, |
| 1445 |
commit=commit, |
| 1446 |
dirty=dirty, |
| 1447 |
branch=branch, |
| 1448 |
timestamp=timestamp, |
| 1449 |
vcs=vcs, |
| 1450 |
) |
| 1451 |
tags = [tag for tags in [line.split(":") for line in msg.splitlines()] for tag in tags] |
| 1452 |
|
| 1453 |
matched_pattern = _match_version_pattern(pattern, tags, latest_tag, highest_tag, strict, pattern_prefix) |
| 1454 |
if matched_pattern is None: |
| 1455 |
return cls._fallback( |
| 1456 |
strict, |
| 1457 |
distance=distance, |
| 1458 |
commit=commit, |
| 1459 |
dirty=dirty, |
| 1460 |
branch=branch, |
| 1461 |
timestamp=timestamp, |
| 1462 |
vcs=vcs, |
| 1463 |
) |
| 1464 |
tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern |
| 1465 |
|
| 1466 |
code, msg = _run_cmd('hg log -r "{0}::{1} - {0}" --template "."'.format(tag, commit), path) |
| 1467 |
# The tag itself is in the list, so offset by 1. |
| 1468 |
distance = max(len(msg) - 1, 0) |
| 1469 |
|
| 1470 |
version = cls( |
| 1471 |
base, |
| 1472 |
stage=stage, |
| 1473 |
distance=distance, |
| 1474 |
commit=commit, |
| 1475 |
dirty=dirty, |
| 1476 |
tagged_metadata=tagged_metadata, |
| 1477 |
epoch=epoch, |
| 1478 |
branch=branch, |
| 1479 |
timestamp=timestamp, |
| 1480 |
vcs=vcs, |
| 1481 |
) |
| 1482 |
version._matched_tag = tag |
| 1483 |
version._newer_unmatched_tags = unmatched |
| 1484 |
return version |
| 1485 |
|
| 1486 |
@classmethod |
| 1487 |
def from_darcs( |
| 1488 |
cls, |
| 1489 |
pattern: Union[str, Pattern] = Pattern.Default, |
| 1490 |
latest_tag: bool = False, |
| 1491 |
strict: bool = False, |
| 1492 |
path: Optional[Path] = None, |
| 1493 |
pattern_prefix: Optional[str] = None, |
| 1494 |
commit_length: Optional[int] = None, |
| 1495 |
highest_tag: bool = False, |
| 1496 |
) -> "Version": |
| 1497 |
r""" |
| 1498 |
Determine a version based on Darcs tags. |
| 1499 |
|
| 1500 |
:param pattern: Regular expression matched against the version source. |
| 1501 |
Refer to `from_any_vcs` for more info. |
| 1502 |
:param latest_tag: If true, only inspect the latest tag on the latest |
| 1503 |
tagged commit for a pattern match. If false, keep looking at tags |
| 1504 |
until there is a match. |
| 1505 |
:param strict: Elevate warnings to errors. |
| 1506 |
When there are no tags, fail instead of falling back to 0.0.0. |
| 1507 |
:param path: Directory to inspect, if not the current working directory. |
| 1508 |
:param pattern_prefix: Insert this after the pattern's start anchor (`^`). |
| 1509 |
:param commit_length: |
| 1510 |
Use this many characters from the start of the full commit hash. |
| 1511 |
:param highest_tag: |
| 1512 |
Only inspect the numerically highest tag across all tagged commits for a pattern match. |
| 1513 |
:returns: Detected version. |
| 1514 |
""" |
| 1515 |
vcs = Vcs.Darcs |
| 1516 |
_detect_vcs(vcs, path) |
| 1517 |
|
| 1518 |
code, msg = _run_cmd("darcs status", path, codes=[0, 1]) |
| 1519 |
dirty = msg != "No changes!" |
| 1520 |
|
| 1521 |
code, msg = _run_cmd("darcs log --last 1 --xml-output", path) |
| 1522 |
root = ElementTree.fromstring(msg) |
| 1523 |
if len(root) == 0: |
| 1524 |
commit = None |
| 1525 |
timestamp = None |
| 1526 |
else: |
| 1527 |
commit = root[0].attrib["hash"] |
| 1528 |
if commit is not None: |
| 1529 |
commit = commit[:commit_length] |
| 1530 |
timestamp = dt.datetime.strptime(root[0].attrib["date"] + "+0000", "%Y%m%d%H%M%S%z") |
| 1531 |
|
| 1532 |
code, msg = _run_cmd("darcs show tags", path) |
| 1533 |
if not msg: |
| 1534 |
try: |
| 1535 |
code, msg = _run_cmd("darcs log --count", path) |
| 1536 |
distance = int(msg) |
| 1537 |
except Exception: |
| 1538 |
distance = 0 |
| 1539 |
return cls._fallback(strict, distance=distance, commit=commit, dirty=dirty, timestamp=timestamp, vcs=vcs) |
| 1540 |
tags = msg.splitlines() |
| 1541 |
|
| 1542 |
matched_pattern = _match_version_pattern(pattern, tags, latest_tag, highest_tag, strict, pattern_prefix) |
| 1543 |
if matched_pattern is None: |
| 1544 |
return cls._fallback( |
| 1545 |
strict, |
| 1546 |
distance=distance, |
| 1547 |
commit=commit, |
| 1548 |
dirty=dirty, |
| 1549 |
timestamp=timestamp, |
| 1550 |
vcs=vcs, |
| 1551 |
) |
| 1552 |
tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern |
| 1553 |
|
| 1554 |
code, msg = _run_cmd("darcs log --from-tag {} --count".format(tag), path) |
| 1555 |
# The tag itself is in the list, so offset by 1. |
| 1556 |
distance = int(msg) - 1 |
| 1557 |
|
| 1558 |
version = cls( |
| 1559 |
base, |
| 1560 |
stage=stage, |
| 1561 |
distance=distance, |
| 1562 |
commit=commit, |
| 1563 |
dirty=dirty, |
| 1564 |
tagged_metadata=tagged_metadata, |
| 1565 |
epoch=epoch, |
| 1566 |
timestamp=timestamp, |
| 1567 |
vcs=vcs, |
| 1568 |
) |
| 1569 |
version._matched_tag = tag |
| 1570 |
version._newer_unmatched_tags = unmatched |
| 1571 |
return version |
| 1572 |
|
| 1573 |
@classmethod |
| 1574 |
def from_subversion( |
| 1575 |
cls, |
| 1576 |
pattern: Union[str, Pattern] = Pattern.Default, |
| 1577 |
latest_tag: bool = False, |
| 1578 |
tag_dir: str = "tags", |
| 1579 |
strict: bool = False, |
| 1580 |
path: Optional[Path] = None, |
| 1581 |
pattern_prefix: Optional[str] = None, |
| 1582 |
commit_length: Optional[int] = None, |
| 1583 |
highest_tag: bool = False, |
| 1584 |
) -> "Version": |
| 1585 |
r""" |
| 1586 |
Determine a version based on Subversion tags. |
| 1587 |
|
| 1588 |
:param pattern: Regular expression matched against the version source. |
| 1589 |
Refer to `from_any_vcs` for more info. |
| 1590 |
:param latest_tag: If true, only inspect the latest tag on the latest |
| 1591 |
tagged commit for a pattern match. If false, keep looking at tags |
| 1592 |
until there is a match. |
| 1593 |
:param tag_dir: Location of tags relative to the root. |
| 1594 |
:param strict: Elevate warnings to errors. |
| 1595 |
When there are no tags, fail instead of falling back to 0.0.0. |
| 1596 |
:param path: Directory to inspect, if not the current working directory. |
| 1597 |
:param pattern_prefix: Insert this after the pattern's start anchor (`^`). |
| 1598 |
:param commit_length: |
| 1599 |
Use this many characters from the start of the full commit hash. |
| 1600 |
:param highest_tag: |
| 1601 |
Only inspect the numerically highest tag across all tagged commits for a pattern match. |
| 1602 |
:returns: Detected version. |
| 1603 |
""" |
| 1604 |
vcs = Vcs.Subversion |
| 1605 |
_detect_vcs(vcs, path) |
| 1606 |
|
| 1607 |
tag_dir = tag_dir.strip("/") |
| 1608 |
|
| 1609 |
code, msg = _run_cmd("svn status", path) |
| 1610 |
dirty = bool(msg) |
| 1611 |
|
| 1612 |
code, msg = _run_cmd("svn info --show-item repos-root-url", path) |
| 1613 |
url = msg.strip("/") |
| 1614 |
|
| 1615 |
code, msg = _run_cmd("svn info --show-item revision", path) |
| 1616 |
if not msg or msg == "0": |
| 1617 |
commit = None |
| 1618 |
else: |
| 1619 |
commit = msg[:commit_length] |
| 1620 |
|
| 1621 |
timestamp = None |
| 1622 |
if commit: |
| 1623 |
code, msg = _run_cmd("svn info --show-item last-changed-date", path) |
| 1624 |
timestamp = _parse_timestamp(msg) |
| 1625 |
|
| 1626 |
if not commit: |
| 1627 |
return cls._fallback(strict, distance=0, commit=commit, dirty=dirty, timestamp=timestamp, vcs=vcs) |
| 1628 |
code, msg = _run_cmd('svn ls -v -r {} "{}/{}"'.format(commit, url, tag_dir), path) |
| 1629 |
lines = [line.split(maxsplit=5) for line in msg.splitlines()[1:]] |
| 1630 |
tags_to_revs = {line[-1].strip("/"): int(line[0]) for line in lines} |
| 1631 |
if not tags_to_revs: |
| 1632 |
try: |
| 1633 |
distance = int(commit) |
| 1634 |
except Exception: |
| 1635 |
distance = 0 |
| 1636 |
return cls._fallback(strict, distance=distance, commit=commit, dirty=dirty, timestamp=timestamp, vcs=vcs) |
| 1637 |
tags_to_sources_revs = {} |
| 1638 |
for tag, rev in tags_to_revs.items(): |
| 1639 |
code, msg = _run_cmd('svn log -v "{}/{}/{}" --stop-on-copy'.format(url, tag_dir, tag), path) |
| 1640 |
for line in msg.splitlines(): |
| 1641 |
match = re.search(r"A /{}/{} \(from .+?:(\d+)\)".format(tag_dir, tag), line) |
| 1642 |
if match: |
| 1643 |
source = int(match.group(1)) |
| 1644 |
tags_to_sources_revs[tag] = (source, rev) |
| 1645 |
tags = sorted(tags_to_sources_revs, key=lambda x: tags_to_sources_revs[x], reverse=True) |
| 1646 |
|
| 1647 |
matched_pattern = _match_version_pattern(pattern, tags, latest_tag, highest_tag, strict, pattern_prefix) |
| 1648 |
if matched_pattern is None: |
| 1649 |
return cls._fallback( |
| 1650 |
strict, |
| 1651 |
distance=distance, |
| 1652 |
commit=commit, |
| 1653 |
dirty=dirty, |
| 1654 |
timestamp=timestamp, |
| 1655 |
vcs=vcs, |
| 1656 |
) |
| 1657 |
tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern |
| 1658 |
|
| 1659 |
source, rev = tags_to_sources_revs[tag] |
| 1660 |
# The tag itself is in the list, so offset by 1. |
| 1661 |
distance = int(commit) - 1 - source |
| 1662 |
|
| 1663 |
version = cls( |
| 1664 |
base, |
| 1665 |
stage=stage, |
| 1666 |
distance=distance, |
| 1667 |
commit=commit, |
| 1668 |
dirty=dirty, |
| 1669 |
tagged_metadata=tagged_metadata, |
| 1670 |
epoch=epoch, |
| 1671 |
timestamp=timestamp, |
| 1672 |
vcs=vcs, |
| 1673 |
) |
| 1674 |
version._matched_tag = tag |
| 1675 |
version._newer_unmatched_tags = unmatched |
| 1676 |
return version |
| 1677 |
|
| 1678 |
@classmethod |
| 1679 |
def from_bazaar( |
| 1680 |
cls, |
| 1681 |
pattern: Union[str, Pattern] = Pattern.Default, |
| 1682 |
latest_tag: bool = False, |
| 1683 |
strict: bool = False, |
| 1684 |
path: Optional[Path] = None, |
| 1685 |
pattern_prefix: Optional[str] = None, |
| 1686 |
commit_length: Optional[int] = None, |
| 1687 |
highest_tag: bool = False, |
| 1688 |
) -> "Version": |
| 1689 |
r""" |
| 1690 |
Determine a version based on Bazaar tags. |
| 1691 |
|
| 1692 |
:param pattern: Regular expression matched against the version source. |
| 1693 |
Refer to `from_any_vcs` for more info. |
| 1694 |
:param latest_tag: If true, only inspect the latest tag on the latest |
| 1695 |
tagged commit for a pattern match. If false, keep looking at tags |
| 1696 |
until there is a match. |
| 1697 |
:param strict: Elevate warnings to errors. |
| 1698 |
When there are no tags, fail instead of falling back to 0.0.0. |
| 1699 |
:param path: Directory to inspect, if not the current working directory. |
| 1700 |
:param pattern_prefix: Insert this after the pattern's start anchor (`^`). |
| 1701 |
:param commit_length: |
| 1702 |
Use this many characters from the start of the full commit hash. |
| 1703 |
:param highest_tag: |
| 1704 |
Only inspect the numerically highest tag across all tagged commits for a pattern match. |
| 1705 |
:returns: Detected version. |
| 1706 |
""" |
| 1707 |
vcs = Vcs.Bazaar |
| 1708 |
_detect_vcs(vcs, path) |
| 1709 |
|
| 1710 |
code, msg = _run_cmd("bzr status", path) |
| 1711 |
dirty = msg != "" |
| 1712 |
|
| 1713 |
code, msg = _run_cmd("bzr log --limit 1", path) |
| 1714 |
commit = None |
| 1715 |
branch = None |
| 1716 |
timestamp = None |
| 1717 |
for line in msg.splitlines(): |
| 1718 |
info = line.split("revno: ", maxsplit=1) |
| 1719 |
if len(info) == 2: |
| 1720 |
commit = info[1][:commit_length] |
| 1721 |
|
| 1722 |
info = line.split("branch nick: ", maxsplit=1) |
| 1723 |
if len(info) == 2: |
| 1724 |
branch = info[1] |
| 1725 |
|
| 1726 |
info = line.split("timestamp: ", maxsplit=1) |
| 1727 |
if len(info) == 2: |
| 1728 |
timestamp = dt.datetime.strptime(info[1], "%a %Y-%m-%d %H:%M:%S %z") |
| 1729 |
|
| 1730 |
code, msg = _run_cmd("bzr tags", path) |
| 1731 |
if not msg or not commit: |
| 1732 |
try: |
| 1733 |
distance = int(commit) if commit is not None else 0 |
| 1734 |
except Exception: |
| 1735 |
distance = 0 |
| 1736 |
return cls._fallback( |
| 1737 |
strict, |
| 1738 |
distance=distance, |
| 1739 |
commit=commit, |
| 1740 |
dirty=dirty, |
| 1741 |
branch=branch, |
| 1742 |
timestamp=timestamp, |
| 1743 |
vcs=vcs, |
| 1744 |
) |
| 1745 |
tags_to_revs = {line.split()[0]: int(line.split()[1]) for line in msg.splitlines() if line.split()[1] != "?"} |
| 1746 |
tags = [x[1] for x in sorted([(v, k) for k, v in tags_to_revs.items()], reverse=True)] |
| 1747 |
|
| 1748 |
matched_pattern = _match_version_pattern(pattern, tags, latest_tag, highest_tag, strict, pattern_prefix) |
| 1749 |
if matched_pattern is None: |
| 1750 |
return cls._fallback( |
| 1751 |
strict, |
| 1752 |
distance=distance, |
| 1753 |
commit=commit, |
| 1754 |
dirty=dirty, |
| 1755 |
branch=branch, |
| 1756 |
timestamp=timestamp, |
| 1757 |
vcs=vcs, |
| 1758 |
) |
| 1759 |
tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern |
| 1760 |
|
| 1761 |
distance = int(commit) - tags_to_revs[tag] |
| 1762 |
|
| 1763 |
version = cls( |
| 1764 |
base, |
| 1765 |
stage=stage, |
| 1766 |
distance=distance, |
| 1767 |
commit=commit, |
| 1768 |
dirty=dirty, |
| 1769 |
tagged_metadata=tagged_metadata, |
| 1770 |
epoch=epoch, |
| 1771 |
branch=branch, |
| 1772 |
timestamp=timestamp, |
| 1773 |
vcs=vcs, |
| 1774 |
) |
| 1775 |
version._matched_tag = tag |
| 1776 |
version._newer_unmatched_tags = unmatched |
| 1777 |
return version |
| 1778 |
|
| 1779 |
@classmethod |
| 1780 |
def from_fossil( |
| 1781 |
cls, |
| 1782 |
pattern: Union[str, Pattern] = Pattern.Default, |
| 1783 |
latest_tag: bool = False, |
| 1784 |
strict: bool = False, |
| 1785 |
path: Optional[Path] = None, |
| 1786 |
pattern_prefix: Optional[str] = None, |
| 1787 |
commit_length: Optional[int] = None, |
| 1788 |
highest_tag: bool = False, |
| 1789 |
) -> "Version": |
| 1790 |
r""" |
| 1791 |
Determine a version based on Fossil tags. |
| 1792 |
|
| 1793 |
:param pattern: Regular expression matched against the version source. |
| 1794 |
Refer to `from_any_vcs` for more info. |
| 1795 |
:param latest_tag: If true, only inspect the latest tag for a pattern |
| 1796 |
match. If false, keep looking at tags until there is a match. |
| 1797 |
:param strict: Elevate warnings to errors. |
| 1798 |
When there are no tags, fail instead of falling back to 0.0.0. |
| 1799 |
:param path: Directory to inspect, if not the current working directory. |
| 1800 |
:param pattern_prefix: Insert this after the pattern's start anchor (`^`). |
| 1801 |
:param commit_length: |
| 1802 |
Use this many characters from the start of the full commit hash. |
| 1803 |
:param highest_tag: |
| 1804 |
Only inspect the numerically highest tag across all tagged commits for a pattern match. |
| 1805 |
:returns: Detected version. |
| 1806 |
""" |
| 1807 |
vcs = Vcs.Fossil |
| 1808 |
_detect_vcs(vcs, path) |
| 1809 |
|
| 1810 |
code, msg = _run_cmd("fossil changes --differ", path) |
| 1811 |
dirty = bool(msg) |
| 1812 |
|
| 1813 |
code, msg = _run_cmd("fossil branch current", path) |
| 1814 |
branch = msg |
| 1815 |
|
| 1816 |
code, msg = _run_cmd("fossil sql \"SELECT value FROM vvar WHERE name = 'checkout-hash' LIMIT 1\"", path) |
| 1817 |
commit = msg.strip("'")[:commit_length] |
| 1818 |
|
| 1819 |
code, msg = _run_cmd( |
| 1820 |
'fossil sql "' |
| 1821 |
"SELECT DATETIME(mtime) FROM event JOIN blob ON event.objid=blob.rid WHERE type = 'ci'" |
| 1822 |
" AND uuid = (SELECT value FROM vvar WHERE name = 'checkout-hash' LIMIT 1) LIMIT 1\"", |
| 1823 |
path, |
| 1824 |
) |
| 1825 |
timestamp = dt.datetime.strptime(msg.strip("'") + "+0000", "%Y-%m-%d %H:%M:%S%z") |
| 1826 |
|
| 1827 |
code, msg = _run_cmd("fossil sql \"SELECT count() FROM event WHERE type = 'ci'\"", path) |
| 1828 |
# The repository creation itself counts as a commit. |
| 1829 |
total_commits = int(msg) - 1 |
| 1830 |
if total_commits <= 0: |
| 1831 |
return cls._fallback( |
| 1832 |
strict, |
| 1833 |
distance=0, |
| 1834 |
commit=commit, |
| 1835 |
dirty=dirty, |
| 1836 |
branch=branch, |
| 1837 |
timestamp=timestamp, |
| 1838 |
vcs=vcs, |
| 1839 |
) |
| 1840 |
|
| 1841 |
# Based on `compute_direct_ancestors` from descendants.c in the |
| 1842 |
# Fossil source code: |
| 1843 |
query = """ |
| 1844 |
CREATE TEMP TABLE IF NOT EXISTS |
| 1845 |
dunamai_ancestor( |
| 1846 |
rid INTEGER UNIQUE NOT NULL, |
| 1847 |
generation INTEGER PRIMARY KEY |
| 1848 |
); |
| 1849 |
DELETE FROM dunamai_ancestor; |
| 1850 |
WITH RECURSIVE g(x, i) |
| 1851 |
AS ( |
| 1852 |
VALUES((SELECT value FROM vvar WHERE name = 'checkout' LIMIT 1), 1) |
| 1853 |
UNION ALL |
| 1854 |
SELECT plink.pid, g.i + 1 FROM plink, g |
| 1855 |
WHERE plink.cid = g.x AND plink.isprim |
| 1856 |
) |
| 1857 |
INSERT INTO dunamai_ancestor(rid, generation) SELECT x, i FROM g; |
| 1858 |
SELECT tag.tagname, dunamai_ancestor.generation |
| 1859 |
FROM tag |
| 1860 |
JOIN tagxref ON tag.tagid = tagxref.tagid |
| 1861 |
JOIN event ON tagxref.origid = event.objid |
| 1862 |
JOIN dunamai_ancestor ON tagxref.origid = dunamai_ancestor.rid |
| 1863 |
WHERE tagxref.tagtype = 1 |
| 1864 |
ORDER BY event.mtime DESC, tagxref.mtime DESC; |
| 1865 |
""" |
| 1866 |
code, msg = _run_cmd('fossil sql "{}"'.format(" ".join(query.splitlines())), path) |
| 1867 |
if not msg: |
| 1868 |
try: |
| 1869 |
distance = int(total_commits) |
| 1870 |
except Exception: |
| 1871 |
distance = 0 |
| 1872 |
return cls._fallback( |
| 1873 |
strict, |
| 1874 |
distance=distance, |
| 1875 |
commit=commit, |
| 1876 |
dirty=dirty, |
| 1877 |
branch=branch, |
| 1878 |
timestamp=timestamp, |
| 1879 |
vcs=vcs, |
| 1880 |
) |
| 1881 |
|
| 1882 |
tags_to_distance = [ |
| 1883 |
(line.rsplit(",", 1)[0][5:-1], int(line.rsplit(",", 1)[1]) - 1) for line in msg.splitlines() |
| 1884 |
] |
| 1885 |
|
| 1886 |
matched_pattern = _match_version_pattern( |
| 1887 |
pattern, [t for t, d in tags_to_distance], latest_tag, highest_tag, strict, pattern_prefix |
| 1888 |
) |
| 1889 |
if matched_pattern is None: |
| 1890 |
return cls._fallback( |
| 1891 |
strict, |
| 1892 |
distance=distance, |
| 1893 |
commit=commit, |
| 1894 |
dirty=dirty, |
| 1895 |
branch=branch, |
| 1896 |
timestamp=timestamp, |
| 1897 |
vcs=vcs, |
| 1898 |
) |
| 1899 |
tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern |
| 1900 |
|
| 1901 |
distance = dict(tags_to_distance)[tag] |
| 1902 |
|
| 1903 |
version = cls( |
| 1904 |
base, |
| 1905 |
stage=stage, |
| 1906 |
distance=distance, |
| 1907 |
commit=commit, |
| 1908 |
dirty=dirty, |
| 1909 |
tagged_metadata=tagged_metadata, |
| 1910 |
epoch=epoch, |
| 1911 |
branch=branch, |
| 1912 |
timestamp=timestamp, |
| 1913 |
vcs=vcs, |
| 1914 |
) |
| 1915 |
version._matched_tag = tag |
| 1916 |
version._newer_unmatched_tags = unmatched |
| 1917 |
return version |
| 1918 |
|
| 1919 |
@classmethod |
| 1920 |
def from_pijul( |
| 1921 |
cls, |
| 1922 |
pattern: Union[str, Pattern] = Pattern.Default, |
| 1923 |
latest_tag: bool = False, |
| 1924 |
strict: bool = False, |
| 1925 |
path: Optional[Path] = None, |
| 1926 |
pattern_prefix: Optional[str] = None, |
| 1927 |
commit_length: Optional[int] = None, |
| 1928 |
highest_tag: bool = False, |
| 1929 |
) -> "Version": |
| 1930 |
r""" |
| 1931 |
Determine a version based on Pijul tags. |
| 1932 |
|
| 1933 |
:param pattern: Regular expression matched against the version source. |
| 1934 |
Refer to `from_any_vcs` for more info. |
| 1935 |
:param latest_tag: If true, only inspect the latest tag on the latest |
| 1936 |
tagged commit for a pattern match. If false, keep looking at tags |
| 1937 |
until there is a match. |
| 1938 |
:param strict: Elevate warnings to errors. |
| 1939 |
When there are no tags, fail instead of falling back to 0.0.0. |
| 1940 |
:param path: Directory to inspect, if not the current working directory. |
| 1941 |
:param pattern_prefix: Insert this after the pattern's start anchor (`^`). |
| 1942 |
:param commit_length: |
| 1943 |
Use this many characters from the start of the full commit hash. |
| 1944 |
:param highest_tag: |
| 1945 |
Only inspect the numerically highest tag across all tagged commits for a pattern match. |
| 1946 |
:returns: Detected version. |
| 1947 |
""" |
| 1948 |
vcs = Vcs.Pijul |
| 1949 |
_detect_vcs(vcs, path) |
| 1950 |
|
| 1951 |
code, msg = _run_cmd("pijul diff --short", path) |
| 1952 |
dirty = msg.strip() != "" |
| 1953 |
|
| 1954 |
code, msg = _run_cmd("pijul channel", path) |
| 1955 |
branch = "main" |
| 1956 |
for line in msg.splitlines(): |
| 1957 |
if line.startswith("* "): |
| 1958 |
branch = line.split("* ", 1)[1] |
| 1959 |
break |
| 1960 |
|
| 1961 |
code, msg = _run_cmd("pijul log --limit 1 --output-format json", path, stderr=False) |
| 1962 |
limited_commits = json.loads(msg) |
| 1963 |
if len(limited_commits) == 0: |
| 1964 |
return cls._fallback(strict, dirty=dirty, branch=branch, vcs=vcs) |
| 1965 |
|
| 1966 |
commit = limited_commits[0]["hash"][:commit_length] |
| 1967 |
timestamp = _parse_timestamp(limited_commits[0]["timestamp"]) |
| 1968 |
|
| 1969 |
code, msg = _run_cmd("pijul log --output-format json", path) |
| 1970 |
channel_commits = json.loads(msg) |
| 1971 |
|
| 1972 |
code, msg = _run_cmd("pijul tag", path) |
| 1973 |
if not msg: |
| 1974 |
# The channel creation is in the list, so offset by 1. |
| 1975 |
distance = len(channel_commits) - 1 |
| 1976 |
return cls._fallback( |
| 1977 |
strict, |
| 1978 |
distance=distance, |
| 1979 |
commit=commit, |
| 1980 |
dirty=dirty, |
| 1981 |
branch=branch, |
| 1982 |
timestamp=timestamp, |
| 1983 |
vcs=vcs, |
| 1984 |
) |
| 1985 |
|
| 1986 |
tag_meta = [] # type: List[dict] |
| 1987 |
tag_state = "" |
| 1988 |
tag_timestamp = dt.datetime.now() |
| 1989 |
tag_message = "" |
| 1990 |
tag_after_header = False |
| 1991 |
for line in msg.splitlines(): |
| 1992 |
if not tag_after_header: |
| 1993 |
if line.startswith("State "): |
| 1994 |
tag_state = line.split("State ", 1)[1] |
| 1995 |
elif line.startswith("Date:"): |
| 1996 |
tag_timestamp = _parse_timestamp(line.split("Date: ", 1)[1]) |
| 1997 |
elif line.startswith(" "): |
| 1998 |
tag_message += line[4:] |
| 1999 |
tag_after_header = True |
| 2000 |
else: |
| 2001 |
if line.startswith("State "): |
| 2002 |
tag_meta.append( |
| 2003 |
{ |
| 2004 |
"state": tag_state, |
| 2005 |
"timestamp": tag_timestamp, |
| 2006 |
"message": tag_message.strip(), |
| 2007 |
} |
| 2008 |
) |
| 2009 |
|
| 2010 |
tag_state = line.split("State ", 1)[1] |
| 2011 |
tag_timestamp = dt.datetime.now() |
| 2012 |
tag_message = "" |
| 2013 |
tag_after_header = False |
| 2014 |
else: |
| 2015 |
tag_message += line |
| 2016 |
if tag_after_header: |
| 2017 |
tag_meta.append({"state": tag_state, "timestamp": tag_timestamp, "message": tag_message.strip()}) |
| 2018 |
|
| 2019 |
tag_meta_by_msg = {} # type: dict |
| 2020 |
for meta in tag_meta: |
| 2021 |
if ( |
| 2022 |
meta["message"] not in tag_meta_by_msg |
| 2023 |
or meta["timestamp"] > tag_meta_by_msg[meta["message"]]["timestamp"] |
| 2024 |
): |
| 2025 |
tag_meta_by_msg[meta["message"]] = meta |
| 2026 |
|
| 2027 |
tags = [t["message"] for t in sorted(tag_meta_by_msg.values(), key=lambda x: x["timestamp"], reverse=True)] |
| 2028 |
|
| 2029 |
matched_pattern = _match_version_pattern(pattern, tags, latest_tag, highest_tag, strict, pattern_prefix) |
| 2030 |
if matched_pattern is None: |
| 2031 |
return cls._fallback( |
| 2032 |
strict, |
| 2033 |
distance=distance, |
| 2034 |
commit=commit, |
| 2035 |
dirty=dirty, |
| 2036 |
branch=branch, |
| 2037 |
timestamp=timestamp, |
| 2038 |
vcs=vcs, |
| 2039 |
) |
| 2040 |
tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern |
| 2041 |
|
| 2042 |
tag_id = tag_meta_by_msg[tag]["state"] |
| 2043 |
_run_cmd("pijul tag checkout {}".format(tag_id), path, codes=[0, 1]) |
| 2044 |
code, msg = _run_cmd("pijul log --output-format json --channel {}".format(tag_id), path) |
| 2045 |
if msg.strip() == "": |
| 2046 |
tag_commits = [] # type: list |
| 2047 |
else: |
| 2048 |
tag_commits = json.loads(msg) |
| 2049 |
|
| 2050 |
distance = len(channel_commits) - len(tag_commits) |
| 2051 |
|
| 2052 |
version = cls( |
| 2053 |
base, |
| 2054 |
stage=stage, |
| 2055 |
distance=distance, |
| 2056 |
commit=commit, |
| 2057 |
dirty=dirty, |
| 2058 |
tagged_metadata=tagged_metadata, |
| 2059 |
epoch=epoch, |
| 2060 |
branch=branch, |
| 2061 |
timestamp=timestamp, |
| 2062 |
vcs=vcs, |
| 2063 |
) |
| 2064 |
version._matched_tag = tag |
| 2065 |
version._newer_unmatched_tags = unmatched |
| 2066 |
return version |
| 2067 |
|
| 2068 |
@classmethod |
| 2069 |
def from_any_vcs( |
| 2070 |
cls, |
| 2071 |
pattern: Union[str, Pattern] = Pattern.Default, |
| 2072 |
latest_tag: bool = False, |
| 2073 |
tag_dir: str = "tags", |
| 2074 |
tag_branch: Optional[str] = None, |
| 2075 |
full_commit: bool = False, |
| 2076 |
strict: bool = False, |
| 2077 |
path: Optional[Path] = None, |
| 2078 |
pattern_prefix: Optional[str] = None, |
| 2079 |
ignore_untracked: bool = False, |
| 2080 |
commit_length: Optional[int] = None, |
| 2081 |
highest_tag: bool = False, |
| 2082 |
) -> "Version": |
| 2083 |
r""" |
| 2084 |
Determine a version based on a detected version control system. |
| 2085 |
|
| 2086 |
:param pattern: Regular expression matched against the version source. |
| 2087 |
This must contain one capture group named `base` corresponding to |
| 2088 |
the release segment of the source. Optionally, it may contain another |
| 2089 |
two groups named `stage` and `revision` corresponding to a prerelease |
| 2090 |
type (such as 'alpha' or 'rc') and number (such as in 'alpha-2' or 'rc3'). |
| 2091 |
It may also contain a group named `tagged_metadata` corresponding to extra |
| 2092 |
metadata after the main part of the version (typically after a plus sign). |
| 2093 |
There may also be a group named `epoch` for the PEP 440 concept. |
| 2094 |
|
| 2095 |
If the `base` group is not included, then this will be interpreted |
| 2096 |
as the name of a variant of the `Pattern` enum. For example, passing |
| 2097 |
`"default"` is the same as passing `Pattern.Default`. |
| 2098 |
:param latest_tag: If true, only inspect the latest tag on the latest |
| 2099 |
tagged commit for a pattern match. If false, keep looking at tags |
| 2100 |
until there is a match. |
| 2101 |
:param tag_dir: Location of tags relative to the root. |
| 2102 |
This is only used for Subversion. |
| 2103 |
:param tag_branch: Branch on which to find tags, if different than the |
| 2104 |
current branch. This is only used for Git currently. |
| 2105 |
:param full_commit: Get the full commit hash instead of the short form. |
| 2106 |
This is only used for Git and Mercurial. |
| 2107 |
:param strict: Elevate warnings to errors. |
| 2108 |
When there are no tags, fail instead of falling back to 0.0.0. |
| 2109 |
:param path: Directory to inspect, if not the current working directory. |
| 2110 |
:param pattern_prefix: Insert this after the pattern's start anchor (`^`). |
| 2111 |
:param ignore_untracked: |
| 2112 |
Ignore untracked files when determining whether the repository is dirty. |
| 2113 |
This is only used for Git currently. |
| 2114 |
:param commit_length: |
| 2115 |
Use this many characters from the start of the full commit hash. |
| 2116 |
:param highest_tag: |
| 2117 |
Only inspect the numerically highest tag across all tagged commits for a pattern match. |
| 2118 |
:returns: Detected version. |
| 2119 |
""" |
| 2120 |
vcs = _detect_vcs_from_archival(path) |
| 2121 |
if vcs is None: |
| 2122 |
vcs = _detect_vcs(None, path) |
| 2123 |
return cls._do_vcs_callback( |
| 2124 |
vcs, |
| 2125 |
pattern, |
| 2126 |
latest_tag, |
| 2127 |
tag_dir, |
| 2128 |
tag_branch, |
| 2129 |
full_commit, |
| 2130 |
strict, |
| 2131 |
path, |
| 2132 |
pattern_prefix, |
| 2133 |
ignore_untracked, |
| 2134 |
commit_length, |
| 2135 |
highest_tag, |
| 2136 |
) |
| 2137 |
|
| 2138 |
@classmethod |
| 2139 |
def from_vcs( |
| 2140 |
cls, |
| 2141 |
vcs: Vcs, |
| 2142 |
pattern: Union[str, Pattern] = Pattern.Default, |
| 2143 |
latest_tag: bool = False, |
| 2144 |
tag_dir: str = "tags", |
| 2145 |
tag_branch: Optional[str] = None, |
| 2146 |
full_commit: bool = False, |
| 2147 |
strict: bool = False, |
| 2148 |
path: Optional[Path] = None, |
| 2149 |
pattern_prefix: Optional[str] = None, |
| 2150 |
ignore_untracked: bool = False, |
| 2151 |
commit_length: Optional[int] = None, |
| 2152 |
highest_tag: bool = False, |
| 2153 |
) -> "Version": |
| 2154 |
r""" |
| 2155 |
Determine a version based on a specific VCS setting. |
| 2156 |
|
| 2157 |
This is primarily intended for other tools that want to generically |
| 2158 |
use some VCS setting based on user configuration, without having to |
| 2159 |
maintain a mapping from the VCS name to the appropriate function. |
| 2160 |
|
| 2161 |
:param pattern: Regular expression matched against the version source. |
| 2162 |
Refer to `from_any_vcs` for more info. |
| 2163 |
:param latest_tag: If true, only inspect the latest tag on the latest |
| 2164 |
tagged commit for a pattern match. If false, keep looking at tags |
| 2165 |
until there is a match. |
| 2166 |
:param tag_dir: Location of tags relative to the root. |
| 2167 |
This is only used for Subversion. |
| 2168 |
:param tag_branch: Branch on which to find tags, if different than the |
| 2169 |
current branch. This is only used for Git currently. |
| 2170 |
:param full_commit: Get the full commit hash instead of the short form. |
| 2171 |
This is only used for Git and Mercurial. |
| 2172 |
:param strict: Elevate warnings to errors. |
| 2173 |
When there are no tags, fail instead of falling back to 0.0.0. |
| 2174 |
:param path: Directory to inspect, if not the current working directory. |
| 2175 |
:param pattern_prefix: Insert this after the pattern's start anchor (`^`). |
| 2176 |
:param ignore_untracked: |
| 2177 |
Ignore untracked files when determining whether the repository is dirty. |
| 2178 |
This is only used for Git currently. |
| 2179 |
:param commit_length: |
| 2180 |
Use this many characters from the start of the full commit hash. |
| 2181 |
:param highest_tag: |
| 2182 |
Only inspect the numerically highest tag across all tagged commits for a pattern match. |
| 2183 |
:returns: Detected version. |
| 2184 |
""" |
| 2185 |
return cls._do_vcs_callback( |
| 2186 |
vcs, |
| 2187 |
pattern, |
| 2188 |
latest_tag, |
| 2189 |
tag_dir, |
| 2190 |
tag_branch, |
| 2191 |
full_commit, |
| 2192 |
strict, |
| 2193 |
path, |
| 2194 |
pattern_prefix, |
| 2195 |
ignore_untracked, |
| 2196 |
commit_length, |
| 2197 |
highest_tag, |
| 2198 |
) |
| 2199 |
|
| 2200 |
@classmethod |
| 2201 |
def _do_vcs_callback( |
| 2202 |
cls, |
| 2203 |
vcs: Vcs, |
| 2204 |
pattern: Union[str, Pattern], |
| 2205 |
latest_tag: bool, |
| 2206 |
tag_dir: str, |
| 2207 |
tag_branch: Optional[str], |
| 2208 |
full_commit: bool, |
| 2209 |
strict: bool, |
| 2210 |
path: Optional[Path], |
| 2211 |
pattern_prefix: Optional[str] = None, |
| 2212 |
ignore_untracked: bool = False, |
| 2213 |
commit_length: Optional[int] = None, |
| 2214 |
highest_tag: bool = False, |
| 2215 |
) -> "Version": |
| 2216 |
mapping = { |
| 2217 |
Vcs.Any: cls.from_any_vcs, |
| 2218 |
Vcs.Git: cls.from_git, |
| 2219 |
Vcs.Mercurial: cls.from_mercurial, |
| 2220 |
Vcs.Darcs: cls.from_darcs, |
| 2221 |
Vcs.Subversion: cls.from_subversion, |
| 2222 |
Vcs.Bazaar: cls.from_bazaar, |
| 2223 |
Vcs.Fossil: cls.from_fossil, |
| 2224 |
Vcs.Pijul: cls.from_pijul, |
| 2225 |
} # type: Mapping[Vcs, Callable[..., "Version"]] |
| 2226 |
kwargs = {} |
| 2227 |
callback = mapping[vcs] |
| 2228 |
for kwarg, value in [ |
| 2229 |
("pattern", pattern), |
| 2230 |
("latest_tag", latest_tag), |
| 2231 |
("tag_dir", tag_dir), |
| 2232 |
("tag_branch", tag_branch), |
| 2233 |
("full_commit", full_commit), |
| 2234 |
("strict", strict), |
| 2235 |
("path", path), |
| 2236 |
("pattern_prefix", pattern_prefix), |
| 2237 |
("ignore_untracked", ignore_untracked), |
| 2238 |
("commit_length", commit_length), |
| 2239 |
("highest_tag", highest_tag), |
| 2240 |
]: |
| 2241 |
if kwarg in inspect.getfullargspec(callback).args: |
| 2242 |
kwargs[kwarg] = value |
| 2243 |
return callback(**kwargs) |
| 2244 |
|
| 2245 |
|
| 2246 |
def check_version(version: str, style: Style = Style.Pep440) -> None: |
| 2247 |
""" |
| 2248 |
Check if a version is valid for a style. |
| 2249 |
|
| 2250 |
:param version: Version to check. |
| 2251 |
:param style: Style against which to check. |
| 2252 |
:raises ValueError: If the version is invalid. |
| 2253 |
""" |
| 2254 |
name, pattern = { |
| 2255 |
Style.Pep440: ("PEP 440", _VALID_PEP440), |
| 2256 |
Style.SemVer: ("Semantic Versioning", _VALID_SEMVER), |
| 2257 |
Style.Pvp: ("PVP", _VALID_PVP), |
| 2258 |
}[style] |
| 2259 |
failure_message = "Version '{}' does not conform to the {} style".format(version, name) |
| 2260 |
if not re.search(pattern, version): |
| 2261 |
raise ValueError(failure_message) |
| 2262 |
if style == Style.SemVer: |
| 2263 |
parts = re.split(r"[.-]", version.split("+", 1)[0]) |
| 2264 |
if any(re.search(r"^0[0-9]+$", x) for x in parts): |
| 2265 |
raise ValueError(failure_message) |
| 2266 |
|
| 2267 |
|
| 2268 |
def get_version( |
| 2269 |
name: str, |
| 2270 |
first_choice: Optional[Callable[[], Optional[Version]]] = None, |
| 2271 |
third_choice: Optional[Callable[[], Optional[Version]]] = None, |
| 2272 |
fallback: Version = Version("0.0.0"), |
| 2273 |
ignore: Optional[Sequence[Version]] = None, |
| 2274 |
parser: Callable[[str], Version] = Version, |
| 2275 |
) -> Version: |
| 2276 |
""" |
| 2277 |
Check importlib-metadata info or a fallback function to determine the version. |
| 2278 |
This is intended as a convenient default for setting your `__version__` if |
| 2279 |
you do not want to include a generated version statically during packaging. |
| 2280 |
|
| 2281 |
:param name: Installed package name. |
| 2282 |
:param first_choice: Callback to determine a version before checking |
| 2283 |
to see if the named package is installed. |
| 2284 |
:param third_choice: Callback to determine a version if the installed |
| 2285 |
package cannot be found by name. |
| 2286 |
:param fallback: If no other matches found, use this version. |
| 2287 |
:param ignore: Ignore a found version if it is part of this list. When |
| 2288 |
comparing the found version to an ignored one, fields with None in the ignored |
| 2289 |
version are not taken into account. If the ignored version has distance=0, |
| 2290 |
then that field is also ignored. |
| 2291 |
:param parser: Callback to convert a string into a Version instance. |
| 2292 |
This will be used for the second choice. |
| 2293 |
For example, you can pass `Version.parse` here. |
| 2294 |
:returns: First available version. |
| 2295 |
""" |
| 2296 |
if ignore is None: |
| 2297 |
ignore = [] |
| 2298 |
|
| 2299 |
if first_choice: |
| 2300 |
first_ver = first_choice() |
| 2301 |
if first_ver and not any(first_ver._matches_partial(v) for v in ignore): |
| 2302 |
return first_ver |
| 2303 |
|
| 2304 |
try: |
| 2305 |
import importlib.metadata as ilm |
| 2306 |
except ImportError: |
| 2307 |
import importlib_metadata as ilm # type: ignore |
| 2308 |
try: |
| 2309 |
ilm_version = parser(ilm.version(name)) |
| 2310 |
if not any(ilm_version._matches_partial(v) for v in ignore): |
| 2311 |
return ilm_version |
| 2312 |
except ilm.PackageNotFoundError: |
| 2313 |
pass |
| 2314 |
|
| 2315 |
if third_choice: |
| 2316 |
third_ver = third_choice() |
| 2317 |
if third_ver and not any(third_ver._matches_partial(v) for v in ignore): |
| 2318 |
return third_ver |
| 2319 |
|
| 2320 |
return fallback |
| 2321 |
|
| 2322 |
|
| 2323 |
def serialize_pep440( |
| 2324 |
base: str, |
| 2325 |
stage: Optional[str] = None, |
| 2326 |
revision: Optional[int] = None, |
| 2327 |
post: Optional[int] = None, |
| 2328 |
dev: Optional[int] = None, |
| 2329 |
epoch: Optional[int] = None, |
| 2330 |
metadata: Optional[Sequence[Union[str, int]]] = None, |
| 2331 |
) -> str: |
| 2332 |
""" |
| 2333 |
Serialize a version based on PEP 440. |
| 2334 |
Use this instead of `Version.serialize()` if you want more control |
| 2335 |
over how the version is mapped. |
| 2336 |
|
| 2337 |
:param base: Release segment, such as 0.1.0. |
| 2338 |
:param stage: Pre-release stage ("a", "b", or "rc"). |
| 2339 |
:param revision: Pre-release revision (e.g., 1 as in "rc1"). |
| 2340 |
This is ignored when `stage` is None. |
| 2341 |
:param post: Post-release number. |
| 2342 |
:param dev: Developmental release number. |
| 2343 |
:param epoch: Epoch number. |
| 2344 |
:param metadata: Any local version label segments. |
| 2345 |
:returns: Serialized version. |
| 2346 |
""" |
| 2347 |
out = [] # type: list |
| 2348 |
|
| 2349 |
if epoch is not None: |
| 2350 |
out.extend([epoch, "!"]) |
| 2351 |
|
| 2352 |
out.append(base) |
| 2353 |
|
| 2354 |
if stage is not None: |
| 2355 |
alternative_stages = {"alpha": "a", "beta": "b", "c": "rc", "pre": "rc", "preview": "rc"} |
| 2356 |
out.append(alternative_stages.get(stage.lower(), stage.lower())) |
| 2357 |
if revision is None: |
| 2358 |
# PEP 440 does not allow omitting the revision, so assume 0. |
| 2359 |
out.append(0) |
| 2360 |
else: |
| 2361 |
out.append(revision) |
| 2362 |
|
| 2363 |
if post is not None: |
| 2364 |
out.extend([".post", post]) |
| 2365 |
|
| 2366 |
if dev is not None: |
| 2367 |
out.extend([".dev", dev]) |
| 2368 |
|
| 2369 |
if metadata is not None and len(metadata) > 0: |
| 2370 |
out.extend(["+", ".".join(map(str, metadata))]) |
| 2371 |
|
| 2372 |
serialized = "".join(map(str, out)) |
| 2373 |
check_version(serialized, Style.Pep440) |
| 2374 |
return serialized |
| 2375 |
|
| 2376 |
|
| 2377 |
def serialize_semver( |
| 2378 |
base: str, |
| 2379 |
pre: Optional[Sequence[Union[str, int]]] = None, |
| 2380 |
metadata: Optional[Sequence[Union[str, int]]] = None, |
| 2381 |
) -> str: |
| 2382 |
""" |
| 2383 |
Serialize a version based on Semantic Versioning. |
| 2384 |
Use this instead of `Version.serialize()` if you want more control |
| 2385 |
over how the version is mapped. |
| 2386 |
|
| 2387 |
:param base: Version core, such as 0.1.0. |
| 2388 |
:param pre: Pre-release identifiers. |
| 2389 |
:param metadata: Build metadata identifiers. |
| 2390 |
:returns: Serialized version. |
| 2391 |
""" |
| 2392 |
out = [base] |
| 2393 |
|
| 2394 |
if pre is not None and len(pre) > 0: |
| 2395 |
out.extend(["-", ".".join(map(str, pre))]) |
| 2396 |
|
| 2397 |
if metadata is not None and len(metadata) > 0: |
| 2398 |
out.extend(["+", ".".join(map(str, metadata))]) |
| 2399 |
|
| 2400 |
serialized = "".join(str(x) for x in out) |
| 2401 |
check_version(serialized, Style.SemVer) |
| 2402 |
return serialized |
| 2403 |
|
| 2404 |
|
| 2405 |
def serialize_pvp(base: str, metadata: Optional[Sequence[Union[str, int]]] = None) -> str: |
| 2406 |
""" |
| 2407 |
Serialize a version based on the Haskell Package Versioning Policy. |
| 2408 |
Use this instead of `Version.serialize()` if you want more control |
| 2409 |
over how the version is mapped. |
| 2410 |
|
| 2411 |
:param base: Version core, such as 0.1.0. |
| 2412 |
:param metadata: Version tag metadata. |
| 2413 |
:returns: Serialized version. |
| 2414 |
""" |
| 2415 |
out = [base] |
| 2416 |
|
| 2417 |
if metadata is not None and len(metadata) > 0: |
| 2418 |
out.extend(["-", "-".join(map(str, metadata))]) |
| 2419 |
|
| 2420 |
serialized = "".join(map(str, out)) |
| 2421 |
check_version(serialized, Style.Pvp) |
| 2422 |
return serialized |
| 2423 |
|
| 2424 |
|
| 2425 |
def bump_version(base: str, index: int = -1, increment: int = 1) -> str: |
| 2426 |
""" |
| 2427 |
Increment one of the numerical positions of a version. |
| 2428 |
|
| 2429 |
:param base: Version core, such as 0.1.0. |
| 2430 |
Do not include pre-release identifiers. |
| 2431 |
:param index: Numerical position to increment. |
| 2432 |
This follows Python indexing rules, so positive numbers start from |
| 2433 |
the left side and count up from 0, while negative numbers start from |
| 2434 |
the right side and count down from -1. |
| 2435 |
:param increment: By how much the `index` needs to increment. |
| 2436 |
:returns: Bumped version. |
| 2437 |
""" |
| 2438 |
bases = [int(x) for x in base.split(".")] |
| 2439 |
bases[index] += increment |
| 2440 |
|
| 2441 |
limit = 0 if index < 0 else len(bases) |
| 2442 |
i = index + 1 |
| 2443 |
while i < limit: |
| 2444 |
bases[i] = 0 |
| 2445 |
i += 1 |
| 2446 |
|
| 2447 |
return ".".join(str(x) for x in bases) |
| 2448 |
|
| 2449 |
|
| 2450 |
def _parse_git_timestamp_iso_strict(raw: str) -> dt.datetime: |
| 2451 |
# Remove colon from timezone offset for pre-3.7 Python: |
| 2452 |
compat = re.sub(r"(.*T.*[-+]\d+):(\d+)", r"\1\2", raw) |
| 2453 |
return _parse_timestamp(compat, _TIMESTAMP_GIT_ISO_STRICT) |
| 2454 |
|
| 2455 |
|
| 2456 |
def _parse_git_timestamp_iso(raw: str) -> dt.datetime: |
| 2457 |
# Remove colon from timezone offset for pre-3.7 Python: |
| 2458 |
compat = re.sub(r"(.* .* [-+]\d+):(\d+)", r"\1\2", raw) |
| 2459 |
return _parse_timestamp(compat, _TIMESTAMP_GIT_ISO) |
| 2460 |
|
| 2461 |
|
| 2462 |
def _parse_timestamp(raw: str, format: str = _TIMESTAMP_GENERIC) -> dt.datetime: |
| 2463 |
# Normalize "Z" for pre-3.7 compatibility: |
| 2464 |
normalized = re.sub(r"Z$", "+0000", raw) |
| 2465 |
# Truncate %f to six digits: |
| 2466 |
normalized = re.sub(r"\.(\d{6})\d+\+0000", r".\g<1>+0000", normalized) |
| 2467 |
|
| 2468 |
return dt.datetime.strptime(normalized, format) |
| 2469 |
|
| 2470 |
|
| 2471 |
__version__ = get_version("dunamai").serialize() |