Files
romm/backend/utils/__init__.py
Sam Dornan d5db9221e8 refactor(steam): store icon filenames once and share the float parser (pr-ready: simplify)
Icon filenames are taken from the CDN URLs when the metadata is built,
so serving a ROM and storing its icons only join paths instead of
re-parsing each URL. A search by Steam ID no longer fetches achievements
it never shows. Pouet's float parser moves to `utils.float_or_none`,
which also rejects NaN and infinity, and Steam's unlock rates use it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NH5s4hBCkRF6nyKoFy6MXw
2026-11-02 02:37:50 +00:00

87 lines
2.5 KiB
Python

import math
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 float_or_none(value: Any) -> float | None:
"""A finite float, or None when it is not one, since JSON holds no NaN or infinity."""
try:
number = float(value)
except TypeError, ValueError:
return None
return number if math.isfinite(number) else 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