|
9 | 9 | import os |
10 | 10 | import sys |
11 | 11 | import warnings |
| 12 | +from contextlib import suppress |
| 13 | +from pathlib import Path |
| 14 | + |
| 15 | +import git |
12 | 16 |
|
13 | 17 | VERSION = "5.1.0-dev" |
14 | | -__version__ = VERSION |
| 18 | + |
| 19 | +PROJECT_DIR = Path(__file__).resolve().parent |
| 20 | +ROOT_DIR = PROJECT_DIR.parent |
| 21 | + |
| 22 | + |
| 23 | +def get_version(version): |
| 24 | + """Return the version including the git describe tag when available.""" |
| 25 | + # The codebase is a git clone |
| 26 | + if git_describe := get_git_describe_from_local_checkout(): |
| 27 | + return git_describe |
| 28 | + |
| 29 | + # The codebase is an extracted git archive |
| 30 | + if git_describe := get_git_describe_from_version_file(): |
| 31 | + return git_describe |
| 32 | + |
| 33 | + return version |
| 34 | + |
| 35 | + |
| 36 | +def get_git_describe_from_local_checkout(): |
| 37 | + """ |
| 38 | + Return the git describe tag from the local checkout. |
| 39 | + This will only provide a result when the codebase is a git clone. |
| 40 | + """ |
| 41 | + with suppress(git.GitError): |
| 42 | + return git.Repo(".").git.describe(tags=True, always=True) |
| 43 | + |
| 44 | + |
| 45 | +def get_git_describe_from_version_file(version_file_location=ROOT_DIR / ".VERSION"): |
| 46 | + """ |
| 47 | + Return the git describe tag from the ".VERSION" file. |
| 48 | + This will only provide a result when the codebase is an extracted git archive |
| 49 | + """ |
| 50 | + try: |
| 51 | + version = version_file_location.read_text().strip() |
| 52 | + except (FileNotFoundError, UnicodeDecodeError): |
| 53 | + return |
| 54 | + |
| 55 | + if version and version.startswith("v"): |
| 56 | + return version |
| 57 | + |
| 58 | + |
| 59 | +def extract_short_commit(git_describe): |
| 60 | + """ |
| 61 | + Extract the short commit hash from a Git describe string while removing |
| 62 | + any leading "g" character if present. |
| 63 | + """ |
| 64 | + short_commit = git_describe.split("-")[-1] |
| 65 | + return short_commit.lstrip("g") |
| 66 | + |
| 67 | + |
| 68 | +__version__ = get_version(VERSION) |
| 69 | + |
15 | 70 |
|
16 | 71 | # Turn off the warnings for the following modules. |
17 | 72 | warnings.filterwarnings("ignore", module="cyclonedx") |
|
0 commit comments