File size: 1,881 Bytes
e4b1ed6
 
c789799
 
 
 
 
 
 
 
 
e4b1ed6
 
c789799
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
"""Live inference API for the datacenter verification demo."""

from __future__ import annotations

import os
import subprocess
from functools import cache
from pathlib import Path
from typing import NamedTuple

__all__ = ["__version__", "BuildInfo", "build_info"]

__version__ = "0.1.0"


class BuildInfo(NamedTuple):
    sha: str | None
    source: str | None


def _clean_sha(value: str | None) -> str | None:
    if not value:
        return None
    cleaned = value.strip()
    if not cleaned or cleaned.lower() in {"unknown", "none", "null"}:
        return None
    return cleaned


def _sha_from_env() -> BuildInfo | None:
    for name in (
        "DCV_BUILD_SHA",
        "SPACE_COMMIT_SHA",
        "HF_SPACE_COMMIT_SHA",
        "GITHUB_SHA",
        "RENDER_GIT_COMMIT",
        "COMMIT_SHA",
        "SOURCE_COMMIT",
    ):
        sha = _clean_sha(os.getenv(name))
        if sha:
            return BuildInfo(sha=sha, source=f"env:{name}")
    return None


def _sha_from_file() -> BuildInfo | None:
    for path in (Path("/app/.dcv-build-sha"), Path.cwd() / ".dcv-build-sha"):
        try:
            sha = _clean_sha(path.read_text(encoding="utf-8"))
        except OSError:
            continue
        if sha:
            return BuildInfo(sha=sha, source=str(path))
    return None


def _sha_from_git() -> BuildInfo | None:
    try:
        result = subprocess.run(
            ["git", "rev-parse", "--short=12", "HEAD"],
            check=True,
            capture_output=True,
            text=True,
            timeout=1,
        )
    except (OSError, subprocess.SubprocessError):
        return None
    sha = _clean_sha(result.stdout)
    if sha:
        return BuildInfo(sha=sha, source="git")
    return None


@cache
def build_info() -> BuildInfo:
    return _sha_from_env() or _sha_from_file() or _sha_from_git() or BuildInfo(sha=None, source=None)