Files
romm/backend/utils/__init__.py
zurdi 5f02a99fd3 fix: trust the repo root as a safe directory for git branch lookup
Addresses Copilot review feedback on PR #4617.

The Docker dev image's bind-mounted .git is host-owned while the
romm-dev container runs as root; git 2.35.2+ refuses that mismatch
as "dubious ownership" and rev-parse fails, so GIT_BRANCH silently
stayed null and the UI kept showing "development" in the very
workflow the mount was added for. Pass safe.directory scoped to
this one read-only invocation instead of touching global git config.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TDMqXzXexRgC89YxeNjn9q
2026-09-18 13:29:38 +02:00

77 lines
2.2 KiB
Python

import re
import subprocess # trunk-ignore(bandit/B404): only used by get_git_branch, argv is hardcoded
import uuid
from functools import lru_cache
from pathlib import Path
from typing import Any, Final
from __version__ import __version__
# Embedded straight into a YouTube URL, so anything outside this must be dropped.
YOUTUBE_ID_RE: Final = re.compile(r"[A-Za-z0-9_-]{11}")
_REPO_ROOT: Final = Path(__file__).resolve().parent.parent.parent
def get_version() -> str:
"""Returns current version tag"""
if __version__ != "<version>":
return __version__
return "development"
@lru_cache(maxsize=1)
def get_git_branch() -> str | None:
"""Current git branch for a dev build's display, or None outside a checkout (cached for the process's life)."""
try:
# The Docker dev image's bind-mounted .git is host-owned while the
# container runs as root, which git 2.35.2+ refuses as "dubious ownership".
# trunk-ignore(bandit/B607): git is resolved from PATH by design
result = subprocess.run(
[
"git",
"-c",
f"safe.directory={_REPO_ROOT}",
"rev-parse",
"--abbrev-ref",
"HEAD",
],
cwd=_REPO_ROOT,
capture_output=True,
text=True,
check=True,
timeout=2,
shell=False, # trunk-ignore(bandit/B603): args are hardcoded
)
except (OSError, subprocess.SubprocessError):
return None
branch = result.stdout.strip()
return branch if branch and branch != "HEAD" else None
def is_valid_uuid(uuid_str: str) -> bool:
"""Check if a string is a valid UUID."""
try:
uuid.UUID(uuid_str, version=4)
return True
except ValueError:
return False
def int_or_none(value: Any) -> int | None:
"""An int, or None when it is not one (``int()`` raises past 4300 digits)."""
if value is None or value == "":
return None
try:
return int(value)
except (TypeError, ValueError):
return None
def valid_youtube_id(value: Any) -> str | None:
"""A video id, or None when it is not one."""
text = str(value or "")
return text if YOUTUBE_ID_RE.fullmatch(text) else None