mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-23 01:57: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
@@ -17,11 +17,10 @@ from pathlib import Path
|
||||
# they share helpers with the rest of scripts/. Putting that directory on the
|
||||
# path once here is what lets every submodule say `from common import ...`
|
||||
# instead of carrying its own bootstrap.
|
||||
_SCRIPTS_DIR = str(Path(__file__).resolve().parent.parent)
|
||||
if _SCRIPTS_DIR not in sys.path:
|
||||
if (_SCRIPTS_DIR := str(Path(__file__).resolve().parent.parent)) not in sys.path:
|
||||
sys.path.insert(0, _SCRIPTS_DIR)
|
||||
|
||||
from .base_scraper import BaseScraper # noqa: E402
|
||||
from .base_scraper import BaseScraper
|
||||
|
||||
_scrapers: dict[str, type] = {}
|
||||
|
||||
@@ -33,7 +32,7 @@ def discover_scrapers() -> dict[str, type]:
|
||||
|
||||
package_dir = Path(__file__).parent
|
||||
|
||||
for finder, name, ispkg in pkgutil.iter_modules([str(package_dir)]):
|
||||
for _finder, name, _ispkg in pkgutil.iter_modules([str(package_dir)]):
|
||||
if not name.endswith("_scraper"):
|
||||
continue
|
||||
|
||||
|
||||
+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:
|
||||
|
||||
@@ -333,18 +333,8 @@ def _resolve_truncated_md5(md5: str, md5_index: dict[str, str]) -> str:
|
||||
return md5
|
||||
|
||||
|
||||
def extract_systems_dict(raw: str) -> dict:
|
||||
"""The `systems` dict of a batocera-systems style script.
|
||||
|
||||
Read with ast.literal_eval, never executed: the text is the platform's
|
||||
code. A key written twice keeps its later value, as it does when Python
|
||||
runs the script.
|
||||
"""
|
||||
match = re.search(r"^systems\s*=\s*\{", raw, re.MULTILINE)
|
||||
if not match:
|
||||
raise ValueError("no 'systems = {' in the script")
|
||||
|
||||
start = match.start() + raw[match.start() :].index("{")
|
||||
def _closing_brace(raw: str, start: int) -> int:
|
||||
"""Index of the brace closing the one at `start`, past strings and comments."""
|
||||
depth = 0
|
||||
i = start
|
||||
in_str = False
|
||||
@@ -370,35 +360,51 @@ def extract_systems_dict(raw: str) -> dict:
|
||||
while i < len(raw) and raw[i] != "\n":
|
||||
i += 1
|
||||
i += 1
|
||||
return i
|
||||
|
||||
dict_str = raw[start : i + 1]
|
||||
|
||||
lines = []
|
||||
for line in dict_str.split("\n"):
|
||||
in_string = False
|
||||
string_char = None
|
||||
clean = []
|
||||
j = 0
|
||||
while j < len(line):
|
||||
ch = line[j]
|
||||
if ch == "\\" and j + 1 < len(line):
|
||||
clean.append(ch)
|
||||
clean.append(line[j + 1])
|
||||
j += 2
|
||||
continue
|
||||
if ch in ('"', "'") and not in_string:
|
||||
in_string = True
|
||||
string_char = ch
|
||||
clean.append(ch)
|
||||
elif ch == string_char and in_string:
|
||||
in_string = False
|
||||
clean.append(ch)
|
||||
elif ch == "#" and not in_string:
|
||||
break
|
||||
else:
|
||||
clean.append(ch)
|
||||
j += 1
|
||||
lines.append("".join(clean))
|
||||
def _strip_comment(line: str) -> str:
|
||||
"""The line without a trailing # comment, strings kept whole."""
|
||||
in_string = False
|
||||
string_char = None
|
||||
clean = []
|
||||
j = 0
|
||||
while j < len(line):
|
||||
ch = line[j]
|
||||
if ch == "\\" and j + 1 < len(line):
|
||||
clean.append(ch)
|
||||
clean.append(line[j + 1])
|
||||
j += 2
|
||||
continue
|
||||
if ch in ('"', "'") and not in_string:
|
||||
in_string = True
|
||||
string_char = ch
|
||||
clean.append(ch)
|
||||
elif ch == string_char and in_string:
|
||||
in_string = False
|
||||
clean.append(ch)
|
||||
elif ch == "#" and not in_string:
|
||||
break
|
||||
else:
|
||||
clean.append(ch)
|
||||
j += 1
|
||||
return "".join(clean)
|
||||
|
||||
|
||||
def extract_systems_dict(raw: str) -> dict:
|
||||
"""The `systems` dict of a batocera-systems style script.
|
||||
|
||||
Read with ast.literal_eval, never executed: the text is the platform's
|
||||
code. A key written twice keeps its later value, as it does when Python
|
||||
runs the script.
|
||||
"""
|
||||
match = re.search(r"^systems\s*=\s*\{", raw, re.MULTILINE)
|
||||
if not match:
|
||||
raise ValueError("no 'systems = {' in the script")
|
||||
|
||||
start = match.start() + raw[match.start() :].index("{")
|
||||
dict_str = raw[start : _closing_brace(raw, start) + 1]
|
||||
lines = [_strip_comment(line) for line in dict_str.split("\n")]
|
||||
|
||||
clean_dict_str = "\n".join(lines)
|
||||
|
||||
|
||||
@@ -315,7 +315,7 @@ class Scraper(BaseScraper):
|
||||
|
||||
def _parse_csv_bios(self, csv_text: str) -> list[dict]:
|
||||
"""Parse BIOS file info from a cheat sheet CSV."""
|
||||
entries = []
|
||||
entries: list[dict] = []
|
||||
if not csv_text.strip():
|
||||
return entries
|
||||
reader = csv.DictReader(io.StringIO(csv_text))
|
||||
@@ -402,17 +402,17 @@ class Scraper(BaseScraper):
|
||||
)
|
||||
)
|
||||
|
||||
for md5 in system_hashes:
|
||||
requirements.append(
|
||||
BiosRequirement(
|
||||
name=f"{system}:{md5}",
|
||||
system=system,
|
||||
md5=md5,
|
||||
destination="",
|
||||
required=True,
|
||||
native_id=system,
|
||||
)
|
||||
requirements.extend(
|
||||
BiosRequirement(
|
||||
name=f"{system}:{md5}",
|
||||
system=system,
|
||||
md5=md5,
|
||||
destination="",
|
||||
required=True,
|
||||
native_id=system,
|
||||
)
|
||||
for md5 in system_hashes
|
||||
)
|
||||
|
||||
for sheet in CSV_SHEETS:
|
||||
csv_text = self._fetch_csv(sheet)
|
||||
|
||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
||||
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from typing import TypedDict
|
||||
|
||||
from .base_scraper import (
|
||||
BaseScraper,
|
||||
@@ -124,6 +125,15 @@ def _core_info_files() -> list[str]:
|
||||
return info_files
|
||||
|
||||
|
||||
class _ExtraSystem(TypedDict):
|
||||
"""A system System.dat lacks, with the files RetroArch needs for it."""
|
||||
|
||||
files: list[dict[str, object]]
|
||||
core: str
|
||||
manufacturer: str
|
||||
docs: str
|
||||
|
||||
|
||||
class Scraper(BaseScraper):
|
||||
"""Scraper for libretro System.dat."""
|
||||
|
||||
@@ -234,6 +244,31 @@ class Scraper(BaseScraper):
|
||||
metadata = self.fetch_metadata()
|
||||
core_meta = self._fetch_core_metadata()
|
||||
|
||||
systems = self._system_entries(requirements, core_meta)
|
||||
self._add_extra_systems(systems)
|
||||
self._add_arcade_files(systems)
|
||||
self._add_system_files(systems)
|
||||
self._add_includes_and_data(systems)
|
||||
|
||||
return {
|
||||
"platform": "RetroArch",
|
||||
"version": metadata["retroarch_version"] or "",
|
||||
"dat_version": metadata["dat_version"] or "",
|
||||
"homepage": "https://www.retroarch.com",
|
||||
"source": (
|
||||
f"https://github.com/{DATABASE_REPO}/blob/"
|
||||
f"{self.revision or 'master'}/dat/System.dat"
|
||||
),
|
||||
"base_destination": "system",
|
||||
"hash_type": "sha1",
|
||||
"verification_mode": "existence",
|
||||
"systems": systems,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _system_entries(
|
||||
requirements: list[BiosRequirement], core_meta: dict[str, dict]
|
||||
) -> dict[str, dict]:
|
||||
systems = {}
|
||||
for req in requirements:
|
||||
if req.system not in systems:
|
||||
@@ -252,10 +287,14 @@ class Scraper(BaseScraper):
|
||||
|
||||
systems[req.system]["files"].append(requirement_entry(req))
|
||||
|
||||
return systems
|
||||
|
||||
@staticmethod
|
||||
def _add_extra_systems(systems: dict[str, dict]) -> None:
|
||||
# Systems not in System.dat but needed for RetroArch: added via
|
||||
# shared groups in _shared.yml. The includes directive is resolved
|
||||
# at load time by load_platform_config().
|
||||
EXTRA_SYSTEMS = {
|
||||
EXTRA_SYSTEMS: dict[str, _ExtraSystem] = {
|
||||
# ref: Vircon32/libretro.c, virtual console, single BIOS
|
||||
"vircon32": {
|
||||
"files": [
|
||||
@@ -292,6 +331,9 @@ class Scraper(BaseScraper):
|
||||
"files": [{**f, "curated": True} for f in sys_data["files"]],
|
||||
}
|
||||
|
||||
|
||||
@staticmethod
|
||||
def _add_arcade_files(systems: dict[str, dict]) -> None:
|
||||
# Arcade BIOS present in the repo but absent from System.dat.
|
||||
# FBNeo expects them in system/ or system/fbneo/.
|
||||
# ref: fbneo/src/burner/libretro/libretro.cpp
|
||||
@@ -336,6 +378,9 @@ class Scraper(BaseScraper):
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@staticmethod
|
||||
def _add_system_files(systems: dict[str, dict]) -> None:
|
||||
# Extra files missing from System.dat for specific systems.
|
||||
# Each traced to the core's source code.
|
||||
EXTRA_SYSTEM_FILES = {
|
||||
@@ -455,6 +500,9 @@ class Scraper(BaseScraper):
|
||||
systems[sys_id]["files"].append({**ef, "curated": True})
|
||||
existing.add(key)
|
||||
|
||||
|
||||
@staticmethod
|
||||
def _add_includes_and_data(systems: dict[str, dict]) -> None:
|
||||
# Inject shared group references for systems that have core-specific
|
||||
# subdirectory requirements already defined in _shared.yml.
|
||||
# Note: fuse/ prefix NOT injected for sinclair-zx-spectrum.
|
||||
@@ -510,20 +558,6 @@ class Scraper(BaseScraper):
|
||||
if sys_id in systems:
|
||||
systems[sys_id]["data_directories"] = data_dirs
|
||||
|
||||
return {
|
||||
"platform": "RetroArch",
|
||||
"version": metadata["retroarch_version"] or "",
|
||||
"dat_version": metadata["dat_version"] or "",
|
||||
"homepage": "https://www.retroarch.com",
|
||||
"source": (
|
||||
f"https://github.com/{DATABASE_REPO}/blob/"
|
||||
f"{self.revision or 'master'}/dat/System.dat"
|
||||
),
|
||||
"base_destination": "system",
|
||||
"hash_type": "sha1",
|
||||
"verification_mode": "existence",
|
||||
"systems": systems,
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
|
||||
@@ -255,6 +255,10 @@ def platform_config(
|
||||
}
|
||||
|
||||
|
||||
def _fetch_with_headers(url: str, headers: dict[str, str] | None = None) -> bytes:
|
||||
return fetch_bytes(url, headers=headers)
|
||||
|
||||
|
||||
class Scraper(BaseScraper):
|
||||
"""Pak scraper for one frontend of the MinUI family."""
|
||||
|
||||
@@ -266,7 +270,7 @@ class Scraper(BaseScraper):
|
||||
url: str | None = None,
|
||||
fetch: Callable[[str, dict[str, str] | None], bytes] | None = None,
|
||||
) -> None:
|
||||
self._fetch = fetch or (lambda u, h=None: fetch_bytes(u, headers=h))
|
||||
self._fetch = fetch or _fetch_with_headers
|
||||
self.revision = ""
|
||||
if url is None:
|
||||
self.revision = fetch_branch_head(self.variant.repo, self.variant.branch)
|
||||
|
||||
@@ -262,7 +262,7 @@ class Scraper(BaseScraper):
|
||||
return False
|
||||
|
||||
has_bios = False
|
||||
for sys_key, sys_data in data.items():
|
||||
for sys_data in data.values():
|
||||
if isinstance(sys_data, dict) and "biosFiles" in sys_data:
|
||||
has_bios = True
|
||||
break
|
||||
@@ -296,9 +296,9 @@ class Scraper(BaseScraper):
|
||||
|
||||
version = fetch_github_latest_version(GITHUB_REPO)
|
||||
es_url = ES_SYSTEMS_URL.format(tag=version)
|
||||
req = urllib.request.Request(es_url, headers={"User-Agent": "retrobios-scraper/1.0"})
|
||||
request = urllib.request.Request(es_url, headers={"User-Agent": "retrobios-scraper/1.0"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
with urllib.request.urlopen(request, timeout=30) as resp:
|
||||
es_text = resp.read().decode("utf-8")
|
||||
cores, standalone = es_systems_cores(es_text)
|
||||
dual = es_systems_dual(es_text)
|
||||
|
||||
@@ -247,9 +247,10 @@ def _extract_bios_entries(component_val: dict) -> list[dict]:
|
||||
bios_data = [bios_data]
|
||||
if not isinstance(bios_data, list):
|
||||
return
|
||||
for entry in bios_data:
|
||||
if isinstance(entry, dict) and entry.get("filename", "").strip():
|
||||
entries.append(entry)
|
||||
entries.extend(
|
||||
entry for entry in bios_data
|
||||
if isinstance(entry, dict) and entry.get("filename", "").strip()
|
||||
)
|
||||
|
||||
if "bios" in component_val:
|
||||
collect(component_val["bios"])
|
||||
@@ -276,6 +277,112 @@ def _map_system(raw_system: str) -> str | None:
|
||||
return raw_system
|
||||
|
||||
|
||||
def _entry_folder(paths_raw: object) -> str | None:
|
||||
"""The folder a BIOS entry's paths resolve to, None for a saves-only entry."""
|
||||
if isinstance(paths_raw, str):
|
||||
resolved = _resolve_path(paths_raw)
|
||||
elif isinstance(paths_raw, list):
|
||||
resolved = ""
|
||||
for p in paths_raw:
|
||||
rp = _resolve_path(str(p))
|
||||
if not rp.startswith("saves"):
|
||||
resolved = rp
|
||||
break
|
||||
if not resolved:
|
||||
return None
|
||||
else:
|
||||
resolved = ""
|
||||
|
||||
# Skip saves-only entries
|
||||
if resolved.startswith("saves"):
|
||||
return None
|
||||
return resolved
|
||||
|
||||
|
||||
def _entry_md5(md5_raw: object) -> str:
|
||||
"""MD5 handling: sanitize upstream errors."""
|
||||
if isinstance(md5_raw, list):
|
||||
parts = [str(m).strip().lower() for m in md5_raw if m]
|
||||
elif md5_raw:
|
||||
parts = [str(md5_raw).strip().lower()]
|
||||
else:
|
||||
parts = []
|
||||
# Keep only valid 32-char hex MD5 hashes
|
||||
valid = [p for p in parts if re.fullmatch(r"[0-9a-f]{32}", p)]
|
||||
return ",".join(valid)
|
||||
|
||||
|
||||
def _entry_requirement(entry: dict, comp_key: str, default_system: object) -> BiosRequirement | None:
|
||||
filename = entry["filename"].strip()
|
||||
raw_system = entry.get("system", default_system)
|
||||
if isinstance(raw_system, list):
|
||||
raw_system = raw_system[0] if raw_system else default_system
|
||||
|
||||
system = _map_system(str(raw_system))
|
||||
if system is None:
|
||||
return None
|
||||
|
||||
resolved = _entry_folder(entry.get("paths"))
|
||||
if resolved is None:
|
||||
return None
|
||||
|
||||
# Build destination: default to bios/ if no path specified
|
||||
if resolved:
|
||||
destination = f"{resolved}/{filename}"
|
||||
else:
|
||||
destination = f"bios/{filename}"
|
||||
|
||||
md5 = _entry_md5(entry.get("md5", ""))
|
||||
|
||||
required_raw = entry.get("required", "")
|
||||
required = bool(required_raw) and str(required_raw).lower() not in (
|
||||
"false",
|
||||
"no",
|
||||
"optional",
|
||||
"",
|
||||
)
|
||||
|
||||
native: dict[str, object] = {"component": comp_key}
|
||||
description = str(entry.get("description", "")).strip()
|
||||
if description:
|
||||
native["description"] = description
|
||||
if required_raw not in (None, ""):
|
||||
native["required_label"] = str(required_raw)
|
||||
|
||||
sha256 = str(entry.get("sha256", "")).strip().lower()
|
||||
|
||||
return BiosRequirement(
|
||||
name=filename,
|
||||
system=system,
|
||||
destination=destination,
|
||||
md5=md5,
|
||||
sha256=sha256 or None,
|
||||
required=required,
|
||||
native_id=str(raw_system),
|
||||
native=native,
|
||||
)
|
||||
|
||||
|
||||
def _warn_md5_conflict(
|
||||
requirements: list[BiosRequirement], key: tuple[str, str], req: BiosRequirement
|
||||
) -> None:
|
||||
existing = next(
|
||||
(
|
||||
r
|
||||
for r in requirements
|
||||
if (r.system, r.name.lower()) == key
|
||||
),
|
||||
None,
|
||||
)
|
||||
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,
|
||||
)
|
||||
|
||||
|
||||
class Scraper(BaseScraper):
|
||||
"""RetroDECK BIOS scraper from component manifests."""
|
||||
|
||||
@@ -410,7 +517,7 @@ class Scraper(BaseScraper):
|
||||
requirements: list[BiosRequirement] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
|
||||
for comp_name, manifest in manifests:
|
||||
for _comp_name, manifest in manifests:
|
||||
for comp_key, comp_val in manifest.items():
|
||||
if not isinstance(comp_val, dict):
|
||||
continue
|
||||
@@ -420,100 +527,15 @@ class Scraper(BaseScraper):
|
||||
default_system = default_system[0] if default_system else comp_key
|
||||
|
||||
for entry in _extract_bios_entries(comp_val):
|
||||
filename = entry["filename"].strip()
|
||||
raw_system = entry.get("system", default_system)
|
||||
if isinstance(raw_system, list):
|
||||
raw_system = raw_system[0] if raw_system else default_system
|
||||
|
||||
system = _map_system(str(raw_system))
|
||||
if system is None:
|
||||
req = _entry_requirement(entry, comp_key, default_system)
|
||||
if req is None:
|
||||
continue
|
||||
|
||||
paths_raw = entry.get("paths")
|
||||
if isinstance(paths_raw, str):
|
||||
resolved = _resolve_path(paths_raw)
|
||||
elif isinstance(paths_raw, list):
|
||||
resolved = ""
|
||||
for p in paths_raw:
|
||||
rp = _resolve_path(str(p))
|
||||
if not rp.startswith("saves"):
|
||||
resolved = rp
|
||||
break
|
||||
if not resolved:
|
||||
continue
|
||||
else:
|
||||
resolved = ""
|
||||
|
||||
# Skip saves-only entries
|
||||
if resolved.startswith("saves"):
|
||||
continue
|
||||
|
||||
# Build destination: default to bios/ if no path specified
|
||||
if resolved:
|
||||
destination = f"{resolved}/{filename}"
|
||||
else:
|
||||
destination = f"bios/{filename}"
|
||||
|
||||
# MD5 handling: sanitize upstream errors
|
||||
md5_raw = entry.get("md5", "")
|
||||
if isinstance(md5_raw, list):
|
||||
parts = [str(m).strip().lower() for m in md5_raw if m]
|
||||
elif md5_raw:
|
||||
parts = [str(md5_raw).strip().lower()]
|
||||
else:
|
||||
parts = []
|
||||
# Keep only valid 32-char hex MD5 hashes
|
||||
valid = [p for p in parts if re.fullmatch(r"[0-9a-f]{32}", p)]
|
||||
md5 = ",".join(valid)
|
||||
|
||||
required_raw = entry.get("required", "")
|
||||
required = bool(required_raw) and str(required_raw).lower() not in (
|
||||
"false",
|
||||
"no",
|
||||
"optional",
|
||||
"",
|
||||
)
|
||||
|
||||
key = (system, filename.lower())
|
||||
key = (req.system, req.name.lower())
|
||||
if key in seen:
|
||||
existing = next(
|
||||
(
|
||||
r
|
||||
for r in requirements
|
||||
if (r.system, r.name.lower()) == key
|
||||
),
|
||||
None,
|
||||
)
|
||||
if existing and md5 and existing.md5 and md5 != existing.md5:
|
||||
print(
|
||||
f" WARNING: {filename} ({system}): MD5 conflict "
|
||||
f"({existing.md5[:12]}... vs {md5[:12]}...)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
_warn_md5_conflict(requirements, key, req)
|
||||
continue
|
||||
seen.add(key)
|
||||
|
||||
native: dict[str, object] = {"component": comp_key}
|
||||
description = str(entry.get("description", "")).strip()
|
||||
if description:
|
||||
native["description"] = description
|
||||
if required_raw not in (None, ""):
|
||||
native["required_label"] = str(required_raw)
|
||||
|
||||
sha256 = str(entry.get("sha256", "")).strip().lower()
|
||||
|
||||
requirements.append(
|
||||
BiosRequirement(
|
||||
name=filename,
|
||||
system=system,
|
||||
destination=destination,
|
||||
md5=md5,
|
||||
sha256=sha256 or None,
|
||||
required=required,
|
||||
native_id=str(raw_system),
|
||||
native=native,
|
||||
)
|
||||
)
|
||||
requirements.append(req)
|
||||
|
||||
return requirements
|
||||
|
||||
|
||||
@@ -281,7 +281,10 @@ class Scraper(BaseScraper):
|
||||
{
|
||||
"files": [],
|
||||
"native_id": req.native_id,
|
||||
"name": names.get(req.native_id, req.system),
|
||||
"name": (
|
||||
names.get(req.native_id, req.system)
|
||||
if req.native_id is not None else req.system
|
||||
),
|
||||
},
|
||||
)
|
||||
entry["files"].append(requirement_entry(req))
|
||||
|
||||
@@ -185,7 +185,7 @@ class Scraper(BaseScraper):
|
||||
raise ValueError("known_bios_files.json format validation failed")
|
||||
|
||||
data = self._parse_json()
|
||||
requirements = []
|
||||
requirements: list[BiosRequirement] = []
|
||||
|
||||
for key, entry in data.items():
|
||||
if ":" not in key:
|
||||
@@ -207,21 +207,21 @@ class Scraper(BaseScraper):
|
||||
for slug, names in FIRMWARE_MIRRORS.get(igdb_slug, {}).items()
|
||||
if names is None or filename in names
|
||||
]
|
||||
for slug in (igdb_slug, *mirrors):
|
||||
requirements.append(
|
||||
BiosRequirement(
|
||||
name=filename,
|
||||
system=SLUG_MAP[slug],
|
||||
sha1=sha1,
|
||||
md5=md5,
|
||||
crc32=crc32,
|
||||
size=size,
|
||||
destination=f"{slug}/{filename}",
|
||||
required=True,
|
||||
native_id=slug,
|
||||
mirror_of=None if slug == igdb_slug else igdb_slug,
|
||||
)
|
||||
requirements.extend(
|
||||
BiosRequirement(
|
||||
name=filename,
|
||||
system=SLUG_MAP[slug],
|
||||
sha1=sha1,
|
||||
md5=md5,
|
||||
crc32=crc32,
|
||||
size=size,
|
||||
destination=f"{slug}/{filename}",
|
||||
required=True,
|
||||
native_id=slug,
|
||||
mirror_of=None if slug == igdb_slug else igdb_slug,
|
||||
)
|
||||
for slug in (igdb_slug, *mirrors)
|
||||
)
|
||||
|
||||
return requirements
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ def discover_target_scrapers() -> dict[str, type]:
|
||||
if _scrapers:
|
||||
return _scrapers
|
||||
package_dir = Path(__file__).parent
|
||||
for finder, name, ispkg in pkgutil.iter_modules([str(package_dir)]):
|
||||
for _finder, name, _ispkg in pkgutil.iter_modules([str(package_dir)]):
|
||||
if not name.endswith("_targets_scraper"):
|
||||
continue
|
||||
module = importlib.import_module(f".{name}", package=__package__)
|
||||
|
||||
@@ -302,7 +302,7 @@ def _parse_es_systems(text: str) -> dict[str, list[str]]:
|
||||
|
||||
package_to_emulators: dict[str, list[str]] = {}
|
||||
|
||||
for _system_name, system_data in data.items():
|
||||
for system_data in data.values():
|
||||
if not isinstance(system_data, dict):
|
||||
continue
|
||||
emulators = system_data.get("emulators")
|
||||
|
||||
@@ -81,6 +81,91 @@ def _expand(value: str, env: dict[str, str]) -> str:
|
||||
)
|
||||
|
||||
|
||||
class _Evaluation:
|
||||
"""The state of one evaluate() run over an options file."""
|
||||
|
||||
def __init__(self, env: dict[str, str]) -> None:
|
||||
self.env = dict(env)
|
||||
# One frame per open if: [parent state, branch taken, this branch's state],
|
||||
# each True, False, or None where a condition read an unknown variable.
|
||||
self.stack: list[list[bool | None]] = []
|
||||
self.case_depth = self.loop_depth = 0
|
||||
|
||||
def state(self) -> bool | None:
|
||||
states = [frame[2] for frame in self.stack]
|
||||
if False in states:
|
||||
return False
|
||||
return None if None in states else True
|
||||
|
||||
def nesting(self, line: str) -> bool:
|
||||
"""Follow case and loop nesting. True when the line is consumed."""
|
||||
if re.match(r"^case\b", line):
|
||||
self.case_depth += 1
|
||||
return True
|
||||
if line == "esac":
|
||||
self.case_depth -= 1
|
||||
return True
|
||||
if re.match(r"^(for|while)\b", line):
|
||||
self.loop_depth += 1
|
||||
return True
|
||||
if line == "done":
|
||||
self.loop_depth -= 1
|
||||
return True
|
||||
return bool(self.loop_depth)
|
||||
|
||||
def branch(self, line: str) -> bool:
|
||||
"""Follow if/elif/else/fi. True when the line is one of them."""
|
||||
go: bool | None
|
||||
branch = _IF_RE.match(line)
|
||||
if branch and branch.group(1) == "if":
|
||||
parent = self.state()
|
||||
go = False if parent is False else (
|
||||
None if parent is None else _condition(branch.group(2), self.env)
|
||||
)
|
||||
self.stack.append([parent, go, go])
|
||||
return True
|
||||
if branch and branch.group(1) == "elif":
|
||||
frame = self.stack[-1]
|
||||
if frame[0] is False or frame[1] is True:
|
||||
go = False
|
||||
elif frame[0] is None or frame[1] is None:
|
||||
go = None
|
||||
else:
|
||||
go = _condition(branch.group(2), self.env)
|
||||
frame[1] = True if go is True else (None if go is None else frame[1])
|
||||
frame[2] = go
|
||||
return True
|
||||
if line == "else":
|
||||
frame = self.stack[-1]
|
||||
if frame[0] is False or frame[1] is True:
|
||||
go = False
|
||||
elif frame[0] is None or frame[1] is None:
|
||||
go = None
|
||||
else:
|
||||
go = True
|
||||
frame[1], frame[2] = True, go
|
||||
return True
|
||||
if line == "fi":
|
||||
self.stack.pop()
|
||||
return True
|
||||
return False
|
||||
|
||||
def assign(self, line: str) -> None:
|
||||
assign = _ASSIGN_RE.match(line)
|
||||
current = self.state()
|
||||
if not assign or current is False:
|
||||
return
|
||||
name, op, value = assign.groups()
|
||||
if self.case_depth or current is None:
|
||||
if name in WATCHED:
|
||||
where = "a case statement" if self.case_depth else "an undecidable branch"
|
||||
raise ShellSubsetError(f"{name} assigned inside {where}")
|
||||
return
|
||||
value = " ".join(_expand(value, self.env).split())
|
||||
env = self.env
|
||||
env[name] = f"{env.get(name, '')} {value}".strip() if op == "+=" else value
|
||||
|
||||
|
||||
def evaluate(text: str, env: dict[str, str]) -> dict[str, str]:
|
||||
"""Run the assignments and if/elif/else blocks of a LibreELEC options file.
|
||||
|
||||
@@ -89,82 +174,13 @@ def evaluate(text: str, env: dict[str, str]) -> dict[str, str]:
|
||||
as a set difference. A watched variable set inside a case statement is
|
||||
ambiguous and stops the scrape rather than guess.
|
||||
"""
|
||||
env = dict(env)
|
||||
lines = re.sub(r"\\\n", " ", text).splitlines()
|
||||
# One frame per open if: [parent state, branch taken, this branch's state],
|
||||
# each True, False, or None where a condition read an unknown variable.
|
||||
stack: list[list[bool | None]] = []
|
||||
case_depth = loop_depth = 0
|
||||
|
||||
def state() -> bool | None:
|
||||
states = [frame[2] for frame in stack]
|
||||
if False in states:
|
||||
return False
|
||||
return None if None in states else True
|
||||
|
||||
for raw in lines:
|
||||
run = _Evaluation(env)
|
||||
for raw in re.sub(r"\\\n", " ", text).splitlines():
|
||||
line = raw.split("#", 1)[0].strip()
|
||||
if not line:
|
||||
if not line or run.nesting(line) or run.branch(line):
|
||||
continue
|
||||
if re.match(r"^case\b", line):
|
||||
case_depth += 1
|
||||
continue
|
||||
if line == "esac":
|
||||
case_depth -= 1
|
||||
continue
|
||||
if re.match(r"^(for|while)\b", line):
|
||||
loop_depth += 1
|
||||
continue
|
||||
if line == "done":
|
||||
loop_depth -= 1
|
||||
continue
|
||||
if loop_depth:
|
||||
continue
|
||||
branch = _IF_RE.match(line)
|
||||
if branch and branch.group(1) == "if":
|
||||
parent = state()
|
||||
go = False if parent is False else (
|
||||
None if parent is None else _condition(branch.group(2), env)
|
||||
)
|
||||
stack.append([parent, go, go])
|
||||
continue
|
||||
if branch and branch.group(1) == "elif":
|
||||
frame = stack[-1]
|
||||
if frame[0] is False or frame[1] is True:
|
||||
go = False
|
||||
elif frame[0] is None or frame[1] is None:
|
||||
go = None
|
||||
else:
|
||||
go = _condition(branch.group(2), env)
|
||||
frame[1] = True if go is True else (None if go is None else frame[1])
|
||||
frame[2] = go
|
||||
continue
|
||||
if line == "else":
|
||||
frame = stack[-1]
|
||||
if frame[0] is False or frame[1] is True:
|
||||
go = False
|
||||
elif frame[0] is None or frame[1] is None:
|
||||
go = None
|
||||
else:
|
||||
go = True
|
||||
frame[1], frame[2] = True, go
|
||||
continue
|
||||
if line == "fi":
|
||||
stack.pop()
|
||||
continue
|
||||
assign = _ASSIGN_RE.match(line)
|
||||
current = state()
|
||||
if not assign or current is False:
|
||||
continue
|
||||
name, op, value = assign.groups()
|
||||
if case_depth or current is None:
|
||||
if name in WATCHED:
|
||||
where = "a case statement" if case_depth else "an undecidable branch"
|
||||
raise ShellSubsetError(f"{name} assigned inside {where}")
|
||||
continue
|
||||
value = " ".join(_expand(value, env).split())
|
||||
env[name] = f"{env.get(name, '')} {value}".strip() if op == "+=" else value
|
||||
return env
|
||||
run.assign(line)
|
||||
return run.env
|
||||
|
||||
|
||||
def device_cores(cores_mk: str, env: dict[str, str]) -> list[str]:
|
||||
|
||||
@@ -93,6 +93,33 @@ _CORE_FILE_RE = re.compile(r"([\w+.-]+)_libretro\.(?:so\b|\{[^}]*\bso\b[^}]*\})"
|
||||
_TEST_RE = re.compile(r'\[\s*"\$\{(\w+)\}"\s*=\s*"([^"]*)"\s*\]')
|
||||
|
||||
|
||||
def _holds(condition: str, values: dict[str, str]) -> bool:
|
||||
tests = _TEST_RE.findall(condition)
|
||||
if not tests or re.sub(_TEST_RE, "", condition).strip(" ;&") not in ("", "then"):
|
||||
raise RuntimeError(f"makeinstall_target tests {condition.strip()!r}")
|
||||
for variable, value in tests:
|
||||
if variable not in values:
|
||||
raise RuntimeError(f"makeinstall_target tests ${{{variable}}}")
|
||||
if values[variable] != value:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _copied_cores(line: str) -> list[str]:
|
||||
"""The core files one line of makeinstall_target copies, by installed name."""
|
||||
found: list[str] = []
|
||||
for sources, target in _COPY_RE.findall(line):
|
||||
if named := _CORE_FILE_RE.search(target):
|
||||
found.append(named.group(1))
|
||||
continue
|
||||
found.extend(
|
||||
named.group(1) for source in sources.split()
|
||||
if not source.startswith("-")
|
||||
and (named := _CORE_FILE_RE.search(source.rsplit("/", 1)[-1]))
|
||||
)
|
||||
return found
|
||||
|
||||
|
||||
def installed_cores(package_mk: str, arch: str, with_32bit: bool) -> list[str]:
|
||||
"""The cores a libretro package installs on a device.
|
||||
|
||||
@@ -110,17 +137,6 @@ def installed_cores(package_mk: str, arch: str, with_32bit: bool) -> list[str]:
|
||||
# config/options:36 sets TARGET_ARCH="${ARCH}".
|
||||
values = {"ARCH": arch, "TARGET_ARCH": arch, "ENABLE_32BIT": "true" if with_32bit else "false"}
|
||||
|
||||
def holds(condition: str) -> bool:
|
||||
tests = _TEST_RE.findall(condition)
|
||||
if not tests or re.sub(_TEST_RE, "", condition).strip(" ;&") not in ("", "then"):
|
||||
raise RuntimeError(f"makeinstall_target tests {condition.strip()!r}")
|
||||
for variable, value in tests:
|
||||
if variable not in values:
|
||||
raise RuntimeError(f"makeinstall_target tests ${{{variable}}}")
|
||||
if values[variable] != value:
|
||||
return False
|
||||
return True
|
||||
|
||||
found: list[str] = []
|
||||
stack: list[bool] = []
|
||||
in_case = False
|
||||
@@ -138,7 +154,7 @@ def installed_cores(package_mk: str, arch: str, with_32bit: bool) -> list[str]:
|
||||
stack[-1] = arch in arm.group(1).split("|") or arm.group(1) == "*"
|
||||
line = arm.group(2)
|
||||
if line.startswith("if "):
|
||||
stack.append(holds(line[3:]))
|
||||
stack.append(_holds(line[3:], values))
|
||||
continue
|
||||
if line == "else":
|
||||
stack[-1] = not stack[-1]
|
||||
@@ -148,13 +164,7 @@ def installed_cores(package_mk: str, arch: str, with_32bit: bool) -> list[str]:
|
||||
continue
|
||||
if not all(stack):
|
||||
continue
|
||||
for sources, target in _COPY_RE.findall(line):
|
||||
if named := _CORE_FILE_RE.search(target):
|
||||
found.append(named.group(1))
|
||||
continue
|
||||
for source in sources.split():
|
||||
if not source.startswith("-") and (named := _CORE_FILE_RE.search(source.rsplit("/", 1)[-1])):
|
||||
found.append(named.group(1))
|
||||
found.extend(_copied_cores(line))
|
||||
if not found:
|
||||
raise RuntimeError("makeinstall_target installs no libretro core")
|
||||
return sorted(set(found))
|
||||
|
||||
Reference in new issue
Block a user