steam-backlog-enforcer/steam_backlog_enforcer/_web_build.py
Krzysztof kuhy Rudnicki 47f77f5f1e
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (push) Waiting to run
Tests / test (push) Waiting to run
Make serve re-runnable, and cover it to 100%
The serve rework was sitting untracked: a /proc-based port guard, the
start-or-defer decision, and a stale-bundle rebuild. It had no tests, and it
changed cmd_serve(_config, state) to cmd_serve(argv) without updating the one
test that called it, so the suite was red and coverage was 251 lines short.

Tests, all against fakes:
- _fake_proc builds a synthetic /proc. _NET_TCP is derived from _PROC at
  import time, so patch_proc redirects both; patching _PROC alone would have
  had these tests parse the host's real process table.
- _serve_guard is split across two test files to stay under the 250-line cap.
  os is replaced wholesale in every termination test, so no signal can reach a
  real process even if the guard's self-protection were removed.
- _web_build mocks subprocess entirely and redirects every path constant into
  tmp_path. _no_subprocess now blocks _web_build.subprocess.run too: an
  unguarded test would fire a real `npm run build`, rewriting web/dist and
  perturbing frontend_is_stale() for every later test in the run.

Source changes, both required rather than incidental:
- _serve_guard's wildcard match was a `# noqa: S104` on a "0.0.0.0" literal,
  which the no-noqa hook rejects outright. It is now the all-zero hex column
  /proc actually prints, so the dotted-quad literal never appears.
- main/__init__.py's serve dispatch arm was itself uncovered; it now has a
  test asserting the raw argv passes through unparsed.

Also drops the document.hidden guard from useBudgetPoll: it skipped the very
first load, so the budget panel sat on "Reading budget state…" forever in a
background tab, which is every tab under browser automation.

Verified: 1712 python tests, 100% branch coverage; 128 vitest, 100%. The
guard's /proc parser was checked read-only against a real listener on :8000
and resolved the same pid as `ss`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MKFzwzwRU1JD7SFLHtQBsz
2026-08-29 18:52:11 +02:00

95 lines
3.0 KiB
Python

"""Rebuild the web bundle when its sources are newer than ``web/dist``.
``_web_server`` reads ``web/dist`` per request, so a rebuild takes effect
without restarting anything - but nothing ever triggered one, which meant
``serve`` could quietly hand the browser a bundle older than the working tree.
This closes that gap: a stale bundle is rebuilt, and a build that fails stops
the launch rather than serving the old files under a new-looking process.
"""
from __future__ import annotations
from pathlib import Path
import shutil
import subprocess
from steam_backlog_enforcer.game_install import _echo
WEB_DIR = (Path(__file__).resolve().parent.parent / "web").resolve()
_BUILT_MARKER = WEB_DIR / "dist" / "index.html"
# Everything whose change invalidates the built bundle. Anything under src,
# plus the build configuration itself - a vite/tsconfig edit changes the
# output even when not one line of src moved.
_SOURCE_DIR = WEB_DIR / "src"
_SOURCE_FILES = (
WEB_DIR / "index.html",
WEB_DIR / "package.json",
WEB_DIR / "vite.config.ts",
WEB_DIR / "tsconfig.json",
WEB_DIR / "tsconfig.app.json",
WEB_DIR / "tsconfig.node.json",
)
_BUILD_TIMEOUT_SECONDS = 600
_NPM_MISSING = (
"npm was not found on PATH, so the stale web bundle cannot be rebuilt.\n"
"npm is installed via nvm here, which only puts it on an interactive\n"
"shell's PATH - a systemd unit or cron job will not see it. Either run\n"
"serve from a normal shell, or build once by hand: cd web && npm run build"
)
def _mtime(path: Path) -> float:
"""Return the mtime of *path*, or 0.0 when it does not exist."""
try:
return path.stat().st_mtime
except OSError:
return 0.0
def frontend_is_stale() -> bool:
"""Check whether any build input is newer than the built bundle.
A missing ``dist/index.html`` counts as stale so the first ``serve`` in a
fresh clone builds instead of serving the "not built" placeholder.
"""
built = _mtime(_BUILT_MARKER)
if built == 0.0:
return WEB_DIR.is_dir()
sources = list(_SOURCE_FILES)
if _SOURCE_DIR.is_dir():
sources.extend(path for path in _SOURCE_DIR.rglob("*") if path.is_file())
return any(_mtime(path) > built for path in sources)
def build_frontend() -> bool:
"""Run ``npm run build`` in ``web/``.
Returns:
True if the bundle was rebuilt, False if the build failed (the
captured output is printed either way).
"""
npm = shutil.which("npm")
if npm is None:
_echo(_NPM_MISSING)
return False
_echo("Frontend sources changed - rebuilding web/dist ...", flush=True)
result = subprocess.run(
[npm, "run", "build"],
cwd=WEB_DIR,
capture_output=True,
text=True,
timeout=_BUILD_TIMEOUT_SECONDS,
check=False,
)
if result.returncode != 0:
_echo("Frontend build FAILED - refusing to serve a stale bundle.\n")
_echo(result.stdout.strip())
_echo(result.stderr.strip())
return False
_echo("Frontend build complete.", flush=True)
return True