3213e3277a3a4dac17f71a4c368bc67b4031c574
[tinc] / version.py
1 #!/usr/bin/env python3
2
3 """Print current tinc version for using in build scripts.
4
5 First try to determine the latest version using git tags. If this fails (because
6 the .git directory is missing, git is not installed, or for some other reason),
7 fall back to using the VERSION file. If it is not present or could not be read,
8 use 'unknown'.
9 """
10
11 from os import path, environ
12 from sys import argv, stderr
13 import subprocess as subp
14 import typing as T
15
16 PREFIX = "release-"
17 SOURCE_ROOT = path.dirname(path.realpath(__file__))
18 SOURCE_ROOT = environ.get("MESON_SOURCE_ROOT", SOURCE_ROOT)
19
20 cmd = [
21     "git",
22     "--git-dir",
23     path.join(SOURCE_ROOT, ".git"),
24     "describe",
25     "--always",
26     "--tags",
27     "--match=" + PREFIX + "*",
28 ]
29
30 if "short" in argv:
31     cmd.append("--abbrev=0")
32
33 version: T.Optional[str] = None
34
35 try:
36     result = subp.run(cmd, stdout=subp.PIPE, encoding="utf-8", check=False)
37     if not result.returncode:
38         version = result.stdout
39 except FileNotFoundError:
40     pass
41
42 if not version:
43     try:
44         with open(path.join(SOURCE_ROOT, "VERSION"), "r", encoding="utf-8") as f:
45             version = f.read().strip()
46     except OSError as e:
47         print("could not read version from file", e, file=stderr)
48 elif version.startswith(PREFIX):
49     version = version[len(PREFIX) :].strip()
50
51 print(version if version else "unknown", end="")