From 35ad46e8c58482a8893280a02ec4ae52b546142b Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:19:23 +0100 Subject: [PATCH] refactor: one rescrape command for both freshness --- scripts/freshness/platforms.py | 24 ++++--------- scripts/freshness/rescrape.py | 12 ++++--- scripts/freshness/scrapers.py | 58 ++++++++++++++++++++++++++++++ scripts/freshness/stalecommands.py | 26 ++------------ scripts/freshness/targets.py | 14 ++------ tests/sources.py | 4 ++- tests/test_check_freshness.py | 24 +++++++++++-- 7 files changed, 104 insertions(+), 58 deletions(-) create mode 100644 scripts/freshness/scrapers.py diff --git a/scripts/freshness/platforms.py b/scripts/freshness/platforms.py index 3fe22cc5d..9ec28a164 100644 --- a/scripts/freshness/platforms.py +++ b/scripts/freshness/platforms.py @@ -13,6 +13,7 @@ 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 +from freshness.scrapers import platform_scraper def _scrapable_platforms(platforms_dir: Path) -> list[tuple[str, str, Path]]: @@ -28,33 +29,22 @@ def _scrapable_platforms(platforms_dir: Path) -> list[tuple[str, str, Path]]: 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")): + module = platform_scraper(registry.get(name) or {}) + if not module or (config.get("inherits") and not config.get("source")): continue - rows.append((name, f"scripts.scraper.{scraper}_scraper", path)) + rows.append((name, module, 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) + registry = load_platform_registry(platforms_dir, required=True) findings: list[Finding] = [] def run(row: tuple[str, str, Path]) -> Finding: - name, module, path = row + name, _module, path = row try: - fresh, error = scrape_into_copy( - module, path, workdir, extra=rescrape_args(platforms_dir, name) - ) + fresh, error = scrape_into_copy("platforms", name, path, workdir, registry) except subprocess.TimeoutExpired: return Finding("platforms", name, ERROR, detail="scraper timed out") if error: diff --git a/scripts/freshness/rescrape.py b/scripts/freshness/rescrape.py index 97d2b8e4a..54693f330 100644 --- a/scripts/freshness/rescrape.py +++ b/scripts/freshness/rescrape.py @@ -4,15 +4,16 @@ from __future__ import annotations import shutil import subprocess -import sys +from collections.abc import Mapping from pathlib import Path from core.paths import REPO_ROOT +from freshness.scrapers import rescrape_command def scrape_into_copy( - module: str, source: Path, workdir: Path, timeout: int = 900, - extra: tuple[str, ...] = (), + area: str, name: str, source: Path, workdir: Path, + registry: Mapping[str, Mapping] | None = None, timeout: int = 900, ) -> tuple[Path, str | None]: """Run a scraper's own write path on a throwaway copy of *source*. @@ -20,9 +21,12 @@ def scrape_into_copy( the scraper preserves and the diff shows only what the scrape changes. """ target = workdir / source.name + command = rescrape_command(area, name, target, registry) + if command is None: + raise ValueError(f"no scraper rewrites {area} {name}") shutil.copyfile(source, target) proc = subprocess.run( - [sys.executable, "-m", module, "-o", str(target), *extra], + command, cwd=REPO_ROOT, capture_output=True, text=True, diff --git a/scripts/freshness/scrapers.py b/scripts/freshness/scrapers.py new file mode 100644 index 000000000..870c2151d --- /dev/null +++ b/scripts/freshness/scrapers.py @@ -0,0 +1,58 @@ +"""Which scraper rewrites a platform file or a target file, and the command that runs it.""" + +from __future__ import annotations + +import sys +from collections.abc import Mapping +from functools import lru_cache +from pathlib import Path + +from scraper.targets import discover_target_scrapers + + +def platform_scraper(entry: Mapping) -> str | None: + """The module that scrapes a platform file, from its registry entry.""" + scraper = entry.get("scraper") + return f"scripts.scraper.{scraper}_scraper" if scraper else None + + +def rescrape_args(entry: Mapping) -> 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. + """ + return tuple(str(a) for a in entry.get("rescrape_args") or ()) + + +@lru_cache(maxsize=1) +def target_scrapers() -> dict[str, str]: + """platform -> scraper module for every target scraper on disk. + + Named from the repository root, as `python -m` runs it there, whatever + path this process imported the package by. + """ + return { + platform: f"scripts.scraper.targets.{cls.__module__.rpartition('.')[2]}" + for platform, cls in discover_target_scrapers().items() + } + + +def rescrape_command( + area: str, platform: str, output: str | Path, registry: Mapping[str, Mapping] | None = None, +) -> list[str] | None: + """The scrape of a platform file or a target file into *output*, None without a scraper. + + The freshness check runs it on a throwaway copy and refresh_stale on the + committed file: both read the scraper and its arguments here. + """ + if area == "platforms": + entry = (registry or {}).get(platform) or {} + module, extra = platform_scraper(entry), rescrape_args(entry) + elif area == "targets": + module, extra = target_scrapers().get(platform), () + else: + raise ValueError(f"no scraper rewrites the {area} area") + if module is None: + return None + return [sys.executable, "-m", module, "-o", str(output), *extra] diff --git a/scripts/freshness/stalecommands.py b/scripts/freshness/stalecommands.py index 34339fc8c..dd0674c3c 100644 --- a/scripts/freshness/stalecommands.py +++ b/scripts/freshness/stalecommands.py @@ -8,6 +8,7 @@ from functools import lru_cache from core.paths import DATA_DIRS_FILE, REPO_ROOT from model.registry import data_dir_registry_at +from freshness.scrapers import rescrape_command DATA_DIRS_REGISTRY = REPO_ROOT / DATA_DIRS_FILE @@ -43,18 +44,7 @@ def export_refresh(platform: str) -> list[str]: def _platform_command(subject: str, registry: dict[str, dict]) -> list[str] | None: - entry = registry.get(subject) or {} - scraper = entry.get("scraper") - if not scraper: - return None - return [ - sys.executable, - "-m", - f"scripts.scraper.{scraper}_scraper", - "-o", - f"platforms/{subject}.yml", - *(str(a) for a in entry.get("rescrape_args") or ()), - ] + return rescrape_command("platforms", subject, f"platforms/{subject}.yml", registry) def _target_command(subject: str, registry: dict[str, dict]) -> list[str] | None: @@ -62,17 +52,7 @@ def _target_command(subject: str, registry: dict[str, dict]) -> list[str] | None # scraper fixes that, a human writes `cores:` or _overrides.yml. if subject.endswith(" cores"): return None - entry = registry.get(subject) or {} - module = entry.get("target_scraper") - if not module: - return None - return [ - sys.executable, - "-m", - f"scripts.scraper.targets.{module}_scraper", - "-o", - f"platforms/targets/{subject}.yml", - ] + return rescrape_command("targets", subject, f"platforms/targets/{subject}.yml") def _data_command(subject: str, registry: dict[str, dict]) -> list[str] | None: diff --git a/scripts/freshness/targets.py b/scripts/freshness/targets.py index c6bc2973f..8e5e1eaf4 100644 --- a/scripts/freshness/targets.py +++ b/scripts/freshness/targets.py @@ -11,10 +11,10 @@ from pathlib import Path 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 +from freshness.scrapers import target_scrapers def profile_name_index(profiles: dict[str, dict]) -> dict[str, set[str]]: @@ -42,14 +42,6 @@ def unresolved_target_cores( 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, @@ -57,7 +49,7 @@ def check_targets( targets_dir = platforms_dir / "targets" overrides = read_target_overrides(targets_dir) index = profile_name_index(profiles) - scrapers = _target_scrapers() + scrapers = target_scrapers() findings: list[Finding] = [] today = datetime.now(timezone.utc) @@ -111,7 +103,7 @@ def check_targets( out.extend(_unresolved_findings(platform, missing)) return out try: - fresh, error = scrape_into_copy(module, path, workdir) + fresh, error = scrape_into_copy("targets", platform, path, workdir) except subprocess.TimeoutExpired: return [Finding("targets", platform, ERROR, detail="scraper timed out")] if error: diff --git a/tests/sources.py b/tests/sources.py index 02e02676a..66db29093 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -94,7 +94,8 @@ COMMANDS = { "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/scrapers.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", @@ -102,6 +103,7 @@ COMMANDS = { "refresh_stale.py": ( "freshness/stalejob.py", "freshness/stalefindings.py", "freshness/stalecommands.py", "freshness/staleplan.py", "freshness/stalerun.py", "freshness/stalereport.py", + "freshness/scrapers.py", ), "pipeline.py": ( "orchestrate/labels.py", "orchestrate/results.py", "orchestrate/runner.py", diff --git a/tests/test_check_freshness.py b/tests/test_check_freshness.py index 7fff4844e..68969a7e8 100644 --- a/tests/test_check_freshness.py +++ b/tests/test_check_freshness.py @@ -56,14 +56,15 @@ 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.scrapers import rescrape_command, target_scrapers from freshness.targets import ( _declared_cores, - _target_scrapers, _unresolved_findings, check_targets, profile_name_index, unresolved_target_cores, ) +from model.registry import load_platform_registry from model.safeparse import yaml_load from model.targets import platform_overrides from scripts.scraper import game_dat_importer @@ -669,6 +670,25 @@ class RepositoryWiringTests(unittest.TestCase): (REPO_ROOT / (module.replace(".", "/") + ".py")).is_file(), module ) + def test_the_registry_names_the_target_scrapers_the_check_runs(self): + """refresh_stale and the check read the same scraper: a target file + the check rescrapes is never left to a human by the refresh.""" + registry = load_platform_registry(REPO_ROOT / "platforms", required=True) + declared = { + name: f"scripts.scraper.targets.{entry['target_scraper']}_scraper" + for name, entry in registry.items() if (entry or {}).get("target_scraper") + } + self.assertEqual(declared, target_scrapers()) + + def test_the_check_and_the_refresh_run_one_scrape(self): + registry = {"retrobat": {"scraper": "retrobat", "rescrape_args": ["--revision", "master"]}} + self.assertEqual( + rescrape_command("platforms", "retrobat", "out.yml", registry)[1:], + ["-m", "scripts.scraper.retrobat_scraper", "-o", "out.yml", "--revision", "master"], + ) + self.assertIsNone(rescrape_command("platforms", "lakka", "out.yml", {"lakka": {}})) + self.assertIsNone(rescrape_command("targets", "retrobat", "out.yml")) + def test_inheriting_platforms_without_a_source_are_not_scraped(self): names = {name for name, _m, _p in _scrapable_platforms(REPO_ROOT / "platforms")} with (REPO_ROOT / "platforms" / "lakka.yml").open(encoding="utf-8") as fh: @@ -747,7 +767,7 @@ class RepositoryWiringTests(unittest.TestCase): import tempfile from pathlib import Path as _Path - scraped = sorted(_target_scrapers()) + scraped = sorted(target_scrapers()) self.assertTrue(scraped) platform = scraped[0] with tempfile.TemporaryDirectory() as tmp: