diff --git a/backend/endpoints/heartbeat.py b/backend/endpoints/heartbeat.py index 60acc35a2..074af1e5a 100644 --- a/backend/endpoints/heartbeat.py +++ b/backend/endpoints/heartbeat.py @@ -59,7 +59,7 @@ from handler.metadata import ( from handler.redis_handler import sync_cache from handler.scan_handler import MetadataSource from logger.logger import log -from utils import get_version +from utils import get_git_branch, get_version from utils.platforms import get_supported_platforms from utils.rate_limit import enforce_rate_limit, get_client_ip from utils.router import APIRouter @@ -109,9 +109,11 @@ async def heartbeat() -> HeartbeatResponse: tgdb_enabled = meta_tgdb_handler.is_enabled() libretro_enabled = meta_libretro_handler.is_enabled() + version = get_version() return { "SYSTEM": { - "VERSION": get_version(), + "VERSION": version, + "GIT_BRANCH": get_git_branch() if version == "development" else None, "SHOW_SETUP_WIZARD": len(db_user_handler.get_admin_users()) == 0 and not DISABLE_SETUP_WIZARD, }, diff --git a/backend/endpoints/responses/heartbeat.py b/backend/endpoints/responses/heartbeat.py index 6479afa51..4803d1205 100644 --- a/backend/endpoints/responses/heartbeat.py +++ b/backend/endpoints/responses/heartbeat.py @@ -3,6 +3,7 @@ from typing import TypedDict class SystemDict(TypedDict): VERSION: str + GIT_BRANCH: str | None SHOW_SETUP_WIZARD: bool diff --git a/backend/tests/endpoints/test_heartbeat.py b/backend/tests/endpoints/test_heartbeat.py index 3b46d44bb..d17c80192 100644 --- a/backend/tests/endpoints/test_heartbeat.py +++ b/backend/tests/endpoints/test_heartbeat.py @@ -10,7 +10,7 @@ from endpoints.heartbeat import METADATA_HEARTBEAT_RATE_LIMIT from exceptions.fs_exceptions import PlatformAlreadyExistsException from handler.metadata.launchbox_handler.handler import LaunchboxHandler from handler.redis_handler import sync_cache -from utils import get_version +from utils import get_git_branch, get_version def test_heartbeat(client): @@ -22,6 +22,9 @@ def test_heartbeat(client): assert "SYSTEM" in heartbeat system = heartbeat["SYSTEM"] assert system["VERSION"] == get_version() + assert system["GIT_BRANCH"] == ( + get_git_branch() if system["VERSION"] == "development" else None + ) assert isinstance(system["SHOW_SETUP_WIZARD"], bool) assert "METADATA_SOURCES" in heartbeat diff --git a/backend/tests/utils/test_git_branch.py b/backend/tests/utils/test_git_branch.py new file mode 100644 index 000000000..be0853bca --- /dev/null +++ b/backend/tests/utils/test_git_branch.py @@ -0,0 +1,52 @@ +import subprocess +from unittest.mock import patch + +import pytest + +from utils import _REPO_ROOT, get_git_branch + + +@pytest.fixture(autouse=True) +def _clear_branch_cache(): + get_git_branch.cache_clear() + yield + get_git_branch.cache_clear() + + +def test_get_git_branch_returns_current_branch(): + with patch("utils.subprocess.run") as mock_run: + mock_run.return_value = subprocess.CompletedProcess( + args=[], returncode=0, stdout="feature/foo\n" + ) + assert get_git_branch() == "feature/foo" + + +def test_get_git_branch_trusts_the_repo_root_as_a_safe_directory(): + """A host-owned .git bind-mounted into a root-run container is otherwise + refused by git 2.35.2+ as having "dubious ownership".""" + with patch("utils.subprocess.run") as mock_run: + mock_run.return_value = subprocess.CompletedProcess( + args=[], returncode=0, stdout="main\n" + ) + get_git_branch() + args = mock_run.call_args.args[0] + assert f"safe.directory={_REPO_ROOT}" in args + + +def test_get_git_branch_returns_none_when_git_unavailable(): + with patch("utils.subprocess.run", side_effect=FileNotFoundError): + assert get_git_branch() is None + + +def test_get_git_branch_returns_none_on_detached_head(): + with patch("utils.subprocess.run") as mock_run: + mock_run.return_value = subprocess.CompletedProcess( + args=[], returncode=0, stdout="HEAD\n" + ) + assert get_git_branch() is None + + +def test_get_git_branch_returns_none_when_not_a_git_repo(): + with patch("utils.subprocess.run") as mock_run: + mock_run.side_effect = subprocess.CalledProcessError(128, ["git"]) + assert get_git_branch() is None diff --git a/backend/utils/__init__.py b/backend/utils/__init__.py index 180c73cb2..9863d4f4a 100644 --- a/backend/utils/__init__.py +++ b/backend/utils/__init__.py @@ -1,5 +1,8 @@ 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__ @@ -7,6 +10,8 @@ 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""" @@ -16,6 +21,36 @@ def get_version() -> str: 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: diff --git a/docker-compose.yml b/docker-compose.yml index b64be6106..565fc30c8 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -29,6 +29,9 @@ services: - /app/frontend/dist # Empty directory - ./romm_mock:/app/romm - ~/.vite-plugin-mkcert:/app/.vite-plugin-mkcert + # Read-only, so the backend can report the checked-out branch (see + # backend/utils/__init__.py get_git_branch) without git write access. + - ./.git:/app/.git:ro depends_on: - romm-db-dev - romm-valkey-dev diff --git a/frontend/src/__generated__/models/SystemDict.ts b/frontend/src/__generated__/models/SystemDict.ts index addfd05a4..9a682d7dd 100644 --- a/frontend/src/__generated__/models/SystemDict.ts +++ b/frontend/src/__generated__/models/SystemDict.ts @@ -4,6 +4,7 @@ /* eslint-disable */ export type SystemDict = { VERSION: string; + GIT_BRANCH: (string | null); SHOW_SETUP_WIZARD: boolean; }; diff --git a/frontend/src/stores/heartbeat.ts b/frontend/src/stores/heartbeat.ts index dd3e1d791..93b3e9980 100644 --- a/frontend/src/stores/heartbeat.ts +++ b/frontend/src/stores/heartbeat.ts @@ -15,6 +15,7 @@ export type MetadataOption = { const defaultHeartbeat: Heartbeat = { SYSTEM: { VERSION: "0.0.0", + GIT_BRANCH: null, SHOW_SETUP_WIZARD: false, }, METADATA_SOURCES: { diff --git a/frontend/src/v2/components/Dialogs/AboutDialog.vue b/frontend/src/v2/components/Dialogs/AboutDialog.vue index a16bfed76..290c802f7 100644 --- a/frontend/src/v2/components/Dialogs/AboutDialog.vue +++ b/frontend/src/v2/components/Dialogs/AboutDialog.vue @@ -4,15 +4,15 @@ // panel instead of the legacy card. import { RDialog, RIcon, RImg } from "@v2/lib"; import type { Emitter } from "mitt"; -import { inject, onBeforeUnmount, ref } from "vue"; +import { computed, inject, onBeforeUnmount, ref } from "vue"; import { useI18n } from "vue-i18n"; -import storeHeartbeat from "@/stores/heartbeat"; import type { Events } from "@/types/emitter"; +import { useVersionDisplay } from "@/v2/composables/useVersionDisplay"; defineOptions({ inheritAttrs: false }); const { t } = useI18n(); -const heartbeatStore = storeHeartbeat(); +const { version, href: versionHref } = useVersionDisplay(); const emitter = inject>("emitter"); const show = ref(false); @@ -34,12 +34,12 @@ type Link = { href: string; }; -const links: Link[] = [ +const links = computed(() => [ { isotipo: true, label: t("common.about-version"), - value: heartbeatStore.value.SYSTEM.VERSION, - href: `https://github.com/rommapp/romm/releases/tag/${heartbeatStore.value.SYSTEM.VERSION}`, + value: version.value, + href: versionHref.value, }, { icon: "mdi-code-braces", @@ -59,7 +59,7 @@ const links: Link[] = [ value: "Discord", href: "https://discord.com/invite/P5HtHnhUDH", }, -]; +]);