From 8a2ef047abfdcf76948dd063253cf6b844b7e64e Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:59:31 +0100 Subject: [PATCH] refactor: move check_freshness logic to freshness --- scripts/check_freshness.py | 1812 +---------------------------- scripts/freshness/__init__.py | 2 +- scripts/freshness/catalogs.py | 287 +++++ scripts/freshness/ci.py | 199 ++++ scripts/freshness/coreinfo.py | 166 +++ scripts/freshness/data.py | 54 + scripts/freshness/findings.py | 28 + scripts/freshness/native.py | 167 +++ scripts/freshness/pinbuilds.py | 127 ++ scripts/freshness/platformdiff.py | 172 +++ scripts/freshness/platforms.py | 114 ++ scripts/freshness/profiles.py | 166 +++ scripts/freshness/report.py | 66 ++ scripts/freshness/rescrape.py | 35 + scripts/freshness/romfolders.py | 117 ++ scripts/freshness/targets.py | 187 +++ tests/sources.py | 7 + tests/test_check_freshness.py | 371 +++--- tests/test_layers.py | 4 + tests/test_measurements.py | 4 +- tests/test_pin_build.py | 38 +- tests/test_refresh_stale.py | 4 +- tests/test_scraper_contract.py | 9 +- tests/test_site_integration.py | 19 +- tests/test_workflow_paths.py | 2 +- wiki/architecture.md | 1 + 26 files changed, 2171 insertions(+), 1987 deletions(-) create mode 100644 scripts/freshness/catalogs.py create mode 100644 scripts/freshness/ci.py create mode 100644 scripts/freshness/coreinfo.py create mode 100644 scripts/freshness/data.py create mode 100644 scripts/freshness/findings.py create mode 100644 scripts/freshness/native.py create mode 100644 scripts/freshness/pinbuilds.py create mode 100644 scripts/freshness/platformdiff.py create mode 100644 scripts/freshness/platforms.py create mode 100644 scripts/freshness/profiles.py create mode 100644 scripts/freshness/report.py create mode 100644 scripts/freshness/rescrape.py create mode 100644 scripts/freshness/romfolders.py create mode 100644 scripts/freshness/targets.py diff --git a/scripts/check_freshness.py b/scripts/check_freshness.py index 1da2bf260..350030418 100644 --- a/scripts/check_freshness.py +++ b/scripts/check_freshness.py @@ -31,1781 +31,35 @@ Usage: from __future__ import annotations import argparse -import contextlib -import http.client -import io import json -import re -import shutil -import subprocess import sys import tempfile -import urllib.request -from collections.abc import Container, Iterator -from concurrent.futures import ThreadPoolExecutor -from dataclasses import asdict, dataclass, field -from datetime import datetime, timezone +from dataclasses import asdict from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -from exporter.native import StaleTruth, export_platform, load_inputs -from exporter.originals import ( - DEFAULT_CACHE, - SOURCES_INDEX, - SourcesIndexUnreadable, - load_sources, - source_key, - wanted_sources, -) -from installer_build import pins as installer_build_pins -from packs import datadirs from core import upstream -from core.cli import InputMissing, add_repo_inputs, require_directory, suggest_names -from model.platforms import inheritance_chain -from model.targets import apply_target_overrides, platform_overrides, read_target_overrides -from model.registry import list_registered_platforms, load_data_dir_registry, load_platform_registry -from model.profiles import load_emulator_profiles, upstream_profile_index -from core.artifacts import write_text_atomic -from model.sources import source_yaml_file -from model.sourcerevision import scraped_revision -from exporter import discover_exporters -from resolve.reconcile import build_native_model -from scripts.scraper import game_dat_importer -from scripts.scraper.redump_dat_scraper import fetch_snapshot -from scripts.scraper.targets import discover_target_scrapers -from core.paths import DATA_DIRS_FILE, REPO_ROOT, TRUTH_DIR - -CORE_INFO_REPO = "https://github.com/libretro/libretro-core-info" -# The git blob of every .info as last reviewed: `--record-coreinfo` writes it. -CORE_INFO_RECORD = REPO_ROOT / "platforms" / "_core_info.json" -NO_INTRO_MIRROR = game_dat_importer.NOINTRO_MIRROR -NO_INTRO_RELEASE = game_dat_importer.NOINTRO_RELEASE -NO_INTRO_ASSET = game_dat_importer.NOINTRO_ASSET -# The mirror rebuilds daily. A pack older than this is a mirror that stopped: -# hugo19941994's failed every day from 2026-07-08, and comparing our import -# date with its asset read OK for four months. -NO_INTRO_MAX_AGE_DAYS = 7 -TOSEC_DOWNLOADS = "https://www.tosecdev.org/downloads" -MAME_REPO = "https://github.com/mamedev/mame" -FBNEO_REPO = "https://github.com/libretro/FBNeo" -PYPI_URL = "https://pypi.org/pypi/{name}/json" -NPM_URL = "https://registry.npmjs.org/{name}/latest" -# The site's npm dependencies, pinned to exact versions and built by Deploy Site. -SITE_PACKAGE = REPO_ROOT / "website" / "package.json" - -SHOWN_ITEMS = 4 # items named in a diff summary before ", ..." -SHOWN_NAMES = 12 # core names named in an unresolved row before ", ..." -AREAS = ( - "platforms", "native", "targets", "romfolders", "coreinfo", "data", "catalogs", "ci", "profiles", -) -OK, STALE, UNKNOWN, ERROR, SKIPPED = "OK", "STALE", "UNKNOWN", "ERROR", "SKIPPED" -# Every status a finding may carry, in the order the summary counts them. -STATUSES = (STALE, UNKNOWN, ERROR, SKIPPED, OK) - - -@dataclass(frozen=True) -class Finding: - area: str - subject: str - status: str - local: str = "" - remote: str = "" - detail: str = "" - # Every name a shortened detail stands for: --json carries them all, so - # a script can act on the 50 cores a row names 12 of. - items: list[str] = field(default_factory=list) - - -@dataclass -class PlatformDiff: - """What a fresh scrape changes in a platform or target file.""" - - version: tuple[str, str] | None = None - systems_added: list[str] = field(default_factory=list) - systems_removed: list[str] = field(default_factory=list) - files_added: list[str] = field(default_factory=list) - files_removed: list[str] = field(default_factory=list) - files_changed: list[str] = field(default_factory=list) - cores_added: list[str] = field(default_factory=list) - cores_removed: list[str] = field(default_factory=list) - # Any other field the scrape writes: launchers, dual_mode_cores, a - # system's core, native_id or data_directories. - fields_changed: list[str] = field(default_factory=list) - - @property - def content_changed(self) -> bool: - return any( - ( - self.systems_added, - self.systems_removed, - self.files_added, - self.files_removed, - self.files_changed, - self.cores_added, - self.cores_removed, - self.fields_changed, - ) - ) - - @property - def changed(self) -> bool: - return self.content_changed or self.version is not None - - def summary(self) -> str: - parts: list[str] = [] - if self.version: - parts.append(f"version {self.version[0]} -> {self.version[1]}") - for label, items in ( - ("+systems", self.systems_added), - ("-systems", self.systems_removed), - ("+files", self.files_added), - ("-files", self.files_removed), - ("~files", self.files_changed), - ("+cores", self.cores_added), - ("-cores", self.cores_removed), - ("~fields", self.fields_changed), - ): - if items: - shown = ", ".join(items[:SHOWN_ITEMS]) + (", ..." if len(items) > SHOWN_ITEMS else "") - parts.append(f"{label} {len(items)} ({shown})") - return "; ".join(parts) if parts else "identical" - - -# --- platforms -------------------------------------------------------------- - - -def _file_key(entry: dict) -> str: - return str(entry.get("destination") or entry.get("name") or "") - - -def _core_names(config: dict) -> set[str]: - cores = config.get("cores") - names = set(map(str, cores)) if isinstance(cores, list) else set() - standalone = config.get("standalone_cores") - if isinstance(standalone, list): - names.update(f"standalone:{c}" for c in standalone) - return names - - -def _keyed_files(files: list[dict]) -> dict[str, dict]: - """Each declaration under its own key. - - A platform declares one destination several times (an archive once per - inner ROM, MD5 alternatives): keyed by destination alone, the dict kept - the last and a change to the others read as identical. - """ - keyed: dict[str, dict] = {} - seen: dict[str, int] = {} - for f in files: - key = _file_key(f) - seen[key] = seen.get(key, 0) + 1 - keyed[key if seen[key] == 1 else f"{key}#{seen[key]}"] = f - return keyed - - -# Compared on their own above. `source` is the revision read: it moves with -# every upstream commit, and what that commit changes is diffed field by field. -_DIFFED_APART = frozenset({"version", "systems", "cores", "standalone_cores", "source"}) - - -def _without_refs(value: object) -> object: - """*value* without its `source_ref` lines. - - A launcher cites lines of the revision read, so they shift with any - upstream commit above them (es_features.cfg:11638 read as :11649 one - RetroBat commit later). The cited content is what is compared. - """ - if isinstance(value, dict): - return {k: _without_refs(v) for k, v in value.items() if k != "source_ref"} - if isinstance(value, list): - return [_without_refs(v) for v in value] - return value - - -def _changed_fields(old: dict, new: dict, skip: frozenset[str], prefix: str = "") -> list[str]: - return [ - f"{prefix}{key}" - for key in sorted(set(old) | set(new), key=str) - if key not in skip and _without_refs(old.get(key)) != _without_refs(new.get(key)) - ] - - -def diff_platform(old: dict, new: dict) -> PlatformDiff: - """Compare two platform files the way a reviewer reads the diff. - - Files are keyed by system and destination, so a hash or flag change on - an existing destination is a change, not a removal plus an addition. - """ - diff = PlatformDiff() - old_version, new_version = str(old.get("version", "")), str(new.get("version", "")) - if old_version != new_version: - diff.version = (old_version, new_version) - old_systems = old.get("systems") or {} - new_systems = new.get("systems") or {} - diff.systems_added = sorted(set(new_systems) - set(old_systems)) - diff.systems_removed = sorted(set(old_systems) - set(new_systems)) - for system in sorted(set(old_systems) & set(new_systems)): - old_files = _keyed_files((old_systems[system] or {}).get("files") or []) - new_files = _keyed_files((new_systems[system] or {}).get("files") or []) - diff.files_added.extend( - f"{system}/{k}" for k in sorted(set(new_files) - set(old_files)) - ) - diff.files_removed.extend( - f"{system}/{k}" for k in sorted(set(old_files) - set(new_files)) - ) - diff.files_changed.extend( - f"{system}/{k}" - for k in sorted(set(old_files) & set(new_files)) - if old_files[k] != new_files[k] - ) - diff.fields_changed.extend(_changed_fields( - old_systems[system] or {}, new_systems[system] or {}, - frozenset({"files"}), f"{system}/", - )) - diff.fields_changed = _changed_fields(old, new, _DIFFED_APART) + diff.fields_changed - old_cores, new_cores = _core_names(old), _core_names(new) - diff.cores_added = sorted(new_cores - old_cores) - diff.cores_removed = sorted(old_cores - new_cores) - return diff - - -def diff_targets(old: dict, new: dict) -> PlatformDiff: - """Compare two target files. The scrape stamp is not a change.""" - diff = PlatformDiff() - old_targets = old.get("targets") or {} - new_targets = new.get("targets") or {} - diff.systems_added = sorted(set(new_targets) - set(old_targets)) - diff.systems_removed = sorted(set(old_targets) - set(new_targets)) - for name in sorted(set(old_targets) & set(new_targets)): - before = set(map(str, (old_targets[name] or {}).get("cores") or [])) - after = set(map(str, (new_targets[name] or {}).get("cores") or [])) - diff.cores_added.extend(f"{name}/{c}" for c in sorted(after - before)) - diff.cores_removed.extend(f"{name}/{c}" for c in sorted(before - after)) - return diff - - -def _scrape_into_copy( - module: str, source: Path, workdir: Path, timeout: int = 900, - extra: tuple[str, ...] = (), -) -> tuple[Path, str | None]: - """Run a scraper's own write path on a throwaway copy of *source*. - - The CLI merges into the file it writes, so the copy carries every field - the scraper preserves and the diff shows only what the scrape changes. - """ - target = workdir / source.name - shutil.copyfile(source, target) - proc = subprocess.run( - [sys.executable, "-m", module, "-o", str(target), *extra], - cwd=REPO_ROOT, - capture_output=True, - text=True, - timeout=timeout, - check=False, - ) - if proc.returncode != 0: - tail = (proc.stderr or proc.stdout).strip().splitlines()[-1:] - return target, tail[0] if tail else f"exit {proc.returncode}" - return target, None - - -def _scrapable_platforms(platforms_dir: Path) -> list[tuple[str, str, Path]]: - """(platform, scraper module, file) for every registered platform. - - A platform that only inherits another and declares no source of its own - (Lakka) has nothing to scrape: its scraper writes the parent's file. - """ - registry = load_platform_registry(platforms_dir, required=True) - rows = [] - for name in list_registered_platforms(str(platforms_dir)): - path = platforms_dir / f"{name}.yml" - if not path.is_file(): - continue - config = source_yaml_file(path) or {} - scraper = (registry.get(name) or {}).get("scraper") - if not scraper or (config.get("inherits") and not config.get("source")): - continue - rows.append((name, f"scripts.scraper.{scraper}_scraper", path)) - return rows - - -def rescrape_args(platforms_dir: Path, name: str) -> tuple[str, ...]: - """What a rescrape passes so the scraper reads upstream's moving head. - - A scraper that rereads the revision its platform file pins by default - (RetroBat) names the ref to move to in the registry's rescrape_args. - """ - registry = load_platform_registry(platforms_dir, required=True) - return tuple(str(a) for a in (registry.get(name) or {}).get("rescrape_args") or ()) - - -def check_platforms(platforms_dir: Path, workdir: Path, jobs: int) -> list[Finding]: - rows = _scrapable_platforms(platforms_dir) - findings: list[Finding] = [] - - def run(row: tuple[str, str, Path]) -> Finding: - name, module, path = row - try: - fresh, error = _scrape_into_copy( - module, path, workdir, extra=rescrape_args(platforms_dir, name) - ) - except subprocess.TimeoutExpired: - return Finding("platforms", name, ERROR, detail="scraper timed out") - if error: - return Finding("platforms", name, ERROR, detail=error) - old = source_yaml_file(path) or {} - new = source_yaml_file(fresh) or {} - diff = diff_platform(old, new) - status = STALE if diff.changed else OK - return Finding( - "platforms", - name, - status, - local=str(old.get("version", "")), - remote=str(new.get("version", "")), - detail=diff.summary(), - ) - - with ThreadPoolExecutor(max_workers=jobs) as pool: - findings.extend(pool.map(run, rows)) - return sorted(findings, key=lambda f: f.subject) - - -_EJS_VERSION_RE = re.compile(r"^ARG EMULATORJS_VERSION=(\S+)", re.MULTILINE) -ROMM_DOCKERFILES = ("docker/Dockerfile", "Dockerfile") - - -def emulatorjs_pin(dockerfile: str) -> str | None: - """The EmulatorJS release a RomM image installs, from its Dockerfile.""" - match = _EJS_VERSION_RE.search(dockerfile) - return match.group(1) if match else None - - -def check_emulatorjs(platforms_dir: Path, offline: bool) -> Finding: - """emulatorjs.yml against the EmulatorJS release RomM's image installs. - - emulatorjs.yml is not a registered platform, so no scrape covers it: a - RomM moving to a newer EmulatorJS changed the cores its users run with - nothing to say so. - """ - subject = "romm emulatorjs" - local = str((source_yaml_file(platforms_dir / "emulatorjs.yml") or {}).get("version", "")) - if offline: - return Finding("platforms", subject, SKIPPED, local=local, detail="offline") - tag = str((source_yaml_file(platforms_dir / "romm.yml") or {}).get("version", "")) - for path in ROMM_DOCKERFILES: - try: - text = upstream.http_text( - f"https://raw.githubusercontent.com/rommapp/romm/{tag}/{path}") - except upstream.UpstreamError as exc: - return Finding("platforms", subject, UNKNOWN, local=local, detail=str(exc)) - pin = emulatorjs_pin(text or "") - if pin: - return Finding("platforms", subject, OK if pin == local else STALE, - local=local, remote=pin, - detail=f"RomM {tag} installs EmulatorJS {pin}") - return Finding("platforms", subject, UNKNOWN, local=local, - detail=f"no EMULATORJS_VERSION in RomM {tag}'s Dockerfile") - - -# --- native originals -------------------------------------------------------- - - -def native_cache_state( - wanted: dict[str, str], - root: Path, - recorded: dict[str, str], - index: Path, - transcribed_at: float, -) -> str: - """Why a platform's cached originals cannot be patched, '' when they can. - - The export corrects the file our data was transcribed from. A cached - original is that file only if it came from the URL the platform file - names today and was fetched no earlier than the platform file was last - rewritten: a branch URL keeps its name while its content moves. - """ - for relative, url in sorted(wanted.items()): - path = root / relative - if not path.is_file(): - return f"{relative} not cached" - known = recorded.get(source_key(path, index)) - if known is None: - return f"{relative} cached from an unrecorded URL" - if known != url: - return f"{relative} cached from another revision" - if path.stat().st_mtime < transcribed_at: - return f"{relative} cached before the platform file was rewritten" - return "" - - -def _export_tree(root: Path, platform: str) -> dict[str, bytes]: - """A platform's published export: its directory and its report.""" - tree = { - path.relative_to(root).as_posix(): path.read_bytes() - for path in (root / platform).rglob("*") if path.is_file() - } - report = root / f"{platform}.json" - if report.is_file(): - tree[report.name] = report.read_bytes() - return tree - - -def published_export_state( - platform: str, - exporter_class: type, - truth_dir: Path, - platforms_dir: Path, - cache_dir: Path, - published: Path, -) -> str: - """Why the committed export is not what the export writes now, '' when it is. - - exports/ is committed and the site publishes it, but CI cannot rebuild - it: the originals it patches live in the local cache. A profile change - that moves a hash leaves the published file behind until someone runs - the export again, and this is what says so. - """ - scratch_root = Path("tmp") - scratch_root.mkdir(exist_ok=True) - with tempfile.TemporaryDirectory(dir=scratch_root) as scratch: - with contextlib.redirect_stdout(io.StringIO()): - ok, messages = export_platform( - platform, exporter_class, truth_dir, Path(scratch), - str(platforms_dir), cache_dir, False, - ) - if not ok: - return f"the export fails: {messages[0] if messages else 'no message'}" - if _export_tree(Path(scratch), platform) != _export_tree(published, platform): - return f"{published.as_posix()}/{platform} is not what the export writes now" - return "" - - -def _transcribed_at(platforms_dir: Path, platform: str) -> float: - """Last rewrite of the platform file or of any file it inherits.""" - return max( - ((platforms_dir / f"{name}.yml").stat().st_mtime - for name in inheritance_chain(platform, platforms_dir)), - default=0.0, - ) - - -# How the truth model settles two cores' hashes: generate_truth reports it, -# and it says nothing about whether a cached original is current. -_MODEL_NOTES = ("WARNING: hash conflict",) - - -@contextlib.contextmanager -def _without_model_notes() -> Iterator[None]: - """Keep the model build's own notes out of the freshness report. - - Anything else written to stderr passes through. - """ - sink = io.StringIO() - try: - with contextlib.redirect_stderr(sink): - yield - finally: - for line in sink.getvalue().splitlines(keepends=True): - if not line.startswith(_MODEL_NOTES): - sys.stderr.write(line) - - -def check_native( - platforms_dir: Path, cache_dir: Path, truth_dir: Path, - published: Path = Path("exports"), -) -> list[Finding]: - exporters = discover_exporters() - index = cache_dir / SOURCES_INDEX - try: - recorded = load_sources(cache_dir) - except SourcesIndexUnreadable as exc: - return [Finding("native", index.name, ERROR, detail=str(exc))] - findings: list[Finding] = [] - for name in list_registered_platforms(str(platforms_dir)): - exporter_class = exporters.get(name) - if not exporter_class: - continue - with _without_model_notes(): - try: - truth, scraped = load_inputs(name, truth_dir, str(platforms_dir)) - except StaleTruth as exc: - findings.append(Finding("native", name, STALE, detail=str(exc))) - continue - systems, _ = build_native_model(truth or {}, scraped) - wanted = wanted_sources(exporter_class(), systems, scraped) - reason = native_cache_state( - wanted, cache_dir / name, recorded, index, _transcribed_at(platforms_dir, name) - ) - if reason: - reason += ( - f", python scripts/export_native.py --platform {name} --refresh-cache" - " fetches it, then the export is written again" - ) - else: - reason = published_export_state( - name, exporter_class, truth_dir, platforms_dir, cache_dir, published - ) - if reason: - reason += f", python scripts/export_native.py --platform {name} writes it again" - findings.append( - Finding( - "native", - name, - STALE if reason else OK, - local=f"{len(wanted)} file(s)", - detail=reason, - ) - ) - return sorted(findings, key=lambda f: f.subject) - - -# --- targets ---------------------------------------------------------------- - - -def profile_name_index(profiles: dict[str, dict]) -> dict[str, set[str]]: - """Upstream core name -> the profiles that claim it, as target filtering reads it.""" - return upstream_profile_index(profiles, include_aliases=True) - - -def unresolved_target_cores( - targets: dict, index: Container[str], overrides: dict -) -> dict[str, list[str]]: - """Core names a target ends up with that no profile claims. - - Read after the overrides, by the function the builder applies - (apply_target_overrides): _default then the target, add_cores - included. A name added by hand without a profile is the false skip - this check exists for, and a copy that read remove_cores alone never - saw it. - """ - unresolved: dict[str, list[str]] = {} - for name, entry in (targets.get("targets") or {}).items(): - cores = {str(c) for c in (entry or {}).get("cores") or []} - for core in sorted(apply_target_overrides(cores, overrides, name)): - if core not in index: - unresolved.setdefault(core, []).append(name) - return {core: sorted(names) for core, names in sorted(unresolved.items())} - - -def _target_scrapers() -> dict[str, str]: - """platform -> scraper module for every target scraper on disk.""" - return { - platform: cls.__module__ - for platform, cls in discover_target_scrapers().items() - } - - -def check_targets( - platforms_dir: Path, workdir: Path, profiles: dict[str, dict], jobs: int, - offline: bool, -) -> list[Finding]: - targets_dir = platforms_dir / "targets" - overrides = read_target_overrides(targets_dir) - index = profile_name_index(profiles) - scrapers = _target_scrapers() - findings: list[Finding] = [] - today = datetime.now(timezone.utc) - - def run(platform: str) -> list[Finding]: - path = targets_dir / f"{platform}.yml" - if not path.is_file(): - return [Finding("targets", platform, ERROR, detail="no target file")] - old = source_yaml_file(path) or {} - module = scrapers.get(platform) - targets = old.get("targets") or {} - if module is not None and offline: - # Scraped, so offline means not compared: SKIPPED, as every other - # section says it. Labelled static and OK, a list 400 days old - # read as current. - stamp = str(old.get("scraped_at", ""))[:10] - out = [Finding("targets", platform, SKIPPED, local=stamp, detail="offline")] - missing = unresolved_target_cores(old, index, platform_overrides(overrides, platform)) - out.extend(_unresolved_findings(platform, missing)) - return out - if module is None and targets and all( - (t or {}).get("cores", []) is None for t in targets.values() - ): - # Every core the platform declares runs on these targets: the list - # is the platform's own and has nothing of its own to age. Its - # names still need a profile each: RetroBat's winuae, jzintv or - # sudachi without one are BIOS its pack never carries. - out = [Finding("targets", platform, OK, local="static", - detail="every declared core")] - declared = _declared_cores(platform) - missing = unresolved_target_cores( - {"targets": {name: {"cores": declared} for name in targets}}, - index, platform_overrides(overrides, platform), - ) - out.extend(_unresolved_findings(platform, missing)) - return out - if module is None: - # No scraper: a hand-written file has no upstream to diff against, - # so only its age and its core names can be reported. - stamp = str(old.get("scraped_at", ""))[:10] - age = _age_days(stamp, today) - out = [ - Finding( - "targets", - platform, - OK if age is not None else UNKNOWN, - local=f"static {stamp}", - detail=f"{age} days old" if age is not None else "no scrape stamp", - ) - ] - missing = unresolved_target_cores(old, index, platform_overrides(overrides, platform)) - out.extend(_unresolved_findings(platform, missing)) - return out - try: - fresh, error = _scrape_into_copy(module, path, workdir) - except subprocess.TimeoutExpired: - return [Finding("targets", platform, ERROR, detail="scraper timed out")] - if error: - return [Finding("targets", platform, ERROR, detail=error)] - new = source_yaml_file(fresh) or {} - diff = diff_targets(old, new) - out = [ - Finding( - "targets", - platform, - STALE if diff.content_changed else OK, - local=str(old.get("scraped_at", ""))[:10], - remote=str(new.get("scraped_at", ""))[:10], - detail=diff.summary(), - ) - ] - missing = unresolved_target_cores(new, index, platform_overrides(overrides, platform)) - out.extend(_unresolved_findings(platform, missing)) - return out - - names = sorted(p.stem for p in targets_dir.glob("*.yml") if not p.name.startswith("_")) - with ThreadPoolExecutor(max_workers=jobs) as pool: - for rows in pool.map(run, names): - findings.extend(rows) - return findings - - -def _declared_cores(platform: str) -> list[str]: - """The cores and standalone emulators a platform's own file names.""" - from model.platforms import load_platform_config - - try: - config = load_platform_config(platform, str(REPO_ROOT / "platforms")) - except (FileNotFoundError, OSError): - return [] - cores = config.get("cores") - names = [str(c) for c in cores] if isinstance(cores, list) else [] - return names + [str(c) for c in config.get("standalone_cores") or []] - - -def _unresolved_findings(platform: str, missing: dict[str, list[str]]) -> list[Finding]: - """One row per platform: the names its targets list that no profile claims. - - A buildbot name without a profile is a core the target filter cannot - see, and a platform's own emulator id without one is an emulator nobody has - profiled yet. Both are actionable, so both are listed, but as one row so - the backlog does not bury the day's changes. - """ - if not missing: - return [] - names = sorted(missing) - shown = ", ".join(names[:SHOWN_NAMES]) + ( - f", ... (--json lists all {len(names)})" if len(names) > SHOWN_NAMES else "" - ) - return [ - Finding( - "targets", - f"{platform} cores", - STALE, - local=f"{len(names)} without a profile", - detail=f"cores: alias or _overrides remove_cores needed for {shown}", - items=names, - ) - ] - - -def _age_days(stamp: str, now: datetime) -> int | None: - try: - then = datetime.strptime(stamp[:10], "%Y-%m-%d").replace(tzinfo=timezone.utc) - except ValueError: - return None - return (now - then).days - - -# --- rom folders ------------------------------------------------------------ - - -def romfolder_sources(platforms_dir: Path) -> dict[str, dict]: - """setup -> its platforms/romfolders/_sources/.yml.""" - out = {} - for path in sorted((platforms_dir / "romfolders" / "_sources").glob("*.yml")): - out[path.stem] = source_yaml_file(path) or {} - return out - - -def _os_source(doc: dict) -> dict: - """The source the setup is pinned on: `os`, else the first declared. - The others follow from it (an EmulationStation pinned by a package.mk).""" - sources = doc.get("sources") or {} - return sources.get("os") or next(iter(sources.values()), {}) - - -def platform_revision(setup: str, doc: dict, platforms_dir: Path) -> str: - """The revision the setup's own platform file was scraped at, when the - setup is a registered platform read from the same repository; '' else.""" - if setup not in load_platform_registry(str(platforms_dir)): - return "" - repo = upstream.parse_repo(str(_os_source(doc).get("repo") or "")) - if repo is None: - return "" - return scraped_revision(platforms_dir / f"{setup}.yml", repo.slug) - - -def romfolder_pin_drift(setup: str, doc: dict, platforms_dir: Path) -> str | None: - """Why the folders and the BIOS of one platform come from two revisions, - None when they do not or when only the forge can tell (a tag on one - side, a commit on the other).""" - revision = platform_revision(setup, doc, platforms_dir) - os_source = _os_source(doc) - tag, commit = os_source.get("tag"), str(os_source.get("commit") or "") - if not revision or revision in (tag, commit): - return None - if tag or len(revision) == len(commit): - return f"platforms/{setup}.yml was scraped at {revision[:12]}, the rom folders at {tag or commit[:12]}" - return None - - -def check_romfolders(platforms_dir: Path, cache_dir: str, offline: bool) -> list[Finding]: - """The pins of platforms/romfolders/_sources/ against what they follow. - - A setup that is a registered platform is read at the revision its - platform file was scraped at: the games-on-card mode otherwise installs - the BIOS of one release for the folders of another. Any other setup is - compared with its project's newest release, or with its branch head - when the project publishes none. A pin is moved by hand, then - `python -m scripts.scraper.romfolders --setup NAME` reads it again. - """ - findings: list[Finding] = [] - for setup, doc in romfolder_sources(platforms_dir).items(): - os_source = _os_source(doc) - pin = str(os_source.get("tag") or str(os_source.get("commit") or "")[:12]) - drift = romfolder_pin_drift(setup, doc, platforms_dir) - if drift: - findings.append(Finding("romfolders", setup, STALE, local=pin, detail=drift)) - continue - revision = platform_revision(setup, doc, platforms_dir) - repo = upstream.parse_repo(str(os_source.get("repo") or "")) - commit = str(os_source.get("commit") or "") - if revision and revision in (os_source.get("tag"), commit): - findings.append(Finding("romfolders", setup, OK, local=pin, - detail=f"read where platforms/{setup}.yml is")) - continue - if offline: - findings.append(Finding("romfolders", setup, SKIPPED, local=pin, detail="offline")) - continue - if repo is None or not commit: - findings.append(Finding("romfolders", setup, UNKNOWN, local=pin, detail="no forge to ask")) - continue - findings.append(_romfolder_upstream(setup, repo, os_source, revision, cache_dir)) - return findings - - -def _romfolder_upstream( - setup: str, repo: upstream.Repo, os_source: dict, revision: str, cache_dir: str, -) -> Finding: - commit, tag = str(os_source["commit"]), os_source.get("tag") - pin = str(tag or commit[:12]) - if revision: - # The platform names a tag and the setup a commit: the tag's commit decides. - tagged = upstream.resolve_tag_commit(repo, revision, cache_dir) - if tagged is None: - return Finding("romfolders", setup, UNKNOWN, local=pin, detail=f"tag {revision} not listed") - if tagged == commit: - return Finding("romfolders", setup, OK, local=pin, detail=f"commit of {revision}") - return Finding("romfolders", setup, STALE, local=pin, remote=revision, - detail=f"platforms/{setup}.yml was scraped at {revision} ({tagged[:12]})") - pinned_at = (upstream.commit_date(repo, commit, cache_dir) or "")[:10] - release = upstream.latest_release(repo, cache_dir) - if release is not None and release.date: - newer = release.tag != tag and release.date > pinned_at - return Finding("romfolders", setup, STALE if newer else OK, local=f"{pin} ({pinned_at})", - remote=f"{release.tag} ({release.date})", - detail="a release is newer than the pin" if newer else "newest release") - head = upstream.resolve_head(repo, cache_dir) - if head is None: - return Finding("romfolders", setup, UNKNOWN, local=pin, detail="branch head unavailable") - if head == commit: - return Finding("romfolders", setup, OK, local=pin, detail="branch head") - counts = upstream.ancestry(repo, commit, head, cache_dir) - behind = f"{counts[0]} commits behind the branch head" if counts else "the branch head moved" - return Finding("romfolders", setup, STALE, local=pin, remote=head[:12], detail=behind) - - -# --- core-info -------------------------------------------------------------- - - -def core_info_blobs(cache_dir: str, offline: bool) -> dict[str, str] | None: - """Every core the libretro core-info repository describes, with the git - blob of its .info.""" - repo = upstream.parse_repo(CORE_INFO_REPO) - if repo is None: - return None - payload = upstream.cached_api( - f"{repo.api_base}/repos/{repo.slug}/contents?per_page=100", - cache_dir, - offline, - upstream.MOVING_TTL, - ) - if not isinstance(payload, list): - return None - blobs = {} - for entry in payload: - name = entry.get("name", "") if isinstance(entry, dict) else "" - if name.endswith("_libretro.info"): - blobs[name[: -len("_libretro.info")]] = str(entry.get("sha") or "") - return dict(sorted(blobs.items())) - - -def core_info_names(cache_dir: str, offline: bool) -> list[str] | None: - """Every core the libretro core-info repository describes.""" - blobs = core_info_blobs(cache_dir, offline) - return None if blobs is None else list(blobs) - - -def load_core_info_record(path: Path = CORE_INFO_RECORD) -> dict[str, str] | None: - if not path.is_file(): - return None - return dict((json.loads(path.read_text(encoding="utf-8")) or {}).get("blobs") or {}) - - -def record_core_info( - blobs: dict[str, str], names: list[str], path: Path = CORE_INFO_RECORD -) -> list[str]: - """Record the current blob of *names* (every .info when empty) as reviewed. - - Naming the cores keeps a change nobody read out of the record. - """ - unknown = sorted(set(names) - set(blobs)) - if unknown: - raise InputMissing( - f"no such .info in core-info: {', '.join(unknown)}. " - + suggest_names(unknown, list(blobs), "libretro-core-info") - ) - recorded = load_core_info_record(path) or {} - recorded.update({n: blobs[n] for n in (names or blobs)}) - payload = {"repository": CORE_INFO_REPO, "blobs": dict(sorted(recorded.items()))} - write_text_atomic(str(path), json.dumps(payload, indent=2) + "\n") - return sorted(names or blobs) - - -def coreinfo_drift( - blobs: dict[str, str], recorded: dict[str, str], profiles: dict[str, dict] -) -> list[str]: - """Profiled cores whose .info is not the one recorded as reviewed. - - The .info is no authority, but a new firmwareN_path in it is the - cheapest sign that a profile needs reading again. - """ - index = {key.casefold() for key in profile_name_index(profiles)} - return [n for n, sha in blobs.items() - if n.casefold() in index and recorded.get(n) != sha] - - -def coreinfo_gaps( - names: list[str], profiles: dict[str, dict] -) -> tuple[list[str], list[tuple[str, str]]]: - """Cores core-info knows that the profiles do not, and profiles that - call standalone a core libretro now builds. - - Matching folds case: the buildbot serves lower-case names while a few - .info files keep the project's own casing. - """ - index: dict[str, set[str]] = {} - for key, claimants in profile_name_index(profiles).items(): - index.setdefault(key.casefold(), set()).update(claimants) - unprofiled = [n for n in names if n.casefold() not in index] - # A name only standalone profiles claim: libretro now builds a core - # nothing in the collection describes as one. - standalone = [ - (n, sorted(index[n.casefold()])[0]) - for n in names - if n.casefold() in index - and all( - str(profiles[c].get("type", "")).strip() == "standalone" - for c in index[n.casefold()] - ) - ] - return unprofiled, standalone - - -def check_coreinfo( - profiles: dict[str, dict], cache_dir: str, offline: bool, - record_path: Path = CORE_INFO_RECORD, -) -> list[Finding]: - blobs = core_info_blobs(cache_dir, offline) - if blobs is None and offline: - # Offline with no cached listing, nothing was asked of the upstream. - return [Finding("coreinfo", "libretro-core-info", SKIPPED, detail="offline")] - if blobs is None: - return [Finding("coreinfo", "libretro-core-info", UNKNOWN, detail="listing unavailable")] - names = list(blobs) - unprofiled, standalone = coreinfo_gaps(names, profiles) - findings = [ - Finding( - "coreinfo", - "libretro-core-info", - STALE if unprofiled or standalone else OK, - local=f"{len(names) - len(unprofiled)} profiled", - remote=f"{len(names)} .info files", - ) - ] - findings.extend( - Finding("coreinfo", name, STALE, detail="no profile claims this core name") - for name in unprofiled - ) - findings.extend( - Finding( - "coreinfo", - name, - STALE, - local=f"{key}: type standalone", - detail="core-info describes a libretro build of it", - ) - for name, key in standalone - ) - recorded = load_core_info_record(record_path) - if recorded is None: - findings.append(Finding( - "coreinfo", "reviewed .info", UNKNOWN, - detail=f"no {record_path.name}: run python scripts/check_freshness.py --record-coreinfo", - )) - return findings - findings.extend( - Finding( - "coreinfo", name, STALE, - local=(recorded.get(name) or "not recorded")[:12], remote=blobs[name][:12], - detail=(".info changed since reviewed: read its firmware, then " - f"python scripts/check_freshness.py --record-coreinfo {name}"), - ) - for name in coreinfo_drift(blobs, recorded, profiles) - ) - return findings - - -# --- data directories ------------------------------------------------------- - - -def check_data(offline: bool) -> list[Finding]: - if offline: - return [Finding("data", "_data_dirs.yml", SKIPPED, detail="offline")] - registry = load_data_dir_registry(REPO_ROOT / "platforms", required=True) - sink = io.StringIO() - with contextlib.redirect_stdout(sink): - results = datadirs.refresh_all(registry, dry_run=True) - findings = [] - for key, result in sorted(results.items()): - if result is None: - findings.append(Finding("data", key, UNKNOWN, detail="remote unreachable")) - elif result: - findings.append(Finding("data", key, STALE, detail="upstream changed, refresh_data_dirs.py fetches it")) - else: - findings.append(Finding("data", key, OK)) - findings.append(_check_buildbot_system()) - return findings - - -def _check_buildbot_system() -> Finding: - """The buildbot's system directory against what _data_dirs.yml tracks. - - The registry entries are refreshed above. An asset published since, or - one the buildbot no longer serves, is only seen by reading its .index. - """ - from scraper import buildbot_system - - with contextlib.redirect_stdout(io.StringIO()): - report = buildbot_system.check( - str(REPO_ROOT / DATA_DIRS_FILE) - ) - if report.get("error"): - return Finding("data", "buildbot system", UNKNOWN, detail="index unreachable") - todo = buildbot_system.pending(report) - if not todo: - return Finding("data", "buildbot system", OK) - every = [f"{e['status'].lower()} {e['zip']}" for e in todo] - names = ", ".join(every[:SHOWN_NAMES]) - more = f", ... (--json lists all {len(todo)})" if len(todo) > SHOWN_NAMES else "" - return Finding("data", "buildbot system", STALE, local=f"{len(todo)} to track", - detail=f"{names}{more} (_data_dirs.yml)", items=every) - - -# --- catalogs and recipes --------------------------------------------------- - - -def _snapshot(path: Path) -> dict: - if not path.is_file(): - return {} - with path.open(encoding="utf-8") as fh: - return json.load(fh) - - -def check_catalogs(cache_dir: str, offline: bool) -> list[Finding]: - findings = [] - findings.append(_check_redump(offline)) - findings.append(_check_no_intro(cache_dir, offline)) - findings.append(_check_tosec(offline)) - findings.append(_check_mame(cache_dir, offline)) - findings.append(_check_fbneo(cache_dir, offline)) - findings.append(_check_nointro_games(cache_dir, offline)) - findings.append(_check_redump_games(offline)) - return findings - - -def _game_catalogs(source: str) -> list[dict]: - """The committed game catalogs of one source, games/catalogs//.""" - return [_snapshot(path) for path in sorted((REPO_ROOT / "games" / "catalogs" / source).glob("*.json"))] - - -def _no_intro_asset_date(cache_dir: str, offline: bool) -> str: - """The day the mirror last rebuilt its No-Intro pack, empty if unlisted.""" - repo = upstream.parse_repo(NO_INTRO_MIRROR) - payload = upstream.cached_api( - f"{repo.api_base}/repos/{repo.slug}/releases/tags/{NO_INTRO_RELEASE}", - cache_dir, - offline, - upstream.MOVING_TTL, - ) - for asset in (payload.get("assets") if isinstance(payload, dict) else None) or []: - if isinstance(asset, dict) and asset.get("name") == NO_INTRO_ASSET: - return str(asset.get("updated_at", ""))[:10] - return "" - - -def _today() -> str: - return datetime.now(timezone.utc).strftime("%Y-%m-%d") - - -def _no_intro_row(subject: str, local: str, updated: str) -> Finding: - """Our import against the mirror's pack, and the pack against today.""" - age = (datetime.fromisoformat(_today()) - datetime.fromisoformat(updated)).days - if age > NO_INTRO_MAX_AGE_DAYS: - return Finding( - "catalogs", subject, STALE, local=local, remote=updated, - detail=f"the mirror last rebuilt {NO_INTRO_ASSET} on {updated}, {age} days ago, " - f"though it rebuilds daily: {NO_INTRO_MIRROR}/actions", - ) - return Finding( - "catalogs", subject, STALE if updated > local else OK, - local=local, remote=updated, detail=f"{NO_INTRO_ASSET} rebuilt {updated}", - ) - - -def _check_nointro_games(cache_dir: str, offline: bool) -> Finding: - """games/catalogs/no-intro/ against the pack it was read from. The pack - holds every DAT: rebuilt after the catalogs were read, it may carry - games the games-on-card mode does not recognise.""" - subject = "no-intro games" - fetched = min((str(doc.get("fetched", "")) for doc in _game_catalogs("no-intro")), default="") - if offline: - return Finding("catalogs", subject, SKIPPED, local=fetched, detail="offline") - updated = _no_intro_asset_date(cache_dir, offline) - if not updated: - return Finding("catalogs", subject, UNKNOWN, local=fetched, detail="asset not listed") - return _no_intro_row(subject, fetched, updated) - - -def redump_datfile_version(code: str) -> str: - """The version redump.info serves for one datfile, read from the name it - gives the download: a HEAD request, nothing downloaded.""" - url = game_dat_importer.REDUMP_DATFILE_URL.format(code=code) - request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "retrobios/1.0"}) - disposition = upstream.open_retrying( - request, lambda response: response.headers.get("Content-Disposition", ""), timeout=60 - ) - named = game_dat_importer.DISPOSITION.search(disposition) - match = game_dat_importer.REDUMP_FILE.match(named["file"]) if named else None - if not match: - raise ValueError(f"{url} names no datfile") - return f"{match['date']} {match['time']}" - - -def _check_redump_games(offline: bool) -> Finding: - """games/catalogs/redump/ against the datfiles redump.info serves now. - A disc dumped since is not recognised by the games-on-card mode.""" - subject = "redump games" - local = {doc.get("system"): str(doc.get("version", "")) for doc in _game_catalogs("redump")} - newest = max(local.values(), default="") - if offline: - return Finding("catalogs", subject, SKIPPED, local=newest, detail="offline") - changed = [] - remote_newest = "" - for code, (_name, system, _floor) in sorted(game_dat_importer.REDUMP_DATS.items()): - try: - remote = redump_datfile_version(code) - except (OSError, http.client.HTTPException, upstream.UpstreamError, ValueError) as exc: - return Finding("catalogs", subject, UNKNOWN, local=newest, detail=str(exc)) - remote_newest = max(remote_newest, remote) - if local.get(system) != remote: - changed.append(system) - return Finding( - "catalogs", subject, STALE if changed else OK, local=newest, remote=remote_newest, - detail=(f"changed: {', '.join(changed)}" if changed else f"{len(local)} DATs"), - items=changed, - ) - - -def _check_redump(offline: bool) -> Finding: - local = _snapshot(REPO_ROOT / "provenance" / "redump.json") - dats = local.get("dats") or {} - stamp = ", ".join(sorted(set(dats.values()))) or "none" - if offline: - return Finding("catalogs", "redump", SKIPPED, local=stamp, detail="offline") - try: - remote_dats, _ = fetch_snapshot() - except (ConnectionError, ValueError) as exc: - return Finding("catalogs", "redump", UNKNOWN, local=stamp, detail=str(exc)) - remote_stamp = ", ".join(sorted(set(remote_dats.values()))) - changed = sorted( - name for name in set(dats) | set(remote_dats) if dats.get(name) != remote_dats.get(name) - ) - return Finding( - "catalogs", - "redump", - STALE if changed else OK, - local=stamp, - remote=remote_stamp, - detail=("changed: " + ", ".join(changed)) if changed else f"{len(dats)} DATs", - ) - - -def _check_no_intro(cache_dir: str, offline: bool) -> Finding: - local = _snapshot(REPO_ROOT / "provenance" / "no-intro.json") - imported = str(local.get("imported_at", "")) - if offline: - return Finding("catalogs", "no-intro", SKIPPED, local=imported, detail="offline") - updated = _no_intro_asset_date(cache_dir, offline) - if not updated: - return Finding("catalogs", "no-intro", UNKNOWN, local=imported, detail="asset not listed") - return _no_intro_row("no-intro", imported, updated) - - -def tosec_latest_pack(html: str) -> str | None: - """Date of the newest TOSEC release the downloads page lists.""" - dates = re.findall(r'/downloads/category/\d+-(\d{4}-\d{2}-\d{2})"', html) - return max(dates) if dates else None - - -def _check_tosec(offline: bool) -> Finding: - local = _snapshot(REPO_ROOT / "provenance" / "tosec.json") - imported = str(local.get("imported_at", "")) - if offline: - return Finding("catalogs", "tosec", SKIPPED, local=imported, detail="offline") - try: - html = upstream.http_text(TOSEC_DOWNLOADS) - except upstream.UpstreamError as exc: - return Finding("catalogs", "tosec", UNKNOWN, local=imported, detail=str(exc)) - latest = tosec_latest_pack(html or "") - if latest is None: - return Finding("catalogs", "tosec", UNKNOWN, local=imported, detail="no release listed") - return Finding( - "catalogs", - "tosec", - STALE if latest > imported else OK, - local=imported, - remote=latest, - detail=f"newest pack TOSEC-v{latest}", - ) - - -def mame_versions(recipes: dict) -> list[str]: - """MAME version tags a recipe snapshot has absorbed, oldest first.""" - tags = set() - for label in (recipes.get("dats") or {}): - match = re.search(r"\b(mame\d{4})\b", str(label)) - if match: - tags.add(match.group(1)) - return sorted(tags) - - -def _check_mame(cache_dir: str, offline: bool) -> Finding: - local = _snapshot(REPO_ROOT / "recipes" / "mame.json") - versions = mame_versions(local) - newest = versions[-1] if versions else "none" - if offline: - return Finding("catalogs", "mame recipes", SKIPPED, local=newest, detail="offline") - release = upstream.latest_release(upstream.parse_repo(MAME_REPO), cache_dir, offline) - if release is None: - return Finding("catalogs", "mame recipes", UNKNOWN, local=newest, detail="no release seen") - return Finding( - "catalogs", - "mame recipes", - OK if release.tag in versions else STALE, - local=newest, - remote=f"{release.tag} ({release.date})", - detail=f"{len(versions)} versions imported", - ) - - -def fbneo_blob_drift(snapshot: dict, listing: object) -> tuple[list[str], bool]: - """DAT files whose git blob differs from the one the snapshot was read - from. The second value says whether the snapshot records blobs at all: - one written before that field existed can only be compared by date. - """ - recorded = (snapshot.get("upstream") or {}).get("blobs") or {} - if not recorded: - return [], False - remote = { - item["name"]: item.get("sha", "") - for item in (listing if isinstance(listing, list) else []) - if isinstance(item, dict) - and item.get("type") == "file" - and str(item.get("name", "")).lower().endswith(".dat") - } - drifted = sorted( - name for name in set(recorded) | set(remote) if recorded.get(name) != remote.get(name) - ) - return drifted, True - - -def _check_fbneo(cache_dir: str, offline: bool) -> Finding: - local = _snapshot(REPO_ROOT / "recipes" / "fbneo.json") - imported = str(local.get("imported_at", "")) - if offline: - return Finding("catalogs", "fbneo recipes", SKIPPED, local=imported, detail="offline") - repo = upstream.parse_repo(FBNEO_REPO) - listing = upstream.cached_api( - f"{repo.api_base}/repos/{repo.slug}/contents/dats", - cache_dir, - offline, - upstream.MOVING_TTL, - ) - if not isinstance(listing, list): - return Finding("catalogs", "fbneo recipes", UNKNOWN, local=imported, detail="dats/ listing unavailable") - drifted, tracked = fbneo_blob_drift(local, listing) - if not tracked: - return Finding( - "catalogs", - "fbneo recipes", - STALE, - local=imported, - detail="snapshot records no upstream blobs: re-import with --fetch", - ) - shown = ", ".join(n.removeprefix("FinalBurn Neo (ClrMame Pro XML, ").removesuffix(" only).dat") for n in drifted[:4]) - return Finding( - "catalogs", - "fbneo recipes", - STALE if drifted else OK, - local=imported, - remote=f"{len(listing)} DATs listed", - detail=(f"{len(drifted)} DAT(s) changed upstream: {shown}" if drifted else "every DAT blob matches"), - ) - - -# --- CI toolchain ----------------------------------------------------------- - -_PIN_RE = re.compile( - r'"?([A-Za-z0-9_.\-]+)(?:\[[^\]]*\])?((?:[<>=!~]=?[^,"\s]+)(?:,[<>=!~]=?[^,"\s]+)*)?"?' -) -_USES_RE = re.compile(r"uses:\s*([\w.\-]+/[\w.\-]+)@([0-9a-f]{40})\s*(?:#\s*(\S+))?") - - -def parse_pip_pins(text: str) -> dict[str, str]: - """Package -> specifier for every ``pip install`` line of a workflow.""" - pins: dict[str, str] = {} - for line in text.splitlines(): - stripped = line.strip() - if "pip install" not in stripped: - continue - args = stripped.split("pip install", 1)[1] - for raw in re.findall(r'"[^"]+"|\S+', args): - token = raw.strip('"') - if token.startswith("-") or not token: - continue - match = _PIN_RE.fullmatch(token) - if match: - pins.setdefault(match.group(1).lower(), match.group(2) or "") - return pins - - -def parse_action_pins(text: str) -> dict[str, tuple[str, str]]: - """Action -> (pinned sha, commented tag) for every ``uses:`` line.""" - return { - repo: (sha, tag or "") for repo, sha, tag in _USES_RE.findall(text) - } - - -def _version_tuple(version: str) -> tuple[int, ...]: - return tuple(int(p) for p in re.findall(r"\d+", version)) - - -_SPEC_CLAUSE = re.compile(r"([<>=!~]=?)\s*(.+)") -_SPEC_TESTS = { - "==": lambda target, bound: target == bound, - "!=": lambda target, bound: target != bound, - ">=": lambda target, bound: target >= bound, - ">": lambda target, bound: target > bound, - "<=": lambda target, bound: target <= bound, - "<": lambda target, bound: target < bound, -} - - -def specifier_allows(spec: str, version: str) -> bool: - """Whether a pip specifier admits a version. Pre-releases are compared - on their numeric parts, which is enough for the operators pip uses here.""" - target = _version_tuple(version) - for clause in filter(None, (c.strip() for c in spec.split(","))): - match = _SPEC_CLAUSE.fullmatch(clause) - test = _SPEC_TESTS.get(match.group(1)) if match else None - if match is None or test is None or not test(target, _version_tuple(match.group(2))): - return False - return True - - -def pypi_latest(name: str) -> str | None: - payload = upstream.http_json(PYPI_URL.format(name=name)) - if not isinstance(payload, dict): - return None - info = payload.get("info") or {} - return str(info.get("version") or "") or None - - -def parse_npm_pins(text: str) -> dict[str, str]: - """Package -> the version a package.json names, dependencies of both kinds.""" - data = json.loads(text) - pins: dict[str, str] = {} - for key in ("dependencies", "devDependencies"): - pins.update({str(k): str(v) for k, v in (data.get(key) or {}).items()}) - return pins - - -def npm_latest(name: str) -> str | None: - payload = upstream.http_json(NPM_URL.format(name=name)) - if not isinstance(payload, dict): - return None - return str(payload.get("version") or "") or None - - -def _npm_findings() -> list[Finding]: - """One row per site dependency: an exact pin is stale once npm's latest - release is newer, since nothing else asks npm.""" - findings = [] - for name, pinned in sorted(parse_npm_pins(SITE_PACKAGE.read_text(encoding="utf-8")).items()): - subject = f"npm:{name}" - if not re.fullmatch(r"\d+(\.\d+)*", pinned): - findings.append(Finding("ci", subject, UNKNOWN, local=pinned, detail="a range, not an exact pin")) - continue - try: - latest = npm_latest(name) - except upstream.UpstreamError as exc: - findings.append(Finding("ci", subject, UNKNOWN, local=pinned, detail=str(exc))) - continue - if latest is None: - findings.append(Finding("ci", subject, UNKNOWN, local=pinned, detail="not on npm")) - continue - newer = _version_tuple(latest) > _version_tuple(pinned) - findings.append( - Finding( - "ci", - subject, - STALE if newer else OK, - local=pinned, - remote=latest, - detail="a newer release is out" if newer else "", - ) - ) - return findings - - -def check_ci(cache_dir: str, offline: bool) -> list[Finding]: - findings = [_check_installer_pins()] - workflows = sorted((REPO_ROOT / ".github" / "workflows").glob("*.yml")) - pins: dict[str, str] = {} - actions: dict[str, tuple[str, str]] = {} - for path in workflows: - text = path.read_text(encoding="utf-8") - for name, spec in parse_pip_pins(text).items(): - pins.setdefault(name, spec) - actions.update(parse_action_pins(text)) - if offline: - findings.append(Finding("ci", "workflow and site pins", SKIPPED, detail="offline")) - return findings - findings.extend(_npm_findings()) - for name, spec in sorted(pins.items()): - try: - latest = pypi_latest(name) - except upstream.UpstreamError as exc: - findings.append(Finding("ci", f"pypi:{name}", UNKNOWN, local=spec, detail=str(exc))) - continue - if latest is None: - findings.append(Finding("ci", f"pypi:{name}", UNKNOWN, local=spec, detail="not on PyPI")) - continue - allowed = specifier_allows(spec, latest) - findings.append( - Finding( - "ci", - f"pypi:{name}", - OK if allowed else STALE, - local=spec or "unpinned", - remote=latest, - detail="latest admitted" if allowed else "latest release outside the pin", - ) - ) - for action, (sha, tag) in sorted(actions.items()): - repo = upstream.parse_repo(f"https://github.com/{action}") - release = upstream.latest_release(repo, cache_dir, offline) - if release is None: - findings.append(Finding("ci", f"action:{action}", UNKNOWN, local=f"{sha[:8]} {tag}", detail="no release seen")) - continue - latest_sha = upstream.tag_commit(repo, release.tag, cache_dir, offline) or "" - findings.append( - Finding( - "ci", - f"action:{action}", - OK if latest_sha == sha else STALE, - local=f"{sha[:8]} {tag}".strip(), - remote=f"{latest_sha[:8]} {release.tag}", - detail="" if latest_sha == sha else f"{release.tag} released {release.date}", - ) - ) - return findings - - -def _check_installer_pins() -> Finding: - """The bootstraps pin install.py by SHA-256, so a stale pin refuses every install.""" - stale = installer_build_pins.stale_pins(REPO_ROOT) - return Finding( - "ci", - "install.py pin", - STALE if stale else OK, - local=installer_build_pins.installer_sha256(REPO_ROOT)[:12], - detail=( - f"pin outdated in {', '.join(stale)}, {installer_build_pins.COMMAND} writes it" - if stale else "install.sh and install.ps1 match" - ), - ) - - -# --- profiles --------------------------------------------------------------- - - -def check_source_paths(profiles: dict) -> Finding: - """The site links a cited path only where source-paths.json records it - in the tree the profile pins. A recorded tree no profile pins any more, - or a pinned tree the record lacks, means a pin moved or a profile was - added and `sitesources.py --fetch` was not run after it. Every tree a run - tries is recorded, read or not, so a lacking one was never tried.""" - from sitegen import sources as sitegen_sources - - pinned = { - sitegen_sources.tree_key(repo, pin) - for profile in profiles.values() if sitegen_sources.cited_paths(profile) - for repo, pin in sitegen_sources.profile_trees(profile) - } | { - # The platform build files pin_build names, linked from a page too. - sitegen_sources.tree_key(repo, pin) - for profile in profiles.values() - for repo, pin, _path in sitegen_sources.build_files(profile) - } - try: - recorded = set(json.loads(sitegen_sources.SOURCE_PATHS.read_text(encoding="utf-8"))) - except (OSError, ValueError) as exc: - return Finding("profiles", "source-paths.json", ERROR, detail=str(exc)) - orphaned = sorted(recorded - pinned) - unrecorded = sorted(pinned - recorded) - problems = [f"{len(found)} {words}" for found, words in ( - (orphaned, "recorded trees no profile pins"), - (unrecorded, "pinned trees not recorded"), - ) if found] - return Finding( - "profiles", - "source-paths.json", - STALE if problems else OK, - local=f"{len(recorded)} trees", - detail=(", ".join(problems) + ": run python scripts/sitesources.py --fetch") if problems - else "every pinned tree is recorded, and only those", - ) - - -def build_variable(lines: list[str], variable: str) -> str | None: - """The value the first assignment to ``variable`` gives in a build file. - - Read as a Buildroot .mk (`X_VERSION = sha`), a LibreELEC package.mk - (`PKG_VERSION="sha"`) or a RetroPie scriptmodule (`rp_module_repo="git - URL tag"`, `local version="20250829"`): quotes and a trailing comment go, - the rest is compared as written. - """ - assignment = re.compile( - rf"^\s*(?:local\s+|export\s+)?{re.escape(variable)}\s*[:?+]?=\s*(.*)$" - ) - for line in lines: - match = assignment.match(line) - if not match: - continue - value = match.group(1).strip() - if value[:1] in "\"'": - end = value.find(value[0], 1) - return value[1:end] if end > 0 else value[1:] - return value.split(" #", 1)[0].strip() - return None - - -def pin_build_revision(reference: dict, platforms_dir: Path) -> str: - """The revision of the platform repository its YAML was last scraped at, - '' when the platform is not registered or reads another repository.""" - repo = upstream.parse_repo(str(reference.get("repo") or "")) - if repo is None: - return "" - return scraped_revision(platforms_dir / f"{reference.get('platform', '')}.yml", repo.slug) - - -def check_pin_builds( - profiles: dict, platforms_dir: Path, cache_dir: str, offline: bool, -) -> list[Finding]: - """Each `pin_build:` read again where the platform now stands. - - A pin_frozen pin is held because one platform builds that revision, and - nothing read the build file again: Recalbox moving mame0278 to another - commit left the profile describing a build no platform ships. The file - is read at the revision the platform's own YAML was scraped at, or at - the repository's branch head for a platform this repository does not - scrape, and its variable compared with the value the profile recorded. - """ - findings: list[Finding] = [] - unreferenced = sorted( - name for name, profile in profiles.items() - if profile.get("pin_frozen") and not profile.get("pin_build") - ) - if unreferenced: - findings.append(Finding( - "profiles", "pin_frozen without pin_build", SKIPPED, - local=f"{len(unreferenced)} profiles", - detail="no platform build file names their revision: " - + ", ".join(unreferenced[:SHOWN_NAMES]) - + (", ..." if len(unreferenced) > SHOWN_NAMES else ""), - items=unreferenced, - )) - for name, profile in sorted(profiles.items()): - for reference in profile.get("pin_build") or []: - subject = f"{name} ({reference['platform']})" - recorded = str(reference["value"]) - revision = pin_build_revision(reference, platforms_dir) - if revision == str(reference["revision"]): - findings.append(Finding( - "profiles", subject, OK, local=recorded[:12], - detail=f"read where platforms/{reference['platform']}.yml is", - )) - continue - repo = upstream.parse_repo(str(reference["repo"])) - try: - at = revision or upstream.resolve_head(repo, cache_dir, offline) - lines = upstream.fetch_file(repo, at, reference["path"], cache_dir, offline) \ - if at else None - if at and lines is None: - # A file of a submodule is read at the commit the - # platform's tree pins: KNULLI builds Batocera's - # amiberry package through its batocera submodule. - modules = upstream.fetch_file(repo, at, ".gitmodules", cache_dir, offline) - declared = upstream.submodule_urls("\n".join(modules or ()), repo) - if any(reference["path"].startswith(f"{p}/") for p in declared): - linked = upstream.through_gitlink(repo, at, reference["path"], - cache_dir, offline) - if linked is not None: - lines = upstream.fetch_file(*linked, cache_dir, offline) - except upstream.NotCachedError: - findings.append(Finding("profiles", subject, SKIPPED, local=recorded[:12], - detail="offline, the build file is not cached")) - continue - except upstream.UpstreamError as exc: - findings.append(Finding("profiles", subject, UNKNOWN, local=recorded[:12], - detail=str(exc))) - continue - if not at: - findings.append(Finding("profiles", subject, UNKNOWN, local=recorded[:12], - detail=f"{repo.slug} answered no branch head")) - continue - current = None if lines is None else build_variable(lines, reference["variable"]) - if current == recorded: - findings.append(Finding( - "profiles", subject, OK, local=recorded[:12], remote=at[:12], - detail=f"{reference['path']} still builds it", - )) - continue - findings.append(Finding( - "profiles", subject, STALE, local=recorded[:12], - remote=(current or "gone")[:12], - detail=( - f"{reference['path']} is gone at {at[:12]}" if lines is None - else f"{reference['variable']} is no longer set there" if current is None - else f"{reference['platform']} now builds {current} " - f"({reference['path']} at {at[:12]}): the pin follows the build" - ), - )) - return findings - - -def check_profiles(run: bool, offline: bool) -> list[Finding]: - if not run: - return [ - Finding( - "profiles", - "profile_sync", - SKIPPED, - detail="pass --profiles, or run python scripts/profile_sync.py --all --triage", - ) - ] - cmd = [ - sys.executable, - str(REPO_ROOT / "scripts" / "profile_sync.py"), - "--all", - "--json", - "--check-version", - "--detect-new-files", - "--watch-hashes", - ] - if offline: - cmd.append("--offline") - proc = subprocess.run(cmd, cwd=REPO_ROOT, capture_output=True, text=True, check=False) - if proc.returncode not in (0, 1): - tail = proc.stderr.strip().splitlines()[-1:] - return [Finding("profiles", "profile_sync", ERROR, detail=tail[0] if tail else f"exit {proc.returncode}")] - try: - report = json.loads(proc.stdout) - except json.JSONDecodeError as exc: - return [Finding("profiles", "profile_sync", ERROR, detail=f"unreadable report: {exc}")] - return summarize_profile_sync(report) - - -def summarize_profile_sync(report: object) -> list[Finding]: - """One row per profile with something to look at, from profile_sync's JSON. - - The JSON carries the ref verdicts and the pin against the tip. A profile - whose refs need review is stale, one the forge could not serve is unknown, - and one whose upstream moved while every ref still anchors is reported as - such without being counted as stale. A cited file that gained a file name - since the pin, or a hash the profile does not declare, is stale too: the - upstream may load a file the profile does not document. - """ - if not isinstance(report, list): - return [Finding("profiles", "profile_sync", ERROR, detail="report is not a list")] - findings = [] - clean = moved = 0 - for row in report: - if not isinstance(row, dict): - continue - name = str(row.get("name") or "?") - if row.get("skipped") and row.get("page_version"): - # Off any forge, the release page is the feed: a version there - # beyond the declared one is a release the profile does not cover. - declared, announced = str(row.get("declared_version") or ""), str(row["page_version"]) - if announced == declared: - status, detail = OK, "" - elif announced == str(row.get("no_genuine_copy") or ""): - # Searched for and found only rebuilt: the profile covers the - # newest build that can be read, until the page moves on. - status, detail = OK, "no genuine copy of the announced release" - else: - status, detail = STALE, "a newer release is announced" - findings.append(Finding("profiles", name, status, local=declared, - remote=announced, detail=detail)) - continue - if row.get("skipped"): - # A skip profile_sync counts as a defect (no repository answers, - # no resolvable pin) is unknown. One that is the profile's nature - # (an upstream declared gone, a host no forge API serves, no - # source_ref) is never checkable and does not hold the exit code. - from profiling.reports import ProfileReport - - reason = str(row["skipped"]) - status = UNKNOWN if reason.startswith(ProfileReport.UNCHECKABLE) else SKIPPED - findings.append(Finding("profiles", name, status, detail=reason)) - continue - review = row.get("needs_review") or 0 - pin, head = str(row.get("pin") or ""), str(row.get("head") or "") - added = sorted({ - str(item.get("name")) - for item in row.get("new_files") or () - if isinstance(item, dict) and item.get("since_pin") - }) - hashes = len(row.get("new_hashes") or ()) - reasons = [f"{review} refs to review"] if review else [] - if added: - reasons.append(f"new file names since the pin: {', '.join(added)}") - if hashes: - reasons.append(f"{hashes} undeclared hashes added since the pin") - if reasons: - findings.append( - Finding( - "profiles", - name, - STALE, - local=pin[:8], - remote=head[:8], - detail=", ".join(reasons), - ) - ) - elif pin and head and pin != head: - moved += 1 - else: - clean += 1 - stale = sum(1 for f in findings if f.status == STALE) - findings.insert( - 0, - Finding( - "profiles", - "profile_sync", - STALE if stale else OK, - local=f"{clean} at tip, {moved} anchored past the tip", - remote=f"{stale} to review", - ), - ) - return findings - - -# --- reporting -------------------------------------------------------------- - - -def render(findings: list[Finding]) -> str: - lines = [] - width = max((len(f.subject) for f in findings), default=10) - width = min(width, 44) - for area in AREAS: - rows = [f for f in findings if f.area == area] - if not rows: - continue - lines.append(f"\n[{area}]") - # Columns are padded, never cut: the profile_sync row says in its - # local and remote values what to re-read, and lost the end of it. - local_width = min(max((len(f.local) for f in rows), default=0), 44) - remote_width = min(max((len(f.remote) for f in rows), default=0), 44) - # The arrow and the remote value, or as many blanks where a row has none. - remote_span = 4 + remote_width if remote_width else 0 - for f in rows: - cols = f" {f.status:7} {f.subject:{width}}" - if f.remote: - cols += f" {f.local:{local_width}} -> {f.remote:{remote_width}}" - elif f.local or (f.detail and (local_width or remote_span)): - # An arrow pointing at nothing read as a lost value. Empty - # local and remote values still take their columns, or the - # detail starts where the other rows show theirs. - cols += f" {f.local:{local_width}}" + " " * remote_span - if f.detail: - cols += f" {f.detail}" - lines.append(cols.rstrip()) - counts = {status: sum(1 for f in findings if f.status == status) for status in STATUSES} - summary = ", ".join(f"{n} {status.lower()}" for status, n in counts.items() if n) - lines.append(f"\nFRESHNESS: {summary}") - if counts[STALE]: - lines.append( - "refresh_stale.py runs the refresher behind every stale row " - "(--dry-run lists them first)" - ) - if counts[UNKNOWN]: - lines.append("an unknown row is an upstream that could not be read: not up to date") - return "\n".join(lines) - - -def main() -> int: +from core.cli import InputMissing, add_repo_inputs, require_directory +from core.paths import REPO_ROOT, TRUTH_DIR +from exporter.originals import DEFAULT_CACHE +from freshness.catalogs import check_catalogs +from freshness.ci import check_ci +from freshness.coreinfo import CORE_INFO_RECORD, check_coreinfo, core_info_blobs, record_core_info +from freshness.data import check_data +from freshness.findings import AREAS, SKIPPED, Finding +from freshness.native import check_native +from freshness.pinbuilds import check_pin_builds +from freshness.platforms import check_emulatorjs, check_platforms +from freshness.profiles import check_profiles, check_source_paths +from freshness.report import exit_code, render, unknown_areas_message +from freshness.romfolders import check_romfolders +from freshness.targets import check_targets +from model.profiles import load_emulator_profiles + + +def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(allow_abbrev=False, description=__doc__.split("\n\n")[0]) # Joined with ", " so argparse wraps between names: one comma-joined # token was cut inside "coreinfo". @@ -1842,6 +96,11 @@ def main() -> int: help="record the current .info of CORE (every core when none is named) " f"as reviewed in {CORE_INFO_RECORD.relative_to(REPO_ROOT)}, then exit", ) + return parser + + +def main() -> int: + parser = build_parser() args = parser.parse_args() if args.record_coreinfo is not None: @@ -1901,27 +160,6 @@ def main() -> int: return exit_code(findings) -def exit_code(findings: list[Finding]) -> int: - """Zero only when every upstream asked answered and nothing is stale. - - An unknown row is an upstream that could not be read: a run without - network gave 28 of them and exited 0, the answer of a fresh collection. - """ - return 1 if any(f.status in (STALE, ERROR, UNKNOWN) for f in findings) else 0 - - -def unknown_areas_message(unknown: list[str]) -> str: - """The refusal of --only, naming the areas it accepts.""" - import difflib - - hints = [ - f"{name} (did you mean {close[0]}?)" if close else name - for name in unknown - for close in [difflib.get_close_matches(name, AREAS, n=1)] - ] - return f"unknown area: {', '.join(hints)}. Areas: {', '.join(AREAS)}" - - if __name__ == "__main__": from core.cli import run_cli diff --git a/scripts/freshness/__init__.py b/scripts/freshness/__init__.py index e21f20b46..cbdc5e71c 100644 --- a/scripts/freshness/__init__.py +++ b/scripts/freshness/__init__.py @@ -1 +1 @@ -"""What has an upstream and whether ours is behind it.""" +"""Freshness checks: every transcribed layer confronted with what its upstream serves today.""" diff --git a/scripts/freshness/catalogs.py b/scripts/freshness/catalogs.py new file mode 100644 index 000000000..63b9d86da --- /dev/null +++ b/scripts/freshness/catalogs.py @@ -0,0 +1,287 @@ +"""Dump catalogs, game catalogs and romset recipes against what upstream serves.""" + +from __future__ import annotations + +import http.client +import json +import re +import urllib.request +from datetime import datetime, timezone +from pathlib import Path + +from core import upstream +from core.paths import REPO_ROOT +from scripts.scraper import game_dat_importer +from scripts.scraper.redump_dat_scraper import fetch_snapshot +from freshness.findings import OK, SKIPPED, STALE, UNKNOWN, Finding + + +NO_INTRO_MIRROR = game_dat_importer.NOINTRO_MIRROR +NO_INTRO_RELEASE = game_dat_importer.NOINTRO_RELEASE +NO_INTRO_ASSET = game_dat_importer.NOINTRO_ASSET +# The mirror rebuilds daily. A pack older than this is a mirror that stopped: +# hugo19941994's failed every day from 2026-07-08, and comparing our import +# date with its asset read OK for four months. +NO_INTRO_MAX_AGE_DAYS = 7 +TOSEC_DOWNLOADS = "https://www.tosecdev.org/downloads" +MAME_REPO = "https://github.com/mamedev/mame" +FBNEO_REPO = "https://github.com/libretro/FBNeo" + + +def _snapshot(path: Path) -> dict: + if not path.is_file(): + return {} + with path.open(encoding="utf-8") as fh: + return json.load(fh) + + +def check_catalogs(cache_dir: str, offline: bool) -> list[Finding]: + findings = [] + findings.append(_check_redump(offline)) + findings.append(_check_no_intro(cache_dir, offline)) + findings.append(_check_tosec(offline)) + findings.append(_check_mame(cache_dir, offline)) + findings.append(_check_fbneo(cache_dir, offline)) + findings.append(_check_nointro_games(cache_dir, offline)) + findings.append(_check_redump_games(offline)) + return findings + + +def _game_catalogs(source: str) -> list[dict]: + """The committed game catalogs of one source, games/catalogs//.""" + return [_snapshot(path) for path in sorted((REPO_ROOT / "games" / "catalogs" / source).glob("*.json"))] + + +def _no_intro_asset_date(cache_dir: str, offline: bool) -> str: + """The day the mirror last rebuilt its No-Intro pack, empty if unlisted.""" + repo = upstream.parse_repo(NO_INTRO_MIRROR) + payload = upstream.cached_api( + f"{repo.api_base}/repos/{repo.slug}/releases/tags/{NO_INTRO_RELEASE}", + cache_dir, + offline, + upstream.MOVING_TTL, + ) + for asset in (payload.get("assets") if isinstance(payload, dict) else None) or []: + if isinstance(asset, dict) and asset.get("name") == NO_INTRO_ASSET: + return str(asset.get("updated_at", ""))[:10] + return "" + + +def _today() -> str: + return datetime.now(timezone.utc).strftime("%Y-%m-%d") + + +def _no_intro_row(subject: str, local: str, updated: str) -> Finding: + """Our import against the mirror's pack, and the pack against today.""" + age = (datetime.fromisoformat(_today()) - datetime.fromisoformat(updated)).days + if age > NO_INTRO_MAX_AGE_DAYS: + return Finding( + "catalogs", subject, STALE, local=local, remote=updated, + detail=f"the mirror last rebuilt {NO_INTRO_ASSET} on {updated}, {age} days ago, " + f"though it rebuilds daily: {NO_INTRO_MIRROR}/actions", + ) + return Finding( + "catalogs", subject, STALE if updated > local else OK, + local=local, remote=updated, detail=f"{NO_INTRO_ASSET} rebuilt {updated}", + ) + + +def _check_nointro_games(cache_dir: str, offline: bool) -> Finding: + """games/catalogs/no-intro/ against the pack it was read from. The pack + holds every DAT: rebuilt after the catalogs were read, it may carry + games the games-on-card mode does not recognise.""" + subject = "no-intro games" + fetched = min((str(doc.get("fetched", "")) for doc in _game_catalogs("no-intro")), default="") + if offline: + return Finding("catalogs", subject, SKIPPED, local=fetched, detail="offline") + updated = _no_intro_asset_date(cache_dir, offline) + if not updated: + return Finding("catalogs", subject, UNKNOWN, local=fetched, detail="asset not listed") + return _no_intro_row(subject, fetched, updated) + + +def redump_datfile_version(code: str) -> str: + """The version redump.info serves for one datfile, read from the name it + gives the download: a HEAD request, nothing downloaded.""" + url = game_dat_importer.REDUMP_DATFILE_URL.format(code=code) + request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "retrobios/1.0"}) + disposition = upstream.open_retrying( + request, lambda response: response.headers.get("Content-Disposition", ""), timeout=60 + ) + named = game_dat_importer.DISPOSITION.search(disposition) + match = game_dat_importer.REDUMP_FILE.match(named["file"]) if named else None + if not match: + raise ValueError(f"{url} names no datfile") + return f"{match['date']} {match['time']}" + + +def _check_redump_games(offline: bool) -> Finding: + """games/catalogs/redump/ against the datfiles redump.info serves now. + A disc dumped since is not recognised by the games-on-card mode.""" + subject = "redump games" + local = {doc.get("system"): str(doc.get("version", "")) for doc in _game_catalogs("redump")} + newest = max(local.values(), default="") + if offline: + return Finding("catalogs", subject, SKIPPED, local=newest, detail="offline") + changed = [] + remote_newest = "" + for code, (_name, system, _floor) in sorted(game_dat_importer.REDUMP_DATS.items()): + try: + remote = redump_datfile_version(code) + except (OSError, http.client.HTTPException, upstream.UpstreamError, ValueError) as exc: + return Finding("catalogs", subject, UNKNOWN, local=newest, detail=str(exc)) + remote_newest = max(remote_newest, remote) + if local.get(system) != remote: + changed.append(system) + return Finding( + "catalogs", subject, STALE if changed else OK, local=newest, remote=remote_newest, + detail=(f"changed: {', '.join(changed)}" if changed else f"{len(local)} DATs"), + items=changed, + ) + + +def _check_redump(offline: bool) -> Finding: + local = _snapshot(REPO_ROOT / "provenance" / "redump.json") + dats = local.get("dats") or {} + stamp = ", ".join(sorted(set(dats.values()))) or "none" + if offline: + return Finding("catalogs", "redump", SKIPPED, local=stamp, detail="offline") + try: + remote_dats, _ = fetch_snapshot() + except (ConnectionError, ValueError) as exc: + return Finding("catalogs", "redump", UNKNOWN, local=stamp, detail=str(exc)) + remote_stamp = ", ".join(sorted(set(remote_dats.values()))) + changed = sorted( + name for name in set(dats) | set(remote_dats) if dats.get(name) != remote_dats.get(name) + ) + return Finding( + "catalogs", + "redump", + STALE if changed else OK, + local=stamp, + remote=remote_stamp, + detail=("changed: " + ", ".join(changed)) if changed else f"{len(dats)} DATs", + ) + + +def _check_no_intro(cache_dir: str, offline: bool) -> Finding: + local = _snapshot(REPO_ROOT / "provenance" / "no-intro.json") + imported = str(local.get("imported_at", "")) + if offline: + return Finding("catalogs", "no-intro", SKIPPED, local=imported, detail="offline") + updated = _no_intro_asset_date(cache_dir, offline) + if not updated: + return Finding("catalogs", "no-intro", UNKNOWN, local=imported, detail="asset not listed") + return _no_intro_row("no-intro", imported, updated) + + +def tosec_latest_pack(html: str) -> str | None: + """Date of the newest TOSEC release the downloads page lists.""" + dates = re.findall(r'/downloads/category/\d+-(\d{4}-\d{2}-\d{2})"', html) + return max(dates) if dates else None + + +def _check_tosec(offline: bool) -> Finding: + local = _snapshot(REPO_ROOT / "provenance" / "tosec.json") + imported = str(local.get("imported_at", "")) + if offline: + return Finding("catalogs", "tosec", SKIPPED, local=imported, detail="offline") + try: + html = upstream.http_text(TOSEC_DOWNLOADS) + except upstream.UpstreamError as exc: + return Finding("catalogs", "tosec", UNKNOWN, local=imported, detail=str(exc)) + latest = tosec_latest_pack(html or "") + if latest is None: + return Finding("catalogs", "tosec", UNKNOWN, local=imported, detail="no release listed") + return Finding( + "catalogs", + "tosec", + STALE if latest > imported else OK, + local=imported, + remote=latest, + detail=f"newest pack TOSEC-v{latest}", + ) + + +def mame_versions(recipes: dict) -> list[str]: + """MAME version tags a recipe snapshot has absorbed, oldest first.""" + tags = set() + for label in (recipes.get("dats") or {}): + match = re.search(r"\b(mame\d{4})\b", str(label)) + if match: + tags.add(match.group(1)) + return sorted(tags) + + +def _check_mame(cache_dir: str, offline: bool) -> Finding: + local = _snapshot(REPO_ROOT / "recipes" / "mame.json") + versions = mame_versions(local) + newest = versions[-1] if versions else "none" + if offline: + return Finding("catalogs", "mame recipes", SKIPPED, local=newest, detail="offline") + release = upstream.latest_release(upstream.parse_repo(MAME_REPO), cache_dir, offline) + if release is None: + return Finding("catalogs", "mame recipes", UNKNOWN, local=newest, detail="no release seen") + return Finding( + "catalogs", + "mame recipes", + OK if release.tag in versions else STALE, + local=newest, + remote=f"{release.tag} ({release.date})", + detail=f"{len(versions)} versions imported", + ) + + +def fbneo_blob_drift(snapshot: dict, listing: object) -> tuple[list[str], bool]: + """DAT files whose git blob differs from the one the snapshot was read + from. The second value says whether the snapshot records blobs at all: + one written before that field existed can only be compared by date. + """ + recorded = (snapshot.get("upstream") or {}).get("blobs") or {} + if not recorded: + return [], False + remote = { + item["name"]: item.get("sha", "") + for item in (listing if isinstance(listing, list) else []) + if isinstance(item, dict) + and item.get("type") == "file" + and str(item.get("name", "")).lower().endswith(".dat") + } + drifted = sorted( + name for name in set(recorded) | set(remote) if recorded.get(name) != remote.get(name) + ) + return drifted, True + + +def _check_fbneo(cache_dir: str, offline: bool) -> Finding: + local = _snapshot(REPO_ROOT / "recipes" / "fbneo.json") + imported = str(local.get("imported_at", "")) + if offline: + return Finding("catalogs", "fbneo recipes", SKIPPED, local=imported, detail="offline") + repo = upstream.parse_repo(FBNEO_REPO) + listing = upstream.cached_api( + f"{repo.api_base}/repos/{repo.slug}/contents/dats", + cache_dir, + offline, + upstream.MOVING_TTL, + ) + if not isinstance(listing, list): + return Finding("catalogs", "fbneo recipes", UNKNOWN, local=imported, detail="dats/ listing unavailable") + drifted, tracked = fbneo_blob_drift(local, listing) + if not tracked: + return Finding( + "catalogs", + "fbneo recipes", + STALE, + local=imported, + detail="snapshot records no upstream blobs: re-import with --fetch", + ) + shown = ", ".join(n.removeprefix("FinalBurn Neo (ClrMame Pro XML, ").removesuffix(" only).dat") for n in drifted[:4]) + return Finding( + "catalogs", + "fbneo recipes", + STALE if drifted else OK, + local=imported, + remote=f"{len(listing)} DATs listed", + detail=(f"{len(drifted)} DAT(s) changed upstream: {shown}" if drifted else "every DAT blob matches"), + ) diff --git a/scripts/freshness/ci.py b/scripts/freshness/ci.py new file mode 100644 index 000000000..99220400d --- /dev/null +++ b/scripts/freshness/ci.py @@ -0,0 +1,199 @@ +"""The CI toolchain pins, the site's npm pins and the installer pin against their latest release.""" + +from __future__ import annotations + +import json +import re + +from core import upstream +from core.paths import REPO_ROOT +from installer_build import pins as installer_build_pins +from freshness.findings import OK, SKIPPED, STALE, UNKNOWN, Finding + + +PYPI_URL = "https://pypi.org/pypi/{name}/json" +NPM_URL = "https://registry.npmjs.org/{name}/latest" +# The site's npm dependencies, pinned to exact versions and built by Deploy Site. +SITE_PACKAGE = REPO_ROOT / "website" / "package.json" + + +_PIN_RE = re.compile( + r'"?([A-Za-z0-9_.\-]+)(?:\[[^\]]*\])?((?:[<>=!~]=?[^,"\s]+)(?:,[<>=!~]=?[^,"\s]+)*)?"?' +) +_USES_RE = re.compile(r"uses:\s*([\w.\-]+/[\w.\-]+)@([0-9a-f]{40})\s*(?:#\s*(\S+))?") + + +def parse_pip_pins(text: str) -> dict[str, str]: + """Package -> specifier for every ``pip install`` line of a workflow.""" + pins: dict[str, str] = {} + for line in text.splitlines(): + stripped = line.strip() + if "pip install" not in stripped: + continue + args = stripped.split("pip install", 1)[1] + for raw in re.findall(r'"[^"]+"|\S+', args): + token = raw.strip('"') + if token.startswith("-") or not token: + continue + match = _PIN_RE.fullmatch(token) + if match: + pins.setdefault(match.group(1).lower(), match.group(2) or "") + return pins + + +def parse_action_pins(text: str) -> dict[str, tuple[str, str]]: + """Action -> (pinned sha, commented tag) for every ``uses:`` line.""" + return { + repo: (sha, tag or "") for repo, sha, tag in _USES_RE.findall(text) + } + + +def _version_tuple(version: str) -> tuple[int, ...]: + return tuple(int(p) for p in re.findall(r"\d+", version)) + + +_SPEC_CLAUSE = re.compile(r"([<>=!~]=?)\s*(.+)") +_SPEC_TESTS = { + "==": lambda target, bound: target == bound, + "!=": lambda target, bound: target != bound, + ">=": lambda target, bound: target >= bound, + ">": lambda target, bound: target > bound, + "<=": lambda target, bound: target <= bound, + "<": lambda target, bound: target < bound, +} + + +def specifier_allows(spec: str, version: str) -> bool: + """Whether a pip specifier admits a version. Pre-releases are compared + on their numeric parts, which is enough for the operators pip uses here.""" + target = _version_tuple(version) + for clause in filter(None, (c.strip() for c in spec.split(","))): + match = _SPEC_CLAUSE.fullmatch(clause) + test = _SPEC_TESTS.get(match.group(1)) if match else None + if match is None or test is None or not test(target, _version_tuple(match.group(2))): + return False + return True + + +def pypi_latest(name: str) -> str | None: + payload = upstream.http_json(PYPI_URL.format(name=name)) + if not isinstance(payload, dict): + return None + info = payload.get("info") or {} + return str(info.get("version") or "") or None + + +def parse_npm_pins(text: str) -> dict[str, str]: + """Package -> the version a package.json names, dependencies of both kinds.""" + data = json.loads(text) + pins: dict[str, str] = {} + for key in ("dependencies", "devDependencies"): + pins.update({str(k): str(v) for k, v in (data.get(key) or {}).items()}) + return pins + + +def npm_latest(name: str) -> str | None: + payload = upstream.http_json(NPM_URL.format(name=name)) + if not isinstance(payload, dict): + return None + return str(payload.get("version") or "") or None + + +def _npm_findings() -> list[Finding]: + """One row per site dependency: an exact pin is stale once npm's latest + release is newer, since nothing else asks npm.""" + findings = [] + for name, pinned in sorted(parse_npm_pins(SITE_PACKAGE.read_text(encoding="utf-8")).items()): + subject = f"npm:{name}" + if not re.fullmatch(r"\d+(\.\d+)*", pinned): + findings.append(Finding("ci", subject, UNKNOWN, local=pinned, detail="a range, not an exact pin")) + continue + try: + latest = npm_latest(name) + except upstream.UpstreamError as exc: + findings.append(Finding("ci", subject, UNKNOWN, local=pinned, detail=str(exc))) + continue + if latest is None: + findings.append(Finding("ci", subject, UNKNOWN, local=pinned, detail="not on npm")) + continue + newer = _version_tuple(latest) > _version_tuple(pinned) + findings.append( + Finding( + "ci", + subject, + STALE if newer else OK, + local=pinned, + remote=latest, + detail="a newer release is out" if newer else "", + ) + ) + return findings + + +def check_ci(cache_dir: str, offline: bool) -> list[Finding]: + findings = [_check_installer_pins()] + workflows = sorted((REPO_ROOT / ".github" / "workflows").glob("*.yml")) + pins: dict[str, str] = {} + actions: dict[str, tuple[str, str]] = {} + for path in workflows: + text = path.read_text(encoding="utf-8") + for name, spec in parse_pip_pins(text).items(): + pins.setdefault(name, spec) + actions.update(parse_action_pins(text)) + if offline: + findings.append(Finding("ci", "workflow and site pins", SKIPPED, detail="offline")) + return findings + findings.extend(_npm_findings()) + for name, spec in sorted(pins.items()): + try: + latest = pypi_latest(name) + except upstream.UpstreamError as exc: + findings.append(Finding("ci", f"pypi:{name}", UNKNOWN, local=spec, detail=str(exc))) + continue + if latest is None: + findings.append(Finding("ci", f"pypi:{name}", UNKNOWN, local=spec, detail="not on PyPI")) + continue + allowed = specifier_allows(spec, latest) + findings.append( + Finding( + "ci", + f"pypi:{name}", + OK if allowed else STALE, + local=spec or "unpinned", + remote=latest, + detail="latest admitted" if allowed else "latest release outside the pin", + ) + ) + for action, (sha, tag) in sorted(actions.items()): + repo = upstream.parse_repo(f"https://github.com/{action}") + release = upstream.latest_release(repo, cache_dir, offline) + if release is None: + findings.append(Finding("ci", f"action:{action}", UNKNOWN, local=f"{sha[:8]} {tag}", detail="no release seen")) + continue + latest_sha = upstream.tag_commit(repo, release.tag, cache_dir, offline) or "" + findings.append( + Finding( + "ci", + f"action:{action}", + OK if latest_sha == sha else STALE, + local=f"{sha[:8]} {tag}".strip(), + remote=f"{latest_sha[:8]} {release.tag}", + detail="" if latest_sha == sha else f"{release.tag} released {release.date}", + ) + ) + return findings + + +def _check_installer_pins() -> Finding: + """The bootstraps pin install.py by SHA-256, so a stale pin refuses every install.""" + stale = installer_build_pins.stale_pins(REPO_ROOT) + return Finding( + "ci", + "install.py pin", + STALE if stale else OK, + local=installer_build_pins.installer_sha256(REPO_ROOT)[:12], + detail=( + f"pin outdated in {', '.join(stale)}, {installer_build_pins.COMMAND} writes it" + if stale else "install.sh and install.ps1 match" + ), + ) diff --git a/scripts/freshness/coreinfo.py b/scripts/freshness/coreinfo.py new file mode 100644 index 000000000..3396abf6e --- /dev/null +++ b/scripts/freshness/coreinfo.py @@ -0,0 +1,166 @@ +"""libretro-core-info against the profiles and the .info blobs recorded as reviewed.""" + +from __future__ import annotations + +import json +from pathlib import Path + +from core import upstream +from core.artifacts import write_text_atomic +from core.cli import InputMissing, suggest_names +from core.paths import REPO_ROOT +from freshness.findings import OK, SKIPPED, STALE, UNKNOWN, Finding +from freshness.targets import profile_name_index + + +CORE_INFO_REPO = "https://github.com/libretro/libretro-core-info" +# The git blob of every .info as last reviewed: `--record-coreinfo` writes it. +CORE_INFO_RECORD = REPO_ROOT / "platforms" / "_core_info.json" + + +def core_info_blobs(cache_dir: str, offline: bool) -> dict[str, str] | None: + """Every core the libretro core-info repository describes, with the git + blob of its .info.""" + repo = upstream.parse_repo(CORE_INFO_REPO) + if repo is None: + return None + payload = upstream.cached_api( + f"{repo.api_base}/repos/{repo.slug}/contents?per_page=100", + cache_dir, + offline, + upstream.MOVING_TTL, + ) + if not isinstance(payload, list): + return None + blobs = {} + for entry in payload: + name = entry.get("name", "") if isinstance(entry, dict) else "" + if name.endswith("_libretro.info"): + blobs[name[: -len("_libretro.info")]] = str(entry.get("sha") or "") + return dict(sorted(blobs.items())) + + +def core_info_names(cache_dir: str, offline: bool) -> list[str] | None: + """Every core the libretro core-info repository describes.""" + blobs = core_info_blobs(cache_dir, offline) + return None if blobs is None else list(blobs) + + +def load_core_info_record(path: Path = CORE_INFO_RECORD) -> dict[str, str] | None: + if not path.is_file(): + return None + return dict((json.loads(path.read_text(encoding="utf-8")) or {}).get("blobs") or {}) + + +def record_core_info( + blobs: dict[str, str], names: list[str], path: Path = CORE_INFO_RECORD +) -> list[str]: + """Record the current blob of *names* (every .info when empty) as reviewed. + + Naming the cores keeps a change nobody read out of the record. + """ + unknown = sorted(set(names) - set(blobs)) + if unknown: + raise InputMissing( + f"no such .info in core-info: {', '.join(unknown)}. " + + suggest_names(unknown, list(blobs), "libretro-core-info") + ) + recorded = load_core_info_record(path) or {} + recorded.update({n: blobs[n] for n in (names or blobs)}) + payload = {"repository": CORE_INFO_REPO, "blobs": dict(sorted(recorded.items()))} + write_text_atomic(str(path), json.dumps(payload, indent=2) + "\n") + return sorted(names or blobs) + + +def coreinfo_drift( + blobs: dict[str, str], recorded: dict[str, str], profiles: dict[str, dict] +) -> list[str]: + """Profiled cores whose .info is not the one recorded as reviewed. + + The .info is no authority, but a new firmwareN_path in it is the + cheapest sign that a profile needs reading again. + """ + index = {key.casefold() for key in profile_name_index(profiles)} + return [n for n, sha in blobs.items() + if n.casefold() in index and recorded.get(n) != sha] + + +def coreinfo_gaps( + names: list[str], profiles: dict[str, dict] +) -> tuple[list[str], list[tuple[str, str]]]: + """Cores core-info knows that the profiles do not, and profiles that + call standalone a core libretro now builds. + + Matching folds case: the buildbot serves lower-case names while a few + .info files keep the project's own casing. + """ + index: dict[str, set[str]] = {} + for key, claimants in profile_name_index(profiles).items(): + index.setdefault(key.casefold(), set()).update(claimants) + unprofiled = [n for n in names if n.casefold() not in index] + # A name only standalone profiles claim: libretro now builds a core + # nothing in the collection describes as one. + standalone = [ + (n, sorted(index[n.casefold()])[0]) + for n in names + if n.casefold() in index + and all( + str(profiles[c].get("type", "")).strip() == "standalone" + for c in index[n.casefold()] + ) + ] + return unprofiled, standalone + + +def check_coreinfo( + profiles: dict[str, dict], cache_dir: str, offline: bool, + record_path: Path = CORE_INFO_RECORD, +) -> list[Finding]: + blobs = core_info_blobs(cache_dir, offline) + if blobs is None and offline: + # Offline with no cached listing, nothing was asked of the upstream. + return [Finding("coreinfo", "libretro-core-info", SKIPPED, detail="offline")] + if blobs is None: + return [Finding("coreinfo", "libretro-core-info", UNKNOWN, detail="listing unavailable")] + names = list(blobs) + unprofiled, standalone = coreinfo_gaps(names, profiles) + findings = [ + Finding( + "coreinfo", + "libretro-core-info", + STALE if unprofiled or standalone else OK, + local=f"{len(names) - len(unprofiled)} profiled", + remote=f"{len(names)} .info files", + ) + ] + findings.extend( + Finding("coreinfo", name, STALE, detail="no profile claims this core name") + for name in unprofiled + ) + findings.extend( + Finding( + "coreinfo", + name, + STALE, + local=f"{key}: type standalone", + detail="core-info describes a libretro build of it", + ) + for name, key in standalone + ) + recorded = load_core_info_record(record_path) + if recorded is None: + findings.append(Finding( + "coreinfo", "reviewed .info", UNKNOWN, + detail=f"no {record_path.name}: run python scripts/check_freshness.py --record-coreinfo", + )) + return findings + findings.extend( + Finding( + "coreinfo", name, STALE, + local=(recorded.get(name) or "not recorded")[:12], remote=blobs[name][:12], + detail=(".info changed since reviewed: read its firmware, then " + f"python scripts/check_freshness.py --record-coreinfo {name}"), + ) + for name in coreinfo_drift(blobs, recorded, profiles) + ) + return findings diff --git a/scripts/freshness/data.py b/scripts/freshness/data.py new file mode 100644 index 000000000..e70c92af8 --- /dev/null +++ b/scripts/freshness/data.py @@ -0,0 +1,54 @@ +"""The data directories and the buildbot system assets against their upstream.""" + +from __future__ import annotations + +import contextlib +import io + +from core.paths import DATA_DIRS_FILE, REPO_ROOT +from model.registry import load_data_dir_registry +from packs import datadirs +from freshness.findings import OK, SHOWN_NAMES, SKIPPED, STALE, UNKNOWN, Finding + + +def check_data(offline: bool) -> list[Finding]: + if offline: + return [Finding("data", "_data_dirs.yml", SKIPPED, detail="offline")] + registry = load_data_dir_registry(REPO_ROOT / "platforms", required=True) + sink = io.StringIO() + with contextlib.redirect_stdout(sink): + results = datadirs.refresh_all(registry, dry_run=True) + findings = [] + for key, result in sorted(results.items()): + if result is None: + findings.append(Finding("data", key, UNKNOWN, detail="remote unreachable")) + elif result: + findings.append(Finding("data", key, STALE, detail="upstream changed, refresh_data_dirs.py fetches it")) + else: + findings.append(Finding("data", key, OK)) + findings.append(_check_buildbot_system()) + return findings + + +def _check_buildbot_system() -> Finding: + """The buildbot's system directory against what _data_dirs.yml tracks. + + The registry entries are refreshed above. An asset published since, or + one the buildbot no longer serves, is only seen by reading its .index. + """ + from scraper import buildbot_system + + with contextlib.redirect_stdout(io.StringIO()): + report = buildbot_system.check( + str(REPO_ROOT / DATA_DIRS_FILE) + ) + if report.get("error"): + return Finding("data", "buildbot system", UNKNOWN, detail="index unreachable") + todo = buildbot_system.pending(report) + if not todo: + return Finding("data", "buildbot system", OK) + every = [f"{e['status'].lower()} {e['zip']}" for e in todo] + names = ", ".join(every[:SHOWN_NAMES]) + more = f", ... (--json lists all {len(todo)})" if len(todo) > SHOWN_NAMES else "" + return Finding("data", "buildbot system", STALE, local=f"{len(todo)} to track", + detail=f"{names}{more} (_data_dirs.yml)", items=every) diff --git a/scripts/freshness/findings.py b/scripts/freshness/findings.py new file mode 100644 index 000000000..dafb2e591 --- /dev/null +++ b/scripts/freshness/findings.py @@ -0,0 +1,28 @@ +"""The finding a freshness check reports, its statuses and the areas it covers.""" + +from __future__ import annotations + +from dataclasses import dataclass, field + + +SHOWN_ITEMS = 4 # items named in a diff summary before ", ..." +SHOWN_NAMES = 12 # core names named in an unresolved row before ", ..." +AREAS = ( + "platforms", "native", "targets", "romfolders", "coreinfo", "data", "catalogs", "ci", "profiles", +) +OK, STALE, UNKNOWN, ERROR, SKIPPED = "OK", "STALE", "UNKNOWN", "ERROR", "SKIPPED" +# Every status a finding may carry, in the order the summary counts them. +STATUSES = (STALE, UNKNOWN, ERROR, SKIPPED, OK) + + +@dataclass(frozen=True) +class Finding: + area: str + subject: str + status: str + local: str = "" + remote: str = "" + detail: str = "" + # Every name a shortened detail stands for: --json carries them all, so + # a script can act on the 50 cores a row names 12 of. + items: list[str] = field(default_factory=list) diff --git a/scripts/freshness/native.py b/scripts/freshness/native.py new file mode 100644 index 000000000..a842491f9 --- /dev/null +++ b/scripts/freshness/native.py @@ -0,0 +1,167 @@ +"""The native export's cached originals and published exports against the platform files.""" + +from __future__ import annotations + +import contextlib +import io +import sys +import tempfile +from collections.abc import Iterator +from pathlib import Path + +from exporter import discover_exporters +from exporter.native import StaleTruth, export_platform, load_inputs +from exporter.originals import SOURCES_INDEX, SourcesIndexUnreadable, load_sources, source_key, wanted_sources +from model.platforms import inheritance_chain +from model.registry import list_registered_platforms +from resolve.reconcile import build_native_model +from freshness.findings import ERROR, OK, STALE, Finding + + +def native_cache_state( + wanted: dict[str, str], + root: Path, + recorded: dict[str, str], + index: Path, + transcribed_at: float, +) -> str: + """Why a platform's cached originals cannot be patched, '' when they can. + + The export corrects the file our data was transcribed from. A cached + original is that file only if it came from the URL the platform file + names today and was fetched no earlier than the platform file was last + rewritten: a branch URL keeps its name while its content moves. + """ + for relative, url in sorted(wanted.items()): + path = root / relative + if not path.is_file(): + return f"{relative} not cached" + known = recorded.get(source_key(path, index)) + if known is None: + return f"{relative} cached from an unrecorded URL" + if known != url: + return f"{relative} cached from another revision" + if path.stat().st_mtime < transcribed_at: + return f"{relative} cached before the platform file was rewritten" + return "" + + +def _export_tree(root: Path, platform: str) -> dict[str, bytes]: + """A platform's published export: its directory and its report.""" + tree = { + path.relative_to(root).as_posix(): path.read_bytes() + for path in (root / platform).rglob("*") if path.is_file() + } + report = root / f"{platform}.json" + if report.is_file(): + tree[report.name] = report.read_bytes() + return tree + + +def published_export_state( + platform: str, + exporter_class: type, + truth_dir: Path, + platforms_dir: Path, + cache_dir: Path, + published: Path, +) -> str: + """Why the committed export is not what the export writes now, '' when it is. + + exports/ is committed and the site publishes it, but CI cannot rebuild + it: the originals it patches live in the local cache. A profile change + that moves a hash leaves the published file behind until someone runs + the export again, and this is what says so. + """ + scratch_root = Path("tmp") + scratch_root.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=scratch_root) as scratch: + with contextlib.redirect_stdout(io.StringIO()): + ok, messages = export_platform( + platform, exporter_class, truth_dir, Path(scratch), + str(platforms_dir), cache_dir, False, + ) + if not ok: + return f"the export fails: {messages[0] if messages else 'no message'}" + if _export_tree(Path(scratch), platform) != _export_tree(published, platform): + return f"{published.as_posix()}/{platform} is not what the export writes now" + return "" + + +def _transcribed_at(platforms_dir: Path, platform: str) -> float: + """Last rewrite of the platform file or of any file it inherits.""" + return max( + ((platforms_dir / f"{name}.yml").stat().st_mtime + for name in inheritance_chain(platform, platforms_dir)), + default=0.0, + ) + + +# How the truth model settles two cores' hashes: generate_truth reports it, +# and it says nothing about whether a cached original is current. +_MODEL_NOTES = ("WARNING: hash conflict",) + + +@contextlib.contextmanager +def _without_model_notes() -> Iterator[None]: + """Keep the model build's own notes out of the freshness report. + + Anything else written to stderr passes through. + """ + sink = io.StringIO() + try: + with contextlib.redirect_stderr(sink): + yield + finally: + for line in sink.getvalue().splitlines(keepends=True): + if not line.startswith(_MODEL_NOTES): + sys.stderr.write(line) + + +def check_native( + platforms_dir: Path, cache_dir: Path, truth_dir: Path, + published: Path = Path("exports"), +) -> list[Finding]: + exporters = discover_exporters() + index = cache_dir / SOURCES_INDEX + try: + recorded = load_sources(cache_dir) + except SourcesIndexUnreadable as exc: + return [Finding("native", index.name, ERROR, detail=str(exc))] + findings: list[Finding] = [] + for name in list_registered_platforms(str(platforms_dir)): + exporter_class = exporters.get(name) + if not exporter_class: + continue + with _without_model_notes(): + try: + truth, scraped = load_inputs(name, truth_dir, str(platforms_dir)) + except StaleTruth as exc: + findings.append(Finding("native", name, STALE, detail=str(exc))) + continue + systems, _ = build_native_model(truth or {}, scraped) + wanted = wanted_sources(exporter_class(), systems, scraped) + reason = native_cache_state( + wanted, cache_dir / name, recorded, index, _transcribed_at(platforms_dir, name) + ) + if reason: + reason += ( + f", python scripts/export_native.py --platform {name} --refresh-cache" + " fetches it, then the export is written again" + ) + else: + reason = published_export_state( + name, exporter_class, truth_dir, platforms_dir, cache_dir, published + ) + if reason: + reason += f", python scripts/export_native.py --platform {name} writes it again" + findings.append( + Finding( + "native", + name, + STALE if reason else OK, + local=f"{len(wanted)} file(s)", + detail=reason, + ) + ) + return sorted(findings, key=lambda f: f.subject) diff --git a/scripts/freshness/pinbuilds.py b/scripts/freshness/pinbuilds.py new file mode 100644 index 000000000..b97c3837f --- /dev/null +++ b/scripts/freshness/pinbuilds.py @@ -0,0 +1,127 @@ +"""Each profile's pin_build read again where its platform now stands.""" + +from __future__ import annotations + +import re +from pathlib import Path + +from core import upstream +from model.sourcerevision import scraped_revision +from freshness.findings import OK, SHOWN_NAMES, SKIPPED, STALE, UNKNOWN, Finding + + +def build_variable(lines: list[str], variable: str) -> str | None: + """The value the first assignment to ``variable`` gives in a build file. + + Read as a Buildroot .mk (`X_VERSION = sha`), a LibreELEC package.mk + (`PKG_VERSION="sha"`) or a RetroPie scriptmodule (`rp_module_repo="git + URL tag"`, `local version="20250829"`): quotes and a trailing comment go, + the rest is compared as written. + """ + assignment = re.compile( + rf"^\s*(?:local\s+|export\s+)?{re.escape(variable)}\s*[:?+]?=\s*(.*)$" + ) + for line in lines: + match = assignment.match(line) + if not match: + continue + value = match.group(1).strip() + if value[:1] in "\"'": + end = value.find(value[0], 1) + return value[1:end] if end > 0 else value[1:] + return value.split(" #", 1)[0].strip() + return None + + +def pin_build_revision(reference: dict, platforms_dir: Path) -> str: + """The revision of the platform repository its YAML was last scraped at, + '' when the platform is not registered or reads another repository.""" + repo = upstream.parse_repo(str(reference.get("repo") or "")) + if repo is None: + return "" + return scraped_revision(platforms_dir / f"{reference.get('platform', '')}.yml", repo.slug) + + +def check_pin_builds( + profiles: dict, platforms_dir: Path, cache_dir: str, offline: bool, +) -> list[Finding]: + """Each `pin_build:` read again where the platform now stands. + + A pin_frozen pin is held because one platform builds that revision, and + nothing read the build file again: Recalbox moving mame0278 to another + commit left the profile describing a build no platform ships. The file + is read at the revision the platform's own YAML was scraped at, or at + the repository's branch head for a platform this repository does not + scrape, and its variable compared with the value the profile recorded. + """ + findings: list[Finding] = [] + unreferenced = sorted( + name for name, profile in profiles.items() + if profile.get("pin_frozen") and not profile.get("pin_build") + ) + if unreferenced: + findings.append(Finding( + "profiles", "pin_frozen without pin_build", SKIPPED, + local=f"{len(unreferenced)} profiles", + detail="no platform build file names their revision: " + + ", ".join(unreferenced[:SHOWN_NAMES]) + + (", ..." if len(unreferenced) > SHOWN_NAMES else ""), + items=unreferenced, + )) + for name, profile in sorted(profiles.items()): + for reference in profile.get("pin_build") or []: + subject = f"{name} ({reference['platform']})" + recorded = str(reference["value"]) + revision = pin_build_revision(reference, platforms_dir) + if revision == str(reference["revision"]): + findings.append(Finding( + "profiles", subject, OK, local=recorded[:12], + detail=f"read where platforms/{reference['platform']}.yml is", + )) + continue + repo = upstream.parse_repo(str(reference["repo"])) + try: + at = revision or upstream.resolve_head(repo, cache_dir, offline) + lines = upstream.fetch_file(repo, at, reference["path"], cache_dir, offline) \ + if at else None + if at and lines is None: + # A file of a submodule is read at the commit the + # platform's tree pins: KNULLI builds Batocera's + # amiberry package through its batocera submodule. + modules = upstream.fetch_file(repo, at, ".gitmodules", cache_dir, offline) + declared = upstream.submodule_urls("\n".join(modules or ()), repo) + if any(reference["path"].startswith(f"{p}/") for p in declared): + linked = upstream.through_gitlink(repo, at, reference["path"], + cache_dir, offline) + if linked is not None: + lines = upstream.fetch_file(*linked, cache_dir, offline) + except upstream.NotCachedError: + findings.append(Finding("profiles", subject, SKIPPED, local=recorded[:12], + detail="offline, the build file is not cached")) + continue + except upstream.UpstreamError as exc: + findings.append(Finding("profiles", subject, UNKNOWN, local=recorded[:12], + detail=str(exc))) + continue + if not at: + findings.append(Finding("profiles", subject, UNKNOWN, local=recorded[:12], + detail=f"{repo.slug} answered no branch head")) + continue + current = None if lines is None else build_variable(lines, reference["variable"]) + if current == recorded: + findings.append(Finding( + "profiles", subject, OK, local=recorded[:12], remote=at[:12], + detail=f"{reference['path']} still builds it", + )) + continue + findings.append(Finding( + "profiles", subject, STALE, local=recorded[:12], + remote=(current or "gone")[:12], + detail=( + f"{reference['path']} is gone at {at[:12]}" if lines is None + else f"{reference['variable']} is no longer set there" if current is None + else f"{reference['platform']} now builds {current} " + f"({reference['path']} at {at[:12]}): the pin follows the build" + ), + )) + return findings diff --git a/scripts/freshness/platformdiff.py b/scripts/freshness/platformdiff.py new file mode 100644 index 000000000..6c1faabe2 --- /dev/null +++ b/scripts/freshness/platformdiff.py @@ -0,0 +1,172 @@ +"""What a fresh scrape changes in a platform or target file.""" + +from __future__ import annotations + +from dataclasses import dataclass, field + +from freshness.findings import SHOWN_ITEMS + + +@dataclass +class PlatformDiff: + """What a fresh scrape changes in a platform or target file.""" + + version: tuple[str, str] | None = None + systems_added: list[str] = field(default_factory=list) + systems_removed: list[str] = field(default_factory=list) + files_added: list[str] = field(default_factory=list) + files_removed: list[str] = field(default_factory=list) + files_changed: list[str] = field(default_factory=list) + cores_added: list[str] = field(default_factory=list) + cores_removed: list[str] = field(default_factory=list) + # Any other field the scrape writes: launchers, dual_mode_cores, a + # system's core, native_id or data_directories. + fields_changed: list[str] = field(default_factory=list) + + @property + def content_changed(self) -> bool: + return any( + ( + self.systems_added, + self.systems_removed, + self.files_added, + self.files_removed, + self.files_changed, + self.cores_added, + self.cores_removed, + self.fields_changed, + ) + ) + + @property + def changed(self) -> bool: + return self.content_changed or self.version is not None + + def summary(self) -> str: + parts: list[str] = [] + if self.version: + parts.append(f"version {self.version[0]} -> {self.version[1]}") + for label, items in ( + ("+systems", self.systems_added), + ("-systems", self.systems_removed), + ("+files", self.files_added), + ("-files", self.files_removed), + ("~files", self.files_changed), + ("+cores", self.cores_added), + ("-cores", self.cores_removed), + ("~fields", self.fields_changed), + ): + if items: + shown = ", ".join(items[:SHOWN_ITEMS]) + (", ..." if len(items) > SHOWN_ITEMS else "") + parts.append(f"{label} {len(items)} ({shown})") + return "; ".join(parts) if parts else "identical" + + +def _file_key(entry: dict) -> str: + return str(entry.get("destination") or entry.get("name") or "") + + +def _core_names(config: dict) -> set[str]: + cores = config.get("cores") + names = set(map(str, cores)) if isinstance(cores, list) else set() + standalone = config.get("standalone_cores") + if isinstance(standalone, list): + names.update(f"standalone:{c}" for c in standalone) + return names + + +def _keyed_files(files: list[dict]) -> dict[str, dict]: + """Each declaration under its own key. + + A platform declares one destination several times (an archive once per + inner ROM, MD5 alternatives): keyed by destination alone, the dict kept + the last and a change to the others read as identical. + """ + keyed: dict[str, dict] = {} + seen: dict[str, int] = {} + for f in files: + key = _file_key(f) + seen[key] = seen.get(key, 0) + 1 + keyed[key if seen[key] == 1 else f"{key}#{seen[key]}"] = f + return keyed + + +# Compared on their own above. `source` is the revision read: it moves with +# every upstream commit, and what that commit changes is diffed field by field. +_DIFFED_APART = frozenset({"version", "systems", "cores", "standalone_cores", "source"}) + + +def _without_refs(value: object) -> object: + """*value* without its `source_ref` lines. + + A launcher cites lines of the revision read, so they shift with any + upstream commit above them (es_features.cfg:11638 read as :11649 one + RetroBat commit later). The cited content is what is compared. + """ + if isinstance(value, dict): + return {k: _without_refs(v) for k, v in value.items() if k != "source_ref"} + if isinstance(value, list): + return [_without_refs(v) for v in value] + return value + + +def _changed_fields(old: dict, new: dict, skip: frozenset[str], prefix: str = "") -> list[str]: + return [ + f"{prefix}{key}" + for key in sorted(set(old) | set(new), key=str) + if key not in skip and _without_refs(old.get(key)) != _without_refs(new.get(key)) + ] + + +def diff_platform(old: dict, new: dict) -> PlatformDiff: + """Compare two platform files the way a reviewer reads the diff. + + Files are keyed by system and destination, so a hash or flag change on + an existing destination is a change, not a removal plus an addition. + """ + diff = PlatformDiff() + old_version, new_version = str(old.get("version", "")), str(new.get("version", "")) + if old_version != new_version: + diff.version = (old_version, new_version) + old_systems = old.get("systems") or {} + new_systems = new.get("systems") or {} + diff.systems_added = sorted(set(new_systems) - set(old_systems)) + diff.systems_removed = sorted(set(old_systems) - set(new_systems)) + for system in sorted(set(old_systems) & set(new_systems)): + old_files = _keyed_files((old_systems[system] or {}).get("files") or []) + new_files = _keyed_files((new_systems[system] or {}).get("files") or []) + diff.files_added.extend( + f"{system}/{k}" for k in sorted(set(new_files) - set(old_files)) + ) + diff.files_removed.extend( + f"{system}/{k}" for k in sorted(set(old_files) - set(new_files)) + ) + diff.files_changed.extend( + f"{system}/{k}" + for k in sorted(set(old_files) & set(new_files)) + if old_files[k] != new_files[k] + ) + diff.fields_changed.extend(_changed_fields( + old_systems[system] or {}, new_systems[system] or {}, + frozenset({"files"}), f"{system}/", + )) + diff.fields_changed = _changed_fields(old, new, _DIFFED_APART) + diff.fields_changed + old_cores, new_cores = _core_names(old), _core_names(new) + diff.cores_added = sorted(new_cores - old_cores) + diff.cores_removed = sorted(old_cores - new_cores) + return diff + + +def diff_targets(old: dict, new: dict) -> PlatformDiff: + """Compare two target files. The scrape stamp is not a change.""" + diff = PlatformDiff() + old_targets = old.get("targets") or {} + new_targets = new.get("targets") or {} + diff.systems_added = sorted(set(new_targets) - set(old_targets)) + diff.systems_removed = sorted(set(old_targets) - set(new_targets)) + for name in sorted(set(old_targets) & set(new_targets)): + before = set(map(str, (old_targets[name] or {}).get("cores") or [])) + after = set(map(str, (new_targets[name] or {}).get("cores") or [])) + diff.cores_added.extend(f"{name}/{c}" for c in sorted(after - before)) + diff.cores_removed.extend(f"{name}/{c}" for c in sorted(before - after)) + return diff diff --git a/scripts/freshness/platforms.py b/scripts/freshness/platforms.py new file mode 100644 index 000000000..3fe22cc5d --- /dev/null +++ b/scripts/freshness/platforms.py @@ -0,0 +1,114 @@ +"""Platform files rescraped and diffed, and the EmulatorJS release RomM installs.""" + +from __future__ import annotations + +import re +import subprocess +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +from core import upstream +from model.registry import list_registered_platforms, load_platform_registry +from model.sources import source_yaml_file +from freshness.findings import ERROR, OK, SKIPPED, STALE, UNKNOWN, Finding +from freshness.platformdiff import diff_platform +from freshness.rescrape import scrape_into_copy + + +def _scrapable_platforms(platforms_dir: Path) -> list[tuple[str, str, Path]]: + """(platform, scraper module, file) for every registered platform. + + A platform that only inherits another and declares no source of its own + (Lakka) has nothing to scrape: its scraper writes the parent's file. + """ + registry = load_platform_registry(platforms_dir, required=True) + rows = [] + for name in list_registered_platforms(str(platforms_dir)): + path = platforms_dir / f"{name}.yml" + if not path.is_file(): + continue + config = source_yaml_file(path) or {} + scraper = (registry.get(name) or {}).get("scraper") + if not scraper or (config.get("inherits") and not config.get("source")): + continue + rows.append((name, f"scripts.scraper.{scraper}_scraper", path)) + return rows + + +def rescrape_args(platforms_dir: Path, name: str) -> tuple[str, ...]: + """What a rescrape passes so the scraper reads upstream's moving head. + + A scraper that rereads the revision its platform file pins by default + (RetroBat) names the ref to move to in the registry's rescrape_args. + """ + registry = load_platform_registry(platforms_dir, required=True) + return tuple(str(a) for a in (registry.get(name) or {}).get("rescrape_args") or ()) + + +def check_platforms(platforms_dir: Path, workdir: Path, jobs: int) -> list[Finding]: + rows = _scrapable_platforms(platforms_dir) + findings: list[Finding] = [] + + def run(row: tuple[str, str, Path]) -> Finding: + name, module, path = row + try: + fresh, error = scrape_into_copy( + module, path, workdir, extra=rescrape_args(platforms_dir, name) + ) + except subprocess.TimeoutExpired: + return Finding("platforms", name, ERROR, detail="scraper timed out") + if error: + return Finding("platforms", name, ERROR, detail=error) + old = source_yaml_file(path) or {} + new = source_yaml_file(fresh) or {} + diff = diff_platform(old, new) + status = STALE if diff.changed else OK + return Finding( + "platforms", + name, + status, + local=str(old.get("version", "")), + remote=str(new.get("version", "")), + detail=diff.summary(), + ) + + with ThreadPoolExecutor(max_workers=jobs) as pool: + findings.extend(pool.map(run, rows)) + return sorted(findings, key=lambda f: f.subject) + + +_EJS_VERSION_RE = re.compile(r"^ARG EMULATORJS_VERSION=(\S+)", re.MULTILINE) +ROMM_DOCKERFILES = ("docker/Dockerfile", "Dockerfile") + + +def emulatorjs_pin(dockerfile: str) -> str | None: + """The EmulatorJS release a RomM image installs, from its Dockerfile.""" + match = _EJS_VERSION_RE.search(dockerfile) + return match.group(1) if match else None + + +def check_emulatorjs(platforms_dir: Path, offline: bool) -> Finding: + """emulatorjs.yml against the EmulatorJS release RomM's image installs. + + emulatorjs.yml is not a registered platform, so no scrape covers it: a + RomM moving to a newer EmulatorJS changed the cores its users run with + nothing to say so. + """ + subject = "romm emulatorjs" + local = str((source_yaml_file(platforms_dir / "emulatorjs.yml") or {}).get("version", "")) + if offline: + return Finding("platforms", subject, SKIPPED, local=local, detail="offline") + tag = str((source_yaml_file(platforms_dir / "romm.yml") or {}).get("version", "")) + for path in ROMM_DOCKERFILES: + try: + text = upstream.http_text( + f"https://raw.githubusercontent.com/rommapp/romm/{tag}/{path}") + except upstream.UpstreamError as exc: + return Finding("platforms", subject, UNKNOWN, local=local, detail=str(exc)) + pin = emulatorjs_pin(text or "") + if pin: + return Finding("platforms", subject, OK if pin == local else STALE, + local=local, remote=pin, + detail=f"RomM {tag} installs EmulatorJS {pin}") + return Finding("platforms", subject, UNKNOWN, local=local, + detail=f"no EMULATORJS_VERSION in RomM {tag}'s Dockerfile") diff --git a/scripts/freshness/profiles.py b/scripts/freshness/profiles.py new file mode 100644 index 000000000..373dc1a62 --- /dev/null +++ b/scripts/freshness/profiles.py @@ -0,0 +1,166 @@ +"""The recorded source trees and profile_sync's verdict on the emulator profiles.""" + +from __future__ import annotations + +import json +import subprocess +import sys + +from core.paths import REPO_ROOT +from freshness.findings import ERROR, OK, SKIPPED, STALE, UNKNOWN, Finding + + +def check_source_paths(profiles: dict) -> Finding: + """The site links a cited path only where source-paths.json records it + in the tree the profile pins. A recorded tree no profile pins any more, + or a pinned tree the record lacks, means a pin moved or a profile was + added and `sitesources.py --fetch` was not run after it. Every tree a run + tries is recorded, read or not, so a lacking one was never tried.""" + from sitegen import sources as sitegen_sources + + pinned = { + sitegen_sources.tree_key(repo, pin) + for profile in profiles.values() if sitegen_sources.cited_paths(profile) + for repo, pin in sitegen_sources.profile_trees(profile) + } | { + # The platform build files pin_build names, linked from a page too. + sitegen_sources.tree_key(repo, pin) + for profile in profiles.values() + for repo, pin, _path in sitegen_sources.build_files(profile) + } + try: + recorded = set(json.loads(sitegen_sources.SOURCE_PATHS.read_text(encoding="utf-8"))) + except (OSError, ValueError) as exc: + return Finding("profiles", "source-paths.json", ERROR, detail=str(exc)) + orphaned = sorted(recorded - pinned) + unrecorded = sorted(pinned - recorded) + problems = [f"{len(found)} {words}" for found, words in ( + (orphaned, "recorded trees no profile pins"), + (unrecorded, "pinned trees not recorded"), + ) if found] + return Finding( + "profiles", + "source-paths.json", + STALE if problems else OK, + local=f"{len(recorded)} trees", + detail=(", ".join(problems) + ": run python scripts/sitesources.py --fetch") if problems + else "every pinned tree is recorded, and only those", + ) + + +def check_profiles(run: bool, offline: bool) -> list[Finding]: + if not run: + return [ + Finding( + "profiles", + "profile_sync", + SKIPPED, + detail="pass --profiles, or run python scripts/profile_sync.py --all --triage", + ) + ] + cmd = [ + sys.executable, + str(REPO_ROOT / "scripts" / "profile_sync.py"), + "--all", + "--json", + "--check-version", + "--detect-new-files", + "--watch-hashes", + ] + if offline: + cmd.append("--offline") + proc = subprocess.run(cmd, cwd=REPO_ROOT, capture_output=True, text=True, check=False) + if proc.returncode not in (0, 1): + tail = proc.stderr.strip().splitlines()[-1:] + return [Finding("profiles", "profile_sync", ERROR, detail=tail[0] if tail else f"exit {proc.returncode}")] + try: + report = json.loads(proc.stdout) + except json.JSONDecodeError as exc: + return [Finding("profiles", "profile_sync", ERROR, detail=f"unreadable report: {exc}")] + return summarize_profile_sync(report) + + +def summarize_profile_sync(report: object) -> list[Finding]: + """One row per profile with something to look at, from profile_sync's JSON. + + The JSON carries the ref verdicts and the pin against the tip. A profile + whose refs need review is stale, one the forge could not serve is unknown, + and one whose upstream moved while every ref still anchors is reported as + such without being counted as stale. A cited file that gained a file name + since the pin, or a hash the profile does not declare, is stale too: the + upstream may load a file the profile does not document. + """ + if not isinstance(report, list): + return [Finding("profiles", "profile_sync", ERROR, detail="report is not a list")] + findings = [] + clean = moved = 0 + for row in report: + if not isinstance(row, dict): + continue + name = str(row.get("name") or "?") + if row.get("skipped") and row.get("page_version"): + # Off any forge, the release page is the feed: a version there + # beyond the declared one is a release the profile does not cover. + declared, announced = str(row.get("declared_version") or ""), str(row["page_version"]) + if announced == declared: + status, detail = OK, "" + elif announced == str(row.get("no_genuine_copy") or ""): + # Searched for and found only rebuilt: the profile covers the + # newest build that can be read, until the page moves on. + status, detail = OK, "no genuine copy of the announced release" + else: + status, detail = STALE, "a newer release is announced" + findings.append(Finding("profiles", name, status, local=declared, + remote=announced, detail=detail)) + continue + if row.get("skipped"): + # A skip profile_sync counts as a defect (no repository answers, + # no resolvable pin) is unknown. One that is the profile's nature + # (an upstream declared gone, a host no forge API serves, no + # source_ref) is never checkable and does not hold the exit code. + from profiling.reports import ProfileReport + + reason = str(row["skipped"]) + status = UNKNOWN if reason.startswith(ProfileReport.UNCHECKABLE) else SKIPPED + findings.append(Finding("profiles", name, status, detail=reason)) + continue + review = row.get("needs_review") or 0 + pin, head = str(row.get("pin") or ""), str(row.get("head") or "") + added = sorted({ + str(item.get("name")) + for item in row.get("new_files") or () + if isinstance(item, dict) and item.get("since_pin") + }) + hashes = len(row.get("new_hashes") or ()) + reasons = [f"{review} refs to review"] if review else [] + if added: + reasons.append(f"new file names since the pin: {', '.join(added)}") + if hashes: + reasons.append(f"{hashes} undeclared hashes added since the pin") + if reasons: + findings.append( + Finding( + "profiles", + name, + STALE, + local=pin[:8], + remote=head[:8], + detail=", ".join(reasons), + ) + ) + elif pin and head and pin != head: + moved += 1 + else: + clean += 1 + stale = sum(1 for f in findings if f.status == STALE) + findings.insert( + 0, + Finding( + "profiles", + "profile_sync", + STALE if stale else OK, + local=f"{clean} at tip, {moved} anchored past the tip", + remote=f"{stale} to review", + ), + ) + return findings diff --git a/scripts/freshness/report.py b/scripts/freshness/report.py new file mode 100644 index 000000000..ed65cd0bb --- /dev/null +++ b/scripts/freshness/report.py @@ -0,0 +1,66 @@ +"""The freshness report as text, its exit code and the refusal of an unknown area.""" + +from __future__ import annotations + +from freshness.findings import AREAS, ERROR, STALE, STATUSES, UNKNOWN, Finding + + +def render(findings: list[Finding]) -> str: + lines = [] + width = max((len(f.subject) for f in findings), default=10) + width = min(width, 44) + for area in AREAS: + rows = [f for f in findings if f.area == area] + if not rows: + continue + lines.append(f"\n[{area}]") + # Columns are padded, never cut: the profile_sync row says in its + # local and remote values what to re-read, and lost the end of it. + local_width = min(max((len(f.local) for f in rows), default=0), 44) + remote_width = min(max((len(f.remote) for f in rows), default=0), 44) + # The arrow and the remote value, or as many blanks where a row has none. + remote_span = 4 + remote_width if remote_width else 0 + for f in rows: + cols = f" {f.status:7} {f.subject:{width}}" + if f.remote: + cols += f" {f.local:{local_width}} -> {f.remote:{remote_width}}" + elif f.local or (f.detail and (local_width or remote_span)): + # An arrow pointing at nothing read as a lost value. Empty + # local and remote values still take their columns, or the + # detail starts where the other rows show theirs. + cols += f" {f.local:{local_width}}" + " " * remote_span + if f.detail: + cols += f" {f.detail}" + lines.append(cols.rstrip()) + counts = {status: sum(1 for f in findings if f.status == status) for status in STATUSES} + summary = ", ".join(f"{n} {status.lower()}" for status, n in counts.items() if n) + lines.append(f"\nFRESHNESS: {summary}") + if counts[STALE]: + lines.append( + "refresh_stale.py runs the refresher behind every stale row " + "(--dry-run lists them first)" + ) + if counts[UNKNOWN]: + lines.append("an unknown row is an upstream that could not be read: not up to date") + return "\n".join(lines) + + +def exit_code(findings: list[Finding]) -> int: + """Zero only when every upstream asked answered and nothing is stale. + + An unknown row is an upstream that could not be read: a run without + network gave 28 of them and exited 0, the answer of a fresh collection. + """ + return 1 if any(f.status in (STALE, ERROR, UNKNOWN) for f in findings) else 0 + + +def unknown_areas_message(unknown: list[str]) -> str: + """The refusal of --only, naming the areas it accepts.""" + import difflib + + hints = [ + f"{name} (did you mean {close[0]}?)" if close else name + for name in unknown + for close in [difflib.get_close_matches(name, AREAS, n=1)] + ] + return f"unknown area: {', '.join(hints)}. Areas: {', '.join(AREAS)}" diff --git a/scripts/freshness/rescrape.py b/scripts/freshness/rescrape.py new file mode 100644 index 000000000..97d2b8e4a --- /dev/null +++ b/scripts/freshness/rescrape.py @@ -0,0 +1,35 @@ +"""A scraper's own write path run on a throwaway copy of the committed file.""" + +from __future__ import annotations + +import shutil +import subprocess +import sys +from pathlib import Path + +from core.paths import REPO_ROOT + + +def scrape_into_copy( + module: str, source: Path, workdir: Path, timeout: int = 900, + extra: tuple[str, ...] = (), +) -> tuple[Path, str | None]: + """Run a scraper's own write path on a throwaway copy of *source*. + + The CLI merges into the file it writes, so the copy carries every field + the scraper preserves and the diff shows only what the scrape changes. + """ + target = workdir / source.name + shutil.copyfile(source, target) + proc = subprocess.run( + [sys.executable, "-m", module, "-o", str(target), *extra], + cwd=REPO_ROOT, + capture_output=True, + text=True, + timeout=timeout, + check=False, + ) + if proc.returncode != 0: + tail = (proc.stderr or proc.stdout).strip().splitlines()[-1:] + return target, tail[0] if tail else f"exit {proc.returncode}" + return target, None diff --git a/scripts/freshness/romfolders.py b/scripts/freshness/romfolders.py new file mode 100644 index 000000000..9beefe878 --- /dev/null +++ b/scripts/freshness/romfolders.py @@ -0,0 +1,117 @@ +"""The pins of platforms/romfolders/_sources/ against what they follow.""" + +from __future__ import annotations + +from pathlib import Path + +from core import upstream +from model.registry import load_platform_registry +from model.sources import source_yaml_file +from model.sourcerevision import scraped_revision +from freshness.findings import OK, SKIPPED, STALE, UNKNOWN, Finding + + +def romfolder_sources(platforms_dir: Path) -> dict[str, dict]: + """setup -> its platforms/romfolders/_sources/.yml.""" + out = {} + for path in sorted((platforms_dir / "romfolders" / "_sources").glob("*.yml")): + out[path.stem] = source_yaml_file(path) or {} + return out + + +def _os_source(doc: dict) -> dict: + """The source the setup is pinned on: `os`, else the first declared. + The others follow from it (an EmulationStation pinned by a package.mk).""" + sources = doc.get("sources") or {} + return sources.get("os") or next(iter(sources.values()), {}) + + +def platform_revision(setup: str, doc: dict, platforms_dir: Path) -> str: + """The revision the setup's own platform file was scraped at, when the + setup is a registered platform read from the same repository; '' else.""" + if setup not in load_platform_registry(str(platforms_dir)): + return "" + repo = upstream.parse_repo(str(_os_source(doc).get("repo") or "")) + if repo is None: + return "" + return scraped_revision(platforms_dir / f"{setup}.yml", repo.slug) + + +def romfolder_pin_drift(setup: str, doc: dict, platforms_dir: Path) -> str | None: + """Why the folders and the BIOS of one platform come from two revisions, + None when they do not or when only the forge can tell (a tag on one + side, a commit on the other).""" + revision = platform_revision(setup, doc, platforms_dir) + os_source = _os_source(doc) + tag, commit = os_source.get("tag"), str(os_source.get("commit") or "") + if not revision or revision in (tag, commit): + return None + if tag or len(revision) == len(commit): + return f"platforms/{setup}.yml was scraped at {revision[:12]}, the rom folders at {tag or commit[:12]}" + return None + + +def check_romfolders(platforms_dir: Path, cache_dir: str, offline: bool) -> list[Finding]: + """The pins of platforms/romfolders/_sources/ against what they follow. + + A setup that is a registered platform is read at the revision its + platform file was scraped at: the games-on-card mode otherwise installs + the BIOS of one release for the folders of another. Any other setup is + compared with its project's newest release, or with its branch head + when the project publishes none. A pin is moved by hand, then + `python -m scripts.scraper.romfolders --setup NAME` reads it again. + """ + findings: list[Finding] = [] + for setup, doc in romfolder_sources(platforms_dir).items(): + os_source = _os_source(doc) + pin = str(os_source.get("tag") or str(os_source.get("commit") or "")[:12]) + drift = romfolder_pin_drift(setup, doc, platforms_dir) + if drift: + findings.append(Finding("romfolders", setup, STALE, local=pin, detail=drift)) + continue + revision = platform_revision(setup, doc, platforms_dir) + repo = upstream.parse_repo(str(os_source.get("repo") or "")) + commit = str(os_source.get("commit") or "") + if revision and revision in (os_source.get("tag"), commit): + findings.append(Finding("romfolders", setup, OK, local=pin, + detail=f"read where platforms/{setup}.yml is")) + continue + if offline: + findings.append(Finding("romfolders", setup, SKIPPED, local=pin, detail="offline")) + continue + if repo is None or not commit: + findings.append(Finding("romfolders", setup, UNKNOWN, local=pin, detail="no forge to ask")) + continue + findings.append(_romfolder_upstream(setup, repo, os_source, revision, cache_dir)) + return findings + + +def _romfolder_upstream( + setup: str, repo: upstream.Repo, os_source: dict, revision: str, cache_dir: str, +) -> Finding: + commit, tag = str(os_source["commit"]), os_source.get("tag") + pin = str(tag or commit[:12]) + if revision: + # The platform names a tag and the setup a commit: the tag's commit decides. + tagged = upstream.resolve_tag_commit(repo, revision, cache_dir) + if tagged is None: + return Finding("romfolders", setup, UNKNOWN, local=pin, detail=f"tag {revision} not listed") + if tagged == commit: + return Finding("romfolders", setup, OK, local=pin, detail=f"commit of {revision}") + return Finding("romfolders", setup, STALE, local=pin, remote=revision, + detail=f"platforms/{setup}.yml was scraped at {revision} ({tagged[:12]})") + pinned_at = (upstream.commit_date(repo, commit, cache_dir) or "")[:10] + release = upstream.latest_release(repo, cache_dir) + if release is not None and release.date: + newer = release.tag != tag and release.date > pinned_at + return Finding("romfolders", setup, STALE if newer else OK, local=f"{pin} ({pinned_at})", + remote=f"{release.tag} ({release.date})", + detail="a release is newer than the pin" if newer else "newest release") + head = upstream.resolve_head(repo, cache_dir) + if head is None: + return Finding("romfolders", setup, UNKNOWN, local=pin, detail="branch head unavailable") + if head == commit: + return Finding("romfolders", setup, OK, local=pin, detail="branch head") + counts = upstream.ancestry(repo, commit, head, cache_dir) + behind = f"{counts[0]} commits behind the branch head" if counts else "the branch head moved" + return Finding("romfolders", setup, STALE, local=pin, remote=head[:12], detail=behind) diff --git a/scripts/freshness/targets.py b/scripts/freshness/targets.py new file mode 100644 index 000000000..3c099b9a8 --- /dev/null +++ b/scripts/freshness/targets.py @@ -0,0 +1,187 @@ +"""Hardware target files rescraped, and the core names no profile claims.""" + +from __future__ import annotations + +import subprocess +from collections.abc import Container +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime, timezone +from pathlib import Path + +from core.paths import REPO_ROOT +from model.profiles import upstream_profile_index +from model.sources import source_yaml_file +from model.targets import apply_target_overrides, platform_overrides, read_target_overrides +from scripts.scraper.targets import discover_target_scrapers +from freshness.findings import ERROR, OK, SHOWN_NAMES, SKIPPED, STALE, UNKNOWN, Finding +from freshness.platformdiff import diff_targets +from freshness.rescrape import scrape_into_copy + + +def profile_name_index(profiles: dict[str, dict]) -> dict[str, set[str]]: + """Upstream core name -> the profiles that claim it, as target filtering reads it.""" + return upstream_profile_index(profiles, include_aliases=True) + + +def unresolved_target_cores( + targets: dict, index: Container[str], overrides: dict +) -> dict[str, list[str]]: + """Core names a target ends up with that no profile claims. + + Read after the overrides, by the function the builder applies + (apply_target_overrides): _default then the target, add_cores + included. A name added by hand without a profile is the false skip + this check exists for, and a copy that read remove_cores alone never + saw it. + """ + unresolved: dict[str, list[str]] = {} + for name, entry in (targets.get("targets") or {}).items(): + cores = {str(c) for c in (entry or {}).get("cores") or []} + for core in sorted(apply_target_overrides(cores, overrides, name)): + if core not in index: + unresolved.setdefault(core, []).append(name) + return {core: sorted(names) for core, names in sorted(unresolved.items())} + + +def _target_scrapers() -> dict[str, str]: + """platform -> scraper module for every target scraper on disk.""" + return { + platform: cls.__module__ + for platform, cls in discover_target_scrapers().items() + } + + +def check_targets( + platforms_dir: Path, workdir: Path, profiles: dict[str, dict], jobs: int, + offline: bool, +) -> list[Finding]: + targets_dir = platforms_dir / "targets" + overrides = read_target_overrides(targets_dir) + index = profile_name_index(profiles) + scrapers = _target_scrapers() + findings: list[Finding] = [] + today = datetime.now(timezone.utc) + + def run(platform: str) -> list[Finding]: + path = targets_dir / f"{platform}.yml" + if not path.is_file(): + return [Finding("targets", platform, ERROR, detail="no target file")] + old = source_yaml_file(path) or {} + module = scrapers.get(platform) + targets = old.get("targets") or {} + if module is not None and offline: + # Scraped, so offline means not compared: SKIPPED, as every other + # section says it. Labelled static and OK, a list 400 days old + # read as current. + stamp = str(old.get("scraped_at", ""))[:10] + out = [Finding("targets", platform, SKIPPED, local=stamp, detail="offline")] + missing = unresolved_target_cores(old, index, platform_overrides(overrides, platform)) + out.extend(_unresolved_findings(platform, missing)) + return out + if module is None and targets and all( + (t or {}).get("cores", []) is None for t in targets.values() + ): + # Every core the platform declares runs on these targets: the list + # is the platform's own and has nothing of its own to age. Its + # names still need a profile each: RetroBat's winuae, jzintv or + # sudachi without one are BIOS its pack never carries. + out = [Finding("targets", platform, OK, local="static", + detail="every declared core")] + declared = _declared_cores(platform) + missing = unresolved_target_cores( + {"targets": {name: {"cores": declared} for name in targets}}, + index, platform_overrides(overrides, platform), + ) + out.extend(_unresolved_findings(platform, missing)) + return out + if module is None: + # No scraper: a hand-written file has no upstream to diff against, + # so only its age and its core names can be reported. + stamp = str(old.get("scraped_at", ""))[:10] + age = _age_days(stamp, today) + out = [ + Finding( + "targets", + platform, + OK if age is not None else UNKNOWN, + local=f"static {stamp}", + detail=f"{age} days old" if age is not None else "no scrape stamp", + ) + ] + missing = unresolved_target_cores(old, index, platform_overrides(overrides, platform)) + out.extend(_unresolved_findings(platform, missing)) + return out + try: + fresh, error = scrape_into_copy(module, path, workdir) + except subprocess.TimeoutExpired: + return [Finding("targets", platform, ERROR, detail="scraper timed out")] + if error: + return [Finding("targets", platform, ERROR, detail=error)] + new = source_yaml_file(fresh) or {} + diff = diff_targets(old, new) + out = [ + Finding( + "targets", + platform, + STALE if diff.content_changed else OK, + local=str(old.get("scraped_at", ""))[:10], + remote=str(new.get("scraped_at", ""))[:10], + detail=diff.summary(), + ) + ] + missing = unresolved_target_cores(new, index, platform_overrides(overrides, platform)) + out.extend(_unresolved_findings(platform, missing)) + return out + + names = sorted(p.stem for p in targets_dir.glob("*.yml") if not p.name.startswith("_")) + with ThreadPoolExecutor(max_workers=jobs) as pool: + for rows in pool.map(run, names): + findings.extend(rows) + return findings + + +def _declared_cores(platform: str) -> list[str]: + """The cores and standalone emulators a platform's own file names.""" + from model.platforms import load_platform_config + + try: + config = load_platform_config(platform, str(REPO_ROOT / "platforms")) + except (FileNotFoundError, OSError): + return [] + cores = config.get("cores") + names = [str(c) for c in cores] if isinstance(cores, list) else [] + return names + [str(c) for c in config.get("standalone_cores") or []] + + +def _unresolved_findings(platform: str, missing: dict[str, list[str]]) -> list[Finding]: + """One row per platform: the names its targets list that no profile claims. + + A buildbot name without a profile is a core the target filter cannot + see, and a platform's own emulator id without one is an emulator nobody has + profiled yet. Both are actionable, so both are listed, but as one row so + the backlog does not bury the day's changes. + """ + if not missing: + return [] + names = sorted(missing) + shown = ", ".join(names[:SHOWN_NAMES]) + ( + f", ... (--json lists all {len(names)})" if len(names) > SHOWN_NAMES else "" + ) + return [ + Finding( + "targets", + f"{platform} cores", + STALE, + local=f"{len(names)} without a profile", + detail=f"cores: alias or _overrides remove_cores needed for {shown}", + items=names, + ) + ] + + +def _age_days(stamp: str, now: datetime) -> int | None: + try: + then = datetime.strptime(stamp[:10], "%Y-%m-%d").replace(tzinfo=timezone.utc) + except ValueError: + return None + return (now - then).days diff --git a/tests/sources.py b/tests/sources.py index 07be4ac79..61538132b 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -105,6 +105,13 @@ COMMANDS = { "auto_fetch.py": ("acquire/fetch.py",), "find_embedded.py": ("acquire/embedded.py",), "find_pinned_revision.py": ("acquire/history.py",), + "check_freshness.py": ( + "freshness/findings.py", "freshness/platformdiff.py", "freshness/rescrape.py", + "freshness/platforms.py", "freshness/native.py", "freshness/targets.py", + "freshness/romfolders.py", "freshness/coreinfo.py", "freshness/data.py", + "freshness/catalogs.py", "freshness/ci.py", "freshness/pinbuilds.py", + "freshness/profiles.py", "freshness/report.py", + ), } diff --git a/tests/test_check_freshness.py b/tests/test_check_freshness.py index 43d615558..8076be520 100644 --- a/tests/test_check_freshness.py +++ b/tests/test_check_freshness.py @@ -12,14 +12,61 @@ import tests import json import os +import subprocess import sys import tempfile import unittest from unittest import mock from pathlib import Path -import check_freshness as cf +from core import upstream +from core.cli import InputMissing +from exporter.originals import SOURCES_INDEX +from freshness.catalogs import ( + NO_INTRO_MIRROR, + _check_no_intro, + _check_nointro_games, + _check_redump_games, + check_catalogs, + fbneo_blob_drift, + mame_versions, + tosec_latest_pack, +) +from freshness.ci import ( + _npm_findings, + check_ci, + parse_action_pins, + parse_npm_pins, + parse_pip_pins, + specifier_allows, +) +from freshness.coreinfo import ( + check_coreinfo, + coreinfo_drift, + coreinfo_gaps, + load_core_info_record, + record_core_info, +) +from freshness.data import _check_buildbot_system +from freshness.findings import AREAS, ERROR, OK, SKIPPED, STALE, UNKNOWN, Finding +from freshness.native import _transcribed_at, check_native, native_cache_state, published_export_state +from freshness.platformdiff import diff_platform, diff_targets +from freshness.platforms import _scrapable_platforms, emulatorjs_pin +from freshness.profiles import check_profiles, summarize_profile_sync +from freshness.report import exit_code, render, unknown_areas_message +from freshness.romfolders import check_romfolders, romfolder_pin_drift, romfolder_sources +from freshness.targets import ( + _declared_cores, + _target_scrapers, + _unresolved_findings, + check_targets, + profile_name_index, + unresolved_target_cores, +) from model.safeparse import yaml_load +from model.targets import platform_overrides +from scripts.scraper import game_dat_importer +from tests.sources import SCRIPTS REPO_ROOT = Path(__file__).resolve().parents[1] @@ -31,7 +78,7 @@ class NativeCacheTests(unittest.TestCase): self._tmp = tempfile.TemporaryDirectory() self.addCleanup(self._tmp.cleanup) self.cache = Path(self._tmp.name) - self.index = self.cache / cf.SOURCES_INDEX + self.index = self.cache / SOURCES_INDEX self.root = self.cache / "plat" self.root.mkdir() self.wanted = {"list.txt": "https://example.invalid/tag-2/list.txt"} @@ -39,9 +86,9 @@ class NativeCacheTests(unittest.TestCase): def test_an_unreadable_index_is_an_error_not_unrecorded(self): """Read as empty, it named "no URL recorded" for every original.""" self.index.write_text("{", encoding="utf-8") - findings = cf.check_native(REPO_ROOT / "platforms", self.cache, self.cache) + findings = check_native(REPO_ROOT / "platforms", self.cache, self.cache) self.assertEqual([(f.subject, f.status) for f in findings], - [(self.index.name, cf.ERROR)]) + [(self.index.name, ERROR)]) self.assertIn("--refresh-cache", findings[0].detail) def _cached(self, mtime: float) -> None: @@ -50,7 +97,7 @@ class NativeCacheTests(unittest.TestCase): os.utime(path, (mtime, mtime)) def _state(self, recorded: dict, transcribed_at: float) -> str: - return cf.native_cache_state( + return native_cache_state( self.wanted, self.root, recorded, self.index, transcribed_at ) @@ -87,8 +134,8 @@ class NativeCacheTests(unittest.TestCase): (platforms / "child.yml").write_text("inherits: parent\n", encoding="utf-8") os.utime(platforms / "parent.yml", (300.0, 300.0)) os.utime(platforms / "child.yml", (100.0, 100.0)) - self.assertEqual(cf._transcribed_at(platforms, "child"), 300.0) - self.assertEqual(cf._transcribed_at(platforms, "parent"), 300.0) + self.assertEqual(_transcribed_at(platforms, "child"), 300.0) + self.assertEqual(_transcribed_at(platforms, "parent"), 300.0) def test_a_repeated_inherits_key_is_refused(self): """refresh_stale read inherits: with yaml.safe_load, which kept the @@ -106,10 +153,10 @@ class NativeCacheTests(unittest.TestCase): refresh_stale._platform_parents({"child": {}}) def test_every_registered_platform_with_an_exporter_gets_a_row(self): - rows = cf.check_native(REPO_ROOT / "platforms", self.cache, self.cache / "truth") + rows = check_native(REPO_ROOT / "platforms", self.cache, self.cache / "truth") self.assertTrue(rows) self.assertEqual({r.area for r in rows}, {"native"}) - self.assertEqual({r.status for r in rows}, {cf.STALE}) + self.assertEqual({r.status for r in rows}, {STALE}) self.assertIn("batocera", {r.subject for r in rows}) def test_the_model_build_notes_stay_out_of_the_report(self): @@ -125,9 +172,9 @@ class NativeCacheTests(unittest.TestCase): return {}, None err = io.StringIO() - with mock.patch.object(cf, "build_native_model", side_effect=noisy), \ + with mock.patch("freshness.native.build_native_model", side_effect=noisy), \ contextlib.redirect_stderr(err): - cf.check_native(REPO_ROOT / "platforms", self.cache, self.cache / "truth") + check_native(REPO_ROOT / "platforms", self.cache, self.cache / "truth") self.assertNotIn("hash conflict", err.getvalue()) self.assertIn("other diagnostic", err.getvalue()) @@ -150,8 +197,8 @@ class PublishedExportTests(unittest.TestCase): (output / f"{platform}.json").write_text("{}", encoding="utf-8") return ok, [] if ok else ["the platform's own file is required"] - with mock.patch.object(cf, "export_platform", fake): - return cf.published_export_state( + with mock.patch("freshness.native.export_platform", fake): + return published_export_state( "plat", object, Path("t"), Path("p"), Path("c"), self.published ) @@ -178,12 +225,12 @@ class PlatformDiffTests(unittest.TestCase): } def test_identical_files_are_not_a_change(self): - diff = cf.diff_platform(self._platform(), self._platform()) + diff = diff_platform(self._platform(), self._platform()) self.assertFalse(diff.changed) self.assertEqual(diff.summary(), "identical") def test_version_alone_is_a_change_but_not_content(self): - diff = cf.diff_platform(self._platform("1"), self._platform("2")) + diff = diff_platform(self._platform("1"), self._platform("2")) self.assertTrue(diff.changed) self.assertFalse(diff.content_changed) self.assertEqual(diff.version, ("1", "2")) @@ -191,7 +238,7 @@ class PlatformDiffTests(unittest.TestCase): def test_hash_change_on_a_destination_is_a_change_not_a_swap(self): old = self._platform(files=[{"name": "x.bin", "destination": "x.bin", "md5": "1"}]) new = self._platform(files=[{"name": "x.bin", "destination": "x.bin", "md5": "2"}]) - diff = cf.diff_platform(old, new) + diff = diff_platform(old, new) self.assertEqual(diff.files_changed, ["sys/x.bin"]) self.assertEqual(diff.files_added, []) self.assertEqual(diff.files_removed, []) @@ -202,7 +249,7 @@ class PlatformDiffTests(unittest.TestCase): new["systems"]["other"] = {"files": []} new["systems"]["sys"]["files"].append({"name": "y.bin", "destination": "y.bin"}) new["standalone_cores"] = ["dolphin"] - diff = cf.diff_platform(old, new) + diff = diff_platform(old, new) self.assertEqual(diff.systems_added, ["other"]) self.assertEqual(diff.files_added, ["sys/y.bin"]) self.assertEqual(diff.cores_added, ["c", "standalone:dolphin"]) @@ -220,7 +267,7 @@ class PlatformDiffTests(unittest.TestCase): new = self._platform() new["launchers"] = [] new["systems"]["sys"].update(core="c2", native_id="psx") - diff = cf.diff_platform(old, new) + diff = diff_platform(old, new) self.assertTrue(diff.content_changed) self.assertEqual( diff.fields_changed, @@ -233,14 +280,14 @@ class PlatformDiffTests(unittest.TestCase): old["source"], new["source"] = "https://x/tar.gz/aaa", "https://x/tar.gz/bbb" old["launchers"] = [{"emulator": "e", "source_ref": "es_features.cfg:11638-11646"}] new["launchers"] = [{"emulator": "e", "source_ref": "es_features.cfg:11649-11657"}] - self.assertFalse(cf.diff_platform(old, new).changed) + self.assertFalse(diff_platform(old, new).changed) def test_target_stamp_is_not_a_change(self): old = {"scraped_at": "2026-01-01", "targets": {"t": {"cores": ["a"]}}} new = {"scraped_at": "2026-02-01", "targets": {"t": {"cores": ["a"]}}} - self.assertFalse(cf.diff_targets(old, new).content_changed) + self.assertFalse(diff_targets(old, new).content_changed) new["targets"]["t"]["cores"].append("b") - diff = cf.diff_targets(old, new) + diff = diff_targets(old, new) self.assertEqual(diff.cores_added, ["t/b"]) @@ -252,12 +299,12 @@ class CoreResolutionTests(unittest.TestCase): } def test_index_maps_key_and_every_core_alias(self): - index = cf.profile_name_index(self.PROFILES) + index = profile_name_index(self.PROFILES) self.assertEqual(index["mednafen_psx"], {"beetle_psx"}) self.assertEqual(index["beetle_psx"], {"beetle_psx"}) def test_unresolved_honours_remove_cores_per_target(self): - index = cf.profile_name_index(self.PROFILES) + index = profile_name_index(self.PROFILES) targets = { "targets": { "android": {"cores": ["mednafen_psx", "na", "ghost"]}, @@ -266,12 +313,12 @@ class CoreResolutionTests(unittest.TestCase): } overrides = {"android": {"remove_cores": ["na"]}} self.assertEqual( - cf.unresolved_target_cores(targets, index, overrides), + unresolved_target_cores(targets, index, overrides), {"ghost": ["android", "linux"]}, ) def test_a_default_override_drops_a_name_on_every_target(self): - index = cf.profile_name_index(self.PROFILES) + index = profile_name_index(self.PROFILES) targets = { "targets": { "x86_64": {"cores": ["A500", "ghost"]}, @@ -287,26 +334,26 @@ class CoreResolutionTests(unittest.TestCase): } } self.assertEqual( - cf.unresolved_target_cores(targets, index, cf.platform_overrides(overrides, "plat")), + unresolved_target_cores(targets, index, platform_overrides(overrides, "plat")), {"ghost": ["x86_64"]}, ) def test_an_added_core_is_read_as_the_builder_reads_it(self): """add_cores without a profile is the false skip this check exists for, and a target may add back what _default removes.""" - index = cf.profile_name_index(self.PROFILES) + index = profile_name_index(self.PROFILES) targets = {"targets": {"board": {"cores": ["mednafen_psx"]}}} overrides = { "_default": {"remove_cores": ["mednafen_psx"]}, "board": {"add_cores": ["mednafen_psx", "citron"]}, } self.assertEqual( - cf.unresolved_target_cores(targets, index, overrides), {"citron": ["board"]} + unresolved_target_cores(targets, index, overrides), {"citron": ["board"]} ) def test_coreinfo_gaps_fold_case_and_flag_standalone_profiles(self): names = ["FreeIntvTSOverlay", "eka2l1", "wqxemu", "mednafen_psx"] - unprofiled, standalone = cf.coreinfo_gaps(names, self.PROFILES) + unprofiled, standalone = coreinfo_gaps(names, self.PROFILES) self.assertEqual(unprofiled, ["wqxemu"]) self.assertEqual(standalone, [("eka2l1", "eka2l1")]) @@ -317,23 +364,23 @@ class CoreResolutionTests(unittest.TestCase): recorded = {"mednafen_psx": "old", "eka2l1": "same"} with tempfile.TemporaryDirectory() as tmp: record = Path(tmp) / "_core_info.json" - record.write_text(cf.json.dumps({"blobs": recorded})) - with mock.patch.object(cf, "core_info_blobs", return_value=blobs): - rows = cf.check_coreinfo(self.PROFILES, "", True, record) - stale = {r.subject: r for r in rows if r.status == cf.STALE} + record.write_text(json.dumps({"blobs": recorded})) + with mock.patch("freshness.coreinfo.core_info_blobs", return_value=blobs): + rows = check_coreinfo(self.PROFILES, "", True, record) + stale = {r.subject: r for r in rows if r.status == STALE} self.assertIn("mednafen_psx", stale) self.assertIn("--record-coreinfo mednafen_psx", stale["mednafen_psx"].detail) self.assertNotIn(".info changed", stale["eka2l1"].detail) - self.assertEqual(cf.coreinfo_drift(blobs, recorded, self.PROFILES), ["mednafen_psx"]) + self.assertEqual(coreinfo_drift(blobs, recorded, self.PROFILES), ["mednafen_psx"]) def test_recording_a_core_leaves_the_others_unread(self): with tempfile.TemporaryDirectory() as tmp: record = Path(tmp) / "_core_info.json" - record.write_text(cf.json.dumps({"blobs": {"a": "1", "b": "1"}})) - cf.record_core_info({"a": "2", "b": "2"}, ["a"], record) - self.assertEqual(cf.load_core_info_record(record), {"a": "2", "b": "1"}) - with self.assertRaises(cf.InputMissing) as raised: - cf.record_core_info({"a": "2", "ghosts": "1"}, ["ghost"], record) + record.write_text(json.dumps({"blobs": {"a": "1", "b": "1"}})) + record_core_info({"a": "2", "b": "2"}, ["a"], record) + self.assertEqual(load_core_info_record(record), {"a": "2", "b": "1"}) + with self.assertRaises(InputMissing) as raised: + record_core_info({"a": "2", "ghosts": "1"}, ["ghost"], record) self.assertIn("Close matches: ghosts.", str(raised.exception)) def test_record_errors_are_one_line(self): @@ -353,14 +400,14 @@ class CoreResolutionTests(unittest.TestCase): def test_offline_without_a_cached_listing_is_skipped(self): """Offline, the row read UNKNOWN and failed the run as an upstream that could not be read, though nothing was asked of it.""" - with mock.patch.object(cf, "core_info_blobs", return_value=None): - (row,) = cf.check_coreinfo(self.PROFILES, "", True) - self.assertEqual((row.status, row.detail), (cf.SKIPPED, "offline")) - (row,) = cf.check_coreinfo(self.PROFILES, "", False) - self.assertEqual(row.status, cf.UNKNOWN) + with mock.patch("freshness.coreinfo.core_info_blobs", return_value=None): + (row,) = check_coreinfo(self.PROFILES, "", True) + self.assertEqual((row.status, row.detail), (SKIPPED, "offline")) + (row,) = check_coreinfo(self.PROFILES, "", False) + self.assertEqual(row.status, UNKNOWN) def test_the_committed_record_holds_git_blobs(self): - recorded = cf.load_core_info_record() + recorded = load_core_info_record() self.assertIsNotNone(recorded) self.assertTrue(all(len(sha) == 40 for sha in recorded.values())) @@ -373,24 +420,24 @@ class PinParsingTests(unittest.TestCase): """ def test_pip_pins_keep_the_specifier(self): - pins = cf.parse_pip_pins(self.WORKFLOW) + pins = parse_pip_pins(self.WORKFLOW) self.assertEqual(pins["pyyaml"], "") self.assertEqual(pins["jsonschema"], "==4.23.0") self.assertEqual(pins["mkdocs-material"], ">=9.7.5,<10") self.assertEqual(pins["pymdown-extensions"], ">=10.14") def test_action_pins_carry_sha_and_optional_tag(self): - pins = cf.parse_action_pins(self.WORKFLOW) + pins = parse_action_pins(self.WORKFLOW) self.assertEqual(pins["actions/checkout"], ("3d3c42e5aac5ba805825da76410c181273ba90b1", "v7")) self.assertEqual(pins["actions/deploy-pages"][1], "") def test_specifier_admits_or_refuses_the_latest(self): - self.assertTrue(cf.specifier_allows("", "9.9")) - self.assertTrue(cf.specifier_allows(">=9.7.5,<10", "9.7.7")) - self.assertFalse(cf.specifier_allows(">=9.7.5,<10", "10.0.0")) - self.assertFalse(cf.specifier_allows("==4.23.0", "4.26.0")) - self.assertTrue(cf.specifier_allows("==4.23.0", "4.23.0")) - self.assertTrue(cf.specifier_allows(">=10.14", "12.0.1")) + self.assertTrue(specifier_allows("", "9.9")) + self.assertTrue(specifier_allows(">=9.7.5,<10", "9.7.7")) + self.assertFalse(specifier_allows(">=9.7.5,<10", "10.0.0")) + self.assertFalse(specifier_allows("==4.23.0", "4.26.0")) + self.assertTrue(specifier_allows("==4.23.0", "4.23.0")) + self.assertTrue(specifier_allows(">=10.14", "12.0.1")) class SiteNpmPins(unittest.TestCase): @@ -399,7 +446,7 @@ class SiteNpmPins(unittest.TestCase): pins: astro 7.4.2 stayed behind 7.4.7 with no STALE row.""" def test_both_dependency_kinds_are_read(self): - pins = cf.parse_npm_pins( + pins = parse_npm_pins( '{"dependencies": {"astro": "7.4.2"}, "devDependencies": {"x": "^1.0.0"}}' ) self.assertEqual(pins, {"astro": "7.4.2", "x": "^1.0.0"}) @@ -414,19 +461,19 @@ class SiteNpmPins(unittest.TestCase): def answer(url): name = url.split("registry.npmjs.org/", 1)[1].rsplit("/latest", 1)[0] return {"version": latest[name]} - with mock.patch.object(cf, "SITE_PACKAGE", package), \ - mock.patch.object(cf.upstream, "http_json", side_effect=answer): - rows = {f.subject: f for f in cf._npm_findings()} - self.assertEqual(rows["npm:astro"].status, cf.STALE) + with mock.patch("freshness.ci.SITE_PACKAGE", package), \ + mock.patch.object(upstream, "http_json", side_effect=answer): + rows = {f.subject: f for f in _npm_findings()} + self.assertEqual(rows["npm:astro"].status, STALE) self.assertEqual(rows["npm:astro"].remote, "7.4.7") - self.assertEqual(rows["npm:@astrojs/starlight"].status, cf.OK) - self.assertEqual(rows["npm:y"].status, cf.UNKNOWN) + self.assertEqual(rows["npm:@astrojs/starlight"].status, OK) + self.assertEqual(rows["npm:y"].status, UNKNOWN) def test_the_ci_area_reads_the_site_pins(self): - with mock.patch.object(cf, "_npm_findings", return_value=[]) as npm, \ - mock.patch.object(cf, "parse_pip_pins", return_value={}), \ - mock.patch.object(cf, "parse_action_pins", return_value={}): - cf.check_ci("unused", offline=False) + with mock.patch("freshness.ci._npm_findings", return_value=[]) as npm, \ + mock.patch("freshness.ci.parse_pip_pins", return_value={}), \ + mock.patch("freshness.ci.parse_action_pins", return_value={}): + check_ci("unused", offline=False) npm.assert_called_once() @@ -449,32 +496,32 @@ class RomFolderPins(unittest.TestCase): with tempfile.TemporaryDirectory() as tmp: root = self._tree(tmp, "https://raw.githubusercontent.com/o/r/v2/list.txt", " tag: v1\n commit: " + "a" * 40 + "\n") - rows = {f.subject: f for f in cf.check_romfolders(root, "", True)} - self.assertEqual(rows["plat"].status, cf.STALE) + rows = {f.subject: f for f in check_romfolders(root, "", True)} + self.assertEqual(rows["plat"].status, STALE) self.assertIn("scraped at v2, the rom folders at v1", rows["plat"].detail) - self.assertEqual(rows["other"].status, cf.SKIPPED) + self.assertEqual(rows["other"].status, SKIPPED) def test_the_same_revision_is_fresh(self): with tempfile.TemporaryDirectory() as tmp: root = self._tree(tmp, "https://github.com/o/r/tree/" + "a" * 40, " commit: " + "a" * 40 + "\n") - rows = {f.subject: f for f in cf.check_romfolders(root, "", True)} - self.assertEqual(rows["plat"].status, cf.OK) + rows = {f.subject: f for f in check_romfolders(root, "", True)} + self.assertEqual(rows["plat"].status, OK) def test_a_newer_release_makes_another_setup_stale(self): - release = cf.upstream.Release("v9", "2026-11-01", False) + release = upstream.Release("v9", "2026-11-01", False) with tempfile.TemporaryDirectory() as tmp: root = self._tree(tmp, "https://github.com/o/r/tree/" + "a" * 40, " commit: " + "a" * 40 + "\n") - with mock.patch.object(cf.upstream, "commit_date", return_value="2026-10-01T00:00:00"), \ - mock.patch.object(cf.upstream, "latest_release", return_value=release): - rows = {f.subject: f for f in cf.check_romfolders(root, "", False)} - self.assertEqual((rows["other"].status, rows["other"].remote), (cf.STALE, "v9 (2026-11-01)")) + with mock.patch.object(upstream, "commit_date", return_value="2026-10-01T00:00:00"), \ + mock.patch.object(upstream, "latest_release", return_value=release): + rows = {f.subject: f for f in check_romfolders(root, "", False)} + self.assertEqual((rows["other"].status, rows["other"].remote), (STALE, "v9 (2026-11-01)")) def test_the_committed_setups_agree_with_their_platform_files(self): platforms = REPO_ROOT / "platforms" - drift = [d for setup, doc in cf.romfolder_sources(platforms).items() - if (d := cf.romfolder_pin_drift(setup, doc, platforms))] + drift = [d for setup, doc in romfolder_sources(platforms).items() + if (d := romfolder_pin_drift(setup, doc, platforms))] self.assertEqual(drift, []) @@ -482,39 +529,39 @@ class CatalogParsingTests(unittest.TestCase): def test_game_catalogs_are_watched(self): """The 38 game catalogs the games-on-card mode identifies discs by had no row: only the BIOS snapshots of provenance/ were compared.""" - versions = {code: "2026-01-01 00-00-00" for code in cf.game_dat_importer.REDUMP_DATS} + versions = {code: "2026-01-01 00-00-00" for code in game_dat_importer.REDUMP_DATS} versions["PSX"] = "2099-01-01 00-00-00" local = [{"system": system, "version": "2026-01-01 00-00-00"} - for _n, system, _f in cf.game_dat_importer.REDUMP_DATS.values()] - with mock.patch.object(cf, "_game_catalogs", return_value=local), \ - mock.patch.object(cf, "redump_datfile_version", side_effect=versions.get): - row = cf._check_redump_games(False) - self.assertEqual((row.status, row.items), (cf.STALE, ["sony-playstation"])) - self.assertEqual(cf._check_redump_games(True).status, cf.SKIPPED) - with mock.patch.object(cf, "_game_catalogs", return_value=[{"fetched": "2026-11-03"}]), \ - mock.patch.object(cf, "_today", return_value="2026-11-06"): - for rebuilt, status in (("2026-11-02", cf.OK), ("2026-11-04", cf.STALE)): - with mock.patch.object(cf, "_no_intro_asset_date", return_value=rebuilt): - self.assertEqual(cf._check_nointro_games("", False).status, status) + for _n, system, _f in game_dat_importer.REDUMP_DATS.values()] + with mock.patch("freshness.catalogs._game_catalogs", return_value=local), \ + mock.patch("freshness.catalogs.redump_datfile_version", side_effect=versions.get): + row = _check_redump_games(False) + self.assertEqual((row.status, row.items), (STALE, ["sony-playstation"])) + self.assertEqual(_check_redump_games(True).status, SKIPPED) + with mock.patch("freshness.catalogs._game_catalogs", return_value=[{"fetched": "2026-11-03"}]), \ + mock.patch("freshness.catalogs._today", return_value="2026-11-06"): + for rebuilt, status in (("2026-11-02", OK), ("2026-11-04", STALE)): + with mock.patch("freshness.catalogs._no_intro_asset_date", return_value=rebuilt): + self.assertEqual(_check_nointro_games("", False).status, status) def test_a_mirror_that_stopped_rebuilding_is_stale(self): """The mirror failed every daily rebuild from 2026-07-08, and both No-Intro rows read OK: an import newer than a dead pack is no sign of a fresh catalog.""" - with mock.patch.object(cf, "_today", return_value="2026-11-06"), \ - mock.patch.object(cf, "_no_intro_asset_date", return_value="2026-07-08"), \ - mock.patch.object(cf, "_game_catalogs", return_value=[{"fetched": "2026-11-03"}]), \ - mock.patch.object(cf, "_snapshot", return_value={"imported_at": "2026-08-08"}): - for row in (cf._check_nointro_games("", False), cf._check_no_intro("", False)): - self.assertEqual(row.status, cf.STALE) + with mock.patch("freshness.catalogs._today", return_value="2026-11-06"), \ + mock.patch("freshness.catalogs._no_intro_asset_date", return_value="2026-07-08"), \ + mock.patch("freshness.catalogs._game_catalogs", return_value=[{"fetched": "2026-11-03"}]), \ + mock.patch("freshness.catalogs._snapshot", return_value={"imported_at": "2026-08-08"}): + for row in (_check_nointro_games("", False), _check_no_intro("", False)): + self.assertEqual(row.status, STALE) self.assertIn("2026-07-08, 121 days ago", row.detail) def test_the_freshness_check_reads_the_importer_mirror(self): - self.assertEqual(cf.NO_INTRO_MIRROR, cf.game_dat_importer.NOINTRO_MIRROR) - self.assertIn(cf.NO_INTRO_MIRROR.removeprefix("https://github.com/"), - cf.game_dat_importer.NOINTRO_RELEASE_API) + self.assertEqual(NO_INTRO_MIRROR, game_dat_importer.NOINTRO_MIRROR) + self.assertIn(NO_INTRO_MIRROR.removeprefix("https://github.com/"), + game_dat_importer.NOINTRO_RELEASE_API) self.assertIn("no-intro games", - [f.subject for f in cf.check_catalogs("", True)]) + [f.subject for f in check_catalogs("", True)]) def test_tosec_newest_release_from_category_links(self): html = ( @@ -522,8 +569,8 @@ class CatalogParsingTests(unittest.TestCase): 'y' 'z' ) - self.assertEqual(cf.tosec_latest_pack(html), "2025-03-13") - self.assertIsNone(cf.tosec_latest_pack("")) + self.assertEqual(tosec_latest_pack(html), "2025-03-13") + self.assertIsNone(tosec_latest_pack("")) def test_fbneo_drift_compares_blob_shas_and_reports_untracked(self): listing = [ @@ -532,14 +579,14 @@ class CatalogParsingTests(unittest.TestCase): {"type": "dir", "name": "old"}, ] snapshot = {"upstream": {"blobs": {"A.dat": "1", "B.dat": "9"}}} - self.assertEqual(cf.fbneo_blob_drift(snapshot, listing), (["B.dat"], True)) - self.assertEqual(cf.fbneo_blob_drift({"upstream": {}}, listing), ([], False)) + self.assertEqual(fbneo_blob_drift(snapshot, listing), (["B.dat"], True)) + self.assertEqual(fbneo_blob_drift({"upstream": {}}, listing), ([], False)) snapshot = {"upstream": {"blobs": {"A.dat": "1", "B.dat": "2", "C.dat": "3"}}} - self.assertEqual(cf.fbneo_blob_drift(snapshot, listing), (["C.dat"], True)) + self.assertEqual(fbneo_blob_drift(snapshot, listing), (["C.dat"], True)) def test_mame_versions_read_from_dat_labels(self): recipes = {"dats": {"MAME mame0250": "0.250", "MAME mame0289": "0.289", "FinalBurn Neo": "x"}} - self.assertEqual(cf.mame_versions(recipes), ["mame0250", "mame0289"]) + self.assertEqual(mame_versions(recipes), ["mame0250", "mame0289"]) class ProfileSummaryTests(unittest.TestCase): @@ -551,14 +598,14 @@ class ProfileSummaryTests(unittest.TestCase): {"name": "d", "skipped": "no declared repository answers"}, {"name": "e", "skipped": "upstream gone (declared): archived 2019"}, ] - findings = cf.summarize_profile_sync(report) + findings = summarize_profile_sync(report) by_subject = {f.subject: f for f in findings} - self.assertEqual(by_subject["profile_sync"].status, cf.STALE) + self.assertEqual(by_subject["profile_sync"].status, STALE) self.assertEqual(by_subject["profile_sync"].local, "1 at tip, 1 anchored past the tip") - self.assertEqual(by_subject["c"].status, cf.STALE) - self.assertEqual(by_subject["d"].status, cf.UNKNOWN) + self.assertEqual(by_subject["c"].status, STALE) + self.assertEqual(by_subject["d"].status, UNKNOWN) # Never checkable by nature: it does not hold the exit code. - self.assertEqual(by_subject["e"].status, cf.SKIPPED) + self.assertEqual(by_subject["e"].status, SKIPPED) self.assertNotIn("a", by_subject) self.assertNotIn("b", by_subject) @@ -578,11 +625,11 @@ class ProfileSummaryTests(unittest.TestCase): {"path": "x.c", "line": 4, "name": "old.rom", "since_pin": False}, ], "new_hashes": []}, ] - by_subject = {f.subject: f for f in cf.summarize_profile_sync(report)} - self.assertEqual(by_subject["a"].status, cf.STALE) + by_subject = {f.subject: f for f in summarize_profile_sync(report)} + self.assertEqual(by_subject["a"].status, STALE) self.assertIn("new.rom", by_subject["a"].detail) self.assertNotIn("old.rom", by_subject["a"].detail) - self.assertEqual(by_subject["b"].status, cf.STALE) + self.assertEqual(by_subject["b"].status, STALE) self.assertNotIn("c", by_subject) def test_profile_sync_accepts_the_command_it_is_given(self): @@ -596,16 +643,16 @@ class ProfileSummaryTests(unittest.TestCase): captured.append(cmd) return mock.Mock(returncode=0, stdout="[]", stderr="") - with mock.patch.object(cf.subprocess, "run", side_effect=run): - cf.check_profiles(True, offline=True) + with mock.patch.object(subprocess, "run", side_effect=run): + check_profiles(True, offline=True) (cmd,) = captured args = profile_sync.build_parser().parse_args(cmd[2:]) profile_sync._refuse_flag_combinations(args) self.assertTrue(args.as_json) def test_a_non_list_report_is_an_error_not_a_crash(self): - findings = cf.summarize_profile_sync({"oops": 1}) - self.assertEqual(findings[0].status, cf.ERROR) + findings = summarize_profile_sync({"oops": 1}) + self.assertEqual(findings[0].status, ERROR) class RepositoryWiringTests(unittest.TestCase): @@ -613,7 +660,7 @@ class RepositoryWiringTests(unittest.TestCase): module does not exist would be skipped in silence.""" def test_every_registered_scraper_module_exists(self): - rows = cf._scrapable_platforms(REPO_ROOT / "platforms") + rows = _scrapable_platforms(REPO_ROOT / "platforms") self.assertGreaterEqual(len(rows), 10) for _name, module, _path in rows: self.assertTrue( @@ -621,7 +668,7 @@ class RepositoryWiringTests(unittest.TestCase): ) def test_inheriting_platforms_without_a_source_are_not_scraped(self): - names = {name for name, _m, _p in cf._scrapable_platforms(REPO_ROOT / "platforms")} + names = {name for name, _m, _p in _scrapable_platforms(REPO_ROOT / "platforms")} with (REPO_ROOT / "platforms" / "lakka.yml").open(encoding="utf-8") as fh: lakka = yaml_load(fh) self.assertTrue(lakka.get("inherits")) @@ -630,11 +677,11 @@ class RepositoryWiringTests(unittest.TestCase): def test_render_counts_every_status_once(self): findings = [ - cf.Finding("ci", "a", cf.OK), - cf.Finding("ci", "b", cf.STALE, detail="x"), - cf.Finding("data", "c", cf.UNKNOWN), + Finding("ci", "a", OK), + Finding("ci", "b", STALE, detail="x"), + Finding("data", "c", UNKNOWN), ] - text = cf.render(findings) + text = render(findings) self.assertIn("FRESHNESS: 1 stale, 1 unknown, 1 ok", text) self.assertIn("[ci]", text) self.assertIn("[data]", text) @@ -642,26 +689,26 @@ class RepositoryWiringTests(unittest.TestCase): def test_an_unanswered_upstream_is_not_fresh(self): """With no network every data row was unknown and the run exited 0, the answer of a collection with nothing to refresh.""" - self.assertEqual(cf.exit_code([cf.Finding("data", "a", cf.UNKNOWN)]), 1) - self.assertEqual(cf.exit_code([cf.Finding("data", "a", cf.SKIPPED), - cf.Finding("data", "b", cf.OK)]), 0) + self.assertEqual(exit_code([Finding("data", "a", UNKNOWN)]), 1) + self.assertEqual(exit_code([Finding("data", "a", SKIPPED), + Finding("data", "b", OK)]), 0) def test_stale_rows_name_the_command_that_refreshes_them(self): - text = cf.render([cf.Finding("native", "batocera", cf.STALE)]) + text = render([Finding("native", "batocera", STALE)]) self.assertIn("refresh_stale.py", text) - self.assertNotIn("refresh_stale.py", cf.render([cf.Finding("ci", "a", cf.OK)])) + self.assertNotIn("refresh_stale.py", render([Finding("ci", "a", OK)])) def test_a_stale_original_names_its_platform(self): """The hint refetched the originals of all twelve platforms to fix one, and wrote no export.""" - source = Path(cf.__file__).read_text(encoding="utf-8") + source = (SCRIPTS / "freshness" / "native.py").read_text(encoding="utf-8") hint = source.index('" fetches it, then the export is written again"') self.assertIn("--platform {name} --refresh-cache", source[hint - 120:hint]) def test_an_unknown_area_names_the_valid_ones(self): - message = cf.unknown_areas_message(["platform"]) + message = unknown_areas_message(["platform"]) self.assertIn("did you mean platforms?", message) - for area in cf.AREAS: + for area in AREAS: self.assertIn(area, message) def test_a_target_of_every_declared_core_does_not_age(self): @@ -675,9 +722,9 @@ class RepositoryWiringTests(unittest.TestCase): targets.mkdir() (targets / "solo.yml").write_text( "platform: solo\nsource: static\ntargets:\n only:\n cores: null\n") - findings = cf.check_targets(_Path(tmp), _Path(tmp), {}, 1, True) + findings = check_targets(_Path(tmp), _Path(tmp), {}, 1, True) solo = [f for f in findings if f.subject == "solo"] - self.assertEqual([(f.status, f.detail) for f in solo], [(cf.OK, "every declared core")]) + self.assertEqual([(f.status, f.detail) for f in solo], [(OK, "every declared core")]) def test_a_scraped_target_offline_is_skipped_not_ok(self): """Offline, scraped target lists were labelled static and counted OK @@ -685,7 +732,7 @@ class RepositoryWiringTests(unittest.TestCase): import tempfile from pathlib import Path as _Path - scraped = sorted(cf._target_scrapers()) + scraped = sorted(_target_scrapers()) self.assertTrue(scraped) platform = scraped[0] with tempfile.TemporaryDirectory() as tmp: @@ -694,21 +741,21 @@ class RepositoryWiringTests(unittest.TestCase): (targets / f"{platform}.yml").write_text( f"platform: {platform}\nscraped_at: '2025-01-01'\n" "targets:\n one:\n cores: []\n") - findings = cf.check_targets(_Path(tmp), _Path(tmp), {}, 1, True) + findings = check_targets(_Path(tmp), _Path(tmp), {}, 1, True) row = [f for f in findings if f.subject == platform] - self.assertEqual([(f.status, f.detail) for f in row], [(cf.SKIPPED, "offline")]) + self.assertEqual([(f.status, f.detail) for f in row], [(SKIPPED, "offline")]) def test_romm_emulatorjs_pin_is_read_from_its_dockerfile(self): """emulatorjs.yml is no registered platform: a RomM image moving to another EmulatorJS changed the cores its users run, unnoticed.""" text = "FROM x\nARG EMULATORJS_VERSION=4.2.3\nARG EMULATORJS_SHA256=ab\n" - self.assertEqual(cf.emulatorjs_pin(text), "4.2.3") - self.assertIsNone(cf.emulatorjs_pin("FROM x\n")) + self.assertEqual(emulatorjs_pin(text), "4.2.3") + self.assertIsNone(emulatorjs_pin("FROM x\n")) def test_render_keeps_long_values_whole(self): """The profile_sync row lost the end of its sentence at 32 characters.""" local = "12 profiles behind upstream, 103 refs to re-read" - text = cf.render([cf.Finding("profiles", "profile_sync", cf.STALE, local=local, + text = render([Finding("profiles", "profile_sync", STALE, local=local, remote="run profile_sync --all --triage")]) self.assertIn(local, text) self.assertIn("run profile_sync --all --triage", text) @@ -716,7 +763,7 @@ class RepositoryWiringTests(unittest.TestCase): class RepeatedDestinations(unittest.TestCase): def test_a_change_to_an_earlier_declaration_is_seen(self): - from check_freshness import diff_platform + from freshness.platformdiff import diff_platform def platform(first_md5: str) -> dict: return {"systems": {"pce": {"files": [ @@ -730,7 +777,7 @@ class RepeatedDestinations(unittest.TestCase): class PinsWithExtras(unittest.TestCase): def test_an_extras_bracket_keeps_its_pin(self): - from check_freshness import parse_pip_pins + from freshness.ci import parse_pip_pins pins = parse_pip_pins(' run: pip install pyyaml "jsonschema[format-nongpl]==4.26.0"') self.assertEqual(pins["jsonschema"], "==4.26.0") @@ -742,9 +789,9 @@ class AStaticTargetStillNamesItsCores(unittest.TestCase): before reading the names, and its 50 unprofiled emulators never showed.""" def test_declared_names_are_checked(self): - names = cf._declared_cores("retrobat") + names = _declared_cores("retrobat") self.assertIn("winuae", names) - source = Path(cf.__file__).read_text() + source = (SCRIPTS / "freshness" / "targets.py").read_text(encoding="utf-8") static = source.index('detail="every declared core"') self.assertLess(static, source.index("_declared_cores(platform)")) @@ -764,11 +811,11 @@ class TheBuildbotIndexIsRead(unittest.TestCase): {"zip": "Old.zip", "status": "OK", "key": "old"}, ]} with mock.patch.object(buildbot_system, "check", lambda registry: report): - finding = cf._check_buildbot_system() - self.assertEqual(finding.status, cf.STALE) + finding = _check_buildbot_system() + self.assertEqual(finding.status, STALE) self.assertIn("new New.zip", finding.detail) with mock.patch.object(buildbot_system, "check", lambda registry: {"error": "x", "entries": []}): - self.assertEqual(cf._check_buildbot_system().status, cf.UNKNOWN) + self.assertEqual(_check_buildbot_system().status, UNKNOWN) self.assertEqual([e["zip"] for e in buildbot_system.pending(report)], ["New.zip"]) @@ -778,15 +825,15 @@ class RowsSayAllTheyStandFor(unittest.TestCase): RetroPie cores without a profile were cut to 12, in --json too.""" def test_no_arrow_without_a_remote_value(self): - text = cf.render([ - cf.Finding("native", "emudeck", "OK", local="1 file(s)"), + text = render([ + Finding("native", "emudeck", "OK", local="1 file(s)"), ]) self.assertNotIn("->", text) def test_a_detail_starts_in_one_column(self): - text = cf.render([ - cf.Finding("native", "amberelec", cf.STALE, detail="no longer matches"), - cf.Finding("native", "bizhawk", cf.STALE, local="1 file(s)", detail="is not what"), + text = render([ + Finding("native", "amberelec", STALE, detail="no longer matches"), + Finding("native", "bizhawk", STALE, local="1 file(s)", detail="is not what"), ]) rows = [line for line in text.splitlines() if line.startswith(" STALE")] self.assertEqual(rows[0].index("no longer"), rows[1].index("is not what")) @@ -794,11 +841,11 @@ class RowsSayAllTheyStandFor(unittest.TestCase): def test_a_remote_value_keeps_the_detail_column(self): """A row with a remote value pushed its detail past the column the rows without one used, in [coreinfo] by some fifteen characters.""" - text = cf.render([ - cf.Finding("coreinfo", "anybor", cf.STALE, detail="no profile claims"), - cf.Finding("coreinfo", "amiberry", cf.STALE, local="e5d1f0f9a143", + text = render([ + Finding("coreinfo", "anybor", STALE, detail="no profile claims"), + Finding("coreinfo", "amiberry", STALE, local="e5d1f0f9a143", remote="ae545d85c06f", detail=".info changed"), - cf.Finding("coreinfo", "x", cf.STALE, local="abc", remote="d", detail="third"), + Finding("coreinfo", "x", STALE, local="abc", remote="d", detail="third"), ]) rows = [line for line in text.splitlines() if line.startswith(" STALE")] columns = {row.index(word) for row, word in zip(rows, ("no profile", ".info", "third"))} @@ -806,14 +853,13 @@ class RowsSayAllTheyStandFor(unittest.TestCase): def test_json_carries_every_unresolved_name(self): missing = {f"core{i:02d}": [] for i in range(50)} - (row,) = cf._unresolved_findings("retropie", missing) + (row,) = _unresolved_findings("retropie", missing) self.assertEqual(len(row.items), 50) self.assertIn("--json lists all 50", row.detail) class AReleasePageMakesAProfileStale(unittest.TestCase): def test_a_newer_announced_version_is_stale(self): - import check_freshness rows = [ {"name": "altirra", "skipped": "unsupported host: x", @@ -821,14 +867,13 @@ class AReleasePageMakesAProfileStale(unittest.TestCase): {"name": "mednafen", "skipped": "unsupported host: y", "declared_version": "1.32.1", "page_version": "1.32.1"}, ] - found = {f.subject: f.status for f in check_freshness.summarize_profile_sync(rows)} - self.assertEqual(found["altirra"], check_freshness.STALE) - self.assertEqual(found["mednafen"], check_freshness.OK) + found = {f.subject: f.status for f in summarize_profile_sync(rows)} + self.assertEqual(found["altirra"], STALE) + self.assertEqual(found["mednafen"], OK) def test_a_release_with_no_genuine_copy_waits_for_the_next(self): """FPse 13.0 exists only as rebuilt copies: the profile stays on 12.1 and flagging it on every run said nothing new. 13.1 would.""" - import check_freshness rows = [ {"name": "fpse", "skipped": "unsupported host: x", "declared_version": "12.1", @@ -836,10 +881,10 @@ class AReleasePageMakesAProfileStale(unittest.TestCase): {"name": "later", "skipped": "unsupported host: x", "declared_version": "12.1", "page_version": "13.1", "no_genuine_copy": "13.0"}, ] - found = {f.subject: f for f in check_freshness.summarize_profile_sync(rows)} - self.assertEqual(found["fpse"].status, check_freshness.OK) + found = {f.subject: f for f in summarize_profile_sync(rows)} + self.assertEqual(found["fpse"].status, OK) self.assertIn("no genuine copy", found["fpse"].detail) - self.assertEqual(found["later"].status, check_freshness.STALE) + self.assertEqual(found["later"].status, STALE) def test_no_genuine_copy_is_never_the_profiled_version(self): """The field names a release the profile could not read.""" diff --git a/tests/test_layers.py b/tests/test_layers.py index a26780ad4..4235d24f2 100644 --- a/tests/test_layers.py +++ b/tests/test_layers.py @@ -47,6 +47,10 @@ SIBLING_IMPORTS: dict[str, frozenset[str]] = { "unattended": frozenset({"devtools"}), # The installer event schema is checked against the one the build writes. "schemas": frozenset({"installer_build"}), + # Each layer is asked through the code that writes it: the scrapers, the + # native export, the data directory refresh, the installer pins, the + # site's source trees and profile_sync's report. + "freshness": frozenset({"scraper", "exporter", "packs", "installer_build", "sitegen", "profiling"}), } # Top-level files that stay whole at their path although packages import them: diff --git a/tests/test_measurements.py b/tests/test_measurements.py index e5b571ecc..ebb7aaaa9 100644 --- a/tests/test_measurements.py +++ b/tests/test_measurements.py @@ -651,10 +651,10 @@ class SitePages(unittest.TestCase): class Freshness(unittest.TestCase): def test_no_measurements_area(self) -> None: - import check_freshness import refresh_stale + from freshness.findings import AREAS - self.assertNotIn("measurements", check_freshness.AREAS) + self.assertNotIn("measurements", AREAS) self.assertNotIn("measurements", refresh_stale.AUTO_AREAS) diff --git a/tests/test_pin_build.py b/tests/test_pin_build.py index 2d7d2d9a0..f22208a32 100644 --- a/tests/test_pin_build.py +++ b/tests/test_pin_build.py @@ -15,7 +15,9 @@ import unittest from pathlib import Path from unittest import mock -import check_freshness as cf +from core import upstream +from freshness.findings import OK, SKIPPED, STALE +from freshness.pinbuilds import build_variable, check_pin_builds, pin_build_revision REPO_ROOT = Path(__file__).resolve().parents[1] @@ -40,8 +42,8 @@ class HeldPinsReadTheirBuildFileAgain(unittest.TestCase): def _check(self, lines=None, offline=False): profiles = {"mame0278": {"pin_frozen": "Recalbox builds it.", "pin_build": [self.REF]}, "raine": {"pin_frozen": "RetroBat installs this release."}} - with mock.patch.object(cf.upstream, "fetch_file", return_value=lines) as fetched: - findings = cf.check_pin_builds(profiles, self.platforms, "cache", offline) + with mock.patch.object(upstream, "fetch_file", return_value=lines) as fetched: + findings = check_pin_builds(profiles, self.platforms, "cache", offline) return {f.subject: f for f in findings}, fetched def test_the_variable_forms_the_platforms_write(self): @@ -56,13 +58,13 @@ class HeldPinsReadTheirBuildFileAgain(unittest.TestCase): ] for lines, variable, expected in cases: with self.subTest(variable=variable): - self.assertEqual(cf.build_variable(lines, variable), expected) + self.assertEqual(build_variable(lines, variable), expected) def test_the_platform_read_at_the_same_revision_needs_no_network(self): self._platform("10.1.1") found, fetched = self._check() fetched.assert_not_called() - self.assertEqual(found["mame0278 (recalbox)"].status, cf.OK) + self.assertEqual(found["mame0278 (recalbox)"].status, OK) def test_a_new_revision_building_another_commit_is_stale(self): self._platform("10.2") @@ -70,18 +72,18 @@ class HeldPinsReadTheirBuildFileAgain(unittest.TestCase): self.assertEqual(fetched.call_args.args[1:3], ("10.2", "package/libretro-mame0278/libretro-mame0278.mk")) row = found["mame0278 (recalbox)"] - self.assertEqual(row.status, cf.STALE) + self.assertEqual(row.status, STALE) self.assertIn("now builds " + "b" * 40, row.detail) def test_a_new_revision_building_the_same_commit_is_ok(self): self._platform("10.2") found, _ = self._check([f"LIBRETRO_MAME0278_VERSION = {'a' * 40}"]) - self.assertEqual(found["mame0278 (recalbox)"].status, cf.OK) + self.assertEqual(found["mame0278 (recalbox)"].status, OK) def test_a_build_file_gone_is_stale(self): self._platform("10.2") found, _ = self._check(None) - self.assertEqual(found["mame0278 (recalbox)"].status, cf.STALE) + self.assertEqual(found["mame0278 (recalbox)"].status, STALE) self.assertIn("is gone", found["mame0278 (recalbox)"].detail) def test_a_file_of_a_submodule_is_read_at_its_gitlink(self): @@ -101,24 +103,24 @@ class HeldPinsReadTheirBuildFileAgain(unittest.TestCase): return None profiles = {"amiberry": {"pin_frozen": "x", "pin_build": [ref]}} - with mock.patch.object(cf.upstream, "fetch_file", side_effect=fetch), \ - mock.patch.object(cf.upstream, "list_gitlinks", return_value={"batocera": "c" * 40}): - (row,) = cf.check_pin_builds(profiles, self.platforms, "cache", False) - self.assertEqual(row.status, cf.OK, row.detail) + with mock.patch.object(upstream, "fetch_file", side_effect=fetch), \ + mock.patch.object(upstream, "list_gitlinks", return_value={"batocera": "c" * 40}): + (row,) = check_pin_builds(profiles, self.platforms, "cache", False) + self.assertEqual(row.status, OK, row.detail) def test_offline_and_uncached_is_skipped(self): self._platform("10.2") profiles = {"mame0278": {"pin_frozen": "x", "pin_build": [self.REF]}} - cold = cf.upstream.NotCachedError("not cached") - with mock.patch.object(cf.upstream, "fetch_file", side_effect=cold): - (row,) = cf.check_pin_builds(profiles, self.platforms, "cache", True) - self.assertEqual(row.status, cf.SKIPPED) + cold = upstream.NotCachedError("not cached") + with mock.patch.object(upstream, "fetch_file", side_effect=cold): + (row,) = check_pin_builds(profiles, self.platforms, "cache", True) + self.assertEqual(row.status, SKIPPED) def test_a_hold_with_no_build_file_is_counted(self): self._platform("10.1.1") found, _ = self._check() row = found["pin_frozen without pin_build"] - self.assertEqual(row.status, cf.SKIPPED) + self.assertEqual(row.status, SKIPPED) self.assertEqual(row.items, ["raine"]) @@ -166,7 +168,7 @@ class EveryBuildReferenceNamesThePin(unittest.TestCase): f"{name}: {reference['platform']} is not read from " f"{reference['repo']}" for reference in references - if not cf.pin_build_revision(reference, REPO_ROOT / "platforms") + if not pin_build_revision(reference, REPO_ROOT / "platforms") ) self.assertEqual(disagree, []) diff --git a/tests/test_refresh_stale.py b/tests/test_refresh_stale.py index 8264113a2..bac77c631 100644 --- a/tests/test_refresh_stale.py +++ b/tests/test_refresh_stale.py @@ -278,9 +278,9 @@ class SavedFindings(unittest.TestCase): """romfolders was added to check_freshness and not here: its rows were dropped from a saved report without a word, and --only romfolders was refused.""" - import check_freshness + from freshness.findings import AREAS - self.assertEqual(set(check_freshness.AREAS), set(rs.AUTO_AREAS + rs.MANUAL_AREAS)) + self.assertEqual(set(AREAS), set(rs.AUTO_AREAS + rs.MANUAL_AREAS)) jobs, surfaced, _ = rs.plan_jobs([finding("romfolders", "muos")], REGISTRY, {}) self.assertEqual((jobs, [f["subject"] for f in surfaced]), ([], ["muos"])) diff --git a/tests/test_scraper_contract.py b/tests/test_scraper_contract.py index 6a67a6f07..b4a773249 100644 --- a/tests/test_scraper_contract.py +++ b/tests/test_scraper_contract.py @@ -724,11 +724,12 @@ class EveryTargetCoreReachesAProfile(unittest.TestCase): import yaml - import check_freshness + from freshness.targets import profile_name_index, unresolved_target_cores from model.profiles import load_emulator_profiles + from model.targets import platform_overrides root = Path(__file__).resolve().parents[1] - index = check_freshness.profile_name_index( + index = profile_name_index( load_emulator_profiles(str(root / "emulators")) ) overrides = yaml.safe_load((root / "platforms/targets/_overrides.yml").read_text()) or {} @@ -736,9 +737,9 @@ class EveryTargetCoreReachesAProfile(unittest.TestCase): platform = os.path.basename(path)[:-4] if platform.startswith("_"): continue - unresolved = check_freshness.unresolved_target_cores( + unresolved = unresolved_target_cores( yaml.safe_load(Path(path).read_text()), index, - check_freshness.platform_overrides(overrides, platform), + platform_overrides(overrides, platform), ) with self.subTest(platform=platform): if platform == "retropie": diff --git a/tests/test_site_integration.py b/tests/test_site_integration.py index 107197013..867661048 100644 --- a/tests/test_site_integration.py +++ b/tests/test_site_integration.py @@ -22,7 +22,8 @@ from unittest import mock import yaml -import check_freshness +from freshness.findings import OK, STALE +from freshness.profiles import check_source_paths from sitegen import emulatorcards from sitegen import emulatorpage from sitegen import startwith @@ -124,8 +125,8 @@ class SourcePathsFreshness(unittest.TestCase): from model.profiles import load_emulator_profiles profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"), skip_aliases=False) - finding = check_freshness.check_source_paths(profiles) - self.assertEqual(finding.status, check_freshness.OK, finding.detail) + finding = check_source_paths(profiles) + self.assertEqual(finding.status, OK, finding.detail) def test_a_recorded_build_file_tree_is_pinned(self): """The record holds the platform trees pin_build reads at a commit, @@ -139,14 +140,14 @@ class SourcePathsFreshness(unittest.TestCase): path = Path(tmp) / "source-paths.json" path.write_text(json.dumps({f"github.com/o/r@{pin}": ["p.mk"]}), encoding="utf-8") with mock.patch.object(sitegen_sources, "SOURCE_PATHS", path): - finding = check_freshness.check_source_paths({"p": profile}) - self.assertEqual(finding.status, check_freshness.OK, finding.detail) + finding = check_source_paths({"p": profile}) + self.assertEqual(finding.status, OK, finding.detail) def test_a_moved_pin_is_stale(self): profile = _profile("geolith") moved = dict(profile, source_commit="f" * 40, upstream_commit="e" * 40) - finding = check_freshness.check_source_paths({"geolith": moved}) - self.assertEqual(finding.status, check_freshness.STALE) + finding = check_source_paths({"geolith": moved}) + self.assertEqual(finding.status, STALE) self.assertIn("sitesources.py --fetch", finding.detail) def test_a_pinned_tree_never_read_is_stale(self): @@ -166,8 +167,8 @@ class SourcePathsFreshness(unittest.TestCase): path = Path(tmp) / "source-paths.json" path.write_text(json.dumps(record), encoding="utf-8") with mock.patch.object(sitegen_sources, "SOURCE_PATHS", path): - finding = check_freshness.check_source_paths({"geolith": profile}) - self.assertEqual(finding.status, check_freshness.STALE) + finding = check_source_paths({"geolith": profile}) + self.assertEqual(finding.status, STALE) self.assertIn("1 pinned trees not recorded", finding.detail) def test_a_tree_read_with_no_cited_path_is_recorded(self): diff --git a/tests/test_workflow_paths.py b/tests/test_workflow_paths.py index 6c7908d37..a6664c242 100644 --- a/tests/test_workflow_paths.py +++ b/tests/test_workflow_paths.py @@ -277,7 +277,7 @@ class DocumentedSteps(unittest.TestCase): def test_the_release_page_names_every_installed_package(self): """The page listed pyyaml and mkdocs and left out jsonschema: a maintainer following it could not run the contract check.""" - from check_freshness import parse_pip_pins + from freshness.ci import parse_pip_pins workflow = (REPO_ROOT / ".github/workflows/deploy-site.yml").read_text(encoding="utf-8") page = (REPO_ROOT / "wiki/release-process.md").read_text(encoding="utf-8") diff --git a/wiki/architecture.md b/wiki/architecture.md index 8e217d3ef..96a159c46 100644 --- a/wiki/architecture.md +++ b/wiki/architecture.md @@ -52,6 +52,7 @@ scripts/ all tooling (Python and pyyaml, jsonschema for schema c devtools/ the commit message rules and the checks of a pull request schemas/ the data contracts behind validate_schemas.py: schemas and semantic invariants unattended/ the job registry, worktree, CI breaker and units behind autorun.py + freshness/ each transcribed layer against its upstream, one module per area (check_freshness.py) install/ JSON install manifests per platform targets/ JSON target manifests per platform (cores per architecture) install.py the installer, with install.sh and install.ps1 to start it,