mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-23 10:07:48 -06:00
refactor: split scraper cli and platform scrapers
This commit is contained in:
1 parent
fbf7ae826d
commit
9af72a1ffb
14 files changed
+491
-377
No files matched your search
+119
-99
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import inspect
|
||||
import json
|
||||
import re
|
||||
@@ -14,7 +15,7 @@ import yaml
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Callable, NoReturn
|
||||
from typing import Callable, NoReturn, Protocol
|
||||
|
||||
from common import github_token, write_text_atomic, yaml_load
|
||||
|
||||
@@ -130,12 +131,16 @@ def requirement_entry(req: BiosRequirement) -> dict:
|
||||
return entry
|
||||
|
||||
|
||||
def _read_limited(resp: object, max_bytes: int = MAX_RESPONSE_SIZE) -> bytes:
|
||||
class _Readable(Protocol):
|
||||
def read(self, size: int = ..., /) -> bytes: ...
|
||||
|
||||
|
||||
def _read_limited(resp: _Readable, max_bytes: int = MAX_RESPONSE_SIZE) -> bytes:
|
||||
"""Read an HTTP response with a size limit to prevent OOM."""
|
||||
chunks: list[bytes] = []
|
||||
total = 0
|
||||
while True:
|
||||
chunk = resp.read(65536) # type: ignore[union-attr]
|
||||
chunk = resp.read(65536)
|
||||
if not chunk:
|
||||
break
|
||||
total += len(chunk)
|
||||
@@ -382,12 +387,114 @@ def _exit_on_scrape_error(error: Exception) -> NoReturn:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def _print_dry_run(reqs: list[BiosRequirement]) -> None:
|
||||
by_system: dict[str, list] = {}
|
||||
for req in reqs:
|
||||
by_system.setdefault(req.system, []).append(req)
|
||||
for system, files in sorted(by_system.items()):
|
||||
req_count = sum(1 for f in files if f.required)
|
||||
opt_count = len(files) - req_count
|
||||
print(f" {system}: {req_count} required, {opt_count} optional")
|
||||
print(f"\nTotal: {len(reqs)} BIOS entries across {len(by_system)} systems")
|
||||
|
||||
|
||||
def _print_json(reqs: list[BiosRequirement]) -> None:
|
||||
data = [
|
||||
{
|
||||
"name": r.name,
|
||||
"system": r.system,
|
||||
"sha1": r.sha1,
|
||||
"md5": r.md5,
|
||||
"size": r.size,
|
||||
"required": r.required,
|
||||
}
|
||||
for r in reqs
|
||||
]
|
||||
print(json.dumps(data, indent=2))
|
||||
|
||||
|
||||
def _generic_config(reqs: list[BiosRequirement]) -> dict:
|
||||
"""Generic fallback: just systems from requirements."""
|
||||
config: dict = {"systems": {}}
|
||||
for req in reqs:
|
||||
sys_id = req.system
|
||||
if sys_id not in config["systems"]:
|
||||
sys_entry: dict = {"files": []}
|
||||
if req.native_id:
|
||||
sys_entry["native_id"] = req.native_id
|
||||
config["systems"][sys_id] = sys_entry
|
||||
entry = {
|
||||
"name": req.name,
|
||||
"destination": req.destination or req.name,
|
||||
"required": req.required,
|
||||
}
|
||||
if req.sha1:
|
||||
entry["sha1"] = req.sha1
|
||||
if req.md5:
|
||||
entry["md5"] = req.md5
|
||||
if req.zipped_file:
|
||||
entry["zipped_file"] = req.zipped_file
|
||||
config["systems"][sys_id]["files"].append(entry)
|
||||
return config
|
||||
|
||||
|
||||
def _keep_existing(config: dict, output_path: Path) -> None:
|
||||
"""Merge into existing YAML: preserve fields the scraper doesn't generate
|
||||
(data_directories, case_insensitive_fs, manually added metadata).
|
||||
The scraper replaces systems + files, everything else is preserved."""
|
||||
with open(output_path) as f:
|
||||
existing = yaml_load(f) or {}
|
||||
# Preserve existing keys not generated by the scraper.
|
||||
# Only keys present in the NEW config are considered scraper-generated.
|
||||
# Everything else in the existing file is preserved.
|
||||
for key, val in existing.items():
|
||||
if key not in config:
|
||||
config[key] = val
|
||||
# Preserve per-system fields not generated by the scraper
|
||||
# (data_directories, native_id from manual additions, etc.)
|
||||
existing_systems = existing.get("systems", {})
|
||||
for sys_id, sys_data in config.get("systems", {}).items():
|
||||
old_sys = existing_systems.get(sys_id, {})
|
||||
for field_name in ("data_directories",):
|
||||
if field_name in old_sys and field_name not in sys_data:
|
||||
sys_data[field_name] = old_sys[field_name]
|
||||
|
||||
|
||||
def _write_output(
|
||||
scraper: BaseScraper, scraper_class: type, reqs: list[BiosRequirement], output: str
|
||||
) -> None:
|
||||
# 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)
|
||||
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"
|
||||
))
|
||||
output_path = Path(output)
|
||||
if output_path.exists():
|
||||
_keep_existing(config, output_path)
|
||||
# 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(
|
||||
config, Dumper=_PlatformDumper,
|
||||
default_flow_style=False, allow_unicode=True, sort_keys=False,
|
||||
))
|
||||
print(f"Written {len(reqs)} entries to {output}")
|
||||
|
||||
|
||||
def scraper_cli(
|
||||
scraper_class: type, description: str = "Scrape BIOS requirements"
|
||||
) -> None:
|
||||
"""Shared CLI entry point for all scrapers. Eliminates main() boilerplate."""
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(allow_abbrev=False, description=description)
|
||||
parser.add_argument("--dry-run", action="store_true", help="Show scraped data")
|
||||
parser.add_argument("--output", "-o", help="Output YAML file")
|
||||
@@ -413,100 +520,13 @@ def scraper_cli(
|
||||
))
|
||||
|
||||
if args.dry_run:
|
||||
by_system: dict[str, list] = {}
|
||||
for req in reqs:
|
||||
by_system.setdefault(req.system, []).append(req)
|
||||
for system, files in sorted(by_system.items()):
|
||||
req_count = sum(1 for f in files if f.required)
|
||||
opt_count = len(files) - req_count
|
||||
print(f" {system}: {req_count} required, {opt_count} optional")
|
||||
print(f"\nTotal: {len(reqs)} BIOS entries across {len(by_system)} systems")
|
||||
return
|
||||
|
||||
if args.json:
|
||||
data = [
|
||||
{
|
||||
"name": r.name,
|
||||
"system": r.system,
|
||||
"sha1": r.sha1,
|
||||
"md5": r.md5,
|
||||
"size": r.size,
|
||||
"required": r.required,
|
||||
}
|
||||
for r in reqs
|
||||
]
|
||||
print(json.dumps(data, indent=2))
|
||||
return
|
||||
|
||||
if args.output:
|
||||
import yaml
|
||||
|
||||
# Use scraper's generate_platform_yaml() if available (includes
|
||||
# platform metadata, cores list, standalone_cores, etc.)
|
||||
if hasattr(scraper, "generate_platform_yaml"):
|
||||
try:
|
||||
config = scraper.generate_platform_yaml()
|
||||
except (OSError, ValueError, RuntimeError) as e:
|
||||
_exit_on_scrape_error(e)
|
||||
else:
|
||||
# Generic fallback: just systems from requirements
|
||||
config = {"systems": {}}
|
||||
for req in reqs:
|
||||
sys_id = req.system
|
||||
if sys_id not in config["systems"]:
|
||||
sys_entry: dict = {"files": []}
|
||||
if req.native_id:
|
||||
sys_entry["native_id"] = req.native_id
|
||||
config["systems"][sys_id] = sys_entry
|
||||
entry = {
|
||||
"name": req.name,
|
||||
"destination": req.destination or req.name,
|
||||
"required": req.required,
|
||||
}
|
||||
if req.sha1:
|
||||
entry["sha1"] = req.sha1
|
||||
if req.md5:
|
||||
entry["md5"] = req.md5
|
||||
if req.zipped_file:
|
||||
entry["zipped_file"] = req.zipped_file
|
||||
config["systems"][sys_id]["files"].append(entry)
|
||||
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"
|
||||
))
|
||||
# Merge into existing YAML: preserve fields the scraper doesn't generate
|
||||
# (data_directories, case_insensitive_fs, manually added metadata).
|
||||
# The scraper replaces systems + files, everything else is preserved.
|
||||
output_path = Path(args.output)
|
||||
if output_path.exists():
|
||||
with open(output_path) as f:
|
||||
existing = yaml_load(f) or {}
|
||||
# Preserve existing keys not generated by the scraper.
|
||||
# Only keys present in the NEW config are considered scraper-generated.
|
||||
# Everything else in the existing file is preserved.
|
||||
for key, val in existing.items():
|
||||
if key not in config:
|
||||
config[key] = val
|
||||
# Preserve per-system fields not generated by the scraper
|
||||
# (data_directories, native_id from manual additions, etc.)
|
||||
existing_systems = existing.get("systems", {})
|
||||
for sys_id, sys_data in config.get("systems", {}).items():
|
||||
old_sys = existing_systems.get(sys_id, {})
|
||||
for field in ("data_directories",):
|
||||
if field in old_sys and field not in sys_data:
|
||||
sys_data[field] = old_sys[field]
|
||||
# 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(
|
||||
config, Dumper=_PlatformDumper,
|
||||
default_flow_style=False, allow_unicode=True, sort_keys=False,
|
||||
))
|
||||
print(f"Written {len(reqs)} entries to {args.output}")
|
||||
return
|
||||
|
||||
print(f"Scraped {len(reqs)} requirements. Use --dry-run, --json, or --output.")
|
||||
_print_dry_run(reqs)
|
||||
elif args.json:
|
||||
_print_json(reqs)
|
||||
elif args.output:
|
||||
_write_output(scraper, scraper_class, reqs, args.output)
|
||||
else:
|
||||
print(f"Scraped {len(reqs)} requirements. Use --dry-run, --json, or --output.")
|
||||
|
||||
|
||||
def fetch_github_latest_tag(repo: str, prefix: str = "") -> str:
|
||||
|
||||
Reference in new issue
Block a user