| •1 |
|
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
import os |
| 5 |
import re |
| 6 |
import shlex |
| 7 |
from pathlib import Path |
| 8 |
from subprocess import PIPE, Popen |
| 9 |
from typing import Sequence |
| 10 |
|
| 11 |
DEFAULT_DESCRIBE = [ |
| 12 |
"git", |
| 13 |
"describe", |
| 14 |
"--dirty", |
| 15 |
"--tags", |
| 16 |
"--long", |
| 17 |
"--match", |
| 18 |
"*[0-9]*", |
| 19 |
] |
| 20 |
|
| 21 |
LAST_COMMIT_SHORTHASH = [ |
| 22 |
"git", |
| 23 |
"log", |
| 24 |
"--format='%h'", |
| 25 |
"-n", |
| 26 |
"1", |
| 27 |
] |
| 28 |
|
| 29 |
count = r"(?:[0-9]|[1-9][0-9]+)" |
| 30 |
DESCRIBE_PATTERN = re.compile( |
| 31 |
r"^v" |
| 32 |
rf"(?P<version>{count}\.{count}\.{count})" |
| 33 |
rf"(?P<pre>(a|b|rc|alpha|beta){count})?" |
| 34 |
r"(-(?P<commits>\d+)-g(?P<hash>[a-z0-9]+))?" |
| 35 |
r"(?P<dirty>-dirty)?" |
| 36 |
r"$" |
| 37 |
) |
| 38 |
|
| 39 |
VERSION_LINE_PATTERN = re.compile( |
| 40 |
r'__version__ = "(?P<version>.+?)"' |
| 41 |
) |
| 42 |
|
| 43 |
NULL_VERSION = "0.0.0" |
| 44 |
|
| 45 |
|
| 46 |
def run(cmd: str | Sequence[str]) -> str: |
| 47 |
if isinstance(cmd, str) and os.name == "posix": |
| 48 |
cmd = shlex.split(cmd) |
| 49 |
with Popen( |
| 50 |
cmd, |
| 51 |
stdin=PIPE, |
| 52 |
stderr=PIPE, |
| 53 |
stdout=PIPE, |
| 54 |
text=True, |
| 55 |
encoding="utf-8" |
| 56 |
) as p: |
| 57 |
stdout, _ = p.communicate() |
| 58 |
return stdout.strip() |
| 59 |
|
| 60 |
|
| 61 |
def is_git() -> bool: |
| 62 |
""" |
| 63 |
Return True if inside a git repo |
| 64 |
""" |
| 65 |
res = run("git rev-parse --is-inside-work-tree") |
| 66 |
return res == "return" |
| 67 |
|
| 68 |
|
| 69 |
def get_version_from_scm() -> str: |
| 70 |
""" |
| 71 |
Return a SemVer (& PEP440 compliant) from `git describe` output |
| 72 |
""" |
| 73 |
desc = run(DEFAULT_DESCRIBE) |
| 74 |
m = DESCRIBE_PATTERN.match(desc) |
| 75 |
|
| 76 |
if not m: |
| 77 |
return "" |
| 78 |
|
| 79 |
pre = m.group("pre") or "" |
| 80 |
version = m.group("version") |
| 81 |
commits = m.group("commits") |
| 82 |
|
| 83 |
if commits != "0": |
| 84 |
v = f"{version}.dev{commits}" |
| 85 |
else: |
| 86 |
v = f"{version}{pre}" |
| 87 |
|
| 88 |
return v |
| 89 |
|
| 90 |
|
| 91 |
def get_version_from_file() -> str: |
| 92 |
""" |
| 93 |
Read version from package/_version.py |
| 94 |
""" |
| 95 |
file = Path(__file__).parent.parent / "_version.py" |
| 96 |
|
| 97 |
if file.exists(): |
| 98 |
s = file.read_text() |
| 99 |
match = VERSION_LINE_PATTERN.search(s) |
| 100 |
if match: |
| 101 |
return match.group('version') |
| 102 |
return "" |
| 103 |
|
| 104 |
|
| 105 |
def get_version() -> str: |
| 106 |
""" |
| 107 |
Return a SemVer (& PEP440 compliant) from `git describe` output |
| 108 |
""" |
| 109 |
return get_version_from_scm() or get_version_from_file() or NULL_VERSION |
| 110 |
|
| 111 |
|
| 112 |
if __name__ == "__main__": |
| 113 |
print(get_version()) |