diff --git a/scripts/freshness/platforms.py b/scripts/freshness/platforms.py index 9ec28a164..7752eeb74 100644 --- a/scripts/freshness/platforms.py +++ b/scripts/freshness/platforms.py @@ -44,7 +44,7 @@ def check_platforms(platforms_dir: Path, workdir: Path, jobs: int) -> list[Findi def run(row: tuple[str, str, Path]) -> Finding: name, _module, path = row try: - fresh, error = scrape_into_copy("platforms", name, path, workdir, registry) + fresh, error, dropped = scrape_into_copy("platforms", name, path, workdir, registry) except subprocess.TimeoutExpired: return Finding("platforms", name, ERROR, detail="scraper timed out") if error: @@ -52,14 +52,19 @@ def check_platforms(platforms_dir: Path, workdir: Path, jobs: int) -> list[Findi old = source_yaml_file(path) or {} new = source_yaml_file(fresh) or {} diff = diff_platform(old, new) - status = STALE if diff.changed else OK + # An entry the scraper left out is in no diff: upstream declares a + # file the platform file does not transcribe. + status = STALE if diff.changed else UNKNOWN if dropped else OK + detail = diff.summary() + if dropped: + detail = f"{detail}; {len(dropped)} upstream entries not transcribed ({dropped[0]})" return Finding( "platforms", name, status, local=str(old.get("version", "")), remote=str(new.get("version", "")), - detail=diff.summary(), + detail=detail, ) with ThreadPoolExecutor(max_workers=jobs) as pool: diff --git a/scripts/freshness/rescrape.py b/scripts/freshness/rescrape.py index 54693f330..e0dd767eb 100644 --- a/scripts/freshness/rescrape.py +++ b/scripts/freshness/rescrape.py @@ -9,16 +9,18 @@ from pathlib import Path from core.paths import REPO_ROOT from freshness.scrapers import rescrape_command +from scraper.base_scraper import DROPPED_PREFIX def scrape_into_copy( area: str, name: str, source: Path, workdir: Path, registry: Mapping[str, Mapping] | None = None, timeout: int = 900, -) -> tuple[Path, str | None]: +) -> tuple[Path, str | None, list[str]]: """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. + The third value lists the upstream entries the scraper left out. """ target = workdir / source.name command = rescrape_command(area, name, target, registry) @@ -35,5 +37,10 @@ def scrape_into_copy( ) 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 + return target, tail[0] if tail else f"exit {proc.returncode}", [] + dropped = [ + line.removeprefix(DROPPED_PREFIX) + for line in (proc.stderr or "").splitlines() + if line.startswith(DROPPED_PREFIX) + ] + return target, None, dropped diff --git a/scripts/freshness/targets.py b/scripts/freshness/targets.py index 8e5e1eaf4..1f3b26ea6 100644 --- a/scripts/freshness/targets.py +++ b/scripts/freshness/targets.py @@ -103,7 +103,7 @@ def check_targets( out.extend(_unresolved_findings(platform, missing)) return out try: - fresh, error = scrape_into_copy("targets", platform, path, workdir) + fresh, error, _dropped = scrape_into_copy("targets", platform, path, workdir) except subprocess.TimeoutExpired: return [Finding("targets", platform, ERROR, detail="scraper timed out")] if error: diff --git a/scripts/scraper/base_scraper.py b/scripts/scraper/base_scraper.py index 8b82f3a0f..1ec1e24e0 100644 --- a/scripts/scraper/base_scraper.py +++ b/scripts/scraper/base_scraper.py @@ -148,6 +148,11 @@ def requirement_entry(req: BiosRequirement) -> dict: return entry +# The stderr line a scraper CLI writes for each upstream entry the platform +# file does not carry. The freshness rescrape reads them on exit 0, where the +# diff of the rewritten file cannot show an entry that was never written. +DROPPED_PREFIX = "dropped: " + SCRAPER_AGENT = "retrobios-scraper/1.0" GITHUB_API = "https://api.github.com" @@ -403,6 +408,8 @@ class BaseScraper(ABC): def __init__(self, url: str = "") -> None: self.url = url + # Upstream entries left out of the platform file, each with its reason. + self.dropped: list[str] = [] self._raw_data: str | None = None self._json_data: dict | None = None @@ -688,6 +695,8 @@ def scraper_cli( exit_on_scrape_error(RuntimeError( f"{scraper_class.__module__}: upstream returned no BIOS entry" )) + for reason in scraper.dropped: + print(f"{DROPPED_PREFIX}{reason}", file=sys.stderr) if args.dry_run: _print_dry_run(reqs) diff --git a/scripts/scraper/retrodeck_scraper.py b/scripts/scraper/retrodeck_scraper.py index f2ffa101b..40fb6bf7b 100644 --- a/scripts/scraper/retrodeck_scraper.py +++ b/scripts/scraper/retrodeck_scraper.py @@ -363,9 +363,11 @@ def _entry_requirement(entry: dict, comp_key: str, default_system: object) -> Bi ) -def _warn_md5_conflict( +def _md5_conflict( requirements: list[BiosRequirement], key: tuple[str, str], req: BiosRequirement -) -> None: +) -> str | None: + """Why *req* is left out: an earlier component declares the same file + with another MD5. None for a plain repeat.""" existing = next( ( r @@ -376,11 +378,11 @@ def _warn_md5_conflict( ) md5 = req.md5 if existing and md5 and existing.md5 and md5 != existing.md5: - print( - f" WARNING: {req.name} ({req.system}): MD5 conflict " - f"({existing.md5[:12]}... vs {md5[:12]}...)", - file=sys.stderr, + return ( + f"{req.name} ({req.system}): MD5 conflict " + f"({existing.md5[:12]}... vs {md5[:12]}... in {req.native['component']})" ) + return None class Scraper(BaseScraper): @@ -493,7 +495,9 @@ class Scraper(BaseScraper): continue key = (req.system, req.name.lower()) if key in seen: - _warn_md5_conflict(requirements, key, req) + conflict = _md5_conflict(requirements, key, req) + if conflict: + self.dropped.append(conflict) continue seen.add(key) requirements.append(req) diff --git a/scripts/scraper/romm_scraper.py b/scripts/scraper/romm_scraper.py index 9264413af..90f9515af 100644 --- a/scripts/scraper/romm_scraper.py +++ b/scripts/scraper/romm_scraper.py @@ -23,7 +23,6 @@ Slugs are IGDB-style platform identifiers. from __future__ import annotations import re -import sys from .base_scraper import ( BaseScraper, @@ -174,6 +173,7 @@ class Scraper(BaseScraper): data = self._fetch_json() requirements: list[BiosRequirement] = [] + unmapped: set[str] = set() for key, entry in data.items(): if ":" not in key: @@ -182,7 +182,7 @@ class Scraper(BaseScraper): igdb_slug, filename = key.split(":", 1) system = SLUG_MAP.get(igdb_slug) if not system: - print(f"Warning: unmapped IGDB slug '{igdb_slug}'", file=sys.stderr) + unmapped.add(igdb_slug) continue sha1 = (entry.get("sha1") or "").strip() or None @@ -211,6 +211,10 @@ class Scraper(BaseScraper): for slug in (igdb_slug, *mirrors) ) + # Skipped, the slug's files left romm.yml with exit 0 and the + # rescrape diff showed nothing for entries never written. + if unmapped: + raise ValueError(f"unmapped IGDB slug {', '.join(sorted(unmapped))}: add it to SLUG_MAP") return requirements def validate_format(self, raw_data: str) -> bool: diff --git a/tests/test_scraper_dropped.py b/tests/test_scraper_dropped.py new file mode 100644 index 000000000..f28c7ebce --- /dev/null +++ b/tests/test_scraper_dropped.py @@ -0,0 +1,118 @@ +"""An upstream entry a scraper leaves out reaches the freshness check. + +The RomM scraper skipped an unmapped IGDB slug and the RetroDECK scraper a +second component's conflicting MD5 with a stderr warning only: the rescrape +exited 0, the rewritten file showed no diff, and check_freshness said OK. +""" + +from __future__ import annotations + +import tests + +import io +import json +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from freshness import platforms, rescrape +from freshness.findings import OK, STALE, UNKNOWN +from scraper.base_scraper import DROPPED_PREFIX, BiosRequirement, scraper_cli +from scripts.scraper import retrodeck_scraper, romm_scraper + + +def _manifest(md5: str) -> dict: + return {"bios": [{"filename": "font.rom", "system": "pc98", "md5": md5}]} + + +class RetrodeckConflicts(unittest.TestCase): + def test_a_conflicting_md5_is_recorded(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + for name, md5 in (("np2kai", "a" * 32), ("xm6", "b" * 32)): + folder = Path(tmp) / name + folder.mkdir() + (folder / "component_manifest.json").write_text(json.dumps({name: _manifest(md5)})) + scraper = retrodeck_scraper.Scraper(manifests_dir=tmp) + reqs = scraper.fetch_requirements() + self.assertEqual([r.md5 for r in reqs], ["a" * 32]) + self.assertEqual(len(scraper.dropped), 1) + self.assertIn("MD5 conflict", scraper.dropped[0]) + self.assertIn("xm6", scraper.dropped[0]) + + def test_a_plain_repeat_is_not_a_drop(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + for name in ("np2kai", "xm6"): + folder = Path(tmp) / name + folder.mkdir() + (folder / "component_manifest.json").write_text(json.dumps({name: _manifest("a" * 32)})) + scraper = retrodeck_scraper.Scraper(manifests_dir=tmp) + scraper.fetch_requirements() + self.assertEqual(scraper.dropped, []) + + +class RommUnmappedSlug(unittest.TestCase): + def test_an_unmapped_slug_fails_the_scrape(self) -> None: + data = {"nosuchconsole:bios.bin": {"size": "4", "md5": "c" * 32}} + with mock.patch.object(romm_scraper, "fetch_github_latest_version", return_value="9.9.9"): + scraper = romm_scraper.Scraper() + scraper._raw_data = json.dumps(data) + with self.assertRaisesRegex(ValueError, "nosuchconsole"): + scraper.fetch_requirements() + + +class _Dropping: + lists_files = True + + def __init__(self) -> None: + self.dropped = ["x.bin (s): MD5 conflict"] + + def fetch_requirements(self) -> list[BiosRequirement]: + return [BiosRequirement(name="a.bin", system="s", md5="d" * 32)] + + +class CliPrintsDrops(unittest.TestCase): + def test_each_drop_is_one_marked_line(self) -> None: + stderr = io.StringIO() + with mock.patch.object(sys, "argv", ["scraper", "--json"]), \ + mock.patch("sys.stderr", stderr), mock.patch("sys.stdout", io.StringIO()): + scraper_cli(_Dropping) + self.assertEqual(stderr.getvalue(), f"{DROPPED_PREFIX}x.bin (s): MD5 conflict\n") + + +class FreshnessReadsDrops(unittest.TestCase): + def _scrape(self, stderr: str) -> tuple[Path, str | None, list[str]]: + done = subprocess.CompletedProcess([], 0, stdout="", stderr=stderr) + with tempfile.TemporaryDirectory() as tmp: + source = Path(tmp) / "src" / "p.yml" + source.parent.mkdir() + source.write_text("systems: {}\n") + with mock.patch.object(rescrape, "rescrape_command", return_value=["true"]), \ + mock.patch.object(rescrape.subprocess, "run", return_value=done): + return rescrape.scrape_into_copy("platforms", "p", source, Path(tmp)) + + def test_marked_lines_are_returned(self) -> None: + _target, error, dropped = self._scrape(f"progress\n{DROPPED_PREFIX}x.bin (s): why\n") + self.assertIsNone(error) + self.assertEqual(dropped, ["x.bin (s): why"]) + + def test_an_unchanged_file_with_drops_is_unknown(self) -> None: + def status(dropped: list[str], new_text: str) -> str: + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "p.yml" + path.write_text("systems: {}\n") + fresh = Path(tmp) / "fresh.yml" + fresh.write_text(new_text) + with mock.patch.object(platforms, "_scrapable_platforms", return_value=[("p", "m", path)]), \ + mock.patch.object(platforms, "load_platform_registry", return_value={}), \ + mock.patch.object(platforms, "scrape_into_copy", return_value=(fresh, None, dropped)): + return platforms.check_platforms(Path(tmp), Path(tmp), 1)[0].status + self.assertEqual(status([], "systems: {}\n"), OK) + self.assertEqual(status(["x.bin (s): why"], "systems: {}\n"), UNKNOWN) + self.assertEqual(status(["x.bin (s): why"], "version: '2'\nsystems: {}\n"), STALE) + + +if __name__ == "__main__": + unittest.main() diff --git a/wiki/adding-a-platform.md b/wiki/adding-a-platform.md index 6ae4f6ab8..9bd515e2d 100644 --- a/wiki/adding-a-platform.md +++ b/wiki/adding-a-platform.md @@ -117,7 +117,10 @@ SLUG_MAP: dict[str, str] = { } ``` -Warn on unmapped slugs so new systems are surfaced during scraping. +An unmapped slug fails the scrape: skipped, its files would leave the platform +file while the run still exits 0. An entry the platform file cannot carry goes +in `self.dropped` with its reason, and `check_freshness.py` reports the +platform UNKNOWN while one is left out. ### generate_platform_yaml (optional) diff --git a/wiki/adding-a-scraper.md b/wiki/adding-a-scraper.md index f7e2cb072..2d857e94d 100644 --- a/wiki/adding-a-scraper.md +++ b/wiki/adding-a-scraper.md @@ -140,7 +140,6 @@ Based on the RomM scraper pattern (JSON source, flat structure): from __future__ import annotations import json -import sys try: from .base_scraper import BaseScraper, BiosRequirement @@ -168,10 +167,11 @@ class Scraper(BaseScraper): data = json.loads(raw) requirements = [] + unmapped = set() for entry in data: system = SLUG_MAP.get(entry["platform"]) if not system: - print(f"Warning: unmapped '{entry['platform']}'", file=sys.stderr) + unmapped.add(entry["platform"]) continue requirements.append(BiosRequirement( name=entry["filename"], @@ -182,6 +182,8 @@ class Scraper(BaseScraper): destination=entry["filename"], required=entry.get("required", True), )) + if unmapped: + raise ValueError(f"unmapped platform {', '.join(sorted(unmapped))}") return requirements def validate_format(self, raw_data: str) -> bool: