Skip to content

Commit 2ada809

Browse files
committed
Fix version endpoint in packaged image
1 parent 6586c4f commit 2ada809

3 files changed

Lines changed: 99 additions & 28 deletions

File tree

src/nameres/handlers/version.py

Lines changed: 2 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,10 @@
1-
import logging
2-
import pathlib
3-
import git
4-
51
from nameres.handlers.base import NameResolutionBaseHandler
6-
7-
logger = logging.getLogger(__name__)
2+
from nameres.version import get_version
83

94

105
class VersionHandler(NameResolutionBaseHandler):
116
name = "version"
127

13-
def get_github_commit_hash(self):
14-
"""Retrieve the current GitHub commit hash using gitpython."""
15-
try:
16-
# Resolve the absolute path to the current file
17-
file_path = pathlib.Path(__file__).resolve()
18-
19-
# Use git.Repo to find the root of the repository
20-
repo = git.Repo(file_path, search_parent_directories=True)
21-
22-
if repo.bare:
23-
# Get the absolute path to the repository root
24-
repo_dir = repo.working_tree_dir
25-
logger.error(f"Git repository not found in directory: {repo_dir}")
26-
return "Unknown"
27-
28-
commit_hash = repo.head.commit.hexsha # Get the latest commit hash
29-
return commit_hash
30-
except Exception as e:
31-
logger.error(f"Error getting GitHub commit hash: {e}")
32-
return "Unknown"
33-
348
async def get(self, *args, **kwargs):
35-
version = self.get_github_commit_hash()
9+
version = get_version()
3610
self.write({"version": version})

src/nameres/version.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import logging
2+
import os
3+
import pathlib
4+
from collections.abc import Iterable
5+
6+
import git
7+
8+
logger = logging.getLogger(__name__)
9+
10+
UNKNOWN_VERSION = "Unknown"
11+
VERSION_FILE_NAME = "version.txt"
12+
VERSION_FILE_ENV_VAR = "NAMERES_VERSION_FILE"
13+
CONTAINER_VERSION_FILE = pathlib.Path("/home/nameres/configuration") / VERSION_FILE_NAME
14+
15+
16+
def read_version_file(version_file_paths: Iterable[pathlib.Path] | None = None) -> str | None:
17+
"""Read the build-time version file when the app is running from a packaged image."""
18+
candidate_paths = []
19+
configured_path = os.getenv(VERSION_FILE_ENV_VAR)
20+
if configured_path:
21+
candidate_paths.append(pathlib.Path(configured_path))
22+
23+
candidate_paths.extend(version_file_paths or [pathlib.Path.cwd() / VERSION_FILE_NAME, CONTAINER_VERSION_FILE])
24+
25+
for version_file_path in candidate_paths:
26+
try:
27+
version = version_file_path.read_text(encoding="utf-8").strip()
28+
except OSError:
29+
continue
30+
31+
if version:
32+
return version
33+
34+
return None
35+
36+
37+
def get_github_commit_hash(source_path: pathlib.Path | None = None) -> str:
38+
"""Retrieve the current GitHub commit hash using gitpython."""
39+
try:
40+
repo_path = source_path or pathlib.Path(__file__).resolve()
41+
repo = git.Repo(repo_path, search_parent_directories=True)
42+
43+
if repo.bare:
44+
logger.error("Git repository not found in directory: %s", repo.working_tree_dir)
45+
return UNKNOWN_VERSION
46+
47+
return repo.head.commit.hexsha
48+
except Exception as exc:
49+
logger.error("Error getting GitHub commit hash: %s", exc)
50+
return UNKNOWN_VERSION
51+
52+
53+
def get_version() -> str:
54+
return read_version_file() or get_github_commit_hash()

test/test_version.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import pytest
2+
3+
from nameres import version as nameres_version
4+
5+
6+
def test_read_version_file_uses_configured_path(tmp_path, monkeypatch):
7+
configured_version_file = tmp_path / "configured-version.txt"
8+
configured_version_file.write_text("configured-sha\n", encoding="utf-8")
9+
fallback_version_file = tmp_path / "version.txt"
10+
fallback_version_file.write_text("fallback-sha\n", encoding="utf-8")
11+
12+
monkeypatch.setenv(nameres_version.VERSION_FILE_ENV_VAR, str(configured_version_file))
13+
14+
assert nameres_version.read_version_file([fallback_version_file]) == "configured-sha"
15+
16+
17+
def test_read_version_file_ignores_missing_and_blank_files(tmp_path, monkeypatch):
18+
blank_version_file = tmp_path / "blank-version.txt"
19+
blank_version_file.write_text("\n", encoding="utf-8")
20+
version_file = tmp_path / "version.txt"
21+
version_file.write_text("build-sha\n", encoding="utf-8")
22+
23+
monkeypatch.delenv(nameres_version.VERSION_FILE_ENV_VAR, raising=False)
24+
25+
assert nameres_version.read_version_file([tmp_path / "missing.txt", blank_version_file, version_file]) == "build-sha"
26+
27+
28+
def test_get_version_prefers_build_version_file(monkeypatch):
29+
monkeypatch.setattr(nameres_version, "read_version_file", lambda: "build-sha")
30+
monkeypatch.setattr(
31+
nameres_version,
32+
"get_github_commit_hash",
33+
lambda: pytest.fail("Git fallback should not run when a build version file exists"),
34+
)
35+
36+
assert nameres_version.get_version() == "build-sha"
37+
38+
39+
def test_get_version_falls_back_to_git(monkeypatch):
40+
monkeypatch.setattr(nameres_version, "read_version_file", lambda: None)
41+
monkeypatch.setattr(nameres_version, "get_github_commit_hash", lambda: "git-sha")
42+
43+
assert nameres_version.get_version() == "git-sha"

0 commit comments

Comments
 (0)