chore: merge the scraper quality work

This commit is contained in:
Abdessamad Derraz committed 2026-11-17 07:51:58 +01:00
commit e2b3daff63
48 files changed
+2250 -1813

No files matched your search

+3 -4
View File
@@ -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
+78 -67
View File
@@ -461,6 +461,82 @@ def _patch_scalar(text: str, key: str, value: str) -> str:
)
def _owned_end(lines: list[str], start_line: int) -> int:
"""The last "owned" line of the entry starting at start_line.
Owned = indented with 4+ spaces (field lines of this entry).
"""
last_owned = start_line
for j in range(start_line + 1, len(lines)):
stripped = lines[j].strip()
if not stripped:
break # blank line = end of entry
if stripped.startswith("#"):
break # comment = belongs to next entry
if re.match(r"^ - ", lines[j]):
break # next list item
if re.match(r"^ ", lines[j]) or re.match(r"^ \w", lines[j]):
last_owned = j
else:
break
return last_owned
def _patch_source_ref(lines: list[str], start_line: int, last_owned: int, source_ref: str) -> int:
"""Patch source_ref in-place, or add it. Returns the new last owned line."""
for j in range(start_line + 1, last_owned + 1):
if re.match(r"^ source_ref:", lines[j]):
lines[j] = f' source_ref: "{source_ref}"'
return last_owned
lines.insert(last_owned + 1, f' source_ref: "{source_ref}"')
return last_owned + 1
def _drop_contents(lines: list[str], start_line: int, last_owned: int) -> int:
"""Remove an existing contents block. Returns the new last owned line."""
contents_start = None
contents_end = None
for j in range(start_line + 1, last_owned + 1):
if re.match(r"^ contents:", lines[j]):
contents_start = j
elif contents_start is not None:
if re.match(r"^ ", lines[j]):
contents_end = j
else:
break
if contents_start is None:
return last_owned
if contents_end is None:
contents_end = contents_start
del lines[contents_start : contents_end + 1]
return last_owned - (contents_end - contents_start + 1)
def _patch_entry(lines: list[str], start_line: int, fe: dict) -> None:
contents = fe.get("contents", [])
source_ref = fe.get("source_ref", "")
last_owned = _owned_end(lines, start_line)
if source_ref:
last_owned = _patch_source_ref(lines, start_line, last_owned, source_ref)
# The source settles required for a set the machine runs without
if "required" in fe:
for j in range(start_line + 1, last_owned + 1):
if re.match(r"^ required:", lines[j]):
lines[j] = f" required: {str(fe['required']).lower()}"
break
last_owned = _drop_contents(lines, start_line, last_owned)
# Insert new contents after last owned line
if contents:
new_lines = _format_contents(contents).split("\n")
for k, cl in enumerate(new_lines):
lines.insert(last_owned + 1 + k, cl)
def _patch_bios_entries(text: str, files: list[dict]) -> str:
"""Patch contents, source_ref and required of bios_zip entries in-place.
@@ -469,8 +545,6 @@ def _patch_bios_entries(text: str, files: list[dict]) -> str:
lines that follow (4+ spaces), stopping at blank lines, comments,
or the next `- name:`.
"""
import re
patches: dict[str, dict] = {}
for fe in files:
if fe.get("category") != "bios_zip":
@@ -491,71 +565,8 @@ def _patch_bios_entries(text: str, files: list[dict]) -> str:
# Process in reverse so line insertions don't shift indices
for idx in range(len(entry_starts) - 1, -1, -1):
start_line, entry_name = entry_starts[idx]
if entry_name not in patches:
continue
fe = patches[entry_name]
contents = fe.get("contents", [])
source_ref = fe.get("source_ref", "")
# Find the last "owned" line of this entry
# Owned = indented with 4+ spaces (field lines of this entry)
last_owned = start_line
for j in range(start_line + 1, len(lines)):
stripped = lines[j].strip()
if not stripped:
break # blank line = end of entry
if stripped.startswith("#"):
break # comment = belongs to next entry
if re.match(r"^ - ", lines[j]):
break # next list item
if re.match(r"^ ", lines[j]) or re.match(r"^ \w", lines[j]):
last_owned = j
else:
break
# Patch source_ref in-place
if source_ref:
found_sr = False
for j in range(start_line + 1, last_owned + 1):
if re.match(r"^ source_ref:", lines[j]):
lines[j] = f' source_ref: "{source_ref}"'
found_sr = True
break
if not found_sr:
lines.insert(last_owned + 1, f' source_ref: "{source_ref}"')
last_owned += 1
# The source settles required for a set the machine runs without
if "required" in fe:
for j in range(start_line + 1, last_owned + 1):
if re.match(r"^ required:", lines[j]):
lines[j] = f" required: {str(fe['required']).lower()}"
break
# Remove existing contents block if present
contents_start = None
contents_end = None
for j in range(start_line + 1, last_owned + 1):
if re.match(r"^ contents:", lines[j]):
contents_start = j
elif contents_start is not None:
if re.match(r"^ ", lines[j]):
contents_end = j
else:
break
if contents_end is None and contents_start is not None:
contents_end = contents_start
if contents_start is not None:
del lines[contents_start : contents_end + 1]
last_owned -= contents_end - contents_start + 1
# Insert new contents after last owned line
if contents:
new_lines = _format_contents(contents).split("\n")
for k, cl in enumerate(new_lines):
lines.insert(last_owned + 1 + k, cl)
if entry_name in patches:
_patch_entry(lines, start_line, patches[entry_name])
return "\n".join(lines)
+10 -22
View File
@@ -21,28 +21,16 @@ import re
from collections.abc import Callable
from typing import Any
try:
from .configgen_launchers import Launcher, Source
from .shell_launchers import (
LauncherPatternMissing,
Script,
config_placement,
describe_keys,
evidence_fields,
settings,
source_ref,
)
except ImportError:
from configgen_launchers import Launcher, Source # type: ignore[no-redef]
from shell_launchers import ( # type: ignore[no-redef]
LauncherPatternMissing,
Script,
config_placement,
describe_keys,
evidence_fields,
settings,
source_ref,
)
from .configgen_launchers import Launcher, Source
from .shell_launchers import (
LauncherPatternMissing,
Script,
config_placement,
describe_keys,
evidence_fields,
settings,
source_ref,
)
BIOS = "/storage/roms/bios"
RUNEMU = "packages/amberelec/sources/scripts/runemu.py"
+129 -91
View File
@@ -37,8 +37,8 @@ from __future__ import annotations
import argparse
import ast
import functools
import hashlib
import io
import json
import re
import sys
@@ -48,6 +48,7 @@ from collections import Counter
from collections.abc import Callable, Iterator
from dataclasses import dataclass, field
from pathlib import Path
from typing import IO
from ..artifacts import write_if_changed
from ..common import load_emulator_profiles, run_cli
@@ -137,7 +138,7 @@ def _attrs(raw: bytes) -> dict[str, str]:
return {k.decode(): v.decode() for k, v in _ATTR.findall(raw)}
def iter_sets(stream: io.BufferedIOBase) -> Iterator[SetEntry]:
def iter_sets(stream: IO[bytes]) -> Iterator[SetEntry]:
"""Every machine or game element of a DAT or -listxml, streamed.
Attributes come in any order (mame2003 writes ``<game runnable="no"
@@ -309,7 +310,7 @@ def _fbneo_driver_names(entries: list[SetEntry], names: dict[str, set[str]]) ->
def fbneo_sets(
openers: list[Callable[[], io.BufferedIOBase]], names: dict[str, set[str]]
openers: list[Callable[[], IO[bytes]]], names: dict[str, set[str]]
) -> tuple[dict[str, SetEntry], dict[str, str]]:
"""Every set of FBNeo's DATs keyed by its driver, and the archive of each
set whose driver name is not its archive name.
@@ -634,55 +635,72 @@ class _Preprocessor:
out.append(line)
continue
word, rest = directive.groups()
if word in ("if", "ifdef", "ifndef"):
if not active:
stack.append((False, True, False))
continue
if word == "if":
value = bool(_condition_value(rest, defines))
else:
value = (rest.split()[0] in defines) == (word == "ifdef")
stack.append((True, value, value))
active = value
elif word in ("elif", "else"):
if not stack:
raise DriverSourceError(f"{path}: #{word} without #if")
outer, taken, _ = stack[-1]
value = (
outer and not taken
and (word == "else" or bool(_condition_value(rest, defines)))
)
stack[-1] = (outer, taken or value, value)
active = value
elif word == "endif":
if not stack:
raise DriverSourceError(f"{path}: #endif without #if")
stack.pop()
active = stack[-1][2] if stack else True
elif not active:
continue
elif word == "define":
head = _MACRO_HEAD.match(rest)
if head:
defines[head.group(1)] = head.group(3)
if local is not None:
params = head.group(2)
local[head.group(1)] = (
[a.strip() for a in params[1:-1].split(",")] if params else None,
head.group(3),
)
elif word == "undef":
defines.pop(rest.strip(), None)
elif word == "include":
target = _INCLUDE.match(rest)
header = self._resolve(target.group(1), path) if target else None
if header and header not in seen:
seen.add(header)
self.run(header, self.headers[header], defines, None, seen)
if word in _CONDITIONALS:
active = _branch(path, word, rest, defines, stack, active)
elif active:
self._define(path, word, rest, defines, local, seen)
if stack:
raise DriverSourceError(f"{path}: #if without #endif")
return "\n".join(out)
def _define(
self, path: str, word: str, rest: str, defines: dict[str, str],
local: dict[str, tuple[list[str] | None, str]] | None, seen: set[str],
) -> None:
"""#define, #undef and #include in an active region."""
if word == "define":
head = _MACRO_HEAD.match(rest)
if head:
defines[head.group(1)] = head.group(3)
if local is not None:
params = head.group(2)
local[head.group(1)] = (
[a.strip() for a in params[1:-1].split(",")] if params else None,
head.group(3),
)
elif word == "undef":
defines.pop(rest.strip(), None)
elif word == "include":
target = _INCLUDE.match(rest)
header = self._resolve(target.group(1), path) if target else None
if header and header not in seen:
seen.add(header)
self.run(header, self.headers[header], defines, None, seen)
_CONDITIONALS = frozenset({"if", "ifdef", "ifndef", "elif", "else", "endif"})
def _branch(
path: str, word: str, rest: str, defines: dict[str, str],
stack: list[tuple[bool, bool, bool]], active: bool,
) -> bool:
"""Apply one conditional directive to *stack*. Returns the new active state."""
if word in ("if", "ifdef", "ifndef"):
if not active:
stack.append((False, True, False))
return active
if word == "if":
value = bool(_condition_value(rest, defines))
else:
value = (rest.split()[0] in defines) == (word == "ifdef")
stack.append((True, value, value))
return value
if word in ("elif", "else"):
if not stack:
raise DriverSourceError(f"{path}: #{word} without #if")
outer, taken, _ = stack[-1]
value = (
outer and not taken
and (word == "else" or bool(_condition_value(rest, defines)))
)
stack[-1] = (outer, taken or value, value)
return value
if not stack:
raise DriverSourceError(f"{path}: #endif without #if")
stack.pop()
return stack[-1][2] if stack else True
def _dumped(args: list[str]) -> bool:
"""A ROM_LOAD whose ROM was dumped: 0.78 writes ``NO_DUMP`` in the hash
@@ -693,6 +711,10 @@ def _dumped(args: list[str]) -> bool:
return not re.fullmatch(r"0[xX]0+|0", crc.strip())
def _argument(values: dict[str, str], match: re.Match[str]) -> str:
return values.get(match.group(0), match.group(0))
def _expand_declarations(text: str, local: dict[str, tuple[list[str] | None, str]]) -> str:
"""Calls of a file's own function-like macros that write a ROM_START or a
GAME line, expanded (pgm.c builds every DoDonPachi II set through
@@ -716,7 +738,7 @@ def _expand_declarations(text: str, local: dict[str, tuple[list[str] | None, str
raise DriverSourceError(f"{match.group(1)} called with {len(args)} arguments")
values = dict(zip(params, args))
out.append(text[position : match.start()])
out.append(_IDENTIFIER.sub(lambda m: values.get(m.group(0), m.group(0)), body))
out.append(_IDENTIFIER.sub(functools.partial(_argument, values), body))
position = end
out.append(text[position:])
return "".join(out)
@@ -732,6 +754,50 @@ def compiled_drivers(driver_c: str, preprocessor: _Preprocessor) -> list[str]:
return [n for n in _DRIVER_ENTRY.findall(text) if n != "NAME"]
def _holds_roms(
body: str, local: dict[str, tuple[list[str] | None, str]], known: dict[str, bool],
seen: frozenset[str] = frozenset(),
) -> bool:
for match in _ROM_LOAD.finditer(body):
if _dumped(_call_args(body, match.end())):
return True
# A ROM list shared through a macro of the same file (a BIOS
# block every game of the board pulls in).
for word in set(_IDENTIFIER.findall(body)) - seen:
if word in local:
if word not in known:
known[word] = _holds_roms(local[word][1], local, known, seen | {word})
if known[word]:
return True
return False
def _read_driver(
path: str, source: str, preprocessor: _Preprocessor,
declared: dict[str, tuple[str | None, bool]], roms: dict[str, tuple[bool, bool]],
) -> None:
"""The ROM_START blocks and GAME declarations of one driver file."""
local: dict[str, tuple[list[str] | None, str]] = {}
text = _expand_declarations(preprocessor.run(path, source, {}, local, set()), local)
known: dict[str, bool] = {}
for match in _ROM_START.finditer(text):
body = match.group(2)
roms.setdefault(
match.group(1), (_holds_roms(body, local, known), bool(_DISK_IMAGE.search(body)))
)
for match in _GAME_MACRO.finditer(text):
args = _call_args(text, match.end())
if len(args) < 9:
raise DriverSourceError(f"{path}: {match.group(1)} with {len(args)} arguments")
name, parent = args[1], args[2]
if name in declared:
raise DriverSourceError(f"{path}: {name} declared twice")
declared[name] = (
None if parent == "0" else parent,
any("NOT_A_DRIVER" in a for a in args[3:]),
)
def driver_source_sets(
driver_c: str, drivers: dict[str, str], headers: dict[str, str]
) -> dict[str, SetEntry]:
@@ -746,38 +812,7 @@ def driver_source_sets(
declared: dict[str, tuple[str | None, bool]] = {}
roms: dict[str, tuple[bool, bool]] = {}
for path, source in sorted(drivers.items()):
local: dict[str, tuple[list[str] | None, str]] = {}
text = _expand_declarations(preprocessor.run(path, source, {}, local, set()), local)
known: dict[str, bool] = {}
def holds_roms(body: str, seen: frozenset[str] = frozenset()) -> bool:
for match in _ROM_LOAD.finditer(body):
if _dumped(_call_args(body, match.end())):
return True
# A ROM list shared through a macro of the same file (a BIOS
# block every game of the board pulls in).
for word in set(_IDENTIFIER.findall(body)) - seen:
if word in local:
if word not in known:
known[word] = holds_roms(local[word][1], seen | {word})
if known[word]:
return True
return False
for match in _ROM_START.finditer(text):
body = match.group(2)
roms.setdefault(match.group(1), (holds_roms(body), bool(_DISK_IMAGE.search(body))))
for match in _GAME_MACRO.finditer(text):
args = _call_args(text, match.end())
if len(args) < 9:
raise DriverSourceError(f"{path}: {match.group(1)} with {len(args)} arguments")
name, parent = args[1], args[2]
if name in declared:
raise DriverSourceError(f"{path}: {name} declared twice")
declared[name] = (
None if parent == "0" else parent,
any("NOT_A_DRIVER" in a for a in args[3:]),
)
_read_driver(path, source, preprocessor, declared, roms)
compiled = compiled_drivers(driver_c, preprocessor)
undeclared = [n for n in compiled if n not in declared]
if undeclared:
@@ -973,7 +1008,11 @@ def _cached_repo_file(slug: str, commit: str, path: str, cache_dir: Path) -> tup
return destination, git_blob_sha(destination.read_bytes())
def _xml_streams(path: Path) -> Iterator[Callable[[], io.BufferedIOBase]]:
def _file_opener(path: Path) -> Callable[[], IO[bytes]]:
return lambda: path.open("rb")
def _xml_streams(path: Path) -> Iterator[Callable[[], IO[bytes]]]:
"""Openers for the XML documents a file holds: itself, or each XML or
DAT member of a ZIP."""
if path.suffix.lower() != ".zip":
@@ -984,16 +1023,15 @@ def _xml_streams(path: Path) -> Iterator[Callable[[], io.BufferedIOBase]]:
n for n in archive.namelist() if n.lower().endswith((".xml", ".dat"))
)
for member in names:
def opener(member: str = member) -> io.BufferedIOBase:
archive = zipfile.ZipFile(path)
stream = archive.open(member)
stream.close_archive = archive # keep the archive alive
return stream
def opener(member: str = member) -> IO[bytes]:
# The member keeps the archive alive: its shared file closes
# through the archive's own _fpclose.
return zipfile.ZipFile(path).open(member)
yield opener
def read_sets(openers: list[Callable[[], io.BufferedIOBase]]) -> dict[str, SetEntry]:
def read_sets(openers: list[Callable[[], IO[bytes]]]) -> dict[str, SetEntry]:
"""Every set of several documents. A set read twice keeps its first
reading: FBNeo's Arcade and Neogeo DATs both carry the neogeo BIOS."""
sets: dict[str, SetEntry] = {}
@@ -1024,6 +1062,8 @@ def import_profile(
commit = str(data.get("source_commit") or "")
source_url = str(data.get("source") or "")
kind = spec["kind"]
source: dict[str, object]
openers: list[Callable[[], IO[bytes]]]
if kind == "listxml":
tag = "mame" + str(data["core_version"]).replace(".", "").zfill(4)
if offline:
@@ -1060,9 +1100,7 @@ def import_profile(
FBNEO_DRIVERLIST: listing_sha,
},
}
openers = [
(lambda p=folder / name: p.open("rb")) for name in sorted(blobs)
]
openers = [_file_opener(folder / name) for name in sorted(blobs)]
sets, archives = fbneo_sets(openers, fbneo_drivers(listing.read_text(encoding="utf-8")))
index = build_index(sets, spec["marker"], archives)
elif kind == "source":
+119 -99
View File
@@ -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:
+182 -122
View File
@@ -15,6 +15,7 @@ launcher looks for nothing".
from __future__ import annotations
import ast
import posixpath
import re
from collections.abc import Callable, Iterable
from typing import Any
@@ -23,6 +24,8 @@ from .configgen_launchers import (
Launcher,
LauncherShapeError,
Source,
assigned_value,
end_line,
_assigned_name,
_calls,
_enclosing_test,
@@ -56,7 +59,7 @@ def _config_option(node: ast.AST) -> tuple[str, Any] | None:
return None
second = node.args[1] if len(node.args) > 1 else None
default = second.value if isinstance(second, ast.Constant) else None
return node.args[0].value, default
return str(node.args[0].value), default
def _option_names(node: ast.AST) -> list[str]:
@@ -86,10 +89,11 @@ def path_constants(source: Source) -> dict[str, str]:
"""batoceraPaths' module constants that are plain paths."""
constants: dict[str, str] = {}
for node in source.tree.body:
name = _assigned_name(node)
if name is None:
assigned = assigned_value(node)
if assigned is None:
continue
value = _path_value(node.value, constants) # type: ignore[union-attr]
name, expr = assigned
value = _path_value(expr, constants)
if value is not None:
constants[name] = value
if "BIOS" not in constants:
@@ -104,8 +108,6 @@ def configs_root(cg: Configgen) -> dict[str, str]:
starts an emulator from (shadPS4's configs/shadps4), with the lines that
build it and BIOS.
"""
import posixpath
src = cg.source(f"{cg.generators.rsplit('/', 1)[0]}/batoceraPaths.py")
if "CONFIGS" not in cg.paths:
src.fail("no CONFIGS path constant")
@@ -227,10 +229,10 @@ class Configgen:
value = node.value.strip('"')
prefix = self.bios.rstrip("/") + "/"
return value[len(prefix):] if value.startswith(prefix) else None
value = _path_value(node, self.paths)
path = _path_value(node, self.paths)
prefix = self.bios.rstrip("/") + "/"
if value is not None and value.startswith(prefix):
return value[len(prefix):]
if path is not None and path.startswith(prefix):
return path[len(prefix):]
return None
def option_name(self, node: ast.AST) -> tuple[str, str] | None:
@@ -252,7 +254,7 @@ class Configgen:
return option[1], option[0]
def _raise_message(source: Source, scope: ast.AST, guard: str) -> str:
def _raise_message(source: Source, scope: ast.AST, guard: str | None) -> str:
"""The message of `if not <guard>: raise X("...")` in scope."""
for node in ast.walk(scope):
if (
@@ -266,7 +268,7 @@ def _raise_message(source: Source, scope: ast.AST, guard: str) -> str:
exc = node.body[0].exc
if isinstance(exc, ast.Call) and exc.args and isinstance(exc.args[0], ast.Constant):
return str(exc.args[0].value)
source.fail(f"no `if not {guard}: raise` with a message")
return source.fail(f"no `if not {guard}: raise` with a message")
def _string_lists(source: Source, node: ast.AST, what: str) -> dict[str, list[str]]:
@@ -291,13 +293,13 @@ def duckstation(cg: Configgen) -> list[Launcher]:
lists = _string_lists(src, lists_node.value, "bios_lists")
finder = src.function("find_bios")
listed = [
call for call in _calls(finder, attr="iterdir")
if isinstance(call.func.value, ast.Name) # type: ignore[attr-defined]
call.func.value.id for call in _calls(finder, attr="iterdir")
if isinstance(call.func, ast.Attribute) and isinstance(call.func.value, ast.Name)
]
lowered = _calls(finder, attr="lower")
if len(listed) != 1 or not lowered:
src.fail("find_bios no longer lists the BIOS directory and compares lowercased names")
search_dir = cg.paths.get(listed[0].func.value.id) # type: ignore[attr-defined]
search_dir = cg.paths.get(listed[0])
if search_dir is None:
src.fail("find_bios lists a directory that is not a batoceraPaths constant")
@@ -320,7 +322,7 @@ def duckstation(cg: Configgen) -> list[Launcher]:
src.assignment("region_mapping", generate).value, "region_mapping"
)
branches = [
node for node in ast.walk(generate)
(node, node.test.left.value) for node in ast.walk(generate)
if isinstance(node, ast.If)
and isinstance(node.test, ast.Compare)
and isinstance(node.test.left, ast.Constant)
@@ -329,9 +331,11 @@ def duckstation(cg: Configgen) -> list[Launcher]:
]
if len(branches) != 1:
src.fail(f"generate no longer branches once on a slot found in {found_var}")
branch = branches[0]
branch, branch_slot = branches[0]
writes = _calls(branch, attr="set")
sections = {call.args[0].value for call in writes if isinstance(call.args[0], ast.Constant)}
sections = {
str(call.args[0].value) for call in writes if isinstance(call.args[0], ast.Constant)
}
if len(sections) != 1 or not any(
isinstance(call.args[1], ast.Subscript)
and ast.unparse(call.args[1].value) == "region_mapping"
@@ -340,16 +344,16 @@ def duckstation(cg: Configgen) -> list[Launcher]:
src.fail("the region paths are not written to one config section through region_mapping")
section = sections.pop()
shared = {
branch.test.left.value: [
call.args[1].value for stmt in branch.body for call in _calls(stmt, attr="set")
branch_slot: [
str(call.args[1].value) for stmt in branch.body for call in _calls(stmt, attr="set")
if isinstance(call.args[1], ast.Constant)
]
}
first, last = _run(body, index, lambda stmt: _mentions(stmt, {section}, {found_var}))
ref = src.ref([
(src.span(first)[0], last.end_lineno),
(finder.lineno, finder.end_lineno),
(src.span(first)[0], end_line(last)),
(finder.lineno, end_line(finder)),
src.span(lists_node),
])
launchers = []
@@ -379,7 +383,10 @@ def duckstation_legacy(cg: Configgen) -> list[Launcher]:
and isinstance(node.target, ast.Name)
):
continue
test = node.body[0].test if isinstance(node.body[0], ast.If) else None
guard = node.body[0]
if not isinstance(guard, ast.If):
continue
test = guard.test
if not (
isinstance(test, ast.Call)
and isinstance(test.func, ast.Attribute)
@@ -390,11 +397,11 @@ def duckstation_legacy(cg: Configgen) -> list[Launcher]:
):
continue
bound = {
_assigned_name(stmt): stmt for stmt in node.body[0].body
_assigned_name(stmt): stmt for stmt in guard.body
if isinstance(stmt, ast.Assign) and ast.unparse(stmt.value) == node.target.id
}
flags = {
_assigned_name(stmt) for stmt in node.body[0].body
_assigned_name(stmt) for stmt in guard.body
if isinstance(stmt, ast.Assign)
and isinstance(stmt.value, ast.Constant)
and stmt.value.value is True
@@ -414,20 +421,30 @@ def duckstation_legacy(cg: Configgen) -> list[Launcher]:
writes: dict[str, tuple[str, str]] = {}
for call in _calls(generate, attr="set"):
if len(call.args) != 3:
continue
section_node, key_node, var_node = call.args
if (
len(call.args) == 3
and all(isinstance(a, ast.Constant) for a in call.args[:2])
and isinstance(call.args[2], ast.Name)
isinstance(section_node, ast.Constant)
and isinstance(key_node, ast.Constant)
and isinstance(var_node, ast.Name)
):
writes[call.args[2].id] = (call.args[0].value, call.args[1].value)
writes[var_node.id] = (str(section_node.value), str(key_node.value))
list_nodes = {name: src.assignment(name, generate) for name, _v, _f, _d in loops}
tracked = {*list_nodes, *(v for _l, v, _f, _d in loops), flag}
first_list = min(list_nodes.values(), key=lambda node: node.lineno)
body, index = _locate(generate, lambda stmt: stmt is first_list) # type: ignore[misc]
# A name never bound (None) is mentioned by no statement.
tracked = {
name for name in (*list_nodes, *(v for _l, v, _f, _d in loops), flag)
if name is not None
}
first_list = min(list_nodes.values(), key=lambda node: node.lineno).node
located = _locate(generate, lambda stmt: stmt is first_list)
if located is None:
src.fail(f"line {first_list.lineno} is outside generate")
body, index = located
sections = {section for section, _key in writes.values()}
first, last = _run(body, index, lambda stmt: _mentions(stmt, sections, tracked))
ref = src.ref([(src.span(first)[0], last.end_lineno)])
ref = src.ref([(src.span(first)[0], end_line(last))])
launchers = []
for list_name, var, _flag, _dir in loops:
@@ -482,20 +499,8 @@ def _trace(body: list[ast.stmt], index: int) -> list[ast.stmt]:
return sorted(kept, key=lambda stmt: stmt.lineno)
def hatari(cg: Configgen) -> list[Launcher]:
"""findBestTos: per machine, each TOS version in each language."""
module = "hatari.hatariGenerator"
src = cg.generator(module)
finder = src.function("findBestTos")
languages = src.literal(src.assignment("all_languages", finder).value, "all_languages")
machines = _string_lists(
src, src.assignment("all_machines_bios", finder).value, "all_machines_bios"
)
if not (
isinstance(languages, list) and languages and all(isinstance(x, str) for x in languages)
):
src.fail("all_languages is not a list of strings")
def _tos_name_parts(src: Source, finder: ast.FunctionDef) -> tuple[str, str, str]:
"""(marker, prefix, suffix) of the names findBestTos builds."""
marker = prefix = suffix = None
for node in ast.walk(finder):
if (
@@ -513,7 +518,7 @@ def hatari(cg: Configgen) -> list[Launcher]:
and isinstance(parts[0], ast.Constant)
and isinstance(parts[1], ast.FormattedValue)
):
marker, prefix = node.test.left.value, parts[0].value
marker, prefix = str(node.test.left.value), str(parts[0].value)
# Batocera: tos_path = biosdir / f"{biosversion}{v_language}.img".
# KNULLI: filename = f"{biosversion}{v_language}.img".
names_built = []
@@ -528,11 +533,55 @@ def hatari(cg: Configgen) -> list[Launcher]:
and all(isinstance(p, ast.FormattedValue) for p in parts[:2])
and isinstance(parts[2], ast.Constant)
):
names_built.append(parts[2].value)
names_built.append(str(parts[2].value))
if len(names_built) == 1:
suffix = names_built[0]
if marker is None or prefix is None or suffix is None:
src.fail("findBestTos no longer builds <tos{version} or etos*><language>.img")
return marker, prefix, suffix
def _tos_command_args(
kept: list[ast.stmt], *, machine_var: str | None, tos_var: str | None,
search_dir: str, paths: dict[str, str],
) -> list[str]:
"""The command-line additions of the traced statements, the TOS as <file>."""
args: list[str] = []
for stmt in kept:
if isinstance(stmt, ast.AugAssign) and isinstance(stmt.value, ast.List):
for element in stmt.value.elts:
if isinstance(element, ast.Constant):
args.append(str(element.value))
elif isinstance(element, ast.Name) and element.id == machine_var:
args.append("{machine}")
elif isinstance(element, ast.Name) and element.id == tos_var:
args.append("<file>")
elif (
isinstance(element, ast.BinOp)
and isinstance(element.right, ast.Name)
and element.right.id == tos_var
and _path_value(element.left, paths) == search_dir
):
# KNULLI returns the bare name and joins it: BIOS / tos.
args.append("<file>")
return args
def hatari(cg: Configgen) -> list[Launcher]:
"""findBestTos: per machine, each TOS version in each language."""
module = "hatari.hatariGenerator"
src = cg.generator(module)
finder = src.function("findBestTos")
languages = src.literal(src.assignment("all_languages", finder).value, "all_languages")
machines = _string_lists(
src, src.assignment("all_machines_bios", finder).value, "all_machines_bios"
)
if not (
isinstance(languages, list) and languages and all(isinstance(x, str) for x in languages)
):
src.fail("all_languages is not a list of strings")
marker, prefix, suffix = _tos_name_parts(src, finder)
raised = [node for node in ast.walk(finder) if isinstance(node, ast.Raise)]
exc = raised[0].exc if len(raised) == 1 else None
if not (isinstance(exc, ast.Call) and exc.args and isinstance(exc.args[0], ast.JoinedStr)):
@@ -548,34 +597,21 @@ def hatari(cg: Configgen) -> list[Launcher]:
if located is None:
src.fail("generate no longer calls findBestTos")
body, index = located
call = body[index].value # type: ignore[attr-defined]
found = body[index]
if not (isinstance(found, ast.Assign) and isinstance(found.value, ast.Call)):
src.fail("generate no longer calls findBestTos")
call = found.value
if not call.args or not isinstance(call.args[0], ast.Name) or call.args[0].id not in cg.paths:
src.fail("findBestTos is not given a batoceraPaths directory")
search_dir = cg.paths[call.args[0].id]
kept = _trace(body, index)
options = list(dict.fromkeys(name for stmt in kept for name in _option_names(stmt)))
spans = [src.span(stmt) for stmt in kept] + [(finder.lineno, finder.end_lineno)]
args: list[str] = []
spans = [src.span(stmt) for stmt in kept] + [(finder.lineno, end_line(finder))]
second = call.args[1] if len(call.args) > 1 else None
machine_var = second.id if isinstance(second, ast.Name) else None
tos_var = _assigned_name(body[index])
for stmt in kept:
if isinstance(stmt, ast.AugAssign) and isinstance(stmt.value, ast.List):
for element in stmt.value.elts:
if isinstance(element, ast.Constant):
args.append(str(element.value))
elif isinstance(element, ast.Name) and element.id == machine_var:
args.append("{machine}")
elif isinstance(element, ast.Name) and element.id == tos_var:
args.append("<file>")
elif (
isinstance(element, ast.BinOp)
and isinstance(element.right, ast.Name)
and element.right.id == tos_var
and _path_value(element.left, cg.paths) == search_dir
):
# KNULLI returns the bare name and joins it: BIOS / tos.
args.append("<file>")
args = _tos_command_args(
kept, machine_var=second.id if isinstance(second, ast.Name) else None,
tos_var=_assigned_name(found), search_dir=search_dir, paths=cg.paths,
)
if "<file>" not in args:
src.fail("the TOS findBestTos returns is not put on the command line")
@@ -605,11 +641,14 @@ def _config_writes(cg: Configgen, src: Source, emulator: str) -> Launcher:
"""parser.set(section, key, <path under BIOS>) calls of one module."""
writes = []
for call in _calls(src.tree, attr="set"):
if len(call.args) != 3 or not all(isinstance(a, ast.Constant) for a in call.args[:2]):
if len(call.args) != 3:
continue
name = cg.bios_name(call.args[2])
section_node, key_node, path = call.args
if not (isinstance(section_node, ast.Constant) and isinstance(key_node, ast.Constant)):
continue
name = cg.bios_name(path)
if name is not None:
writes.append((call, call.args[0].value, call.args[1].value, name))
writes.append((call, str(section_node.value), str(key_node.value), name))
if not writes:
src.fail("writes no /userdata/bios path into its config")
spans = []
@@ -666,27 +705,31 @@ def melonds(cg: Configgen) -> list[Launcher]:
]
if len(console) != 1 or len(enabled) != 1:
src.fail("generate no longer sets Emu.ConsoleType from an option with external BIOS on")
option = _option_names(console[0].value)[0] # type: ignore[attr-defined]
option = _option_names(console[0].value)[0]
enabled_key, enabled_value = enabled[0]
if enabled_key is None:
src.fail("base_config unpacks the section that enables the external BIOS")
launchers = []
for key, value in zip(base.value.keys, base.value.values):
if not isinstance(value, ast.Dict) or not isinstance(key, ast.Constant):
continue
entries = [
(k.value, cg.bios_name(v)) for k, v in zip(value.keys, value.values)
read = [
(str(k.value), cg.bios_name(v)) for k, v in zip(value.keys, value.values)
if isinstance(k, ast.Constant)
]
entries = [(k, name) for k, name in entries if name is not None]
entries = [(k, name) for k, name in read if name is not None]
if not entries:
continue
section = str(key.value)
launchers.append(Launcher(
emulator=cg.emulator(module), build="standalone", kind="fixed_name",
names=[name for _k, name in entries], case_insensitive=False,
search_dir=cg.bios,
passes_to=", ".join(f"{key.value}.{k}" for k, _n in entries),
passes_to=", ".join(f"{section}.{k}" for k, _n in entries),
depends_on_option=option,
source_ref=src.ref([
(key.lineno, value.end_lineno),
(enabled[0][0].lineno, enabled[0][1].end_lineno),
(key.lineno, end_line(value)),
(enabled_key.lineno, end_line(enabled_value)),
src.span(console[0]),
]),
))
@@ -704,17 +747,20 @@ def x16emu(cg: Configgen) -> list[Launcher]:
if isinstance(node, ast.List):
for flag, value in zip(node.elts, node.elts[1:]):
name = cg.bios_name(value)
is_flag = isinstance(flag, ast.Constant) and str(flag.value).startswith("-")
if is_flag and name is not None:
found.append((flag, value, name))
if (
isinstance(flag, ast.Constant)
and str(flag.value).startswith("-")
and name is not None
):
found.append((flag, str(flag.value), value, name))
if not found:
src.fail("the command line passes no /userdata/bios path")
return [Launcher(
emulator=cg.emulator(module), build="standalone", kind="fixed_name",
names=[name for _f, _v, name in found], case_insensitive=False,
names=[name for _f, _t, _v, name in found], case_insensitive=False,
search_dir=cg.bios,
passes_to=", ".join(f"command line {f.value}" for f, _v, _n in found),
source_ref=src.ref([(f.lineno, v.end_lineno) for f, v, _n in found]),
passes_to=", ".join(f"command line {text}" for _f, text, _v, _n in found),
source_ref=src.ref([(f.lineno, end_line(v)) for f, _t, v, _n in found]),
)]
@@ -727,7 +773,7 @@ def gsplus(cg: Configgen) -> list[Launcher]:
if len(call.args) == 2 and isinstance(call.args[0], ast.Constant):
named = cg.option_name(call.args[1])
if named is not None:
found.append((call, call.args[0].value, *named))
found.append((call, str(call.args[0].value), *named))
if len(found) != 1:
src.fail(f"expected one ROM path built from an option, found {len(found)}")
call, key, name, option = found[0]
@@ -762,19 +808,29 @@ def _guard_message(
) -> tuple[ast.If, ast.JoinedStr]:
"""The `if not <test>: raise X(f"...")` statement and its message."""
found = [
node for node in ast.walk(scope)
(node, message) for node in ast.walk(scope)
if isinstance(node, ast.If)
and isinstance(node.test, ast.UnaryOp)
and isinstance(node.test.op, ast.Not)
and test(node.test.operand)
and isinstance(node.body[0], ast.Raise)
and isinstance(node.body[0].exc, ast.Call)
and node.body[0].exc.args
and isinstance(node.body[0].exc.args[0], ast.JoinedStr)
and (message := _raised_fstring(node)) is not None
]
if len(found) != 1:
src.fail(f"expected one `if not {what}: raise` with a message, found {len(found)}")
return found[0], found[0].body[0].exc.args[0] # type: ignore[attr-defined, no-any-return]
return found[0]
def _raised_fstring(node: ast.If) -> ast.JoinedStr | None:
"""The f-string message of `raise X(f"...")` opening the if body."""
first = node.body[0]
if (
isinstance(first, ast.Raise)
and isinstance(first.exc, ast.Call)
and first.exc.args
and isinstance(first.exc.args[0], ast.JoinedStr)
):
return first.exc.args[0]
return None
def _render(message: ast.JoinedStr, var: str, value: str) -> str:
@@ -782,10 +838,13 @@ def _render(message: ast.JoinedStr, var: str, value: str) -> str:
for part in message.values:
if isinstance(part, ast.Constant):
parts.append(str(part.value))
elif isinstance(part.value, ast.Name) and part.value.id == var: # type: ignore[attr-defined]
continue
# The other parts of an f-string are its {placeholders}.
expr = part.value if isinstance(part, ast.FormattedValue) else part
if isinstance(expr, ast.Name) and expr.id == var:
parts.append(value)
else:
parts.append(f"{{{ast.unparse(part.value)}}}") # type: ignore[attr-defined]
parts.append(f"{{{ast.unparse(expr)}}}")
return "".join(parts)
@@ -804,15 +863,17 @@ def lexaloffle(cg: Configgen) -> list[Launcher]:
generate = src.function("generate")
command = [
node for node in ast.walk(generate)
if _assigned_name(node) == "commandArray"
and isinstance(node.value, ast.List) # type: ignore[attr-defined]
and node.value.elts # type: ignore[attr-defined]
and isinstance(node.value.elts[0], ast.Name) # type: ignore[attr-defined]
(node, head.id) for node in ast.walk(generate)
if isinstance(node, (ast.Assign, ast.AnnAssign))
and (assigned := assigned_value(node)) is not None
and assigned[0] == "commandArray"
and isinstance(assigned[1], ast.List)
and assigned[1].elts
and isinstance((head := assigned[1].elts[0]), ast.Name)
]
if len(command) != 1:
src.fail("generate no longer starts commandArray with the binary it runs")
binary = command[0].value.elts[0].id # type: ignore[attr-defined]
command_stmt, binary = command[0]
exists, missing = _guard_message(src, generate, lambda test: (
isinstance(test, ast.Call)
@@ -842,35 +903,37 @@ def lexaloffle(cg: Configgen) -> list[Launcher]:
launchers = []
for system, branch in _system_branches(generate):
bound = {
name: (stmt, _path_value(stmt.value, constants)) # type: ignore[attr-defined]
for stmt in branch.body if (name := _assigned_name(stmt)) is not None
assigned[0]: (stmt, assigned[1], _path_value(assigned[1], constants))
for stmt in branch.body if (assigned := assigned_value(stmt)) is not None
}
if binary not in bound or not (bound[binary][1] or "").startswith(prefix):
if binary not in bound or not (bound[binary][2] or "").startswith(prefix):
src.fail(f"the {system} branch binds {binary} to no path under {cg.bios}")
library = [
name for name in bound
if name != binary and _mentions(env_value, set(), {name})
]
if len(library) != 1 or not (bound[library[0]][1] or "").startswith(prefix):
if len(library) != 1 or not (bound[library[0]][2] or "").startswith(prefix):
src.fail(f"the {system} branch puts no /userdata/bios folder on LD_LIBRARY_PATH")
binary_stmt, path = bound[binary]
library_stmt, folder = bound[library[0]]
binary_stmt, binary_value, path = bound[binary]
library_stmt, _library_value, folder = bound[library[0]]
if path is None:
src.fail(f"the {system} branch binds {binary} to no path under {cg.bios}")
test_line = src.span(branch.test)
constant = next(
(defined[n.id] for n in ast.walk(binary_stmt.value) # type: ignore[attr-defined]
(defined[n.id] for n in ast.walk(binary_value)
if isinstance(n, ast.Name) and n.id in defined),
None,
)
spans = [test_line, src.span(binary_stmt), src.span(exists), src.span(access),
src.span(command[0])]
src.span(command_stmt)]
if constant is not None:
spans.append(src.span(constant))
launchers.append(Launcher(
emulator=cg.emulator(module), build="standalone", kind="fixed_name",
slot=system, names=[path[len(prefix):]], # type: ignore[index]
slot=system, names=[path[len(prefix):]],
case_insensitive=False, search_dir=cg.bios, passes_to="exec",
fails_when_missing=", ".join(
_render(message, binary, path) for message in (missing, not_executable) # type: ignore[arg-type]
_render(message, binary, path) for message in (missing, not_executable)
),
source_ref=src.ref(spans),
))
@@ -893,7 +956,7 @@ ENVIRONMENT_GENERATORS = (("flycast.flycastGenerator", "flycast/flycastPaths.py"
def environment_directories(cg: Configgen) -> list[Launcher]:
"""Command(..., env={KEY: <path under BIOS>}) in the generator."""
launchers = []
launchers: list[Launcher] = []
for module, paths_module in ENVIRONMENT_GENERATORS:
src = cg.generator(module)
constants = dict(cg.paths)
@@ -904,7 +967,7 @@ def environment_directories(cg: Configgen) -> list[Launcher]:
constants[name] = value
prefix = cg.bios.rstrip("/")
found = [
(key.value, value, key)
(str(key.value), value, key)
for call in _calls(src.tree, attr="Command")
for keyword in call.keywords
if keyword.arg == "env" and isinstance(keyword.value, ast.Dict)
@@ -919,7 +982,7 @@ def environment_directories(cg: Configgen) -> list[Launcher]:
Launcher(
emulator=cg.emulator(module), build="standalone", kind="passes_path",
names=[], search_dir=value, passes_to=f"environment {key}",
source_ref=src.ref([(node.lineno, node.end_lineno)]),
source_ref=src.ref([(node.lineno, end_line(node))]),
)
for key, value, node in found
)
@@ -1032,7 +1095,7 @@ def core_file_options(cg: Configgen) -> list[Launcher]:
cores: dict[str, list[str]] = {}
for key, value in zip(table.keys, table.values):
if isinstance(key, ast.Constant) and isinstance(value, ast.Name):
cores.setdefault(value.id, []).append(key.value)
cores.setdefault(value.id, []).append(str(key.value))
launchers = []
for function_name, setting in FILE_OPTIONS:
function = src.function(function_name)
@@ -1048,17 +1111,17 @@ def core_file_options(cg: Configgen) -> list[Launcher]:
src.fail(f"{function_name} no longer sets {setting} once")
call = calls[0]
named = call.args[3] if len(call.args) > 3 else None
option = named.value if isinstance(named, ast.Constant) else setting
option = str(named.value) if isinstance(named, ast.Constant) else setting
default = next((k.value for k in call.keywords if k.arg == "default"), None)
if isinstance(default, ast.Constant):
names = [default.value]
names = [str(default.value)]
condition = None
elif (
isinstance(default, ast.IfExp)
and isinstance(default.body, ast.Constant)
and isinstance(default.orelse, ast.Constant)
):
names = [default.body.value, default.orelse.value]
names = [str(default.body.value), str(default.orelse.value)]
condition = ast.unparse(default.test)
else:
src.fail(f"{setting} has no literal default")
@@ -1127,10 +1190,7 @@ SEARCH_PATH_GENERATORS = ("mame/mameGenerator.py",)
def search_paths(cg: Configgen) -> list[Launcher]:
"""Every /userdata/bios path a generator's command line names, read as
KNULLI's generic reader reads its fork of the same generator."""
try:
from .knulli_launchers import GenericSites, bios_sites
except ImportError:
from knulli_launchers import GenericSites, bios_sites # type: ignore[no-redef]
from .knulli_launchers import GenericSites, bios_sites
# A boot disk image the command line names (the Macintosh's
# /userdata/bios/<boot_disk>.img) is a file, no search path.
return [
+45 -39
View File
@@ -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)
+7 -16
View File
@@ -20,22 +20,13 @@ from __future__ import annotations
import re
try:
from .base_scraper import (
requirement_entry,
BaseScraper,
BiosRequirement,
fetch_github_latest_version,
scraper_cli,
)
except ImportError:
from base_scraper import (
requirement_entry,
BaseScraper,
BiosRequirement,
fetch_github_latest_version,
scraper_cli,
)
from .base_scraper import (
requirement_entry,
BaseScraper,
BiosRequirement,
fetch_github_latest_version,
scraper_cli,
)
PLATFORM_NAME = "bizhawk"
+55 -15
View File
@@ -10,13 +10,30 @@ from __future__ import annotations
import ast
from collections.abc import Callable, Iterator
from dataclasses import dataclass
from typing import Any, NoReturn
from typing import Any, NoReturn, Protocol
class LauncherShapeError(ValueError):
"""A generator no longer has the shape its extractor reads."""
class Located(Protocol):
"""A node that carries source lines: a statement, an expression, an argument."""
@property
def lineno(self) -> int: ...
@property
def end_lineno(self) -> int | None: ...
def end_line(node: Located) -> int:
"""The last line of a parsed node, which ast.parse always sets."""
if node.end_lineno is None:
raise LauncherShapeError(f"node at line {node.lineno} has no end line")
return node.end_lineno
@dataclass
class Launcher:
"""One thing a launcher looks for or hands over, as its code says it."""
@@ -60,6 +77,22 @@ class Launcher:
return {key: getattr(self, key) for key in order if getattr(self, key) is not None}
@dataclass(frozen=True)
class Assignment:
"""A single-name assignment statement and the value it binds."""
node: ast.Assign | ast.AnnAssign
value: ast.expr
@property
def lineno(self) -> int:
return self.node.lineno
@property
def end_lineno(self) -> int | None:
return self.node.end_lineno
class Source:
"""One configgen file, parsed, with the lines its nodes span."""
@@ -83,27 +116,28 @@ class Source:
self.fail(f"expected one function {name}, found {len(found)}")
return found[0]
def assignment(self, name: str, scope: ast.AST | None = None) -> ast.Assign | ast.AnnAssign:
def assignment(self, name: str, scope: ast.AST | None = None) -> Assignment:
found = [
node for node in ast.walk(scope or self.tree)
if _assigned_name(node) == name
Assignment(node, assigned[1]) for node in ast.walk(scope or self.tree)
if isinstance(node, (ast.Assign, ast.AnnAssign))
and (assigned := assigned_value(node)) is not None and assigned[0] == name
]
if len(found) != 1:
self.fail(f"expected one assignment to {name}, found {len(found)}")
return found[0]
def literal(self, node: ast.AST | None, what: str) -> Any:
def literal(self, node: ast.AST, what: str) -> Any:
try:
return ast.literal_eval(node) # type: ignore[arg-type]
return ast.literal_eval(node)
except (ValueError, TypeError, SyntaxError) as e:
self.fail(f"{what} is not a literal: {e}")
def span(self, node: ast.AST) -> tuple[int, int]:
def span(self, node: Located) -> tuple[int, int]:
"""Lines of a node, with the comment lines written right above it."""
start = node.lineno # type: ignore[attr-defined]
start = node.lineno
while start > 1 and self.lines[start - 2].strip().startswith("#"):
start -= 1
return start, node.end_lineno # type: ignore[attr-defined]
return start, end_line(node)
def ref(self, spans: list[tuple[int, int]]) -> str:
"""`path:a-b, c-d`, ranges joined across blank and comment lines."""
@@ -123,14 +157,20 @@ class Source:
)
def _assigned_name(node: ast.AST) -> str | None:
def assigned_value(node: ast.AST) -> tuple[str, ast.expr] | None:
"""The name a single-name assignment binds, and the value it binds."""
if isinstance(node, ast.Assign) and len(node.targets) == 1:
target = node.targets[0]
target, value = node.targets[0], node.value
elif isinstance(node, ast.AnnAssign) and node.value is not None:
target = node.target
target, value = node.target, node.value
else:
return None
return target.id if isinstance(target, ast.Name) else None
return (target.id, value) if isinstance(target, ast.Name) else None
def _assigned_name(node: ast.AST) -> str | None:
assigned = assigned_value(node)
return assigned[0] if assigned is not None else None
def _statement_lists(node: ast.AST) -> Iterator[list[ast.stmt]]:
@@ -202,11 +242,11 @@ def _enclosing_test(scope: ast.AST, node: ast.AST) -> str | None:
return None
def _innermost_function(src: Source, node: ast.AST) -> ast.FunctionDef:
def _innermost_function(src: Source, node: ast.stmt | ast.expr) -> ast.FunctionDef:
holders = [
f for f in ast.walk(src.tree)
if isinstance(f, ast.FunctionDef) and any(child is node for child in ast.walk(f))
]
if not holders:
src.fail(f"line {node.lineno} is outside any function") # type: ignore[attr-defined]
src.fail(f"line {node.lineno} is outside any function")
return max(holders, key=lambda f: f.lineno)
+12 -16
View File
@@ -13,30 +13,26 @@ Complements libretro_scraper (System.dat) with:
from __future__ import annotations
import importlib
import json
import os
import re
import sys
import urllib.error
import urllib.request
try:
from .base_scraper import (
BaseScraper,
BiosRequirement,
fetch_github_latest_version,
github_headers,
)
except ImportError:
if not __package__:
# Allow running directly: python scripts/scraper/coreinfo_scraper.py
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from scraper.base_scraper import (
BaseScraper,
BiosRequirement,
fetch_github_latest_version,
github_headers,
)
importlib.import_module("scraper")
__package__ = "scraper"
from .base_scraper import (
BaseScraper,
BiosRequirement,
fetch_github_latest_version,
github_headers,
)
PLATFORM_NAME = "libretro_coreinfo"
+1 -1
View File
@@ -77,7 +77,7 @@ def import_pack(source: str, pack: Path) -> tuple[dict, list[dict], int]:
dats = {}
entries = []
skipped = 0
for member, content in _iter_dat_contents(pack):
for _member, content in _iter_dat_contents(pack):
try:
dat = parse_logiqx(content)
except (ValueError, SyntaxError):
+1 -1
View File
@@ -61,7 +61,7 @@ def parse_dat(content: str) -> list[DatRom]:
continue
current_system = value
elif stripped.startswith("rom (") or stripped.startswith("rom("):
elif stripped.startswith(("rom (", "rom(")):
rom = _parse_rom_line(stripped, current_system)
if rom:
roms.append(rom)
+28 -35
View File
@@ -14,28 +14,16 @@ import posixpath
import re
from collections.abc import Callable
try:
from .configgen_launchers import Launcher
from .shell_launchers import (
LauncherPatternMissing,
RepoTree,
Script,
describe_keys,
settings,
source_ref,
words,
)
except ImportError:
from configgen_launchers import Launcher
from shell_launchers import (
LauncherPatternMissing,
RepoTree,
Script,
describe_keys,
settings,
source_ref,
words,
)
from .configgen_launchers import Launcher
from .shell_launchers import (
LauncherPatternMissing,
RepoTree,
Script,
describe_keys,
settings,
source_ref,
words,
)
EMUSCRIPTS = "functions/EmuScripts"
CONFIGS = "configs"
@@ -170,7 +158,8 @@ def setter_records(tree: RepoTree, name: str, option_key: str | None = None) ->
"""
script = _script(tree, name)
emulator = _emulator(name)
records: list[Launcher] = []
# Each record with the config file it names.
records: list[tuple[Launcher, str]] = []
groups: dict[tuple[str, str], tuple[list[tuple[str, str]], list[str], set[int]]] = {}
for file, section, key, value, lines in setters(script):
config = posixpath.basename(file)
@@ -189,7 +178,7 @@ def setter_records(tree: RepoTree, name: str, option_key: str | None = None) ->
continue
if key not in DIRECTORY_KINDS:
raise script.missing(f"known directory key, got {key}")
records.append(
records.append((
Launcher(
emulator=emulator,
build="libretro" if emulator == "retroarch" else "standalone",
@@ -198,10 +187,11 @@ def setter_records(tree: RepoTree, name: str, option_key: str | None = None) ->
source_ref=source_ref([(script.path, lines)]),
search_dir=value,
passes_to=describe_keys(config, ((section, key),)),
)
)
),
config,
))
for (config, folder), (keys, names, refs) in groups.items():
records.append(
records.append((
Launcher(
emulator=emulator,
build="standalone",
@@ -210,19 +200,22 @@ def setter_records(tree: RepoTree, name: str, option_key: str | None = None) ->
source_ref=source_ref([(script.path, refs)]),
search_dir=folder,
passes_to=describe_keys(config, tuple(keys)),
)
)
),
config,
))
if not records:
raise script.missing(f"setter writing a path under {BIOS}")
if option_key:
for record in records:
_add_option(tree, script, record, option_key)
return records
for record, config in records:
# passes_to starts with the config name, cut at its first space.
_add_option(tree, script, record, config.split(" ", 1)[0], option_key)
return [record for record, _config in records]
def _add_option(tree: RepoTree, script: Script, record: Launcher, option_key: str) -> None:
def _add_option(
tree: RepoTree, script: Script, record: Launcher, config: str, option_key: str
) -> None:
"""depends_on_option from the value the shipped config gives option_key."""
config = record.passes_to.split(" ", 1)[0]
file_var = script.assignment_ending("/" + config)
if file_var is None:
raise script.missing(f"config variable for {config}")
@@ -395,7 +388,7 @@ def configured(tree: RepoTree) -> list[Launcher]:
def links(tree: RepoTree) -> list[Launcher]:
records = []
records: list[Launcher] = []
for name in LINK_SCRIPTS:
script = _script(tree, name)
found = script.links(BIOS)
+21 -33
View File
@@ -17,28 +17,16 @@ import re
import urllib.error
import urllib.request
try:
from .base_scraper import (
BaseScraper,
BiosRequirement,
fetch_branch_head,
fetch_github_latest_version,
github_headers,
requirement_entry,
)
from .emudeck_launchers import emulator_of_script, extract_launchers
from .shell_launchers import RepoTree
except ImportError:
from base_scraper import (
BaseScraper,
BiosRequirement,
fetch_branch_head,
fetch_github_latest_version,
github_headers,
requirement_entry,
)
from emudeck_launchers import emulator_of_script, extract_launchers
from shell_launchers import RepoTree
from .base_scraper import (
BaseScraper,
BiosRequirement,
fetch_branch_head,
fetch_github_latest_version,
github_headers,
requirement_entry,
)
from .emudeck_launchers import emulator_of_script, extract_launchers
from .shell_launchers import RepoTree
PLATFORM_NAME = "emudeck"
@@ -327,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))
@@ -414,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)
+7 -2
View File
@@ -89,9 +89,14 @@ class Runs:
name = next(
(posixpath.basename(w.text) for w in command if _SCRIPT.fullmatch(w.text)), None
)
if name is None or (emu is None and arm is None):
if name is None:
continue
if emu is not None:
names, at = [emu[0]], emu[1]
elif arm is not None:
names, at = arm
else:
continue
names, at = ([emu[0]], emu[1]) if emu else arm # type: ignore[misc]
entry = self.by_script.setdefault(name, Dispatch())
entry.emulators.extend(n for n in names if n not in entry.emulators)
entry.lines |= {at, number}
+2 -4
View File
@@ -196,12 +196,10 @@ def _format_diff(
return "\n".join(lines)
if show_added:
for label in added:
lines.append(f" + {label}")
lines.extend(f" + {label}" for label in added)
elif added:
lines.append(f" + {len(added)} new ROMs available (main profile only)")
for label in updated:
lines.append(f" ~ {label}")
lines.extend(f" ~ {label}" for label in updated)
lines.append(f" = {diff['unchanged']} unchanged")
if oos:
lines.append(f" . {oos} out of scope")
+6 -7
View File
@@ -36,16 +36,15 @@ from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
_SCRIPTS_DIR = str(Path(__file__).resolve().parents[1])
if _SCRIPTS_DIR not in sys.path:
if (_SCRIPTS_DIR := str(Path(__file__).resolve().parents[1])) not in sys.path:
sys.path.insert(0, _SCRIPTS_DIR)
from artifacts import copy_stream_atomic, write_if_changed, write_text_atomic # noqa: E402
from common import parse_untrusted_xml # noqa: E402
from region import REGIONS, WORLD # noqa: E402
from region_audit import NOINTRO # noqa: E402
from artifacts import copy_stream_atomic, write_if_changed, write_text_atomic
from common import parse_untrusted_xml
from region import REGIONS, WORLD
from region_audit import NOINTRO
from .base_scraper import github_headers # noqa: E402
from .base_scraper import github_headers
SOURCES = ("no-intro", "redump")
CACHE_DIR = Path(".cache") / "game-dats"
+117 -128
View File
@@ -28,62 +28,32 @@ from typing import Any
import yaml
try:
from .batocera_launchers import (
PATH_PATCHES,
Configgen,
config_directories,
_path_value,
_render,
_system_branches,
duckstation,
duckstation_legacy,
environment_directories,
hatari,
melonds,
mupen64plus,
patched_paths,
x16emu,
working_directories,
xemu,
)
from .configgen_launchers import (
Launcher,
LauncherShapeError,
Source,
_assigned_name,
)
from .shell_launchers import LauncherPatternMissing, Script, source_ref
except ImportError:
from batocera_launchers import ( # type: ignore[no-redef]
PATH_PATCHES,
Configgen,
config_directories,
_path_value,
_render,
_system_branches,
duckstation,
duckstation_legacy,
environment_directories,
hatari,
melonds,
mupen64plus,
patched_paths,
x16emu,
working_directories,
xemu,
)
from configgen_launchers import ( # type: ignore[no-redef]
Launcher,
LauncherShapeError,
Source,
_assigned_name,
)
from shell_launchers import ( # type: ignore[no-redef]
LauncherPatternMissing,
Script,
source_ref,
)
from .batocera_launchers import (
PATH_PATCHES,
Configgen,
config_directories,
_path_value,
_render,
_system_branches,
duckstation,
duckstation_legacy,
environment_directories,
hatari,
melonds,
mupen64plus,
patched_paths,
x16emu,
working_directories,
xemu,
)
from .configgen_launchers import (
Launcher,
LauncherShapeError,
Source,
_assigned_name,
end_line,
)
from .shell_launchers import LauncherPatternMissing, Script, source_ref
CONFIGGEN = "package/system/knulli-configgen/configgen/configgen"
GENERATORS = f"{CONFIGGEN}/generators"
@@ -166,7 +136,10 @@ def lexaloffle(cg: Configgen) -> list[Launcher]:
and isinstance(t.operand, ast.Call) and ast.unparse(t.operand.func).endswith(".exists"),
"not <binary>.exists()",
)
binary = ast.unparse(missing.test.operand.func).removesuffix(".exists") # type: ignore[attr-defined]
tested = missing.test
if not (isinstance(tested, ast.UnaryOp) and isinstance(tested.operand, ast.Call)):
src.fail("not <binary>.exists() tests no call")
binary = ast.unparse(tested.operand.func).removesuffix(".exists")
access, access_message = _error_guard(
src, generate,
lambda t: isinstance(t, ast.UnaryOp) and isinstance(t.op, ast.Not)
@@ -184,12 +157,13 @@ def lexaloffle(cg: Configgen) -> list[Launcher]:
launchers = []
for system, branch in _system_branches(generate):
bound = [
stmt for stmt in branch.body
if _assigned_name(stmt) == binary and isinstance(_bound(stmt), ast.Name)
(stmt, held) for stmt in branch.body
if _assigned_name(stmt) == binary and isinstance((held := _bound(stmt)), ast.Name)
]
if len(bound) != 1:
src.fail(f"the {system} branch does not set {binary} once")
constant = ast.unparse(bound[0].value) # type: ignore[attr-defined]
bound_stmt, bound_value = bound[0]
constant = ast.unparse(bound_value)
path = constants.get(constant)
if path is None or not path.startswith(prefix):
src.fail(f"{constant} is not a path under {cg.bios}")
@@ -200,7 +174,7 @@ def lexaloffle(cg: Configgen) -> list[Launcher]:
search_dir=cg.bios, passes_to="exec",
fails_when_missing=", ".join(messages),
source_ref=src.ref([
src.span(defined[constant]), src.span(branch.test), src.span(bound[0]),
src.span(defined[constant]), src.span(branch.test), src.span(bound_stmt),
_lines(missing), _lines(access),
src.span(commands[0]),
]),
@@ -463,8 +437,10 @@ class _Reader:
if isinstance(part, ast.Constant):
parts.append(str(part.value))
else:
inner = self.resolve(part.value) # type: ignore[attr-defined]
parts.append(inner if inner is not None else f"<{ast.unparse(part.value)}>") # type: ignore[attr-defined]
# The other parts of an f-string are its {placeholders}.
expr = part.value if isinstance(part, ast.FormattedValue) else part
inner = self.resolve(expr)
parts.append(inner if inner is not None else f"<{ast.unparse(expr)}>")
return "".join(parts).strip('"')
if (
isinstance(node, ast.BinOp)
@@ -497,7 +473,7 @@ class _Reader:
return (name.id, values) if values else None
return None
def _literal_list(self, node: ast.AST, scope_of: ast.AST) -> list[str] | None:
def _literal_list(self, node: ast.AST | None, scope_of: ast.AST) -> list[str] | None:
if isinstance(node, ast.List):
return [str(e.value) for e in node.elts if isinstance(e, ast.Constant)]
if isinstance(node, ast.Name):
@@ -507,14 +483,15 @@ class _Reader:
if _assigned_name(n) == node.id and isinstance(_bound(n), ast.List)
]
if len(bound) == 1:
return self._literal_list(_bound(bound[0]), scope_of) # type: ignore[arg-type]
return self._literal_list(_bound(bound[0]), scope_of)
return None
def function_of(self, node: ast.AST) -> ast.FunctionDef | None:
while node is not None:
node = self.parents.get(id(node)) # type: ignore[assignment]
if isinstance(node, ast.FunctionDef):
return node
current: ast.AST | None = node
while current is not None:
current = self.parents.get(id(current))
if isinstance(current, ast.FunctionDef):
return current
return None
def statement_of(self, node: ast.AST) -> ast.stmt:
@@ -535,7 +512,7 @@ class _Reader:
if written and isinstance(parent, ast.Call) and ast.unparse(parent.func).endswith(".write"):
yield node, written.group(0)
continue
if not self.under_bios(value):
if value is None or not self.under_bios(value):
continue
parent = self.parents.get(id(node))
if isinstance(parent, (ast.FormattedValue, ast.JoinedStr)):
@@ -544,7 +521,7 @@ class _Reader:
continue
if isinstance(parent, ast.Call) and ast.unparse(parent.func) == "str":
continue
yield node, value # type: ignore[misc]
yield node, value
def conditions(
self, node: ast.AST, guards: bool = False
@@ -657,65 +634,77 @@ class _Reader:
def consumer(self, node: ast.AST, value: str) -> tuple[str | None, str | None]:
parent = self.parents.get(id(node))
if isinstance(parent, ast.Attribute):
return None, None
if isinstance(parent, (ast.List, ast.Tuple)):
holder = self.parents.get(id(parent))
if isinstance(holder, (ast.For, ast.comprehension)):
return None, None
if not self._command_line(parent):
return None, None
index = next(i for i, e in enumerate(parent.elts) if e is node)
if isinstance(node, ast.JoinedStr) and isinstance(node.values[0], ast.Constant):
flag = str(node.values[0].value)
if flag.startswith("-") and flag.endswith("=") and value.startswith(flag):
return f"command line {flag[:-1]}", None
previous = parent.elts[index - 1] if index else None
if isinstance(previous, ast.Constant) and str(previous.value).startswith("-"):
return f"command line {previous.value!s}", None
if index:
return f"command line argument {index}", None
return None, None
return self._listed_consumer(node, parent, value)
if isinstance(parent, ast.Call):
func = parent.func
attr = func.attr if isinstance(func, ast.Attribute) else None
consts = [a.value for a in parent.args if isinstance(a, ast.Constant)]
if attr == "save" and len(parent.args) == 2 and parent.args[1] is node and consts:
return str(consts[0]), None
if attr == "set" and len(parent.args) == 3 and parent.args[2] is node and len(consts) >= 2:
return f"[{consts[0]!s}] {consts[1]!s}", None
receiver = func.value if isinstance(func, ast.Attribute) else None
if attr in ("copy", "copyfile", "copy2") and receiver is not None and ast.unparse(receiver) == "shutil":
source, target = parent.args[0], parent.args[1]
self.copy_sources[id(node)] = value if source is node else (
self.resolve(source) or ast.unparse(source)
)
return (value if target is node else self.resolve(target) or ast.unparse(target)), "copies"
if (
attr == "append"
and isinstance(receiver, ast.Name)
and receiver.id in COMMAND_NAMES
and isinstance(node, ast.JoinedStr)
and isinstance(node.values[0], ast.Constant)
):
flag = str(node.values[0].value)
if flag.startswith("-") and flag.endswith("=") and value.startswith(flag):
return f"command line {flag[:-1]}", None
if attr == "write" and isinstance(node, ast.Constant):
return f"written: {str(node.value).strip()}", None
return None, None
return self._call_consumer(node, parent, value)
if isinstance(parent, ast.Dict):
key = next(
(k for k, v in zip(parent.keys, parent.values) if v is node), None
)
if isinstance(key, ast.Constant):
holder = self.parents.get(id(parent))
is_env = (
isinstance(holder, ast.keyword) and holder.arg == "env"
) or _assigned_name(holder) == "env" # type: ignore[arg-type]
return (f"environment {key.value!s}" if is_env else str(key.value)), None
return self._dict_consumer(node, parent)
return None, None
def _listed_consumer(
self, node: ast.AST, parent: ast.List | ast.Tuple, value: str
) -> tuple[str | None, str | None]:
holder = self.parents.get(id(parent))
if isinstance(holder, (ast.For, ast.comprehension)):
return None, None
if not self._command_line(parent):
return None, None
index = next(i for i, e in enumerate(parent.elts) if e is node)
if isinstance(node, ast.JoinedStr) and isinstance(node.values[0], ast.Constant):
flag = str(node.values[0].value)
if flag.startswith("-") and flag.endswith("=") and value.startswith(flag):
return f"command line {flag[:-1]}", None
previous = parent.elts[index - 1] if index else None
if isinstance(previous, ast.Constant) and str(previous.value).startswith("-"):
return f"command line {previous.value!s}", None
if index:
return f"command line argument {index}", None
return None, None
def _call_consumer(
self, node: ast.AST, parent: ast.Call, value: str
) -> tuple[str | None, str | None]:
func = parent.func
attr = func.attr if isinstance(func, ast.Attribute) else None
consts = [a.value for a in parent.args if isinstance(a, ast.Constant)]
if attr == "save" and len(parent.args) == 2 and parent.args[1] is node and consts:
return str(consts[0]), None
if attr == "set" and len(parent.args) == 3 and parent.args[2] is node and len(consts) >= 2:
return f"[{consts[0]!s}] {consts[1]!s}", None
receiver = func.value if isinstance(func, ast.Attribute) else None
if attr in ("copy", "copyfile", "copy2") and receiver is not None and ast.unparse(receiver) == "shutil":
source, target = parent.args[0], parent.args[1]
self.copy_sources[id(node)] = value if source is node else (
self.resolve(source) or ast.unparse(source)
)
return (value if target is node else self.resolve(target) or ast.unparse(target)), "copies"
if (
attr == "append"
and isinstance(receiver, ast.Name)
and receiver.id in COMMAND_NAMES
and isinstance(node, ast.JoinedStr)
and isinstance(node.values[0], ast.Constant)
):
flag = str(node.values[0].value)
if flag.startswith("-") and flag.endswith("=") and value.startswith(flag):
return f"command line {flag[:-1]}", None
if attr == "write" and isinstance(node, ast.Constant):
return f"written: {str(node.value).strip()}", None
return None, None
def _dict_consumer(self, node: ast.AST, parent: ast.Dict) -> tuple[str | None, str | None]:
key = next(
(k for k, v in zip(parent.keys, parent.values) if v is node), None
)
if not isinstance(key, ast.Constant):
return None, None
holder = self.parents.get(id(parent))
is_env = (
isinstance(holder, ast.keyword) and holder.arg == "env"
) or (holder is not None and _assigned_name(holder) == "env")
return (f"environment {key.value!s}" if is_env else str(key.value)), None
def sites(self) -> list[_Site]:
found: list[_Site] = []
guards: list[tuple[ast.AST, str]] = []
@@ -774,7 +763,7 @@ class _Reader:
tests, spans = self.conditions(test)
return _Site(
value, f"presence sets {described}", None,
[(test.lineno, first.end_lineno), *spans], # type: ignore[list-item]
[(test.lineno, end_line(first)), *spans],
tests, self.cores(test), self._expands(read),
)
@@ -799,7 +788,7 @@ def _caller_cores(cg: Configgen, caller: tuple[str, str]) -> list[str]:
for stmt in node.body for n in ast.walk(stmt)
):
return _cores_of(node.test)
src.fail(f"no core test calls {function}")
return src.fail(f"no core test calls {function}")
def bios_sites(cg: Configgen, spec: GenericSites) -> list[Launcher]:
@@ -906,7 +895,7 @@ def relative_folders(
and all(isinstance(a, ast.Constant) for a in call.args)
):
continue
section, key, value = (str(a.value) for a in call.args) # type: ignore[attr-defined]
section, key, value = (str(a.value) for a in call.args if isinstance(a, ast.Constant))
if not value.startswith("../"):
continue
resolved = posixpath.normpath(posixpath.join(base, value))
+49 -15
View File
@@ -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:
+4 -5
View File
@@ -19,14 +19,13 @@ files hash/<list>.xml (attribute_softlists) and the floppy sound samples
from __future__ import annotations
import html
import io
import re
import zipfile
from collections.abc import Callable, Collection, Iterable, Iterator
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from pathlib import Path
from typing import NamedTuple
from typing import IO, NamedTuple
from common import yaml_load
@@ -96,7 +95,7 @@ def _device_roms(body: bytes) -> list[dict]:
@contextmanager
def open_listxml(path: Path) -> Iterator[io.BufferedIOBase]:
def open_listxml(path: Path) -> Iterator[IO[bytes]]:
"""Byte stream over a -listxml document, plain or as MAME's release zip."""
if path.suffix.lower() != ".zip":
with path.open("rb") as stream:
@@ -133,7 +132,7 @@ class Release(NamedTuple):
machines: dict[str, MachineLinks]
def scan_release(stream: io.BufferedIOBase) -> Release:
def scan_release(stream: IO[bytes]) -> Release:
"""Release tag, device sets with dumped ROMs and every element's links.
The document is read through a sliding window, never whole: the 0.289
@@ -192,7 +191,7 @@ def scan_release(stream: io.BufferedIOBase) -> Release:
return Release(tag, devices, machines)
def scan_device_sets(stream: io.BufferedIOBase) -> tuple[str, dict[str, dict]]:
def scan_device_sets(stream: IO[bytes]) -> tuple[str, dict[str, dict]]:
"""Release tag of a -listxml document and its device sets with dumped ROMs."""
release = scan_release(stream)
return release.tag, release.devices
+7 -6
View File
@@ -303,8 +303,7 @@ def _format_diff(
elif added:
lines.append(f" + {len(added)} new sets available (main profile only)")
for set_name in updated:
lines.append(f" ~ {set_name}.zip (refreshed)")
lines.extend(f" ~ {set_name}.zip (refreshed)" for set_name in updated)
oos = diff.get("out_of_scope", 0)
lines.append(f" = {unchanged} unchanged")
@@ -318,9 +317,9 @@ def _format_diff(
def _fetch_hashes(force: bool) -> dict[str, Any]:
cache = _load_cache()
if not force and not _is_stale(cache):
if not force and cache is not None and not _is_stale(cache):
log.info("using cached data from %s", cache.get("fetched_at", ""))
return cache # type: ignore[return-value]
return cache
try:
tag = _get_release_tag()
@@ -540,8 +539,10 @@ def _platform_archives() -> list[tuple[str, str]]:
for name in list_registered_platforms(str(_PLATFORMS_DIR)):
config = load_platform_config(name, str(_PLATFORMS_DIR))
for system, data in (config.get("systems") or {}).items():
for entry in (data or {}).get("files") or []:
stated.append((str(entry.get("name") or ""), str(system)))
stated.extend(
(str(entry.get("name") or ""), str(system))
for entry in (data or {}).get("files") or []
)
return stated
+1 -2
View File
@@ -398,8 +398,7 @@ def _parse_rom_entries(block: str, keep_no_dump: bool = False) -> list[dict]:
events: list[tuple[int, str, re.Match]] = []
for tag, pat in token_patterns:
for m in pat.finditer(block):
events.append((m.start(), tag, m))
events.extend((m.start(), tag, m) for m in pat.finditer(block))
# Walked in source order: a ROM_LOAD belongs to the last ROM_REGION above it.
events.sort(key=lambda e: e[0])
+13 -21
View File
@@ -29,22 +29,13 @@ import urllib.parse
from collections.abc import Callable, Mapping
from dataclasses import dataclass
try:
from .base_scraper import (
BaseScraper,
BiosRequirement,
fetch_branch_head,
fetch_bytes,
github_headers,
)
except ImportError:
from base_scraper import (
BaseScraper,
BiosRequirement,
fetch_branch_head,
fetch_bytes,
github_headers,
)
from .base_scraper import (
BaseScraper,
BiosRequirement,
fetch_branch_head,
fetch_bytes,
github_headers,
)
PLATFORM_NAME = "minui"
@@ -264,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."""
@@ -275,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)
@@ -336,10 +331,7 @@ class Scraper(BaseScraper):
def main() -> None:
try:
from .base_scraper import scraper_cli
except ImportError:
from base_scraper import scraper_cli
from .base_scraper import scraper_cli
scraper_cli(Scraper, "Scrape the MinUI pak list")
+8 -20
View File
@@ -28,22 +28,13 @@ import urllib.request
import zipfile
from datetime import datetime, timezone
try:
from .base_scraper import (
BaseScraper,
BiosRequirement,
_read_limited,
fetch_branch_head,
requirement_entry,
)
except ImportError:
from base_scraper import (
BaseScraper,
BiosRequirement,
_read_limited,
fetch_branch_head,
requirement_entry,
)
from .base_scraper import (
BaseScraper,
BiosRequirement,
_read_limited,
fetch_branch_head,
requirement_entry,
)
PLATFORM_NAME = "misterfpga"
@@ -238,10 +229,7 @@ class Scraper(BaseScraper):
def main() -> None:
"""Entry point."""
try:
from .base_scraper import scraper_cli
except ImportError:
from base_scraper import scraper_cli
from .base_scraper import scraper_cli
scraper_cli(Scraper, "Scrape MiSTer FPGA BIOS requirements")
+2 -8
View File
@@ -3,10 +3,7 @@
from __future__ import annotations
try:
from . import minui_scraper
except ImportError:
import minui_scraper
from . import minui_scraper
PLATFORM_NAME = "myminui"
@@ -18,10 +15,7 @@ class Scraper(minui_scraper.Scraper):
def main() -> None:
try:
from .base_scraper import scraper_cli
except ImportError:
from base_scraper import scraper_cli
from .base_scraper import scraper_cli
scraper_cli(Scraper, "Scrape the MyMinUI pak list")
+2 -8
View File
@@ -3,10 +3,7 @@
from __future__ import annotations
try:
from . import minui_scraper
except ImportError:
import minui_scraper
from . import minui_scraper
PLATFORM_NAME = "nextui"
@@ -18,10 +15,7 @@ class Scraper(minui_scraper.Scraper):
def main() -> None:
try:
from .base_scraper import scraper_cli
except ImportError:
from base_scraper import scraper_cli
from .base_scraper import scraper_cli
scraper_cli(Scraper, "Scrape the NextUI pak list")
File diff suppressed because it is too large. Load diff
+90 -69
View File
@@ -14,10 +14,7 @@ import bisect
import re
from collections.abc import Callable, Iterator
try:
from .shell_launchers import is_feature_ref, split_ref
except ImportError:
from shell_launchers import is_feature_ref, split_ref # type: ignore[no-redef]
from .shell_launchers import is_feature_ref, split_ref
GENERATORS = "emulatorLauncher/Generators"
FEATURES = ".emulationstation/es_features.cfg"
@@ -1534,20 +1531,19 @@ def cxbx(sources: dict[str, Source]) -> list[Record]:
f"{CXBX_DATA_FOLDER}, the folder holding {settings.group(1)},"
" which the launcher writes beside the binary"
)
records = []
for match in named:
records.append(
_record(
match.group(1),
"standalone",
"passes_path",
[],
source_ref((src.path, [src.lines(match.start(), match.end()), settings_span])),
search_dir=f'<AppConfig.GetFullPath("{match.group(2)}")>',
passes_to=passes_to,
fails_when_missing=False,
)
records = [
_record(
match.group(1),
"standalone",
"passes_path",
[],
source_ref((src.path, [src.lines(match.start(), match.end()), settings_span])),
search_dir=f'<AppConfig.GetFullPath("{match.group(2)}")>',
passes_to=passes_to,
fails_when_missing=False,
)
for match in named
]
first, *rest = fallbacks
others = "neither core nor emulator is " + " or ".join(f'"{m.group(1)}"' for m in named)
records.append(
@@ -1793,8 +1789,8 @@ def _negate(condition: str) -> str:
anything else is wrapped in not (...).
"""
tests = condition.split(" && ")
compared = [re.fullmatch(rf"(\w+) != ({STRING})", t) for t in tests]
if all(compared):
compared = [m for t in tests if (m := re.fullmatch(rf"(\w+) != ({STRING})", t))]
if len(compared) == len(tests):
return " || ".join(f"{m.group(1)} == {m.group(2)}" for m in compared)
return f"not ({condition})"
@@ -2071,7 +2067,7 @@ def _wrapped(expr: str, opener: str) -> str | None:
return None
inner = expr[len(opener) + 1 : -1]
depth = 0
for offset, char in _code_chars(inner):
for _offset, char in _code_chars(inner):
depth += {"(": 1, ")": -1}.get(char, 0)
if depth < 0:
return None
@@ -2165,16 +2161,9 @@ def _braceless_if(src: Source, offset: int) -> str | None:
def _render(src: Source, expr: str, scope: int, before: int) -> Rendered | None:
"""A path expression as text, with the lines of the declarations it read."""
expr = " ".join(expr.split())
if re.fullmatch(_BIOS_ROOT, expr):
return "bios", []
changed = re.fullmatch(r'Path\.ChangeExtension\(exe, "(\.\w+)"\)', expr)
if changed:
return f"<exe>{changed.group(1)}", []
named = re.fullmatch(r'(?:Program\.)?AppConfig\.GetFullPath\("([\w.-]+)"\)', expr)
if named:
return f"<{named.group(1)}>", []
if expr in _KNOWN:
return _KNOWN[expr], []
fixed = _render_fixed(expr)
if fixed is not None:
return fixed
replaced = re.fullmatch(rf"(.+)\.Replace\({STRING}, {STRING}\)", expr)
if replaced:
return _render(src, replaced.group(1), scope, before)
@@ -2186,28 +2175,10 @@ def _render(src: Source, expr: str, scope: int, before: int) -> Rendered | None:
if len(ternary) == 2:
branches = _split_top(ternary[1], ":")
if len(branches) == 2:
first = _render(src, branches[0], scope, before)
second = _render(src, branches[1], scope, before)
if first is None or second is None:
return None
return f"{first[0]} when {ternary[0]}, else {second[0]}", first[1] + second[1]
return _render_choice(src, ternary[0], branches, scope, before)
terms = _split_top(expr, " + ")
if len(terms) > 1:
while terms and terms[0] == '"\\""':
terms = terms[1:]
while terms and terms[-1] in ('"\\""', '"\\\\"'):
terms = terms[:-1]
pieces, spans = [], []
for term in terms:
if term == '";"':
pieces.append(";")
continue
done = _render(src, term, scope, before)
if done is None:
return None
pieces.append(done[0])
spans += done[1]
return "".join(pieces), spans
return _render_terms(src, terms, scope, before)
combine = _wrapped(expr, "Path.Combine")
if combine is not None:
base, *rest = _split_top(combine, ",")
@@ -2219,28 +2190,78 @@ def _render(src: Source, expr: str, scope: int, before: int) -> Rendered | None:
if expr in _PATH_PARAMS:
return _PATH_PARAMS[expr], []
if re.fullmatch(r"\w+", expr):
code = _code(src)
decls = list(re.compile(rf"(?:string|var)\s+{expr}\s*=\s*").finditer(code, scope, before))
if not decls:
return (_PATH_PARAMS[expr], []) if expr in _PATH_PARAMS else None
decl = decls[-1]
decl_end = _statement_end(src, decl.end())
base = _render(src, src.text[decl.end() : decl_end], scope, decl.start())
if base is None:
return None
text, spans = base[0], [*base[1], src.lines(decl.start(), decl_end)]
for again in re.compile(rf"(?<![\w.]){expr}\s*=(?!=)\s*").finditer(code, decl_end, before):
again_end = _statement_end(src, again.end())
value = _render(src, src.text[again.end() : again_end], scope, again.start())
if value is None:
return None
condition = _braceless_if(src, again.start())
text += f", or {value[0]}" + (f" when {_readable(condition)}" if condition else "")
spans += [*value[1], src.lines(_statement_start(src, again.start()), again_end)]
return text, spans
return _render_variable(src, expr, scope, before)
return None
def _render_fixed(expr: str) -> Rendered | None:
"""The expressions that name one known folder or file."""
if re.fullmatch(_BIOS_ROOT, expr):
return "bios", []
changed = re.fullmatch(r'Path\.ChangeExtension\(exe, "(\.\w+)"\)', expr)
if changed:
return f"<exe>{changed.group(1)}", []
named = re.fullmatch(r'(?:Program\.)?AppConfig\.GetFullPath\("([\w.-]+)"\)', expr)
if named:
return f"<{named.group(1)}>", []
if expr in _KNOWN:
return _KNOWN[expr], []
return None
def _render_choice(
src: Source, condition: str, branches: list[str], scope: int, before: int
) -> Rendered | None:
"""A `condition ? a : b` expression."""
first = _render(src, branches[0], scope, before)
second = _render(src, branches[1], scope, before)
if first is None or second is None:
return None
return f"{first[0]} when {condition}, else {second[0]}", first[1] + second[1]
def _render_terms(src: Source, terms: list[str], scope: int, before: int) -> Rendered | None:
"""A concatenation, the quotes wrapped around it dropped."""
while terms and terms[0] == '"\\""':
terms = terms[1:]
while terms and terms[-1] in ('"\\""', '"\\\\"'):
terms = terms[:-1]
pieces, spans = [], []
for term in terms:
if term == '";"':
pieces.append(";")
continue
done = _render(src, term, scope, before)
if done is None:
return None
pieces.append(done[0])
spans += done[1]
return "".join(pieces), spans
def _render_variable(src: Source, expr: str, scope: int, before: int) -> Rendered | None:
"""A local variable, from its declaration and every later assignment before use."""
code = _code(src)
decls = list(re.compile(rf"(?:string|var)\s+{expr}\s*=\s*").finditer(code, scope, before))
if not decls:
return (_PATH_PARAMS[expr], []) if expr in _PATH_PARAMS else None
decl = decls[-1]
decl_end = _statement_end(src, decl.end())
declared = _render(src, src.text[decl.end() : decl_end], scope, decl.start())
if declared is None:
return None
text, spans = declared[0], [*declared[1], src.lines(decl.start(), decl_end)]
for again in re.compile(rf"(?<![\w.]){expr}\s*=(?!=)\s*").finditer(code, decl_end, before):
again_end = _statement_end(src, again.end())
value = _render(src, src.text[again.end() : again_end], scope, again.start())
if value is None:
return None
condition = _braceless_if(src, again.start())
text += f", or {value[0]}" + (f" when {_readable(condition)}" if condition else "")
spans += [*value[1], src.lines(_statement_start(src, again.start()), again_end)]
return text, spans
_OPTION_FORMS = (
(r'SystemConfig\.isOptSet\("(\w+)"\) && SystemConfig\.getOptBoolean\("\1"\)', r"\1 on"),
(
+14 -27
View File
@@ -14,30 +14,17 @@ import urllib.error
import urllib.request
from pathlib import Path
try:
from .base_scraper import (
BaseScraper,
BiosRequirement,
fetch_branch_head,
fetch_bytes,
fetch_github_latest_version,
requirement_entry,
)
from .batocera_scraper import SYSTEM_SLUG_MAP as BATOCERA_SLUGS
from .retrobat_launchers import SOURCE_FILES as LAUNCHER_FILES
from .retrobat_launchers import extract_launchers
except ImportError:
from base_scraper import (
BaseScraper,
BiosRequirement,
fetch_branch_head,
fetch_bytes,
fetch_github_latest_version,
requirement_entry,
)
from batocera_scraper import SYSTEM_SLUG_MAP as BATOCERA_SLUGS
from retrobat_launchers import SOURCE_FILES as LAUNCHER_FILES
from retrobat_launchers import extract_launchers
from .base_scraper import (
BaseScraper,
BiosRequirement,
fetch_branch_head,
fetch_bytes,
fetch_github_latest_version,
requirement_entry,
)
from .batocera_scraper import SYSTEM_SLUG_MAP as BATOCERA_SLUGS
from .retrobat_launchers import SOURCE_FILES as LAUNCHER_FILES
from .retrobat_launchers import extract_launchers
PLATFORM_NAME = "retrobat"
PLATFORM_FILE = Path(__file__).resolve().parents[2] / "platforms" / "retrobat.yml"
@@ -275,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
@@ -309,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)
+39 -30
View File
@@ -23,10 +23,7 @@ from collections.abc import Callable
from pathlib import PurePosixPath
from typing import Any
try:
from .retropie_launchers import Launcher, LauncherPatternMissing, merge_records, source_ref
except ImportError:
from retropie_launchers import Launcher, LauncherPatternMissing, merge_records, source_ref
from .retropie_launchers import Launcher, LauncherPatternMissing, merge_records, source_ref
BIOS = "$bios_path"
PLACEHOLDER = "RETRODECKBIOSDIR"
@@ -170,18 +167,7 @@ class Component:
words = [self.resolve(w) for w in words]
raw = " ".join(words)
if command == "set_setting_value" and len(words) >= 4:
value = _unquote(words[3])
if _mentions_bios(value):
section = words[5] if len(words) > 5 else None
where = f"[{section}] {words[2]}" if section else words[2]
target = self.config_name(words[1])
if _is_file(value):
settings.setdefault(("fixed_name", target, depends or ""), []).append(
(number, value, where)
)
else:
key = ("passes_path", target, where, depends or "")
settings.setdefault(key, []).append((number, value, where))
self._setting(number, words, depends, settings)
continue
if command == "dir_prep" and len(words) == 3:
self._dir_prep(path, number, words[1], words[2], depends)
@@ -195,18 +181,7 @@ class Component:
copies.setdefault((folder, depends), []).append((number, name, target))
continue
if command == "tar" and "-C" in words and _mentions_bios(words[words.index("-C") + 1]):
if "-czf" in words:
continue
archive = next((w for w in words if w.endswith((".tar.gz", ".tgz", ".tar"))), None)
if archive is None:
raise LauncherPatternMissing(
f"{path}:{number}", f"tar into bios/ of no archive: {raw}"
)
self.record(
"copies", [], [(path, number)], search_dir=archive,
passes_to=words[words.index("-C") + 1], fails_when_missing=False,
depends_on_option=depends,
)
self._tar(path, number, words, raw, depends)
continue
if command == "sed" and PLACEHOLDER in raw:
self._preset(script, number, words)
@@ -218,8 +193,8 @@ class Component:
raise LauncherPatternMissing(
f"{path}:{number}", f"unrecognised use of $bios_path: {raw}"
)
for key, hits in settings.items():
self._settings(path, key, hits)
for setting, hits in settings.items():
self._settings(path, setting, hits)
for (folder, depends), hits in copies.items():
names = [name for _n, name, _t in hits]
targets = [target for _n, _name, target in hits]
@@ -229,6 +204,40 @@ class Component:
depends_on_option=depends or None,
)
def _setting(
self, number: int, words: list[str], depends: str | None,
settings: dict[tuple[str, ...], list[tuple[int, str, str]]],
) -> None:
"""A set_setting_value that writes a bios/ path into a config."""
value = _unquote(words[3])
if not _mentions_bios(value):
return
section = words[5] if len(words) > 5 else None
where = f"[{section}] {words[2]}" if section else words[2]
target = self.config_name(words[1])
if _is_file(value):
settings.setdefault(("fixed_name", target, depends or ""), []).append(
(number, value, where)
)
else:
key = ("passes_path", target, where, depends or "")
settings.setdefault(key, []).append((number, value, where))
def _tar(self, path: str, number: int, words: list[str], raw: str, depends: str | None) -> None:
"""A tar that extracts an archive into bios/."""
if "-czf" in words:
return
archive = next((w for w in words if w.endswith((".tar.gz", ".tgz", ".tar"))), None)
if archive is None:
raise LauncherPatternMissing(
f"{path}:{number}", f"tar into bios/ of no archive: {raw}"
)
self.record(
"copies", [], [(path, number)], search_dir=archive,
passes_to=words[words.index("-C") + 1], fails_when_missing=False,
depends_on_option=depends,
)
def _settings(self, path: str, key: tuple[str, ...], hits: list[tuple[int, str, str]]) -> None:
kind, target = key[0], key[1]
depends = key[-1] or None
+133 -120
View File
@@ -27,6 +27,7 @@ Verification logic (api_data_processing.sh:289-405):
from __future__ import annotations
import importlib
import json
import re
import sys
@@ -34,29 +35,22 @@ import urllib.error
import urllib.request
from pathlib import Path
try:
from .base_scraper import (
BaseScraper,
BiosRequirement,
fetch_branch_head,
fetch_bytes,
fetch_github_latest_version,
github_headers,
requirement_entry,
)
from .retrodeck_launchers import extract_launchers
except ImportError:
if not __package__:
# Allow running directly: python scripts/scraper/retrodeck_scraper.py
sys.path.insert(0, str(Path(__file__).parent.parent))
from scraper.base_scraper import (
BaseScraper,
BiosRequirement,
fetch_branch_head,
fetch_bytes,
fetch_github_latest_version,
github_headers,
requirement_entry,
)
from scraper.retrodeck_launchers import extract_launchers
importlib.import_module("scraper")
__package__ = "scraper"
from .base_scraper import (
BaseScraper,
BiosRequirement,
fetch_branch_head,
fetch_bytes,
fetch_github_latest_version,
github_headers,
requirement_entry,
)
from .retrodeck_launchers import extract_launchers
PLATFORM_NAME = "retrodeck"
COMPONENTS_REPO = "RetroDECK/components"
@@ -253,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"])
@@ -282,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."""
@@ -416,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
@@ -426,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
@@ -578,10 +594,7 @@ class Scraper(BaseScraper):
def main() -> None:
try:
from .base_scraper import scraper_cli
except ImportError:
from scraper.base_scraper import scraper_cli
from .base_scraper import scraper_cli
scraper_cli(Scraper, "Scrape RetroDECK BIOS requirements")
+104 -56
View File
@@ -23,6 +23,7 @@ import re
import shlex
from collections.abc import Iterator
from dataclasses import dataclass, field
from functools import partial
from itertools import product
from pathlib import PurePosixPath
from typing import Any
@@ -224,8 +225,8 @@ class Scripts:
lines = text.splitlines()
fields: dict[str, tuple[str, int]] = {}
for found in _MODULE_FIELD.finditer(text):
line = text.count("\n", 0, found.start()) + 1
fields.setdefault(found.group(1), (found.group(2), line))
field_line = text.count("\n", 0, found.start()) + 1
fields.setdefault(found.group(1), (found.group(2), field_line))
if "id" not in fields:
return None
repo = fields.get("repo")
@@ -299,21 +300,15 @@ class Scripts:
for number, text, opener in _logical_lines(module.lines, start + 1, end - 1):
stripped = text.strip()
if array is not None:
body = re.sub(r"\s+#.*$", "", stripped)
closed = body.endswith(")")
array[1].append(body[:-1] if closed else body)
if closed:
words = _split(" ".join(array[1]))
env[array[0]] = [v for w in words for v in self.expand(w, package, env)]
if self._array_line(array, stripped, package, env):
array = None
continue
if opener is not None:
if self._live(branches):
words = [self.expand(w, package, env) for w in stripped.split()]
events.setdefault((module.path, number), Event(
module.path, number, words, stripped,
conditions + self._shown(branches, package, env), True,
[self.expand(w, package, env) for w in _split(opener)],
module.path, number, self._expand_all(stripped.split(), package, env),
stripped, conditions + self._shown(branches, package, env), True,
self._expand_all(_split(opener), package, env),
))
continue
if not stripped or stripped.startswith("#"):
@@ -322,35 +317,16 @@ class Scripts:
continue
if not self._live(branches):
continue
loop = _FOR.match(stripped)
if loop is not None:
values = [v for w in _split(loop.group(2)) for v in self.expand(w, package, env)]
loops.append((loop.group(1), env.get(loop.group(1))))
env[loop.group(1)] = values
continue
if re.match(r"^(while|until)\b|^for\s*\(\(", stripped):
loops.append((None, None))
continue
if stripped == "done" or stripped.startswith("done ") or stripped.startswith("done;"):
if loops:
var, previous = loops.pop()
if var is not None:
if previous is None:
env.pop(var, None)
else:
env[var] = previous
if self._loop(stripped, package, env, loops):
continue
if stripped in ("do", "then", "else", "fi", "esac", "{", "}"):
continue
guard = re.match(r"^\[\[\s*(.*?)\s*\]\]\s*&&\s*(.*)$", stripped)
shown = conditions + self._shown(branches, package, env)
if guard is not None:
verdict = self._md_id_test(f"[[ {guard.group(1)} ]]", package)
if verdict is False or "$md_mode" in guard.group(1) or "$mode" in guard.group(1):
continue
if verdict is None:
shown = shown + [self._render(guard.group(1), package, env)]
stripped = guard.group(2)
guarded = self._guard(
stripped, package, env, conditions + self._shown(branches, package, env)
)
if guarded is None:
continue
stripped, shown = guarded
opens = re.match(r"^(?:local\s+)?([A-Za-z_]\w*)=\(([^)]*)$", stripped)
if opens is not None:
array = (opens.group(1), [opens.group(2)])
@@ -362,10 +338,79 @@ class Scripts:
events.setdefault(
(module.path, number), Event(module.path, number, words, stripped, shown, False)
)
callee = words[0][0] if words and words[0] else None
if callee in self.owner and callee != name:
call_args = {str(i): w for i, w in enumerate(words[1:], 1)}
self._walk(package, callee, call_args, shown, stack | {name}, events)
self._descend(package, name, words, shown, stack, events)
def _descend(
self,
package: Module,
name: str,
words: list[list[str]],
shown: list[str],
stack: set[str],
events: dict[tuple[str, int], Event],
) -> None:
"""Walk the function a statement calls, with the words it passes."""
callee = words[0][0] if words and words[0] else None
if callee in self.owner and callee != name:
call_args = {str(i): w for i, w in enumerate(words[1:], 1)}
self._walk(package, callee, call_args, shown, stack | {name}, events)
def _expand_all(
self, words: list[str], package: Module, env: dict[str, list[str]]
) -> list[list[str]]:
return [self.expand(w, package, env) for w in words]
def _array_line(
self, array: tuple[str, list[str]], stripped: str, package: Module,
env: dict[str, list[str]],
) -> bool:
"""Add one line to a multi-line array, and say whether it closed it."""
body = re.sub(r"\s+#.*$", "", stripped)
closed = body.endswith(")")
array[1].append(body[:-1] if closed else body)
if closed:
words = _split(" ".join(array[1]))
env[array[0]] = [v for w in words for v in self.expand(w, package, env)]
return closed
def _loop(
self, stripped: str, package: Module, env: dict[str, list[str]],
loops: list[tuple[str | None, list[str] | None]],
) -> bool:
"""Track for/while/until/done, and say whether the line was one of them."""
loop = _FOR.match(stripped)
if loop is not None:
values = [v for w in _split(loop.group(2)) for v in self.expand(w, package, env)]
loops.append((loop.group(1), env.get(loop.group(1))))
env[loop.group(1)] = values
return True
if re.match(r"^(while|until)\b|^for\s*\(\(", stripped):
loops.append((None, None))
return True
if stripped == "done" or stripped.startswith(("done ", "done;")):
if loops:
var, previous = loops.pop()
if var is not None:
if previous is None:
env.pop(var, None)
else:
env[var] = previous
return True
return False
def _guard(
self, stripped: str, package: Module, env: dict[str, list[str]], shown: list[str]
) -> tuple[str, list[str]] | None:
"""The statement a `[[ test ]] && statement` runs and its conditions, None if never."""
guard = re.match(r"^\[\[\s*(.*?)\s*\]\]\s*&&\s*(.*)$", stripped)
if guard is None:
return stripped, shown
verdict = self._md_id_test(f"[[ {guard.group(1)} ]]", package)
if verdict is False or "$md_mode" in guard.group(1) or "$mode" in guard.group(1):
return None
if verdict is None:
shown = shown + [self._render(guard.group(1), package, env)]
return guard.group(2), shown
def _branch(
self, stripped: str, package: Module, env: dict[str, list[str]],
@@ -462,14 +507,10 @@ class Scripts:
if not bound:
results.append(braced)
continue
for values in product(*(env[n] for n in bound)):
chosen = dict(zip(bound, values))
def replace(found: re.Match[str]) -> str:
key = found.group(1) or found.group(3)
return chosen.get(key, found.group(0))
results.append(_VAR.sub(replace, braced))
results.extend(
_VAR.sub(partial(_bound_value, dict(zip(bound, values))), braced)
for values in product(*(env[n] for n in bound))
)
return results
@@ -483,6 +524,11 @@ LIST_SEPARATORS = {"advmame": ":", "advmame-0.94": ":", "advmame-1.4": ":"}
DEFAULT_LIST_SEPARATOR = ";"
def _bound_value(chosen: dict[str, str], found: re.Match[str]) -> str:
key = found.group(1) or found.group(3)
return chosen.get(key, found.group(0))
def _search_list_in_roms(event: Event, separator: str = DEFAULT_LIST_SEPARATOR) -> bool:
"""An iniSet whose value is a list of folders below the roms root.
@@ -494,7 +540,7 @@ def _search_list_in_roms(event: Event, separator: str = DEFAULT_LIST_SEPARATOR)
return False
parts = [p for p in event.words[2][0].split(separator) if p]
return len(parts) > 1 and all(
p.startswith(ROMDIR + "/") or p.startswith("${romdir}/") for p in parts
p.startswith((ROMDIR + "/", "${romdir}/")) for p in parts
)
@@ -541,9 +587,11 @@ class PackageReader:
def read(self) -> list[Launcher]:
events = self.scripts.walk(self.package)
for event in events:
if not event.heredoc and event.words and event.words[0] == ["copyDefaultConfig"]:
if len(event.words) >= 3 and len(event.words[1]) == 1 and len(event.words[2]) == 1:
self.installed_as.setdefault(event.words[1][0], event.words[2][0])
if (
not event.heredoc and event.words and event.words[0] == ["copyDefaultConfig"]
and len(event.words) >= 3 and len(event.words[1]) == 1 and len(event.words[2]) == 1
):
self.installed_as.setdefault(event.words[1][0], event.words[2][0])
links: list[Event] = []
for event in events:
if not event.words or not event.words[0]:
@@ -825,8 +873,8 @@ class PackageReader:
if flag.startswith("-") and _mentions_bios(value)
]
found += [
tuple(token.split("=", 1)) for token in tokens
if token.startswith("-") and "=" in token and _mentions_bios(token.split("=", 1)[1])
(head, tail) for head, sep, tail in (token.partition("=") for token in tokens)
if head.startswith("-") and sep and _mentions_bios(tail)
]
if not found:
raise LauncherPatternMissing(
+5 -14
View File
@@ -29,16 +29,10 @@ import tarfile
import urllib.error
import urllib.request
try:
from .base_scraper import BaseScraper, BiosRequirement, fetch_branch_head
from .retropie_launchers import SCRIPTMODULES
from .retropie_launchers import SECTIONS as _SCRIPT_SECTIONS
from .retropie_launchers import extract_launchers
except ImportError:
from base_scraper import BaseScraper, BiosRequirement, fetch_branch_head
from retropie_launchers import SCRIPTMODULES
from retropie_launchers import SECTIONS as _SCRIPT_SECTIONS
from retropie_launchers import extract_launchers
from .base_scraper import BaseScraper, BiosRequirement, fetch_branch_head
from .retropie_launchers import SCRIPTMODULES
from .retropie_launchers import SECTIONS as _SCRIPT_SECTIONS
from .retropie_launchers import extract_launchers
PLATFORM_NAME = "retropie"
@@ -189,10 +183,7 @@ class Scraper(BaseScraper):
def main() -> None:
try:
from .base_scraper import scraper_cli
except ImportError:
from base_scraper import scraper_cli
from .base_scraper import scraper_cli
scraper_cli(Scraper, "Scrape the RetroPie package list")
+42 -45
View File
@@ -13,35 +13,22 @@ from __future__ import annotations
import posixpath
import re
from collections.abc import Callable
from collections.abc import Callable, Hashable
from dataclasses import dataclass
from typing import TypeVar
try:
from .configgen_launchers import Launcher
from .shell_launchers import config_placement, evidence_fields
from .shell_launchers import (
LauncherPatternMissing,
Link,
RepoTree,
Script,
Setting,
describe_keys,
settings,
source_ref,
)
except ImportError:
from configgen_launchers import Launcher
from shell_launchers import config_placement, evidence_fields # type: ignore[no-redef]
from shell_launchers import (
LauncherPatternMissing,
Link,
RepoTree,
Script,
Setting,
describe_keys,
settings,
source_ref,
)
from .configgen_launchers import Launcher
from .shell_launchers import config_placement, evidence_fields
from .shell_launchers import (
LauncherPatternMissing,
Link,
RepoTree,
Script,
Setting,
describe_keys,
settings,
source_ref,
)
ROCKNIX = "projects/ROCKNIX"
DEVICES = f"{ROCKNIX}/devices"
@@ -53,6 +40,8 @@ CONFIG_ROOT = "/storage/.config"
USERCONFIG = f"{ROCKNIX}/packages/sysutils/systemd/scripts/userconfig-setup"
Lines = list[tuple[str, set[int]]]
# What per_device groups configs by: equal values make one group.
Found = TypeVar("Found", bound=Hashable)
@dataclass
@@ -82,13 +71,13 @@ def device_configs(
if not re.search(rf"CONFIG=|\$\{{PKG_DIR\}}/{folder}/", body):
continue
offset = block.start(1)
for arm in re.finditer(r"^\s*([\w*|]+)\)(.*?);;", body, re.M | re.S):
for case_arm in re.finditer(r"^\s*([\w*|]+)\)(.*?);;", body, re.M | re.S):
chosen = re.search(
rf'CONFIG="([^"]+)"|\$\{{PKG_DIR\}}/{folder}/([^/\s]+)', arm.group(2)
rf'CONFIG="([^"]+)"|\$\{{PKG_DIR\}}/{folder}/([^/\s]+)', case_arm.group(2)
)
if chosen:
arms.append((arm.group(1).split("|"), chosen.group(1) or chosen.group(2)))
mk_lines.add(mk.text.count("\n", 0, offset + arm.start(2)) + 1)
arms.append((case_arm.group(1).split("|"), chosen.group(1) or chosen.group(2)))
mk_lines.add(mk.text.count("\n", 0, offset + case_arm.start(2)) + 1)
break
if not arms:
number, _ = mk.find(
@@ -121,15 +110,15 @@ def per_device(
tree: RepoTree,
configs: list[DeviceConfig],
mk_path: str,
read: Callable[[str, str], tuple[object, set[int]]],
) -> list[tuple[str | None, object, Lines]]:
read: Callable[[str, str], tuple[Found, set[int]]],
) -> list[tuple[str | None, Found, Lines]]:
"""Configs grouped by what read() finds in them.
read(path, text) returns a comparable value and the lines it comes from.
One group gives one result without a device. Otherwise each group names
its devices, in the order of the devices directory.
"""
groups: dict[object, tuple[list[str], Lines]] = {}
groups: dict[Found, tuple[list[str], Lines]] = {}
for config in configs:
value, lines = read(config.path, tree.read(config.path))
devices, refs = groups.setdefault(value, ([], []))
@@ -223,6 +212,14 @@ def _keys(value: FixedPaths) -> list[str]:
return [f"[{section}] {key}" if section else key for section, key in value.keys]
@dataclass(frozen=True)
class Installed:
"""Where the launch puts a per-device config, and the start script doing it."""
target: str = ""
start: Script | None = None
def config_records(
tree: RepoTree,
emulator: str,
@@ -230,8 +227,7 @@ def config_records(
file: str,
passes_to_suffix: str = "",
depends_on_option: str | None = None,
target: str = "",
start: Script | None = None,
installed: Installed | None = None,
unread: Callable[[tuple[str, str]], bool] = lambda key: False,
) -> list[Launcher]:
"""fixed_name records for the bios paths of a config installed per device.
@@ -239,11 +235,12 @@ def config_records(
``unread`` drops the keys the shipped configs leave the emulator
reading no file from.
"""
installed = installed or Installed()
configs = device_configs(tree, package, file)
keys = [k for k in bios_keys(tree, [c.path for c in configs]) if not unread(k)]
name = posixpath.basename(file)
def read(path: str, text: str) -> tuple[object, set[int]]:
def read(path: str, text: str) -> tuple[FixedPaths, set[int]]:
return fixed_paths(settings(text), keys, path)
records = []
@@ -265,9 +262,9 @@ def config_records(
device=device,
depends_on_option=depends_on_option,
),
target or f"{CONFIG_ROOT}/{posixpath.basename(package)}/{name}",
installed.target or f"{CONFIG_ROOT}/{posixpath.basename(package)}/{name}",
_keys(value),
start,
installed.start,
))
return records
@@ -277,7 +274,7 @@ def retroarch(tree: RepoTree) -> list[Launcher]:
configs = device_configs(tree, RETROARCH, "retroarch.cfg", folder="sources")
wanted = ("system_directory", "systemfiles_in_content_dir")
def read(path: str, text: str) -> tuple[object, set[int]]:
def read(path: str, text: str) -> tuple[tuple[tuple[str, str], ...], set[int]]:
found = {s.key: s for s in settings(text) if s.key in wanted}
if "system_directory" not in found:
raise LauncherPatternMissing(path, "system_directory")
@@ -497,7 +494,7 @@ def melonds(tree: RepoTree) -> list[Launcher]:
conf_line, conf = script.find(r'^\s*CONF_DIR="([^"]+)"', "CONF_DIR")
records = config_records(
tree, "melonds", package, "melonDS.ini", depends_on_option=condition,
target=f"{conf.group(1)}/melonDS.ini", start=script, unread=unread,
installed=Installed(f"{conf.group(1)}/melonDS.ini", script), unread=unread,
)
for record in records:
record.source_ref += (
@@ -514,7 +511,7 @@ def dsperate(tree: RepoTree) -> list[Launcher]:
run_line, _ = script.find(r"/usr/bin/dsperate --config ", "dsperate --config")
records = config_records(
tree, "dsperate", package, "dsperate.ini", " (--config)",
target=script.expand("${DSPERATE_INI}", run_line, set()), start=script,
installed=Installed(script.expand("${DSPERATE_INI}", run_line, set()), script),
)
for record in records:
record.source_ref += f", {source_ref([(script.path, {run_line})])}"
@@ -531,7 +528,7 @@ def xemu(tree: RepoTree) -> list[Launcher]:
)
records = config_records(
tree, "xemu", package, "xemu.toml", " (copied at each launch)",
target=script.expand("${CONF_DIR}/${XEMU_INI}", copy_line, set()), start=script,
installed=Installed(script.expand("${CONF_DIR}/${XEMU_INI}", copy_line, set()), script),
)
for record in records:
record.source_ref += f", {source_ref([(script.path, {copy_line})])}"
@@ -667,7 +664,7 @@ def directory_records(
configs = device_configs(tree, package, file)
name = posixpath.basename(file)
def read(path: str, text: str) -> tuple[object, set[int]]:
def read(path: str, text: str) -> tuple[str, set[int]]:
found = {(s.section, s.key): s for s in settings(text)}
if folder_key not in found:
raise LauncherPatternMissing(path, f"[{folder_key[0]}] {folder_key[1]}")
@@ -830,7 +827,7 @@ def patched_directories(tree: RepoTree) -> list[Launcher]:
),
None,
)
if returned is None:
if start is None or returned is None:
raise LauncherPatternMissing(path, f"{function}() patched to return a fixed path")
number, directory = returned
records.append(Launcher(
+14 -25
View File
@@ -17,26 +17,15 @@ from __future__ import annotations
import re
try:
from .base_scraper import (
BaseScraper,
BiosRequirement,
fetch_github_latest_version,
md5_field,
requirement_entry,
)
from .rocknix_launchers import extract_launchers
from .shell_launchers import RepoTree
except ImportError:
from base_scraper import (
BaseScraper,
BiosRequirement,
fetch_github_latest_version,
md5_field,
requirement_entry,
)
from rocknix_launchers import extract_launchers
from shell_launchers import RepoTree
from .base_scraper import (
BaseScraper,
BiosRequirement,
fetch_github_latest_version,
md5_field,
requirement_entry,
)
from .rocknix_launchers import extract_launchers
from .shell_launchers import RepoTree
PLATFORM_NAME = "rocknix"
@@ -292,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))
@@ -321,10 +313,7 @@ class Scraper(BaseScraper):
def main() -> None:
"""Entry point."""
try:
from .base_scraper import scraper_cli
except ImportError:
from base_scraper import scraper_cli
from .base_scraper import scraper_cli
scraper_cli(Scraper, "Scrape ROCKNIX BIOS requirements")
+3 -4
View File
@@ -20,12 +20,11 @@ from collections.abc import Callable
from dataclasses import dataclass, field
from pathlib import Path
_SCRIPTS_DIR = str(Path(__file__).resolve().parents[2])
if _SCRIPTS_DIR not in sys.path:
if (_SCRIPTS_DIR := str(Path(__file__).resolve().parents[2])) not in sys.path:
sys.path.insert(0, _SCRIPTS_DIR)
import upstream # noqa: E402
from safeparse import yaml_load # noqa: E402
import upstream
from safeparse import yaml_load
CACHE_DIR = upstream.CACHE_DIR
+15 -9
View File
@@ -208,14 +208,20 @@ def parse_crossmix(spec: dict, fetcher: Fetcher) -> list[dict]:
# Koriki
class _CaseConfigParser(ConfigParser):
"""Option names kept as written: Koriki's keys are case-sensitive."""
def optionxform(self, optionstr: str) -> str:
return optionstr
@register("koriki")
def parse_koriki(spec: dict, fetcher: Fetcher) -> list[dict]:
params = spec["params"]
key = params["source"]
path = params["sections"]
text = fetcher.text(key, path)
parser = ConfigParser(interpolation=None, strict=False)
parser.optionxform = str # type: ignore[assignment]
parser = _CaseConfigParser(interpolation=None, strict=False)
parser.read_string(text)
skip = set(params.get("skip", []))
rows = []
@@ -353,8 +359,8 @@ def parse_minui(spec: dict, fetcher: Fetcher) -> list[dict]:
match = re.match(r"^skeleton/[^/]+/Roms/([^/]+)/", path)
if match:
name = match.group(1)
tag = re.search(r"\(([^()]*)\)\s*$", name)
shipped.setdefault(tag.group(1) if tag else name, name)
paren = re.search(r"\(([^()]*)\)\s*$", name)
shipped.setdefault(paren.group(1) if paren else name, name)
paks: dict[str, dict[str, tuple[str, str]]] = {}
for path in tree:
match = _PAK.match(path)
@@ -492,12 +498,12 @@ def parse_gmenu2x(spec: dict, fetcher: Fetcher) -> list[dict]:
}
key = params["source"]
for path in fetcher.tree(key, params["shipped_roms"] + "/"):
folder = path[len(params["shipped_roms"]) + 1:].split("/")
if len(folder) < 2 or folder[0] in rows:
parts = path[len(params["shipped_roms"]) + 1:].split("/")
if len(parts) < 2 or parts[0] in rows:
continue
rows[folder[0]] = {
"folder": folder[0],
"source_ref": ref(key, f"{params['shipped_roms']}/{folder[0]}"),
rows[parts[0]] = {
"folder": parts[0],
"source_ref": ref(key, f"{params['shipped_roms']}/{parts[0]}"),
"note": "folder the image ships. Its emulator link lives in a release package no repository holds",
}
return list(rows.values())
+47 -34
View File
@@ -160,8 +160,8 @@ def batocera_es(spec: dict, fetcher: Fetcher) -> list[dict]:
continue
if not system.get("emulators") and not system.get("force"):
continue
path = system.get("path", name)
if not path or str(path).startswith("/"):
folder = system.get("path", name)
if not folder or str(folder).startswith("/"):
continue
base = defaults.get(name) or {}
emulator, core = base.get("emulator"), base.get("core")
@@ -175,7 +175,7 @@ def batocera_es(spec: dict, fetcher: Fetcher) -> list[dict]:
if name in def_lines:
refs.append(_ref(key, def_path, def_lines[name]))
rows.append({
"folder": str(path),
"folder": str(folder),
"name": name,
"extensions": _extensions(system.get("extensions")),
"core": str(core) if core else None,
@@ -393,6 +393,40 @@ def _conf_values(text: str) -> tuple[dict[str, str], dict[str, int]]:
return values, lines
def _nesting(line: str, stack: list[list[str]]) -> bool:
"""Follow case and if nesting. True when the line is consumed."""
match = re.match(r'case\s+"?\$\{?(\w+)\}?"?\s+in', line)
if match:
stack.append(["case", match.group(1), ""])
return True
if line == "esac":
stack.pop()
return True
if line.startswith("if ") or line.startswith("[") and "&&" not in line and line.endswith("then"):
stack.append(["if", line, ""])
return True
if line in ("fi",):
if stack and stack[-1][0] == "if":
stack.pop()
return True
return line in ("then", "else") or line.startswith("elif ")
def _record_call(
words: list[str], number: int, stack: list[list[str]],
cores: list[dict], systems: dict[str, list[int]],
) -> None:
branches = [(s[1], s[2]) for s in stack]
if words[:1] == ["add_emu_core"] and len(words) >= 4:
cores.append({
"system": words[1], "emulator": words[2], "core": words[3],
"default": len(words) > 4 and words[4] == "true",
"branches": branches, "line": number,
})
elif words[:1] == ["add_es_system"] and len(words) >= 2:
systems.setdefault(words[1], []).append(number)
def _package_calls(text: str) -> tuple[list[dict], dict[str, list[int]]]:
"""add_emu_core and add_es_system calls of makeinstall_target, each
with the `case` branches it sits under as (variable, pattern) pairs.
@@ -412,21 +446,7 @@ def _package_calls(text: str) -> tuple[list[dict], dict[str, list[int]]]:
continue
if raw.startswith("}"):
break
match = re.match(r'case\s+"?\$\{?(\w+)\}?"?\s+in', line)
if match:
stack.append(["case", match.group(1), ""])
continue
if line == "esac":
stack.pop()
continue
if line.startswith("if ") or line.startswith("[") and "&&" not in line and line.endswith("then"):
stack.append(["if", line, ""])
continue
if line in ("fi",):
if stack and stack[-1][0] == "if":
stack.pop()
continue
if line in ("then", "else") or line.startswith("elif "):
if _nesting(line, stack):
continue
ends = line.endswith(";;")
if ends:
@@ -436,16 +456,7 @@ def _package_calls(text: str) -> tuple[list[dict], dict[str, list[int]]]:
if match and not line.startswith(("add_", "[", "sed", "cp", "mkdir")):
stack[-1][2] = match.group(1).strip()
line = match.group(2).strip()
words = line.split()
branches = [(s[1], s[2]) for s in stack]
if words[:1] == ["add_emu_core"] and len(words) >= 4:
cores.append({
"system": words[1], "emulator": words[2], "core": words[3],
"default": len(words) > 4 and words[4] == "true",
"branches": branches, "line": number,
})
elif words[:1] == ["add_es_system"] and len(words) >= 2:
systems.setdefault(words[1], []).append(number)
_record_call(line.split(), number, stack, cores, systems)
if ends and stack and stack[-1][0] == "case":
stack[-1][2] = ""
return cores, systems
@@ -487,7 +498,8 @@ def elec_conf(spec: dict, fetcher: Fetcher) -> list[dict]:
flagged = [c for c in mine if c["default"]]
plain = [c for c in flagged if not c["branches"]]
star = [c for c in flagged if c["branches"] and c["branches"][-1][1] == "*"]
pick = (plain or star or flagged or [None])[0]
candidates = plain or star or flagged
pick: dict | None = candidates[0] if candidates else None
if pick is None:
pick = next((c for c in mine if not c["branches"]), mine[0] if mine else None)
board_defaults = {}
@@ -861,10 +873,11 @@ def recalbox(spec: dict, fetcher: Fetcher) -> list[dict]:
core, core_line = _recalbox_get(sections, lines, section, "core", board)
emulator, _ = _recalbox_get(sections, lines, section, "emulator", board)
exts, _ = _recalbox_get(sections, lines, section, "extensions", board)
if (exts or "").startswith(_FILES_PREFIX):
names.update(_recalbox_names(exts[len(_FILES_PREFIX):]))
listed = exts or ""
if listed.startswith(_FILES_PREFIX):
names.update(_recalbox_names(listed[len(_FILES_PREFIX):]))
else:
extensions.update((exts or "").split())
extensions.update(listed.split())
cores.append({
"core": core, "emulator": emulator, "priority": int(priority or "255"),
"source_ref": "; ".join([
@@ -968,8 +981,8 @@ def retropie(spec: dict, fetcher: Fetcher) -> list[dict]:
cfg_path = params["platforms_cfg"]
cfg = fetcher.text(key, cfg_path)
exts: dict[str, tuple[str, int]] = {}
for number, line in enumerate(cfg.splitlines(), 1):
match = re.match(r'^([\w-]+)_exts="([^"]*)"', line)
for number, cfg_line in enumerate(cfg.splitlines(), 1):
match = re.match(r'^([\w-]+)_exts="([^"]*)"', cfg_line)
if match:
exts[match.group(1)] = (match.group(2), number)
platform = set(params["platform_flags"])
+22 -31
View File
@@ -26,22 +26,13 @@ import json
import re
import sys
try:
from .base_scraper import (
BaseScraper,
BiosRequirement,
fetch_bytes,
fetch_github_latest_version,
requirement_entry,
)
except ImportError:
from base_scraper import (
BaseScraper,
BiosRequirement,
fetch_bytes,
fetch_github_latest_version,
requirement_entry,
)
from .base_scraper import (
BaseScraper,
BiosRequirement,
fetch_bytes,
fetch_github_latest_version,
requirement_entry,
)
PLATFORM_NAME = "romm"
@@ -194,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:
@@ -216,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
+87 -56
View File
@@ -31,7 +31,6 @@ from __future__ import annotations
import argparse
import hashlib
import io
import json
import os
import re
@@ -41,8 +40,10 @@ import urllib.parse
import urllib.request
import zipfile
from collections.abc import Callable, Iterator
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import IO
from ..common import (
list_registered_platforms,
@@ -62,9 +63,9 @@ DEFAULT_OUTPUT = "recipes/{source}.json"
def relevant_archives(emulators_dir: str, platforms_dir: str) -> set[str]:
"""Archive names any profile or platform refers to."""
names: set[str] = set()
for _profile_name, profile in load_emulator_profiles(
for profile in load_emulator_profiles(
emulators_dir, skip_aliases=False
).items():
).values():
for entry in profile.get("files", []) or []:
name = entry.get("name", "")
if name.endswith(".zip"):
@@ -283,7 +284,7 @@ def _machine_roms(blob: bytes) -> list[dict]:
def _scan_listxml(
stream: io.BufferedIOBase,
stream: IO[bytes],
selector: Callable[[str], bool],
targets: Targets | None = None,
) -> dict[str, tuple[str | None, list[dict]]]:
@@ -326,7 +327,7 @@ def _scan_listxml(
def listxml_entries(
open_stream: Callable[[], io.BufferedIOBase],
open_stream: Callable[[], IO[bytes]],
label: str,
keep: set[str] | None,
targets: Targets | None = None,
@@ -575,6 +576,8 @@ def fetch_pack(
if not sha:
raise BlobMismatchError(f"libretro/FBNeo has no revision {tag}")
listing = _api_json(f"{FBNEO_API}/contents/dats?ref={sha}")
if not isinstance(listing, list):
raise BlobMismatchError(f"libretro/FBNeo lists no dats at {sha}")
target = cache_dir / "fbneo-dats"
target.mkdir(parents=True, exist_ok=True)
blobs: dict[str, str] = {}
@@ -616,21 +619,21 @@ def _is_listxml(pack: Path) -> bool:
return b"<!ELEMENT mame" in handle.read(4096)
def _listxml_opener(pack: Path) -> Callable[[], io.BufferedIOBase]:
def _listxml_opener(pack: Path) -> Callable[[], IO[bytes]]:
"""A callable giving a fresh byte stream over the listxml document."""
if pack.suffix.lower() == ".zip":
def opener() -> zipfile.ZipExtFile:
def opener() -> IO[bytes]:
archive = zipfile.ZipFile(pack)
name = next(n for n in archive.namelist() if n.lower().endswith(".xml"))
stream = archive.open(name)
stream.close_archive = archive # keep the archive alive
return stream
# The member keeps the archive alive: its shared file closes
# through the archive's own _fpclose.
return archive.open(name)
return opener
return lambda: pack.open("rb")
def main() -> int:
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(allow_abbrev=False, description=__doc__)
parser.add_argument(
"--source", choices=SOURCES, required=True,
@@ -677,6 +680,76 @@ def main() -> int:
"--dry-run", action="store_true",
help="print what would change and write nothing",
)
return parser
@dataclass(frozen=True)
class _Selection:
"""Which sets a snapshot keeps: None everywhere keeps every set."""
keep: set[str] | None = None
targets: Targets | None = None
by_members: ByMembers | None = None
def _selection(args: argparse.Namespace) -> _Selection:
if args.all:
return _Selection()
held, by_members = collection_archives(args.db)
keep = relevant_archives(args.emulators_dir, args.platforms_dir) | held
targets = catalog_targets(args.provenance_dir, args.db)
return _Selection(keep, targets, by_members)
def _import_listxml(pack: Path, args: argparse.Namespace, output: str, chosen: _Selection) -> int:
label = f"MAME {pack.stem.replace('lx', '')}"
entries = listxml_entries(
_listxml_opener(pack), label, chosen.keep, chosen.targets, chosen.by_members
)
dats = {label: pack.stem}
print(f" {label}: {len(entries)} sets retenus")
members = sum(len(entry["members"]) for entry in entries)
print(f"{len(entries)} recettes, {members} membres, depuis 1 listxml")
if args.dry_run:
return 0
changed = merge_snapshot(output, args.source, dats, entries)
print(f"{'Wrote' if changed else 'Unchanged'} {output}")
return 0
def _dat_recipes(
pack: Path, revision: str, chosen: _Selection
) -> tuple[dict[str, str], list[dict]]:
"""Recipes of every Logiqx DAT a pack holds, and each DAT's version."""
dats: dict[str, str] = {}
entries: list[dict] = []
skipped = 0
for member, content in _iter_dat_contents(pack):
try:
dat = parse_logiqx(content)
except (ValueError, SyntaxError) as exc:
print(f" Skipped {member}: {exc}", file=sys.stderr)
skipped += 1
continue
if not dat.roms:
skipped += 1
continue
if revision:
dat.name = f"{dat.name or member} @ {revision}"
found = recipe_entries(dat, chosen.keep, chosen.targets, chosen.by_members)
if not found:
continue
dats[dat.name or member] = dat.version
entries.extend(found)
print(f" {dat.name or member}: {len(found)} sets retenus")
if skipped:
print(f" {skipped} fichier(s) ignore(s) (non-Logiqx ou vides)")
return dats, entries
def main() -> int:
parser = _parser()
args = parser.parse_args()
blobs: dict[str, str] = {}
@@ -708,54 +781,12 @@ def main() -> int:
output = args.output or DEFAULT_OUTPUT.format(source=args.source)
Path(output).parent.mkdir(parents=True, exist_ok=True)
keep: set[str] | None = None
targets = None
by_members: ByMembers | None = None
if not args.all:
held, by_members = collection_archives(args.db)
keep = relevant_archives(args.emulators_dir, args.platforms_dir) | held
targets = catalog_targets(args.provenance_dir, args.db)
dats: dict[str, str] = {}
entries: list[dict] = []
skipped = 0
chosen = _selection(args)
if _is_listxml(pack):
label = f"MAME {pack.stem.replace('lx', '')}"
entries = listxml_entries(
_listxml_opener(pack), label, keep, targets, by_members
)
dats[label] = pack.stem
print(f" {label}: {len(entries)} sets retenus")
members = sum(len(entry["members"]) for entry in entries)
print(f"{len(entries)} recettes, {members} membres, depuis 1 listxml")
if args.dry_run:
return 0
changed = merge_snapshot(output, args.source, dats, entries)
print(f"{'Wrote' if changed else 'Unchanged'} {output}")
return 0
return _import_listxml(pack, args, output, chosen)
for member, content in _iter_dat_contents(pack):
try:
dat = parse_logiqx(content)
except (ValueError, SyntaxError) as exc:
print(f" Skipped {member}: {exc}", file=sys.stderr)
skipped += 1
continue
if not dat.roms:
skipped += 1
continue
if revision:
dat.name = f"{dat.name or member} @ {revision}"
found = recipe_entries(dat, keep, targets, by_members)
if not found:
continue
dats[dat.name or member] = dat.version
entries.extend(found)
print(f" {dat.name or member}: {len(found)} sets retenus")
if skipped:
print(f" {skipped} fichier(s) ignore(s) (non-Logiqx ou vides)")
dats, entries = _dat_recipes(pack, revision, chosen)
members = sum(len(entry["members"]) for entry in entries)
print(f"{len(entries)} recettes, {members} membres, depuis {len(dats)} DAT")
+140 -97
View File
@@ -15,12 +15,8 @@ import re
from collections.abc import Callable, Iterable
from dataclasses import dataclass, field
try:
from .base_scraper import fetch_bytes, github_headers
from .configgen_launchers import LauncherShapeError
except ImportError:
from base_scraper import fetch_bytes, github_headers
from configgen_launchers import LauncherShapeError
from .base_scraper import fetch_bytes, github_headers
from .configgen_launchers import LauncherShapeError
NAME = r"[A-Za-z_][A-Za-z0-9_]*"
# A single-quoted "$" is literal: it is carried as this mark through expansion.
@@ -120,62 +116,89 @@ def words(line: str) -> list[Word]:
ended a name ("$a""b") still ends it. A "$" inside single quotes is kept
as LITERAL_DOLLAR so a later expansion leaves it alone.
"""
result: list[Word] = []
raw, text, quote, started, segment = "", "", "", False, 0
def close_segment() -> None:
nonlocal text, segment
text = text[:segment] + re.sub(rf"\$({NAME})", r"${\1}", text[segment:])
segment = len(text)
lexer = _Lexer(line)
i = 0
while i < len(line):
char = line[i]
if quote == "'":
raw += char
if char == "'":
quote = ""
segment = len(text)
else:
text += LITERAL_DOLLAR if char == "$" else char
elif quote == '"':
raw += char
if char == "\\" and i + 1 < len(line) and line[i + 1] in '"\\$`':
raw += line[i + 1]
text += LITERAL_DOLLAR if line[i + 1] == "$" else line[i + 1]
i += 1
elif char == '"':
quote = ""
close_segment()
else:
text += char
elif char in "'\"":
close_segment()
quote, started = char, True
raw += char
elif char == "\\" and i + 1 < len(line):
raw += char + line[i + 1]
text += line[i + 1]
started = True
i += 1
elif char == "#" and not started:
break
elif char.isspace() or char == ";":
if started:
close_segment()
result.append(Word(raw, text))
raw, text, started, segment = "", "", False, 0
if char == ";":
result.append(Word(";", ";"))
if lexer.quote == "'":
lexer.single(line[i])
elif lexer.quote == '"':
i = lexer.double(i)
else:
raw += char
text += char
started = True
step = lexer.plain(i)
if step is None:
break
i = step
i += 1
if started:
close_segment()
result.append(Word(raw, text))
return result
if lexer.started:
lexer.close_segment()
lexer.result.append(Word(lexer.raw, lexer.text))
return lexer.result
class _Lexer:
"""The state words() keeps while it reads a line character by character."""
def __init__(self, line: str) -> None:
self.line = line
self.result: list[Word] = []
self.raw, self.text, self.quote, self.started, self.segment = "", "", "", False, 0
def close_segment(self) -> None:
self.text = self.text[:self.segment] + re.sub(
rf"\$({NAME})", r"${\1}", self.text[self.segment:]
)
self.segment = len(self.text)
def single(self, char: str) -> None:
"""One character inside single quotes."""
self.raw += char
if char == "'":
self.quote = ""
self.segment = len(self.text)
else:
self.text += LITERAL_DOLLAR if char == "$" else char
def double(self, i: int) -> int:
"""The character at i inside double quotes; the index of the last one read."""
line, char = self.line, self.line[i]
self.raw += char
if char == "\\" and i + 1 < len(line) and line[i + 1] in '"\\$`':
self.raw += line[i + 1]
self.text += LITERAL_DOLLAR if line[i + 1] == "$" else line[i + 1]
return i + 1
if char == '"':
self.quote = ""
self.close_segment()
else:
self.text += char
return i
def plain(self, i: int) -> int | None:
"""The character at i outside quotes; the index of the last one read, None at a comment."""
line, char = self.line, self.line[i]
if char in "'\"":
self.close_segment()
self.quote, self.started = char, True
self.raw += char
elif char == "\\" and i + 1 < len(line):
self.raw += char + line[i + 1]
self.text += line[i + 1]
self.started = True
return i + 1
elif char == "#" and not self.started:
return None
elif char.isspace() or char == ";":
if self.started:
self.close_segment()
self.result.append(Word(self.raw, self.text))
self.raw, self.text, self.started, self.segment = "", "", False, 0
if char == ";":
self.result.append(Word(";", ";"))
else:
self.raw += char
self.text += char
self.started = True
return i
@dataclass
@@ -492,6 +515,58 @@ def _quoted_glob(command: str) -> bool:
return "*" in raw and "*" not in re.sub(r'"[^"]*"|\'[^\']*\'', "", raw)
def _copy_skips(
script: Script,
number: int,
line: str,
copy: re.Match[str],
target: str,
source_name: str,
sources: tuple[str, ...],
) -> bool | None:
"""For a copy that installs ``target``, whether it leaves a file already there.
None when the copy installs something else.
"""
args = []
for word in words(line[copy.start(1):])[1:]:
# The command ends at a separator or a redirection.
if word.raw in {";", "&&", "||", "|"} or re.match(r"\d*>|&>", word.raw):
break
args.append(word.text)
operands = [a for a in args if not a.startswith("-")]
if not operands:
return None
# A quoted "*" is a file named *, which no package installs:
# the copy does nothing (EmuELEC's duckstation.sh).
if _quoted_glob(line[copy.start(1):]):
return None
destination = script.expand(operands[-1], number, set()).rstrip("/")
source = script.expand(operands[0], number, set()).rstrip("/")
hits = target == destination or target.startswith(
(destination + "/", f"{destination}/{source.rsplit('/', 1)[-1]}")
)
# A copy of another file into the same place is another
# record's: amiberry copies the A500 or the A1200 setup.
named = source.rsplit("/", 1)[-1]
if not hits or (source_name and "." in named and named != source_name):
return None
# A named file copied into a folder above the target is
# another file of that folder (ARMSX2's secrets.ini).
if (
not source_name and "." in named and "*" not in named
and destination != target and named != target.rsplit("/", 1)[-1]
):
return None
if sources and not source.startswith(sources):
return None
# cp -i fed by false answers no to every overwrite.
prompted = any(
a.startswith("-") and not a.startswith("--") and "i" in a[1:] for a in args
) and re.search(r"\bfalse\s*\|\s*$", line[:copy.start(1)])
return "-n" in args or "--ignore-existing" in args or bool(prompted)
def config_placement(
script: Script,
target: str,
@@ -517,43 +592,10 @@ def config_placement(
for number, line in script.code():
if (copy := _COPY.search(line)) or (writer and writer.search(line)):
if copy:
args = []
for word in words(line[copy.start(1):])[1:]:
# The command ends at a separator or a redirection.
if word.raw in {";", "&&", "||", "|"} or re.match(r"\d*>|&>", word.raw):
break
args.append(word.text)
operands = [a for a in args if not a.startswith("-")]
if not operands:
copied = _copy_skips(script, number, line, copy, target, source_name, sources)
if copied is None:
continue
# A quoted "*" is a file named *, which no package installs:
# the copy does nothing (EmuELEC's duckstation.sh).
if _quoted_glob(line[copy.start(1):]):
continue
destination = script.expand(operands[-1], number, set()).rstrip("/")
source = script.expand(operands[0], number, set()).rstrip("/")
hits = target == destination or target.startswith(destination + "/") or (
target.startswith(f"{destination}/{source.rsplit('/', 1)[-1]}")
)
# A copy of another file into the same place is another
# record's: amiberry copies the A500 or the A1200 setup.
named = source.rsplit("/", 1)[-1]
if not hits or (source_name and "." in named and named != source_name):
continue
# A named file copied into a folder above the target is
# another file of that folder (ARMSX2's secrets.ini).
if (
not source_name and "." in named and "*" not in named
and destination != target and named != target.rsplit("/", 1)[-1]
):
continue
if sources and not source.startswith(sources):
continue
# cp -i fed by false answers no to every overwrite.
prompted = any(
a.startswith("-") and not a.startswith("--") and "i" in a[1:] for a in args
) and re.search(r"\bfalse\s*\|\s*$", line[:copy.start(1)])
skip = "-n" in args or "--ignore-existing" in args or bool(prompted)
skip = copied
else:
skip = False
install.add(number)
@@ -561,9 +603,10 @@ def config_placement(
kept = False
elif re.search(r"\bsed\b.*\s-i\b|\bsed -i", line) and bare:
expanded = script.expand(line, number, set())
if target in expanded or target.rsplit("/", 1)[-1] in expanded:
if any(re.search(rf"\b{re.escape(k)}\b", expanded) for k in bare):
overrides.add(number)
if (target in expanded or target.rsplit("/", 1)[-1] in expanded) and any(
re.search(rf"\b{re.escape(k)}\b", expanded) for k in bare
):
overrides.add(number)
if not install and required:
raise script.missing(f"install of {target}")
return ConfigPlacement(script.path, target, install, kept, overrides)
+1 -1
View File
@@ -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__)
@@ -24,23 +24,16 @@ from datetime import datetime, timezone
import yaml
from . import BaseTargetScraper
from ..amberelec_scraper import BUILDS_OF, ES_SYSTEMS_TEMPLATE, RUNNERS
from ..base_scraper import fetch_bytes
from ..batocera_scraper import _not_cores
from ..es_emulators import es_cores, xml_systems
PLATFORM_NAME = "amberelec"
RAW_BASE = "https://raw.githubusercontent.com/AmberELEC/AmberELEC/{ref}"
META_MK = "packages/amberelec/package.mk"
try:
from ..amberelec_scraper import BUILDS_OF, ES_SYSTEMS_TEMPLATE, RUNNERS
from ..base_scraper import fetch_bytes
from ..batocera_scraper import _not_cores
from ..es_emulators import es_cores, xml_systems
except ImportError:
from scraper.amberelec_scraper import BUILDS_OF, ES_SYSTEMS_TEMPLATE, RUNNERS
from scraper.base_scraper import fetch_bytes
from scraper.batocera_scraper import _not_cores
from scraper.es_emulators import es_cores, xml_systems
_DEVICE_RE = re.compile(
r"^(\w+):\n\tDEVICE=(\w+) ARCH=(\w+) \./scripts/build_distro$", re.MULTILINE
)
@@ -30,14 +30,10 @@ import yaml
from safeparse import yaml_load_upstream
from . import BaseTargetScraper
from ..base_scraper import github_headers
PLATFORM_NAME = "batocera"
try:
from ..base_scraper import github_headers
except ImportError:
from scraper.base_scraper import github_headers
_TARGET_FLAG_RE = re.compile(r"^(BR2_PACKAGE_BATOCERA_TARGET_\w+)=y", re.MULTILINE)
# The images a target flag builds, each a board directory whose last segment
@@ -306,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")
@@ -35,6 +35,12 @@ from typing import NamedTuple
import yaml
from . import BaseTargetScraper
from ..base_scraper import fetch_bytes, github_headers
from ..batocera_scraper import _not_cores
from ..emuelec_scraper import (
BUILDS_OF, ES_SYSTEMS_TEMPLATE, PORTS_TEMPLATE, RUNNERS, port_engines, with_ports,
)
from ..es_emulators import SystemEmulators, es_cores
PLATFORM_NAME = "emuelec"
@@ -45,21 +51,6 @@ META_MK = "packages/sx05re/emuelec/package.mk"
OPTIONS = "distributions/EmuELEC/options"
ES_MK = "packages/sx05re/emuelec-emulationstation/package.mk"
try:
from ..base_scraper import fetch_bytes, github_headers
from ..batocera_scraper import _not_cores
from ..emuelec_scraper import (
BUILDS_OF, ES_SYSTEMS_TEMPLATE, PORTS_TEMPLATE, RUNNERS, port_engines, with_ports,
)
from ..es_emulators import SystemEmulators, es_cores
except ImportError:
from scraper.base_scraper import fetch_bytes, github_headers
from scraper.batocera_scraper import _not_cores
from scraper.emuelec_scraper import (
BUILDS_OF, ES_SYSTEMS_TEMPLATE, PORTS_TEMPLATE, RUNNERS, port_engines, with_ports,
)
from scraper.es_emulators import SystemEmulators, es_cores
_ASSET_RE = re.compile(r"^EmuELEC-(?P<device>[A-Za-z0-9-]+)\.(?P<arch>[a-z0-9_]+)-")
# The metapackage, line for line. Each rule below transcribes these lines;
@@ -21,6 +21,7 @@ from datetime import datetime, timezone
import yaml
from . import BaseTargetScraper
from ..base_scraper import fetch_bytes, github_headers
PLATFORM_NAME = "lakka"
@@ -29,11 +30,6 @@ RAW_BASE = "https://raw.githubusercontent.com/" + REPO + "/{tag}"
API_BASE = "https://api.github.com/repos/" + REPO
CORES_MK = "packages/lakka/libretro_cores/package.mk"
try:
from ..base_scraper import fetch_bytes, github_headers
except ImportError:
from scraper.base_scraper import fetch_bytes, github_headers
_IF_RE = re.compile(r"^(if|elif)\s+\[\s+(.*?)\s+\];?\s*(?:then)?\s*$")
_TEST_RE = re.compile(r'^(!\s+)?"\$\{?(\w+)\}?"\s*(=|!=)\s*"?([^"\s]*)"?$')
_SET_RE = re.compile(r"^\s*-([nz])\s+\"\$\{?(\w+)\}?\"\s*$")
@@ -85,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.
@@ -93,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]:
@@ -22,6 +22,8 @@ from datetime import datetime, timezone
import yaml
from . import BaseTargetScraper
from ..base_scraper import fetch_bytes
from ..recalbox_scraper import SYSTEMS_TREE_URL, Scraper as PlatformScraper, board_cores
PLATFORM_NAME = "recalbox"
@@ -33,13 +35,6 @@ DEFCONFIG_URL = "https://gitlab.com/recalbox/recalbox/-/raw/{tag}/configs/{name}
_DEFCONFIG_RE = re.compile(r"^recalbox-(\w+)_defconfig$")
_ENABLED_RE = re.compile(r"^(BR2_PACKAGE_\w+)=y\s*$", re.MULTILINE)
try:
from ..base_scraper import fetch_bytes
from ..recalbox_scraper import SYSTEMS_TREE_URL, Scraper as PlatformScraper, board_cores
except ImportError:
from scraper.base_scraper import fetch_bytes
from scraper.recalbox_scraper import SYSTEMS_TREE_URL, Scraper as PlatformScraper, board_cores
def enabled_packages(defconfig: str) -> set[str]:
"""The Buildroot packages a defconfig turns on."""
@@ -23,6 +23,8 @@ from datetime import datetime, timezone
import yaml
from . import BaseTargetScraper
from ..base_scraper import fetch_bytes, github_headers
from ..rocknix_scraper import standalone_emulators
PLATFORM_NAME = "rocknix"
@@ -31,13 +33,6 @@ GITHUB_API = "https://api.github.com/repos/ROCKNIX/distribution/contents"
EMULATORS_MK = "projects/ROCKNIX/packages/virtual/emulators/package.mk"
DEVICES_DIR = "projects/ROCKNIX/devices"
try:
from ..base_scraper import fetch_bytes, github_headers
from ..rocknix_scraper import standalone_emulators
except ImportError:
from scraper.base_scraper import fetch_bytes, github_headers
from scraper.rocknix_scraper import standalone_emulators
# `NAME="a b \
# c"` or `NAME+=" a b"`, continuation lines joined first.
_ASSIGN_RE = re.compile(r'^\s*(?:\[[^\]]*\]\s*&&\s*)?(\w+)(\+?=)"([^"]*)"', re.MULTILINE)
@@ -98,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.
@@ -115,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
@@ -143,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]
@@ -153,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))