|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Print ITK_VERSION_TWEAK: commits since the closest ``v*`` tag. |
| 3 | +
|
| 4 | +CMake runs this at configure time to set the fourth (tweak) version |
| 5 | +component. The count comes from ``git describe`` in a working tree, or from |
| 6 | +the ``git archive``-substituted ``.git_archival.txt`` in an exported tarball; |
| 7 | +it falls back to ``0`` when neither is available. |
| 8 | +""" |
| 9 | + |
| 10 | +import re |
| 11 | +import subprocess |
| 12 | +import sys |
| 13 | +from pathlib import Path |
| 14 | + |
| 15 | +SOURCE_DIR = Path(__file__).resolve().parents[2] |
| 16 | +DESCRIBE_COUNT = re.compile(r"-(\d+)-g[0-9a-f]+$") |
| 17 | +VERSION_TAG = re.compile(r"^v[0-9]\S*$") |
| 18 | + |
| 19 | + |
| 20 | +def _count_from_describe(describe: str) -> int | None: |
| 21 | + match = DESCRIBE_COUNT.search(describe) |
| 22 | + if match: |
| 23 | + return int(match.group(1)) |
| 24 | + if VERSION_TAG.match(describe): |
| 25 | + return 0 |
| 26 | + return None |
| 27 | + |
| 28 | + |
| 29 | +def from_git(source_dir: Path) -> int | None: |
| 30 | + try: |
| 31 | + result = subprocess.run( |
| 32 | + [ |
| 33 | + "git", |
| 34 | + "-C", |
| 35 | + str(source_dir), |
| 36 | + "describe", |
| 37 | + "--tags", |
| 38 | + "--long", |
| 39 | + "--match", |
| 40 | + "v[0-9]*", |
| 41 | + ], |
| 42 | + capture_output=True, |
| 43 | + text=True, |
| 44 | + check=True, |
| 45 | + ) |
| 46 | + except (OSError, subprocess.CalledProcessError): |
| 47 | + return None |
| 48 | + return _count_from_describe(result.stdout.strip()) |
| 49 | + |
| 50 | + |
| 51 | +def from_archival(source_dir: Path) -> int | None: |
| 52 | + try: |
| 53 | + text = (source_dir / ".git_archival.txt").read_text() |
| 54 | + except OSError: |
| 55 | + return None |
| 56 | + for line in text.splitlines(): |
| 57 | + if line.startswith("describe-name:"): |
| 58 | + value = line.split(":", 1)[1].strip() |
| 59 | + if not value or value.startswith("$Format"): |
| 60 | + return None |
| 61 | + return _count_from_describe(value) |
| 62 | + return None |
| 63 | + |
| 64 | + |
| 65 | +def main() -> int: |
| 66 | + source_dir = Path(sys.argv[1]) if len(sys.argv) > 1 else SOURCE_DIR |
| 67 | + for compute in (from_git, from_archival): |
| 68 | + count = compute(source_dir) |
| 69 | + if count is not None: |
| 70 | + print(count) |
| 71 | + return 0 |
| 72 | + print(0) |
| 73 | + return 0 |
| 74 | + |
| 75 | + |
| 76 | +if __name__ == "__main__": |
| 77 | + sys.exit(main()) |
0 commit comments