summaryrefslogtreecommitdiffstats
path: root/src/debputy/version.py
blob: de56318dd3b9d8c00f4342c693af8429406fd4ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from typing import Optional, Callable

__version__ = "N/A"

IS_RELEASE_BUILD = False

if __version__ in ("N/A",):
    import subprocess

    class LazyString:
        def __init__(self, initializer: Callable[[], str]) -> None:
            self._initializer = initializer
            self._value: Optional[str] = None

        def __str__(self) -> str:
            value = object.__getattribute__(self, "_value")
            if value is None:
                value = object.__getattribute__(self, "_initializer")()
                object.__setattr__(self, "_value", value)
            return value

        def __getattribute__(self, item):
            value = str(self)
            return getattr(value, item)

        def __contains__(self, item):
            return item in str(self)

    def _initialize_version() -> str:
        try:
            devnull: Optional[int] = subprocess.DEVNULL
        except AttributeError:
            devnull = None  # Not supported, but not critical

        try:
            v = (
                subprocess.check_output(
                    ["git", "describe", "--tags"],
                    stderr=devnull,
                )
                .strip()
                .decode("utf-8")
            )
        except (subprocess.CalledProcessError, FileNotFoundError):
            try:
                v = (
                    subprocess.check_output(
                        ["dpkg-parsechangelog", "-SVersion"],
                        stderr=devnull,
                    )
                    .strip()
                    .decode("utf-8")
                )

            except (subprocess.CalledProcessError, FileNotFoundError):
                v = "N/A"

        if v.startswith("debian/"):
            v = v[7:]
        return v

    __version__ = LazyString(_initialize_version)
    IS_RELEASE_BUILD = False

else:
    # Disregard snapshot versions (gbp dch -S) as "release builds"
    IS_RELEASE_BUILD = ".gbp" not in __version__