Source code for trader.versioning

"""Detecting which git commit this process is actually running (issue #30).

`git rev-parse` is a subprocess call — the first one in this codebase — and
it is sandboxed to this module, never raising: a future packaged deploy that
is not a live git checkout must not block `trader run`/`run-once` from
starting over a version-log nicety.
"""

import subprocess
from pathlib import Path

__all__ = ["UNKNOWN_GIT_SHA", "detect_git_version"]

#: Recorded explicitly when the SHA cannot be determined at all — never a
#: guess. Same "unknown is not zero" discipline as the fill-poll settle guard
#: and the missing-analyst-coverage check.
UNKNOWN_GIT_SHA = "unknown"


[docs] def detect_git_version(cwd: Path | None = None) -> tuple[str, str | None]: """`(git_sha, git_ref)` for the checkout at `cwd` (default: the CWD). `git_sha` is `UNKNOWN_GIT_SHA` when it cannot be read at all — no `git` on `PATH`, not a git checkout, or any other failure. `git_ref` is `None` whenever no branch name resolves (detached `HEAD`, or the SHA itself is unknown) — never a guess at which branch is running. """ sha = _git(["rev-parse", "HEAD"], cwd) if sha is None: return UNKNOWN_GIT_SHA, None ref = _git(["rev-parse", "--abbrev-ref", "HEAD"], cwd) if ref is None or ref == "HEAD": ref = None return sha, ref
def _git(args: list[str], cwd: Path | None) -> str | None: try: result = subprocess.run( # noqa: S603 - fixed argv, no shell, no user input ["git", *args], # noqa: S607 - relies on PATH deliberately, like every git wrapper cwd=cwd, capture_output=True, text=True, timeout=5, check=True, ) except Exception: # noqa: BLE001 - never block startup over a version read return None value = result.stdout.strip() return value or None