diff --git a/scripts/freshness/rescrape.py b/scripts/freshness/rescrape.py index e0dd767eb..454325a5d 100644 --- a/scripts/freshness/rescrape.py +++ b/scripts/freshness/rescrape.py @@ -9,7 +9,19 @@ from pathlib import Path from core.paths import REPO_ROOT from freshness.scrapers import rescrape_command -from scraper.base_scraper import DROPPED_PREFIX +from scraper.base_scraper import DROPPED_PREFIX, ERROR_PREFIX + + +def failure_cause(output: str, returncode: int) -> str: + """Why a scraper run failed: its error line, not the hint printed after it. + + Output without that line (a traceback) gives its last line. + """ + lines = output.strip().splitlines() + cause = next((line.removeprefix(ERROR_PREFIX) for line in lines if line.startswith(ERROR_PREFIX)), None) + if cause is not None: + return cause + return lines[-1] if lines else f"exit {returncode}" def scrape_into_copy( @@ -36,8 +48,7 @@ def scrape_into_copy( 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, failure_cause(proc.stderr or proc.stdout, proc.returncode), [] dropped = [ line.removeprefix(DROPPED_PREFIX) for line in (proc.stderr or "").splitlines() diff --git a/scripts/scraper/base_scraper.py b/scripts/scraper/base_scraper.py index 1ec1e24e0..de38aefae 100644 --- a/scripts/scraper/base_scraper.py +++ b/scripts/scraper/base_scraper.py @@ -152,6 +152,8 @@ def requirement_entry(req: BiosRequirement) -> dict: # 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: " +# The line that names why a scrape failed, read back by the freshness check. +ERROR_PREFIX = "Error: " SCRAPER_AGENT = "retrobios-scraper/1.0" GITHUB_API = "https://api.github.com" @@ -569,7 +571,7 @@ PlatformDumper.add_representer(str, _quoted_str) def exit_on_scrape_error(error: Exception) -> NoReturn: """Print what failed and what to try, then exit 1 without a traceback.""" - print(f"Error: {error}", file=sys.stderr) + print(f"{ERROR_PREFIX}{error}", file=sys.stderr) refused = re.search(r"\b(403|429)\b|rate limit", str(error), re.I) if refused and not github_token(): # A gh login is read on its own, so the hint is the login itself. @@ -637,28 +639,49 @@ def _keep_existing(config: dict, output_path: Path) -> None: sys_data[field_name] = old_sys[field_name] -def _write_output( - scraper: BaseScraper, scraper_class: type, reqs: list[BiosRequirement], output: str -) -> None: +def scrape(scraper_class: type, revision: str | None = None) -> tuple[BaseScraper, list[BiosRequirement]]: + """Run one scraper and return it with what it read. + + Raises OSError, ValueError or RuntimeError carrying the cause, an empty + read included. The entries upstream lists and the scraper leaves out + are on the scraper's `dropped`. + """ + scraper = scraper_class(revision=revision) if revision is not None else scraper_class() + reqs = scraper.fetch_requirements() + if scraper.lists_files and not reqs: + # Written, an empty read became a platform with no system that + # verify and the pack count 0/0 and call consistent. + raise RuntimeError(f"{scraper_class.__module__}: upstream returned no BIOS entry") + return scraper, reqs + + +def platform_config( + scraper: BaseScraper, reqs: list[BiosRequirement], existing: Path | None = None +) -> dict: + """The platform file a scrape writes, merged into *existing* when given. + + Raises OSError, ValueError or RuntimeError carrying the cause, a + platform that lists no file included. + """ # Use scraper's generate_platform_yaml() if available (includes # platform metadata, cores list, standalone_cores, etc.) generate = getattr(scraper, "generate_platform_yaml", None) - if generate is not None: - try: - config = generate() - except (OSError, ValueError, RuntimeError) as e: - exit_on_scrape_error(e) - else: - config = _generic_config(reqs) + config = generate() if generate is not None else _generic_config(reqs) if scraper.lists_files and not any( (system or {}).get("files") for system in (config.get("systems") or {}).values() ): - exit_on_scrape_error(RuntimeError( - f"{scraper_class.__module__}: the generated platform lists no file" - )) + raise RuntimeError(f"{type(scraper).__module__}: the generated platform lists no file") + if existing is not None and existing.exists(): + _keep_existing(config, existing) + return config + + +def _write_output(scraper: BaseScraper, reqs: list[BiosRequirement], output: str) -> None: output_path = Path(output) - if output_path.exists(): - _keep_existing(config, output_path) + try: + config = platform_config(scraper, reqs, output_path) + except (OSError, ValueError, RuntimeError) as e: + exit_on_scrape_error(e) # Written whole or not at all: a reader in the middle of a streamed # dump parsed a valid platform with a fraction of its systems. write_text_atomic(output_path, yaml.dump( @@ -685,16 +708,9 @@ def scraper_cli( args = parser.parse_args() try: - scraper = scraper_class(revision=args.revision) if takes_revision else scraper_class() - reqs = scraper.fetch_requirements() + scraper, reqs = scrape(scraper_class, args.revision if takes_revision else None) except (OSError, ValueError, RuntimeError) as e: exit_on_scrape_error(e) - if scraper.lists_files and not reqs: - # Written, an empty read became a platform with no system that - # verify and the pack count 0/0 and call consistent. - 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) @@ -703,7 +719,7 @@ def scraper_cli( elif args.json: _print_json(reqs) elif args.output: - _write_output(scraper, scraper_class, reqs, args.output) + _write_output(scraper, reqs, args.output) else: print(f"Scraped {len(reqs)} requirements. Use --dry-run, --json, or --output.") diff --git a/tests/test_scraper_dropped.py b/tests/test_scraper_dropped.py index 516c580c7..61503f4cd 100644 --- a/tests/test_scraper_dropped.py +++ b/tests/test_scraper_dropped.py @@ -20,7 +20,10 @@ 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 scraper import base_scraper +from scraper.base_scraper import ( + DROPPED_PREFIX, BiosRequirement, exit_on_scrape_error, platform_config, scrape, scraper_cli, +) from scripts.scraper import retrodeck_scraper, romm_scraper @@ -91,9 +94,41 @@ class CliPrintsDrops(unittest.TestCase): self.assertEqual(stderr.getvalue(), f"{DROPPED_PREFIX}x.bin (s): MD5 conflict\n") +class _Empty(_Dropping): + def fetch_requirements(self) -> list[BiosRequirement]: + return [] + + +class _NoFile(_Dropping): + def generate_platform_yaml(self) -> dict: + return {"systems": {"s": {"files": []}}} + + +class ScrapeStep(unittest.TestCase): + """The scrape and the file it writes, reached without the command line.""" + + def test_an_empty_read_raises_its_cause(self) -> None: + with self.assertRaisesRegex(RuntimeError, "upstream returned no BIOS entry"): + scrape(_Empty) + + def test_the_config_keeps_what_the_scraper_does_not_write(self) -> None: + scraper, reqs = scrape(_Dropping) + self.assertEqual(scraper.dropped, ["x.bin (s): MD5 conflict"]) + with tempfile.TemporaryDirectory() as tmp: + existing = Path(tmp) / "p.yml" + existing.write_text("case_insensitive_fs: true\nsystems: {}\n") + config = platform_config(scraper, reqs, existing) + self.assertTrue(config["case_insensitive_fs"]) + self.assertEqual(list(config["systems"]), ["s"]) + + def test_a_platform_without_files_raises(self) -> None: + with self.assertRaisesRegex(RuntimeError, "lists no file"): + platform_config(_NoFile(), []) # type: ignore[arg-type] + + class FreshnessReadsDrops(unittest.TestCase): - def _scrape(self, stderr: str) -> tuple[Path, str | None, list[str]]: - done = subprocess.CompletedProcess([], 0, stdout="", stderr=stderr) + def _scrape(self, stderr: str, returncode: int = 0) -> tuple[Path, str | None, list[str]]: + done = subprocess.CompletedProcess([], returncode, stdout="", stderr=stderr) with tempfile.TemporaryDirectory() as tmp: source = Path(tmp) / "src" / "p.yml" source.parent.mkdir() @@ -107,6 +142,22 @@ class FreshnessReadsDrops(unittest.TestCase): self.assertIsNone(error) self.assertEqual(dropped, ["x.bin (s): why"]) + def test_a_failure_reports_its_cause_not_the_hint(self) -> None: + """The last stderr line is the hint printed after the cause: every + failure, an empty upstream read included, read as a network issue.""" + stderr = io.StringIO() + with mock.patch("sys.stderr", stderr), self.assertRaises(SystemExit), \ + mock.patch.object(base_scraper, "github_token", return_value="t"): + exit_on_scrape_error(RuntimeError("scripts.scraper.x: upstream returned no BIOS entry")) + _target, error, dropped = self._scrape(stderr.getvalue(), returncode=1) + self.assertEqual(error, "scripts.scraper.x: upstream returned no BIOS entry") + self.assertEqual(dropped, []) + + def test_a_crash_reports_its_last_line(self) -> None: + _target, error, _dropped = self._scrape("Traceback\n line\nKeyError: 'x'\n", returncode=1) + self.assertEqual(error, "KeyError: 'x'") + self.assertEqual(self._scrape("", returncode=2)[1], "exit 2") + 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: