diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e179c2d..916cc58 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -24,6 +24,27 @@ jobs: - name: Checkout uses: actions/checkout@v7 + # The tag (v1.0.0-rc.2) and pyproject.toml (1.0.0rc2) spell the same release differently; + # compare them as versions so a forgotten bump can't ship an image showing another version. + - name: Check the tag matches pyproject.toml + run: | + python3 - <<'PY' + import os, re, tomllib + + def normalize(version: str) -> str: + """Reduce SemVer (1.0.0-rc.2) and PEP 440 (1.0.0rc2) to one spelling.""" + version = version.lstrip("v").split("+")[0] + version = re.sub(r"[-.]?(alpha|a)[-.]?(\d+)", r"a\2", version) + version = re.sub(r"[-.]?(beta|b)[-.]?(\d+)", r"b\2", version) + return re.sub(r"[-.]?rc[-.]?(\d+)", r"rc\1", version) + + tag = os.environ["GITHUB_REF_NAME"] + declared = tomllib.load(open("pyproject.toml", "rb"))["project"]["version"] + if normalize(tag) != normalize(declared): + raise SystemExit(f"Tag {tag} does not match pyproject.toml version {declared}") + print(f"Tag {tag} matches pyproject.toml version {declared}") + PY + - name: Compute image name (registry paths must be lowercase) run: echo "IMAGE=ghcr.io/${GITHUB_REPOSITORY,,}" >> "$GITHUB_ENV" diff --git a/Dockerfile b/Dockerfile index bae3a84..a70cdb9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -38,6 +38,11 @@ RUN pip install --no-deps . ENV NUMBA_CACHE_DIR=/app/.numba_cache RUN mkdir -p /app/.numba_cache && chown app:app /app/.numba_cache +# Marks images built outside a release tag (``+`` after the version in the UI); empty for +# release images. Declared late so changing it never invalidates the layers above. +ARG APP_BUILD="" +ENV APP_BUILD=${APP_BUILD} + USER app RUN python -c "from app.processor.dither import warm_up; warm_up()" VOLUME ["/data"] diff --git a/app/api/routes/system.py b/app/api/routes/system.py index 74793b6..c10d21b 100644 --- a/app/api/routes/system.py +++ b/app/api/routes/system.py @@ -24,6 +24,7 @@ from app.services.delivery import FrameTelemetry, LastDelivery, PendingUpload from app.services.ephemeral import EphemeralView from app.services.scheduler import SchedulerSnapshot +from app.version import release_label router = APIRouter(prefix="/api", tags=["system"]) @@ -83,7 +84,12 @@ class ServiceConfigured(BaseModel): class StatusResponse(BaseModel): """Overall system status.""" - version: str + version: str = Field(description="Engine version (PEP 440, same as /api/health)") + release: str = Field( + description="Version as spelled by the git tag and the Docker image tag (SemVer, e.g. " + "1.0.0-rc.2), with + appended for images built outside a release tag; " + "informational, for display only" + ) uptime_s: float auth_enabled: bool auth_mode: str = Field(description="open, key (API key only) or password (admin login)") @@ -131,6 +137,7 @@ async def status( started_at: float = request.app.state.started_at return StatusResponse( version=__version__, + release=release_label(), uptime_s=round(time.monotonic() - started_at, 1), auth_enabled=auth.mode != "open", auth_mode=auth.mode, diff --git a/app/main.py b/app/main.py index d857e0c..ec48a48 100644 --- a/app/main.py +++ b/app/main.py @@ -57,6 +57,7 @@ from app.services.ephemeral import EphemeralService from app.services.now_playing import NowPlayingService from app.services.scheduler import SchedulerService, immich_runner, tmdb_runner +from app.version import release_label logger = logging.getLogger(__name__) @@ -217,7 +218,7 @@ async def _on_config_change(_: RuntimeConfig) -> None: logger.info( "Smart Frame Engine %s started (instance=%s, data_dir=%s, auth=%s, root_path=%r, " "panel=%s, power_mode=%s, pending=%s, scheduler=%s)", - __version__, + release_label(), identity.instance_id, settings.data_dir, auth_state.mode, diff --git a/app/templates/index.html b/app/templates/index.html index 5e9e3d3..55ce8eb 100644 --- a/app/templates/index.html +++ b/app/templates/index.html @@ -248,7 +248,7 @@

Services

  • Immich
  • TMDB
  • Smart Mix
  • -
  • Version
  • +
  • Version
  • diff --git a/app/version.py b/app/version.py new file mode 100644 index 0000000..53a1b6e --- /dev/null +++ b/app/version.py @@ -0,0 +1,68 @@ +"""Human-facing release label, spelled like the git tag and the Docker image tag. + +``pyproject.toml`` carries a PEP 440 version (``1.0.0rc2``) while the git tag and the published +image tag are SemVer (``v1.0.0-rc.2`` / ``1.0.0-rc.2``). The API keeps reporting the PEP 440 +spelling (``GET /api/health`` -> ``version``, see ``docs/API_CONTRACT.md``); the UI shows the +SemVer spelling so it matches what users pulled. +""" + +from __future__ import annotations + +import os +import re +from typing import Final + +from app import __version__ + +_PRE_RELEASE_NAMES: Final = {"a": "alpha", "b": "beta", "rc": "rc"} + +_PEP440: Final = re.compile( + r"""^ + (?P\d+(?:\.\d+)*) + (?:(?P
    a|b|rc)(?P\d+))?
    +    (?:\.post(?P\d+))?
    +    (?:\.dev(?P\d+))?
    +    (?:\+(?P[A-Za-z0-9.]+))?
    +    $""",
    +    re.VERBOSE,
    +)
    +
    +#: Environment variable set at image build time (``--build-arg APP_BUILD=``).
    +BUILD_ENV: Final = "APP_BUILD"
    +
    +
    +def display_version(version: str) -> str:
    +    """Convert a normalized PEP 440 version to the SemVer spelling used by tags.
    +
    +    ``1.0.0rc2`` -> ``1.0.0-rc.2``; ``1.0.0`` and unparseable values are returned unchanged.
    +    """
    +    match = _PEP440.match(version.strip())
    +    if match is None:
    +        return version
    +    result = match["release"]
    +    identifiers: list[str] = []
    +    if match["pre"]:
    +        identifiers.append(f"{_PRE_RELEASE_NAMES[match['pre']]}.{int(match['pre_n'])}")
    +    if match["post"]:
    +        identifiers.append(f"post.{int(match['post'])}")
    +    if match["dev"]:
    +        identifiers.append(f"dev.{int(match['dev'])}")
    +    if identifiers:
    +        result += "-" + ".".join(identifiers)
    +    if match["local"]:
    +        result += "+" + match["local"]
    +    return result
    +
    +
    +def release_label(version: str = __version__, build: str | None = None) -> str:
    +    """The version as shown in the UI: SemVer spelling, plus ``+`` for non-tag builds.
    +
    +    ``build`` defaults to the ``APP_BUILD`` environment variable (empty for release images).
    +    """
    +    label = display_version(version)
    +    if build is None:
    +        build = os.environ.get(BUILD_ENV, "")
    +    build = re.sub(r"[^A-Za-z0-9.]", "", build.strip())[:40]
    +    if build and "+" not in label:
    +        label += f"+{build}"
    +    return label
    diff --git a/docker-compose.build.yml b/docker-compose.build.yml
    index 079f13e..c1dff99 100644
    --- a/docker-compose.build.yml
    +++ b/docker-compose.build.yml
    @@ -6,7 +6,11 @@
     # ./data by default so it is easy to inspect while developing.
     services:
       smart-frame-engine:
    -    build: .
    +    build:
    +      context: .
    +      args:
    +        # Shown as "+dev" in the UI so a local build is never mistaken for a release.
    +        APP_BUILD: ${APP_BUILD:-dev}
         image: smart-frame-engine:dev
         container_name: smart-frame-engine
         restart: unless-stopped
    diff --git a/docs/API_CONTRACT.md b/docs/API_CONTRACT.md
    index 29438f5..5d28f4e 100644
    --- a/docs/API_CONTRACT.md
    +++ b/docs/API_CONTRACT.md
    @@ -220,6 +220,13 @@ changelog) and run `python scripts/export_openapi.py` (see `CLAUDE.md`).
     
     ## Contract Changelog
     
    +### 1.2 (unreleased), additive
    +
    +- `GET /api/status` gains `release`: the engine version spelled like the git tag and the Docker
    +  image tag (SemVer, `1.0.0-rc.2`), with `+` appended for images built outside a release
    +  tag. It is for display only; `version` (PEP 440) on `/api/status` and `/api/health` is
    +  unchanged. No `api_version` change.
    +
     ### 1.1 (engine 1.0.0rc2), additive
     
     - `GET /api/health` gains `instance_id` and `instance_name`; Zeroconf TXT gains `instance_id` and
    diff --git a/docs/openapi.json b/docs/openapi.json
    index dbd3276..d8fc128 100644
    --- a/docs/openapi.json
    +++ b/docs/openapi.json
    @@ -3484,6 +3484,11 @@
                 "title": "Public Image Endpoints",
                 "type": "boolean"
               },
    +          "release": {
    +            "description": "Version as spelled by the git tag and the Docker image tag (SemVer, e.g. 1.0.0-rc.2), with + appended for images built outside a release tag; informational, for display only",
    +            "title": "Release",
    +            "type": "string"
    +          },
               "scheduler": {
                 "$ref": "#/components/schemas/SchedulerSnapshot",
                 "description": "Autonomous refresh: timer and last run"
    @@ -3496,12 +3501,14 @@
                 "type": "number"
               },
               "version": {
    +            "description": "Engine version (PEP 440, same as /api/health)",
                 "title": "Version",
                 "type": "string"
               }
             },
             "required": [
               "version",
    +          "release",
               "uptime_s",
               "auth_enabled",
               "auth_mode",
    diff --git a/tests/test_version.py b/tests/test_version.py
    new file mode 100644
    index 0000000..8f08638
    --- /dev/null
    +++ b/tests/test_version.py
    @@ -0,0 +1,61 @@
    +"""Release label shown in the UI: spelled like the git tag and the Docker image tag."""
    +
    +from __future__ import annotations
    +
    +import pytest
    +
    +from app import __version__
    +from app.version import display_version, release_label
    +from tests.conftest import ClientFactory
    +
    +
    +@pytest.mark.parametrize(
    +    ("pep440", "expected"),
    +    [
    +        ("1.0.0", "1.0.0"),
    +        ("1.0.0rc2", "1.0.0-rc.2"),
    +        ("1.2.0b1", "1.2.0-beta.1"),
    +        ("2.0.0a3", "2.0.0-alpha.3"),
    +        ("1.0.1.post1", "1.0.1-post.1"),
    +        ("1.1.0.dev4", "1.1.0-dev.4"),
    +        ("1.0.0rc2+g1a2b3c", "1.0.0-rc.2+g1a2b3c"),
    +        ("0.0.0+unknown", "0.0.0+unknown"),
    +        ("not a version", "not a version"),
    +    ],
    +)
    +def test_display_version(pep440: str, expected: str) -> None:
    +    assert display_version(pep440) == expected
    +
    +
    +def test_release_label_without_build() -> None:
    +    assert release_label("1.0.0rc2", build="") == "1.0.0-rc.2"
    +
    +
    +def test_release_label_marks_non_release_builds() -> None:
    +    assert release_label("1.0.0rc2", build="abc1234") == "1.0.0-rc.2+abc1234"
    +    assert release_label("1.0.0rc2", build="dev") == "1.0.0-rc.2+dev"
    +
    +
    +def test_release_label_does_not_double_the_local_segment() -> None:
    +    assert release_label("1.0.0rc2+g1a2b3c", build="abc") == "1.0.0-rc.2+g1a2b3c"
    +
    +
    +def test_release_label_sanitizes_the_build() -> None:
    +    assert release_label("1.0.0", build=" a/b c!\n") == "1.0.0+abc"
    +
    +
    +def test_release_label_reads_the_environment(monkeypatch: pytest.MonkeyPatch) -> None:
    +    monkeypatch.setenv("APP_BUILD", "deadbee")
    +    assert release_label("1.0.0") == "1.0.0+deadbee"
    +    monkeypatch.delenv("APP_BUILD")
    +    assert release_label("1.0.0") == "1.0.0"
    +
    +
    +def test_status_reports_both_spellings(
    +    make_client: ClientFactory, monkeypatch: pytest.MonkeyPatch
    +) -> None:
    +    monkeypatch.delenv("APP_BUILD", raising=False)
    +    body = make_client().get("/api/status").json()
    +    assert body["version"] == __version__
    +    assert body["release"] == display_version(__version__)
    +    assert make_client().get("/api/health").json()["version"] == __version__