chore: merge main into the lint work

This commit is contained in:
Abdessamad Derraz committed 2026-11-17 09:05:08 +01:00
commit 0e763fd013
140 files changed
+5578 -4151

No files matched your search

+1
View File
@@ -243,6 +243,7 @@ def step2_scan_branches(entry: dict) -> bytes | None:
["git", "ls-tree", "-r", "--name-only", ref],
capture_output=True,
text=True,
check=False,
)
for filepath in result.stdout.strip().split("\n"):
+8 -10
View File
@@ -587,11 +587,10 @@ def sync_worktree(worktree: Path) -> str:
ahead = int(git(worktree, "rev-list", "--count", f"{upstream}..HEAD").stdout)
if ahead == 0:
git(worktree, "merge", "--ff-only", "--quiet", upstream)
elif git(worktree, "merge-base", "--is-ancestor", upstream, "HEAD",
check=False).returncode != 0:
if git(worktree, "rebase", "--quiet", upstream, check=False).returncode != 0:
git(worktree, "rebase", "--abort", check=False)
raise AutorunError(BLOCKED, f"{ahead} automation commits conflict with {upstream}")
elif (git(worktree, "merge-base", "--is-ancestor", upstream, "HEAD", check=False).returncode != 0
and git(worktree, "rebase", "--quiet", upstream, check=False).returncode != 0):
git(worktree, "rebase", "--abort", check=False)
raise AutorunError(BLOCKED, f"{ahead} automation commits conflict with {upstream}")
return git(worktree, "rev-parse", upstream).stdout.strip()
@@ -608,11 +607,10 @@ def push_batch(worktree: Path, gate_base: str, regate: Callable[[], bool]) -> st
upstream = f"{REMOTE}/{TARGET}"
if int(git(worktree, "rev-list", "--count", f"{upstream}..HEAD").stdout) == 0:
return ""
if git(worktree, "merge-base", "--is-ancestor", upstream, "HEAD",
check=False).returncode != 0:
if git(worktree, "rebase", "--quiet", upstream, check=False).returncode != 0:
git(worktree, "rebase", "--abort", check=False)
raise AutorunError(BLOCKED, f"rebase onto {upstream} conflicts, batch kept")
if (git(worktree, "merge-base", "--is-ancestor", upstream, "HEAD", check=False).returncode != 0
and git(worktree, "rebase", "--quiet", upstream, check=False).returncode != 0):
git(worktree, "rebase", "--abort", check=False)
raise AutorunError(BLOCKED, f"rebase onto {upstream} conflicts, batch kept")
if git(worktree, "rev-parse", upstream).stdout.strip() != gate_base and not regate():
raise AutorunError(FAILED, f"gate failed on the batch rebased onto {upstream}")
git(worktree, "push", "--quiet", REMOTE, f"HEAD:{TARGET}", env=token_env())
+211 -127
View File
@@ -64,6 +64,7 @@ import argparse
import contextlib
import datetime as dt
import hashlib
import http.client
import io
import json
import os
@@ -82,6 +83,10 @@ import zipfile
from collections.abc import Callable, Iterator, Sequence
from dataclasses import dataclass, field
from pathlib import Path
from typing import IO, TYPE_CHECKING, TypedDict, TypeVar
if TYPE_CHECKING:
from typing_extensions import Unpack
sys.path.insert(0, str(Path(__file__).resolve().parent))
@@ -95,6 +100,9 @@ import autorun
import campaign_profiles
import campaign_rules as rules
import measurement_records as mr
from autorun import now_iso
T = TypeVar("T")
ROOT = Path(__file__).resolve().parent.parent
CONTENT_FILE = ROOT / "tests" / "campaign" / "content.yml"
@@ -134,10 +142,6 @@ class Unavailable(RuntimeError):
# Small helpers
# --------------------------------------------------------------------------
def now_iso() -> str:
return dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat()
def slug(text: str) -> str:
return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-") or "x"
@@ -213,8 +217,18 @@ def is_bios(entry: dict) -> bool:
# Host
# --------------------------------------------------------------------------
class PopenOptions(TypedDict, total=False):
"""The Popen arguments the campaign passes through run_group."""
cwd: str | Path
env: dict[str, str]
text: bool
stdout: int | IO[str] | IO[bytes]
stderr: int | IO[str] | IO[bytes]
def run_group(argv: Sequence[str], *, timeout: float | None = None, check: bool = False,
capture_output: bool = False, **kwargs: object) -> subprocess.CompletedProcess:
capture_output: bool = False, **kwargs: Unpack[PopenOptions]) -> subprocess.CompletedProcess:
"""subprocess.run in a process group of its own, the whole group killed
on a timeout or an interruption: a hung core never outlives its run."""
if capture_output:
@@ -245,7 +259,7 @@ class Host:
free_gb: Callable[[Path], float] = autorun.free_gb
poll: float = 60.0
run: Callable[..., subprocess.CompletedProcess] = run_group
urlopen: Callable[..., object] = urllib.request.urlopen
urlopen: Callable[..., http.client.HTTPResponse] = urllib.request.urlopen
@property
def max_load(self) -> float:
@@ -413,11 +427,11 @@ def export_commit(mirror: Callable[[str], Path], url: str, commit: str, dest: Pa
except subprocess.CalledProcessError:
git_out("-C", str(bare), "fetch", "--quiet", repo_url, sha)
extract_tar(git_out("-C", str(bare), "archive", "--format=tar", sha), target)
links = {}
links: dict[str, str] = {}
for entry in git_out("-C", str(bare), "ls-tree", "-r", "-z", sha).split(b"\0"):
if entry.startswith(b"160000 commit "):
meta, path = entry.split(b"\t", 1)
links[path.decode()] = meta.split()[2].decode()
meta, raw_path = entry.split(b"\t", 1)
links[raw_path.decode()] = meta.split()[2].decode()
if not links:
return
try:
@@ -739,7 +753,7 @@ class Cores:
self.c = campaign
self.listing: set[str] | None = None
def retrying(self, what: str, call: Callable[[], object]) -> object:
def retrying(self, what: str, call: Callable[[], T]) -> T:
for attempt, delay in enumerate((*self.c.settings.delays, None)):
try:
return call()
@@ -896,6 +910,28 @@ class Unit:
buildbot_only: bool = False
@dataclass(frozen=True)
class Trial:
"""One core on one content: what every check of that pairing shares."""
unit: Unit
core: Core
content: Content
load: Path
frames: list[str]
digest: str
@dataclass(frozen=True)
class Held:
"""A declared file the collection holds, at its place."""
index: int
entry: dict
dest: str
local: Path
@dataclass
class Pass:
started: str
@@ -1168,12 +1204,7 @@ class Campaign:
if local and entry_dest(entry) not in staged:
staged[entry_dest(entry)] = (index, entry, local)
tested = {dest: item for dest, item in staged.items() if region_matches(item[1], content.region)}
keys = {"files": self.check_key(core, content, "files"),
"none": self.check_key(core, content, "none")}
for dest in tested:
keys[f"negative:{dest}"] = self.check_key(core, content, f"negative:{dest}")
if self.settings.bench:
keys["bench"] = self.check_key(core, content, "bench")
keys = self.content_keys(core, content, tested)
# The rules run on every pass, from the records kept when nothing
# needs to run again: a change of the table applies without a run.
try:
@@ -1185,73 +1216,103 @@ class Campaign:
self.pending(emulator, key, str(exc), digest)
return
frames = ["--frames", str(content.frames), "--frame-hash-every", str(content.frame_hash_every)]
repeat = ["--repeat", str(self.settings.check_repeat)]
stem = f"{core.name}-{slug(content.name)}"
# files: every declared file the collection holds, at its place.
argv = self.probe_args("run", core, emulator, slug(f"files-{stem}"), content, load) + frames + repeat
for dest, (_, _, local) in sorted(staged.items()):
argv += ["--system-file", f"{dest}={local}"]
files_record = self.check(emulator, keys["files"], core, digest, argv, f"{emulator}-{stem}-files")
# none: no BIOS at all.
argv = self.probe_args("run", core, emulator, slug(f"none-{stem}"), content, load) + frames + repeat
none_record = self.check(emulator, keys["none"], core, digest, argv, f"{emulator}-{stem}-none")
if not files_record or not none_record:
trial = Trial(unit, core, content, load, frames, digest)
records = self.reference_runs(trial, keys, staged)
if not records:
return
files_record, none_record = records
full = rules.run_of(files_record, files_record["variants"][0]["label"])
none = rules.run_of(none_record, none_record["variants"][0]["label"])
self.log(f"{emulator}: {core.name} on {content.name}: full set {full.verdict}, "
f"no BIOS {none.verdict}")
for dest, (index, entry, local) in sorted(tested.items()):
record = self.negative(unit, core, content, load, frames, digest, keys[f"negative:{dest}"],
dest, entry, local, staged)
if not record:
continue
labels = [v["label"] for v in record["variants"]]
present = rules.run_of(record, labels[0])
zeros, half = (rules.run_of(record, label) for label in labels[1:3])
for label in labels[3:]:
self.log(f"{emulator}: {rules.rule_region(rules.run_of(record, label), present, entry, content.region)}")
if dest in self.opened(files_record, 0) or dest in self.opened(record, 0):
verdicts = rules.rule_need(none, present, entry, rules.read(none, present, zeros, half))
validation = rules.rule_validation(zeros, half, none, present, entry)
if validation:
verdicts.append(validation)
self.settle(emulator, content, core, index, entry, verdicts)
variants = self.variant_files(entry, local)
if variants:
self.run_variants(unit, core, content, load, frames, digest, index, entry, dest,
local, variants)
else:
self.moved(unit, core, content, load, frames, digest, index, entry, dest, local,
files_record, record)
self.test_entry(trial, keys[f"negative:{dest}"], Held(index, entry, dest, local), staged,
files_record, none)
boot = self.boot_entry(entries, content)
if boot and entry_dest(boot[1]) in tested:
index, entry = boot
self.follow_aliases(unit, core, content, load, frames, digest, index, entry,
tested[entry_dest(entry)][2], none_record)
self.follow_aliases(trial, index, entry, tested[entry_dest(entry)][2], none_record)
if self.settings.bench and full.verdict == rules.BOOTS:
argv = self.probe_args("bench", core, emulator, slug(f"bench-{stem}"), content, load)
argv += ["--warmup", str(self.settings.bench_warmup), "--frames",
str(self.settings.bench_frames), "--repeat", str(self.settings.bench_repeat),
"--no-trace"]
if boot:
argv += ["--system-file", f"{entry_dest(boot[1])}={self.local_file(boot[1])}"]
self.check(emulator, keys["bench"], core, digest, argv, f"{emulator}-{stem}-bench")
self.bench(trial, keys["bench"], boot)
def negative(self, unit: Unit, core: Core, content: Content, load: Path, frames: list[str],
digest: str, key: str, dest: str, entry: dict, local: Path,
def content_keys(self, core: Core, content: Content,
tested: dict[str, tuple[int, dict, Path]]) -> dict[str, str]:
keys = {"files": self.check_key(core, content, "files"),
"none": self.check_key(core, content, "none")}
for dest in tested:
keys[f"negative:{dest}"] = self.check_key(core, content, f"negative:{dest}")
if self.settings.bench:
keys["bench"] = self.check_key(core, content, "bench")
return keys
def reference_runs(self, trial: Trial, keys: dict[str, str],
staged: dict[str, tuple[int, dict, Path]]) -> tuple[dict, dict] | None:
"""The full set and no BIOS at all, or None while either is missing."""
core, emulator, content, load = trial.core, trial.unit.emulator, trial.content, trial.load
repeat = ["--repeat", str(self.settings.check_repeat)]
stem = f"{core.name}-{slug(content.name)}"
# files: every declared file the collection holds, at its place.
argv = self.probe_args("run", core, emulator, slug(f"files-{stem}"), content, load) + trial.frames + repeat
for dest, (_, _, local) in sorted(staged.items()):
argv += ["--system-file", f"{dest}={local}"]
files_record = self.check(emulator, keys["files"], core, trial.digest, argv, f"{emulator}-{stem}-files")
# none: no BIOS at all.
argv = self.probe_args("run", core, emulator, slug(f"none-{stem}"), content, load) + trial.frames + repeat
none_record = self.check(emulator, keys["none"], core, trial.digest, argv, f"{emulator}-{stem}-none")
if not files_record or not none_record:
return None
return files_record, none_record
def test_entry(self, trial: Trial, key: str, held: Held, staged: dict[str, tuple[int, dict, Path]],
files_record: dict, none: rules.Run) -> None:
"""One declared file alone and replaced, then what its runs settle."""
emulator, content, entry = trial.unit.emulator, trial.content, held.entry
record = self.negative(trial, key, held, staged)
if not record:
return
labels = [v["label"] for v in record["variants"]]
present = rules.run_of(record, labels[0])
zeros, half = (rules.run_of(record, label) for label in labels[1:3])
for label in labels[3:]:
self.log(f"{emulator}: {rules.rule_region(rules.run_of(record, label), present, entry, content.region)}")
if held.dest in self.opened(files_record, 0) or held.dest in self.opened(record, 0):
verdicts = rules.rule_need(none, present, entry, rules.read(none, present, zeros, half))
validation = rules.rule_validation(zeros, half, none, present, entry)
if validation:
verdicts.append(validation)
self.settle(emulator, content, trial.core, held.index, entry, verdicts)
variants = self.variant_files(entry, held.local)
if variants:
self.run_variants(trial, held, variants)
else:
self.moved(trial, held, files_record, record)
def bench(self, trial: Trial, key: str, boot: tuple[int, dict] | None) -> None:
core, emulator, content = trial.core, trial.unit.emulator, trial.content
stem = f"{core.name}-{slug(content.name)}"
argv = self.probe_args("bench", core, emulator, slug(f"bench-{stem}"), content, trial.load)
argv += ["--warmup", str(self.settings.bench_warmup), "--frames",
str(self.settings.bench_frames), "--repeat", str(self.settings.bench_repeat),
"--no-trace"]
if boot:
argv += ["--system-file", f"{entry_dest(boot[1])}={self.local_file(boot[1])}"]
self.check(emulator, key, core, trial.digest, argv, f"{emulator}-{stem}-bench")
def negative(self, trial: Trial, key: str, held: Held,
staged: dict[str, tuple[int, dict, Path]]) -> dict | None:
"""The file alone, then wrong files under its name: zeros of its
size, its first half, and other regions' dumps."""
core, content, entry, dest, local = trial.core, trial.content, held.entry, held.dest, held.local
unit = trial.unit
stem = f"{core.name}-{slug(content.name)}"
size = local.stat().st_size
others = self.other_regions(entry, staged, local)
argv = self.probe_args("check", core, unit.emulator, slug(f"negative-{entry['name']}-{stem}"),
content, load) + frames
content, trial.load) + trial.frames
argv += ["--vary", f"{dest}={local}", "--vary", f"{dest}=@zeros:{size}",
"--vary", f"{dest}=@head:{size // 2}:{local}"]
for other in others:
@@ -1266,20 +1327,19 @@ class Campaign:
f"{content.frames} frames with no button pressed, every "
f"{content.frame_hash_every}th frame hashed. The boot oracle judges "
f"each variant against the reference frames of {content.name}.")]
return self.check(unit.emulator, key, core, digest, argv, f"{unit.emulator}-{stem}-negative")
return self.check(unit.emulator, key, core, trial.digest, argv, f"{unit.emulator}-{stem}-negative")
def moved(self, unit: Unit, core: Core, content: Content, load: Path, frames: list[str],
digest: str, index: int, entry: dict, dest: str, local: Path, files_record: dict,
alone: dict) -> None:
def moved(self, trial: Trial, held: Held, files_record: dict, alone: dict) -> None:
"""A file the core opened neither in the full set nor alone: where
else it looked for a file of that name, else flagged."""
unit, core, content = trial.unit, trial.core, trial.content
index, entry, dest = held.index, held.entry, held.dest
probed = [p for record in (files_record, alone) for r in record["variants"][0]["repetitions"]
for p in r.get("files_probed_absent") or ()]
others = [p for p in dict.fromkeys(probed) if p != dest
and p.rsplit("/", 1)[-1].casefold() == dest.rsplit("/", 1)[-1].casefold()]
for candidate in others[:MAX_ALIAS_CANDIDATES]:
found = self.follow_up(unit, core, content, load, frames, digest, entry, local, candidate,
f"path:{entry['name']}:{candidate}")
found = self.follow_up(trial, entry, held.local, candidate, f"path:{entry['name']}:{candidate}")
if found and candidate in self.opened(found, 0):
verdict = rules.rule_path(entry, dest, rules.Opened(candidate, found["id"]))
if verdict:
@@ -1308,7 +1368,7 @@ class Campaign:
def judged(self, emulator: str, rid: str) -> bool:
"""True for a record the boot oracle judged: only those prove a field."""
record = self.read_record(emulator, rid)
return bool(record) and record.get("record_version", 0) >= 4
return record is not None and record.get("record_version", 0) >= 4
@staticmethod
def opened(record: dict, position: int) -> set[str]:
@@ -1317,18 +1377,18 @@ class Campaign:
out |= {item["path"] for item in rep.get("files_opened") or ()}
return out
def follow_up(self, unit: Unit, core: Core, content: Content, load: Path, frames: list[str],
digest: str, entry: dict, local: Path, dest: str, check: str) -> dict | None:
def follow_up(self, trial: Trial, entry: dict, local: Path, dest: str, check: str) -> dict | None:
"""The file staged at dest alone: does the core open it there."""
unit, core, content = trial.unit, trial.core, trial.content
stem = f"{core.name}-{slug(content.name)}"
argv = self.probe_args("run", core, unit.emulator, slug(f"{check}-{stem}"), content, load)
argv += frames + ["--system-file", f"{dest}={local}"]
return self.check(unit.emulator, self.check_key(core, content, check), core, digest, argv,
argv = self.probe_args("run", core, unit.emulator, slug(f"{check}-{stem}"), content, trial.load)
argv += trial.frames + ["--system-file", f"{dest}={local}"]
return self.check(unit.emulator, self.check_key(core, content, check), core, trial.digest, argv,
f"{unit.emulator}-{stem}-{slug(check)}")
def follow_aliases(self, unit: Unit, core: Core, content: Content, load: Path, frames: list[str],
digest: str, index: int, entry: dict, local: Path, none_record: dict) -> None:
def follow_aliases(self, trial: Trial, index: int, entry: dict, local: Path, none_record: dict) -> None:
"""Names the core looked for, with no BIOS, that no entry declares."""
unit, core, content = trial.unit, trial.core, trial.content
declared = {e["name"] for e in unit.profile.get("files") or ()}
declared |= {a for e in unit.profile.get("files") or () for a in e.get("aliases") or ()}
suffix = Path(entry["name"]).suffix.casefold()
@@ -1343,23 +1403,23 @@ class Campaign:
and path not in probed):
probed.append(path)
for candidate in probed[:MAX_ALIAS_CANDIDATES]:
found = self.follow_up(unit, core, content, load, frames, digest, entry, local, candidate,
found = self.follow_up(trial, entry, local, candidate,
f"alias:{entry['name']}:{candidate.rsplit('/', 1)[-1]}")
if found and candidate in self.opened(found, 0):
verdict = rules.rule_alias(self.reload_entry(unit, index), rules.Opened(candidate, found["id"]))
if verdict:
self.settle(unit.emulator, content, core, index, self.reload_entry(unit, index), [verdict])
def run_variants(self, unit: Unit, core: Core, content: Content, load: Path, frames: list[str],
digest: str, index: int, entry: dict, dest: str, primary: Path,
variants: list[Path]) -> None:
def run_variants(self, trial: Trial, held: Held, variants: list[Path]) -> None:
unit, core, content, digest = trial.unit, trial.core, trial.content, trial.digest
index, entry, dest = held.index, held.entry, held.dest
key = self.check_key(core, content, f"variants:{entry['name']}")
if not self.needed(unit.emulator, key, core, digest):
return
stem = f"{core.name}-{slug(content.name)}"
argv = self.probe_args("check", core, unit.emulator, slug(f"variants-{entry['name']}-{stem}"),
content, load) + frames
for path in [primary, *variants]:
content, trial.load) + trial.frames
for path in [held.local, *variants]:
argv += ["--vary", f"{dest}={path}"]
argv += ["--observable", "frame_hashes", "--repeat", str(self.settings.check_repeat),
"--claim", f"every copy of {entry['name']} boots {content.name} on {core.name}",
@@ -1508,7 +1568,7 @@ class Campaign:
argv += ["--frames", str(content.frames), "--frame-hash-every",
str(content.frame_hash_every), "--repeat", str(self.settings.check_repeat),
"--png-dir", str(target)]
for index, entry in self.system_entries(unit.profile, content.system):
for _, entry in self.system_entries(unit.profile, content.system):
local = self.local_file(entry)
if local and f"{entry_dest(entry)}=" not in " ".join(argv):
argv += ["--system-file", f"{entry_dest(entry)}={local}"]
@@ -1821,10 +1881,9 @@ def render_status(report: dict) -> str:
counts = report["counts"]
lines.append(f"{counts.get(DONE, 0)} done, {counts.get(FAILED, 0)} failed, "
f"{counts.get(PENDING, 0)} pending")
for reason, number in sorted(report["pending_reasons"].items(), key=lambda kv: -kv[1]):
lines.append(f" pending {number:5} {reason}")
for item in report["failed"]:
lines.append(f" FAILED {item['emulator']} {item['check']}: {item['reason']}")
lines.extend(f" pending {number:5} {reason}"
for reason, number in sorted(report["pending_reasons"].items(), key=lambda kv: -kv[1]))
lines.extend(f" FAILED {item['emulator']} {item['check']}: {item['reason']}" for item in report["failed"])
for emulator, checks in report["emulators"].items():
ran = [k for k, v in checks.items() if v["status"] != PENDING]
if ran:
@@ -1894,7 +1953,7 @@ def review_finding(root: Path, key: str, status: str, reason: str,
# Command line
# --------------------------------------------------------------------------
def main(argv: Sequence[str] | None = None) -> int:
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(allow_abbrev=False, description=__doc__.split("\n\n")[0],
formatter_class=argparse.RawDescriptionHelpFormatter)
sub = parser.add_subparsers(dest="command", required=True)
@@ -1942,44 +2001,72 @@ def main(argv: Sequence[str] | None = None) -> int:
help="with --status applied, a field to write into the entry")
review_p.add_argument("--index", type=int, help="the entry's position when several share its name")
sub.add_parser("gate", help="tests, schemas, verify and pack of the changed profiles")
return parser
def _review(parser: argparse.ArgumentParser, args: argparse.Namespace, paths: Paths) -> int:
updates: dict[str, object] = {}
for item in args.set:
name, sep, value = item.partition("=")
if not sep or not name:
parser.error(f"--set {item!r}: FIELD=YAML")
updates[name] = yaml.safe_load(value)
try:
line = review_finding(paths.root, args.key, args.status, args.reason, updates,
args.index)
except (ValueError, campaign_profiles.ProfileEditError) as exc:
print(f"campaign: {exc}", file=sys.stderr)
return 1
print(f"{line['status']} {line['key']} [{line['id']}]")
return 0
def _findings(args: argparse.Namespace, paths: Paths) -> int:
lines = open_findings(paths.root, args.all)
if args.json:
print(json.dumps(lines, indent=2))
for line in [] if args.json else lines:
print(f"{line['status']:8} {line['key']}: profile says {json.dumps(line['profile_says'])}, "
f"run shows {json.dumps(line['run_shows'])}. {line['statement']} "
f"[{', '.join(line['evidence'])}]")
return 0
def _settings(args: argparse.Namespace) -> Settings:
if args.command == "run":
return Settings(budget=args.budget, max_load_wait=args.max_load_wait,
min_free_gb=args.min_free_gb, cache_cap_gb=args.cache_cap_gb,
romfetch=args.romfetch, network=not args.offline,
allow_unsandboxed=args.allow_unsandboxed, bench=args.bench)
if args.command == "references":
return Settings(romfetch=args.romfetch, network=not args.offline,
allow_unsandboxed=args.allow_unsandboxed)
return Settings()
def _references(campaign: Campaign, args: argparse.Namespace, only: set[str]) -> int:
try:
with host_lock(campaign.lock_path):
listed = campaign.references(only, args.system, Path(args.png_dir))
except autorun.LockBusy as exc:
print(f"campaign: deferred, {exc}", file=sys.stderr)
return 75
print(json.dumps(listed, indent=2))
return 0
def main(argv: Sequence[str] | None = None) -> int:
parser = _parser()
args = parser.parse_args(argv)
paths = Paths.default()
if args.command == "gate":
return gate(paths.root, changed_profiles(paths.root))
if args.command == "review":
updates: dict[str, object] = {}
for item in args.set:
name, sep, value = item.partition("=")
if not sep or not name:
parser.error(f"--set {item!r}: FIELD=YAML")
updates[name] = yaml.safe_load(value)
try:
line = review_finding(paths.root, args.key, args.status, args.reason, updates,
args.index)
except (ValueError, campaign_profiles.ProfileEditError) as exc:
print(f"campaign: {exc}", file=sys.stderr)
return 1
print(f"{line['status']} {line['key']} [{line['id']}]")
return 0
return _review(parser, args, paths)
if args.command == "findings":
lines = open_findings(paths.root, args.all)
if args.json:
print(json.dumps(lines, indent=2))
for line in [] if args.json else lines:
print(f"{line['status']:8} {line['key']}: profile says {json.dumps(line['profile_says'])}, "
f"run shows {json.dumps(line['run_shows'])}. {line['statement']} "
f"[{', '.join(line['evidence'])}]")
return 0
settings = Settings()
if args.command == "run":
settings = Settings(budget=args.budget, max_load_wait=args.max_load_wait,
min_free_gb=args.min_free_gb, cache_cap_gb=args.cache_cap_gb,
romfetch=args.romfetch, network=not args.offline,
allow_unsandboxed=args.allow_unsandboxed, bench=args.bench)
elif args.command == "references":
settings = Settings(romfetch=args.romfetch, network=not args.offline,
allow_unsandboxed=args.allow_unsandboxed)
return _findings(args, paths)
settings = _settings(args)
if args.command in ("run", "references"):
paths.content_file = Path(args.content_file)
campaign = Campaign(paths, settings)
@@ -1989,17 +2076,14 @@ def main(argv: Sequence[str] | None = None) -> int:
return 0
only = {item.strip() for item in args.only.split(",") if item.strip()}
if args.command == "references":
try:
with host_lock(campaign.lock_path):
listed = campaign.references(only, args.system, Path(args.png_dir))
except autorun.LockBusy as exc:
print(f"campaign: deferred, {exc}", file=sys.stderr)
return 75
print(json.dumps(listed, indent=2))
return 0
return _references(campaign, args, only)
if args.dry_run:
campaign.run(only, args.system, dry_run=True)
return 0
return _run_pass(campaign, args, only, paths)
def _run_pass(campaign: Campaign, args: argparse.Namespace, only: set[str], paths: Paths) -> int:
campaign.dirty_at_start = set(autorun.changed_files(paths.root)) if args.commit else set()
def stop(signum: int, frame: object) -> None:
+3 -3
View File
@@ -95,11 +95,11 @@ def key_lines(lines: list[str], first: int, stop: int, key_indent: int) -> dict[
match = KEY.match(line)
if match and len(match["indent"]) == key_indent:
order.append((match["key"], i))
for position, (key, line) in enumerate(order):
for position, (key, start) in enumerate(order):
end = order[position + 1][1] if position + 1 < len(order) else stop
while end > line + 1 and (not lines[end - 1].strip() or lines[end - 1].strip().startswith("#")):
while end > start + 1 and (not lines[end - 1].strip() or lines[end - 1].strip().startswith("#")):
end -= 1
keys[key] = (line, end)
keys[key] = (start, end)
return keys
+6 -4
View File
@@ -40,7 +40,7 @@ Standard library only.
from __future__ import annotations
from collections.abc import Iterable, Sequence
from collections.abc import Callable, Iterable, Sequence
from dataclasses import dataclass, field
BOOTS = "boots"
@@ -122,7 +122,8 @@ def current(entry: dict, name: str) -> object:
def agrees(entry: dict, verdict: Verdict) -> bool:
"""True when the profile already says what the run showed."""
if verdict.field == "aliases":
return set(verdict.value or ()) <= set(entry.get("aliases") or ())
shown = verdict.value if isinstance(verdict.value, (list, tuple)) else ()
return set(shown) <= set(entry.get("aliases") or ())
if verdict.field == "validation":
return verdict.rule == "validation_agrees"
return current(entry, verdict.field) == verdict.value
@@ -211,7 +212,8 @@ def rule_validation(zeros: Run | None, half: Run | None, none: Run, present: Run
entry: dict) -> Verdict | None:
"""Same-size and short wrong files against the right one: validation."""
name = entry["name"]
content = {REFUSED: True, USED: False}.get(file_use(zeros, none, present)) if zeros else None
zeros_use = file_use(zeros, none, present) if zeros else None
content = {REFUSED: True, USED: False}.get(zeros_use) if zeros_use else None
half_use = file_use(half, none, present) if half else None
size: bool | None = None
if half_use == USED:
@@ -297,7 +299,7 @@ def rule_variants(runs: Iterable[Run], entry: dict) -> Verdict | None:
def merge_evidence(existing: dict | None, verdict: Verdict,
keep: object = lambda rid: True) -> dict:
keep: Callable[[str], bool] = lambda rid: True) -> dict:
"""The entry's evidence: map with the verdict's record ids added under its
field. An id `keep` refuses is dropped from that field: a record from
before the oracle no longer proves anything."""
+1 -4
View File
@@ -102,10 +102,7 @@ def check(registry_path: str = DEFAULT_REGISTRY) -> dict:
buildbot_set = set(index_zips)
tracked_set = set(tracked.keys())
results: list[dict] = []
for z in sorted(buildbot_set - tracked_set):
results.append({"zip": z, "status": "NEW", "key": None})
results: list[dict] = [{"zip": z, "status": "NEW", "key": None} for z in sorted(buildbot_set - tracked_set)]
for z in sorted(tracked_set - buildbot_set):
key, _ = tracked[z]
+4 -4
View File
@@ -40,7 +40,7 @@ import subprocess
import sys
import tempfile
import urllib.request
from collections.abc import Iterator
from collections.abc import Container, Iterator
from concurrent.futures import ThreadPoolExecutor
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
@@ -585,7 +585,7 @@ def _platform_overrides(overrides: dict, platform: str) -> dict:
def unresolved_target_cores(
targets: dict, index: dict[str, str], overrides: dict
targets: dict, index: Container[str], overrides: dict
) -> dict[str, list[str]]:
"""Core names a target ends up with that no profile claims.
@@ -618,7 +618,7 @@ def check_targets(
) -> list[Finding]:
targets_dir = platforms_dir / "targets"
overrides_path = targets_dir / "_overrides.yml"
overrides = {}
overrides: dict = {}
if overrides_path.is_file():
with overrides_path.open(encoding="utf-8") as fh:
overrides = yaml_load(fh) or {}
@@ -1380,7 +1380,7 @@ def specifier_allows(spec: str, version: str) -> bool:
for clause in filter(None, (c.strip() for c in spec.split(","))):
match = _SPEC_CLAUSE.fullmatch(clause)
test = _SPEC_TESTS.get(match.group(1)) if match else None
if test is None or not test(target, _version_tuple(match.group(2))):
if match is None or test is None or not test(target, _version_tuple(match.group(2))):
return False
return True
+4 -4
View File
@@ -23,14 +23,14 @@ def accepts(entry: dict, path: Path, mode: str) -> bool:
with zipfile.ZipFile(path) as archive:
names = {name.casefold(): name for name in archive.namelist()}
member = names.get(entry["zipped_file"].casefold())
return bool(member) and hashlib.new(digest, archive.read(member)).hexdigest() in values
return member is not None and hashlib.new(digest, archive.read(member)).hexdigest() in values
actual = hashlib.new(digest, path.read_bytes()).hexdigest()
if entry.get("zip_digest") != "composite" and actual in values:
return True # whole digests, as batocera-systems:1088 compares them
if digest == DIGESTS["md5"] and path.suffix.lower() == ".zip": # Recalbox: members in name order
with zipfile.ZipFile(path) as archive:
names = sorted(name for name in archive.namelist() if not name.endswith("/"))
return hashlib.md5(b"".join(map(archive.read, names))).hexdigest() in values
members = sorted(name for name in archive.namelist() if not name.endswith("/"))
return hashlib.md5(b"".join(map(archive.read, members))).hexdigest() in values
except (OSError, zipfile.BadZipFile):
return False
return False
@@ -60,7 +60,7 @@ if __name__ == "__main__":
except urllib.request.HTTPError as error: # a 404: no platform has that name
with urllib.request.urlopen(API.replace("platforms/", "catalog.json")) as response:
known = sorted(i["url"][10:-5] for i in json.load(response)["items"] if i["url"].startswith("manifests/"))
sys.exit(f"unknown platform: {sys.argv[1]}. Known: {', '.join(known)}" if error.code == 404 else error)
sys.exit(f"unknown platform: {sys.argv[1]}. Known: {', '.join(known)}" if error.code == 404 else str(error))
except OSError as error: # no such folder, or no network (URLError)
sys.exit(f"error: {error}")
for verdict in ("ok", "wrong", "missing"):
+21 -20
View File
@@ -65,6 +65,18 @@ def parse_sums(text: str) -> dict[str, str]:
return sums
def _registry_findings(packs: dict, released: set[str]) -> list[Finding]:
"""Each platform marked release_pack has a pack, and each pack serves one."""
served = {p for pack in packs.values() for p in pack.get("platforms", ())}
findings = [Finding("no-pack", platform, "release_pack: true, no pack in release.json")
for platform in sorted(released - served)]
findings.extend(Finding(
"not-released", pack_name,
"serves no platform marked release_pack in platforms/_registry.yml",
) for pack_name, pack in sorted(packs.items()) if not set(pack.get("platforms", ())) & released)
return findings
def compare_release(
record: dict,
sums: dict[str, str],
@@ -84,18 +96,7 @@ def compare_release(
if record.get("tag") != tag:
findings.append(Finding("tag", tag, f"release.json records {record.get('tag')}"))
if released is not None:
packs = record.get("packs", {})
served = {p for pack in packs.values() for p in pack.get("platforms", ())}
for platform in sorted(released - served):
findings.append(Finding(
"no-pack", platform, "release_pack: true, no pack in release.json"
))
for pack_name, pack in sorted(packs.items()):
if not set(pack.get("platforms", ())) & released:
findings.append(Finding(
"not-released", pack_name,
"serves no platform marked release_pack in platforms/_registry.yml",
))
findings += _registry_findings(record.get("packs", {}), released)
recorded = {
name: pack_name
@@ -105,14 +106,14 @@ def compare_release(
expected = set(recorded) | set(sums) | {SUMS} | set(local_files or ())
allowed = expected | {SIGNATURE}
for name in sorted(expected - set(assets)):
findings.append(Finding("missing", name, "not attached to the release"))
for name in sorted(set(assets) - allowed):
findings.append(Finding("extra", name, "attached but neither recorded nor listed"))
for name in sorted(set(recorded) - set(sums)):
findings.append(Finding("unlisted", name, f"absent from {SUMS}"))
for name in sorted(set(sums) - set(recorded)):
findings.append(Finding("unrecorded", name, f"listed in {SUMS}, absent from release.json"))
findings.extend(Finding("missing", name, "not attached to the release")
for name in sorted(expected - set(assets)))
findings.extend(Finding("extra", name, "attached but neither recorded nor listed")
for name in sorted(set(assets) - allowed))
findings.extend(Finding("unlisted", name, f"absent from {SUMS}")
for name in sorted(set(recorded) - set(sums)))
findings.extend(Finding("unrecorded", name, f"listed in {SUMS}, absent from release.json")
for name in sorted(set(sums) - set(recorded)))
wanted = {**sums, **(local_files or {})}
for name, digest in sorted(wanted.items()):
+4 -3
View File
@@ -90,10 +90,11 @@ def compare(
served = next(
(name for name in _spellings(names[path]) if name in assets), None
)
published = assets[served] if served else None
if published is None:
if not served:
findings.append(AssetFinding("missing", path, size, None))
elif published != size:
continue
published = assets[served]
if published != size:
findings.append(AssetFinding("size", path, size, published))
else:
ours = (expected_digests or {}).get(path)
+2 -3
View File
@@ -29,6 +29,7 @@ Usage:
from __future__ import annotations
import argparse
import contextlib
import os
import re
import shutil
@@ -81,10 +82,8 @@ def busy_paths() -> set[str]:
if not pid.name.isdigit():
continue
links = [pid / "cwd"]
try:
with contextlib.suppress(OSError):
links += list((pid / "fd").iterdir())
except OSError:
pass
for link in links:
try:
found.add(os.readlink(link))
+136 -83
View File
@@ -36,9 +36,10 @@ import sys
import tempfile
import time
import zlib
from collections.abc import Iterable, Iterator, Sequence
from collections.abc import Callable, Iterable, Iterator, Sequence
from dataclasses import dataclass, field
from pathlib import Path
from typing import IO
# The probe tools do not import common.py, which states the 3.9 floor for the
# other scripts. Under 3.8 they stopped on a str.removesuffix AttributeError.
@@ -396,7 +397,7 @@ InputFn = ctypes.CFUNCTYPE(ctypes.c_int16, ctypes.c_uint, ctypes.c_uint, ctypes.
class Frontend:
"""The libretro callbacks for one run."""
def __init__(self, spec: dict) -> None:
def __init__(self, spec: dict, events: IO[str] | None = None) -> None:
self.spec = spec
self.system_dir = spec["system_dir"].encode()
self.save_dir = spec["save_dir"].encode()
@@ -417,10 +418,19 @@ class Frontend:
self.unanswered: dict[int, int] = {}
self.input_queries = 0
self.input_pressed = 0
# What a run showed so far, one JSON line per event, flushed at once:
# a core that kills the worker leaves its logs and frames behind.
events = spec.get("events")
self.events = open(events, "a", encoding="utf-8", buffering=1) if events else None # noqa: SIM115
self.events = events
self.env_handlers: dict[int, Callable[[int, int], bool]] = {
ENV_GET_CAN_DUPE: self.env_can_dupe,
ENV_GET_SYSTEM_DIRECTORY: self.env_directory,
ENV_GET_SAVE_DIRECTORY: self.env_directory,
ENV_SET_PIXEL_FORMAT: self.env_pixel_format,
ENV_SET_VARIABLES: self.env_set_variables,
ENV_GET_VARIABLE: self.env_get_variable,
ENV_GET_VARIABLE_UPDATE: self.env_variable_update,
ENV_SET_SUPPORT_NO_GAME: lambda cmd, data: True,
ENV_GET_LOG_INTERFACE: self.env_log_interface,
ENV_GET_CORE_OPTIONS_VERSION: self.env_core_options_version,
}
self.callbacks = (
EnvFn(self.environment), VideoFn(self.video_refresh), AudioFn(self.audio_sample),
AudioBatchFn(self.audio_batch), PollFn(lambda: None), InputFn(self.input_state),
@@ -439,54 +449,63 @@ class Frontend:
def environment(self, cmd: int, data: int) -> bool:
cmd &= ~ENV_EXPERIMENTAL
if cmd == ENV_GET_CAN_DUPE:
ctypes.cast(data, ctypes.POINTER(ctypes.c_bool))[0] = True
return True
if cmd in (ENV_GET_SYSTEM_DIRECTORY, ENV_GET_SAVE_DIRECTORY):
value = self.system_dir if cmd == ENV_GET_SYSTEM_DIRECTORY else self.save_dir
buffer = ctypes.create_string_buffer(value)
self.option_buffers.append(buffer)
ctypes.cast(data, ctypes.POINTER(ctypes.c_char_p))[0] = ctypes.cast(buffer, ctypes.c_char_p)
return True
if cmd == ENV_SET_PIXEL_FORMAT:
fmt = ctypes.cast(data, ctypes.POINTER(ctypes.c_int))[0]
if fmt not in PIXEL_BYTES:
return False
self.pixel_format = fmt
return True
if cmd == ENV_SET_VARIABLES:
array = ctypes.cast(data, ctypes.POINTER(RetroVariable))
index = 0
while array[index].key:
key, desc = array[index].key, (array[index].value or b"").decode("utf-8", "replace")
values = desc.split(";", 1)[-1].strip().split("|")
self.declared[key.decode()] = values
self.defaults[key] = values[0].encode()
index += 1
return True
if cmd == ENV_GET_VARIABLE:
var = ctypes.cast(data, ctypes.POINTER(RetroVariable))[0]
value = self.options.get(var.key, self.defaults.get(var.key))
if value is None:
return False
buffer = ctypes.create_string_buffer(value)
self.option_buffers.append(buffer)
ctypes.cast(data, ctypes.POINTER(RetroVariable))[0].value = ctypes.cast(buffer, ctypes.c_char_p)
return True
if cmd == ENV_GET_VARIABLE_UPDATE:
ctypes.cast(data, ctypes.POINTER(ctypes.c_bool))[0] = False
return True
if cmd == ENV_SET_SUPPORT_NO_GAME:
return True
if cmd == ENV_GET_LOG_INTERFACE:
ctypes.cast(data, ctypes.POINTER(RetroLogCallback))[0] = self.log_callback
return True
if cmd == ENV_GET_CORE_OPTIONS_VERSION:
ctypes.cast(data, ctypes.POINTER(ctypes.c_uint))[0] = 0
return True
handler = self.env_handlers.get(cmd)
if handler:
return handler(cmd, data)
self.unanswered[cmd] = self.unanswered.get(cmd, 0) + 1
return False
def env_can_dupe(self, cmd: int, data: int) -> bool:
ctypes.cast(data, ctypes.POINTER(ctypes.c_bool))[0] = True
return True
def env_directory(self, cmd: int, data: int) -> bool:
value = self.system_dir if cmd == ENV_GET_SYSTEM_DIRECTORY else self.save_dir
buffer = ctypes.create_string_buffer(value)
self.option_buffers.append(buffer)
ctypes.cast(data, ctypes.POINTER(ctypes.c_char_p))[0] = ctypes.cast(buffer, ctypes.c_char_p)
return True
def env_pixel_format(self, cmd: int, data: int) -> bool:
fmt = ctypes.cast(data, ctypes.POINTER(ctypes.c_int))[0]
if fmt not in PIXEL_BYTES:
return False
self.pixel_format = fmt
return True
def env_set_variables(self, cmd: int, data: int) -> bool:
array = ctypes.cast(data, ctypes.POINTER(RetroVariable))
index = 0
while array[index].key:
key, desc = array[index].key, (array[index].value or b"").decode("utf-8", "replace")
values = desc.split(";", 1)[-1].strip().split("|")
self.declared[key.decode()] = values
self.defaults[key] = values[0].encode()
index += 1
return True
def env_get_variable(self, cmd: int, data: int) -> bool:
var = ctypes.cast(data, ctypes.POINTER(RetroVariable))[0]
value = self.options.get(var.key, self.defaults.get(var.key))
if value is None:
return False
buffer = ctypes.create_string_buffer(value)
self.option_buffers.append(buffer)
ctypes.cast(data, ctypes.POINTER(RetroVariable))[0].value = ctypes.cast(buffer, ctypes.c_char_p)
return True
def env_variable_update(self, cmd: int, data: int) -> bool:
ctypes.cast(data, ctypes.POINTER(ctypes.c_bool))[0] = False
return True
def env_log_interface(self, cmd: int, data: int) -> bool:
ctypes.cast(data, ctypes.POINTER(RetroLogCallback))[0] = self.log_callback
return True
def env_core_options_version(self, cmd: int, data: int) -> bool:
ctypes.cast(data, ctypes.POINTER(ctypes.c_uint))[0] = 0
return True
def video_refresh(self, data: int, width: int, height: int, pitch: int) -> None:
if data and data != ctypes.c_void_p(-1).value:
row = width * PIXEL_BYTES[self.pixel_format]
@@ -530,7 +549,15 @@ def run_worker(spec: dict) -> dict:
os.environ.clear()
os.environ.update(spec["env"])
core = ctypes.CDLL(spec["core"])
front = Frontend(spec)
# What a run showed so far, one JSON line per event, flushed at once:
# a core that kills the worker leaves its logs and frames behind.
events_path = spec.get("events")
with (open(events_path, "a", encoding="utf-8", buffering=1) if events_path
else contextlib.nullcontext()) as events:
return drive_core(core, Frontend(spec, events), spec)
def drive_core(core: ctypes.CDLL, front: Frontend, spec: dict) -> dict:
for name, fn in zip(("retro_set_environment", "retro_set_video_refresh", "retro_set_audio_sample",
"retro_set_audio_sample_batch", "retro_set_input_poll", "retro_set_input_state"),
front.callbacks):
@@ -578,7 +605,7 @@ def run_worker(spec: dict) -> dict:
if spec.get("state_out"):
Path(spec["state_out"]).write_bytes(state)
state_vars = mednafen_state_vars(state)
observables = {
observables: dict[str, object] = {
"frame_sha1": hashlib.sha1(front.last_frame).hexdigest(),
"video_sha1": front.video.hexdigest(),
"audio_sha1": front.audio.hexdigest(),
@@ -697,13 +724,20 @@ class Synthetic:
def label(self, dest: str) -> str:
if self.kind == "zeros":
return f"{dest}-zeros-{self.size}"
return f"{dest}-head-{self.size}-of-{self.source.name}"
return f"{dest}-head-{self.size}-of-{self.head_source.name}"
@property
def head_source(self) -> Path:
"""The file a head is cut from: parse() refuses a head without one."""
if self.source is None:
raise ValueError(f"@head:{self.size} names no file")
return self.source
def write(self, out: Path) -> None:
if self.kind == "zeros":
out.write_bytes(bytes(self.size))
return
with self.source.open("rb") as handle:
with self.head_source.open("rb") as handle:
out.write_bytes(handle.read(self.size))
@@ -889,7 +923,7 @@ def exit_description(returncode: int) -> dict:
def partial_result(events: Path, spec: dict) -> dict:
"""A repetition rebuilt from the events a worker wrote before it died."""
lines = []
lines: list[dict] = []
if events.is_file():
for line in events.read_text(encoding="utf-8", errors="replace").splitlines():
with contextlib.suppress(ValueError):
@@ -1034,7 +1068,8 @@ def run_variant(args: argparse.Namespace, base: dict[str, Path], variant: Varian
reference = reps[0].get("observables")
for index, rep in enumerate(reps[1:], 1):
if rep.get("observables") != reference:
differing = sorted(k for k in (reference or {}) if (rep.get("observables") or {}).get(k) != reference[k])
shown = reference or {}
differing = sorted(k for k in shown if (rep.get("observables") or {}).get(k) != shown[k])
flags.append(f"repetition {index} disagrees with repetition 0 on {', '.join(differing)}")
out = {
"label": variant.label,
@@ -1153,15 +1188,14 @@ def not_a_checkout_root(directory: Path) -> str | None:
return None
def validate_args(args: argparse.Namespace) -> list[str]:
def _input_problems(args: argparse.Namespace) -> list[str]:
problems: list[str] = []
if not Path(args.core).is_file():
problems.append(f"--core {args.core}: not a file")
if args.content and not Path(args.content).is_file():
problems.append(f"--content {args.content}: not a file")
for dest, src in args.system_file:
if not Path(src).is_file():
problems.append(f"--system-file {dest}={src}: not a file")
problems.extend(f"--system-file {dest}={src}: not a file"
for dest, src in args.system_file if not Path(src).is_file())
if args.repeat < 1:
problems.append("--repeat must be >= 1")
if args.frames < 1 or args.warmup < 0:
@@ -1176,13 +1210,18 @@ def validate_args(args: argparse.Namespace) -> list[str]:
# A library the loader cannot find is skipped without a word, and
# the run would record a fixed clock it never had. Only a file that
# exists is bound into the sandbox and recorded by sha256.
for library in value.replace(":", " ").split():
if not (Path(library).is_absolute() and Path(library).is_file()):
problems.append(f"--env LD_PRELOAD: {library} is not an absolute path to a file")
problems.extend(f"--env LD_PRELOAD: {library} is not an absolute path to a file"
for library in value.replace(":", " ").split()
if not (Path(library).is_absolute() and Path(library).is_file()))
if args.oracle and not Path(args.oracle).is_file():
problems.append(f"--oracle {args.oracle}: not a file")
if args.png_dir and not args.frame_hash_every:
problems.append("--png-dir needs --frame-hash-every")
return problems
def _record_problems(args: argparse.Namespace) -> list[str]:
problems: list[str] = []
if args.record:
wrong = not_a_checkout_root(Path(args.record))
if wrong:
@@ -1199,26 +1238,40 @@ def validate_args(args: argparse.Namespace) -> list[str]:
problems.append(f"{flag} {value!r}: lowercase letters, digits, - and _ only")
if args.mode == "bench" and args.record and args.repeat < MIN_BENCH_REPETITIONS:
problems.append(f"a recorded benchmark needs --repeat >= {MIN_BENCH_REPETITIONS}")
return problems
def _vary_problem(dest: str, src: str) -> str:
if src.startswith("@"):
try:
made = Synthetic.parse(src)
except argparse.ArgumentTypeError as exc:
return f"--vary {dest}: {exc}"
if made.source and not made.source.is_file():
return f"--vary {dest}={src}: {made.source} is not a file"
elif src and not Path(src).is_file():
return f"--vary {dest}={src}: not a file"
return ""
def _check_mode_problems(args: argparse.Namespace) -> list[str]:
problems: list[str] = []
dests = {dest for dest, _ in args.vary}
if len(dests) != 1:
problems.append("--vary must name the same DEST in every occurrence")
problems.extend(problem for dest, src in args.vary if (problem := _vary_problem(dest, src)))
names = set(BASE_OBSERVABLES) | {f"state:{v}" for v in args.state_var}
if args.frame_hash_every:
names.update(("frame_hashes", "uniform_frames"))
if args.observable not in names:
problems.append(f"--observable {args.observable}: not one of {', '.join(sorted(names))}")
return problems
def validate_args(args: argparse.Namespace) -> list[str]:
problems = _input_problems(args) + _record_problems(args)
if args.mode == "check":
dests = {dest for dest, _ in args.vary}
if len(dests) != 1:
problems.append("--vary must name the same DEST in every occurrence")
for dest, src in args.vary:
if src.startswith("@"):
try:
made = Synthetic.parse(src)
except argparse.ArgumentTypeError as exc:
problems.append(f"--vary {dest}: {exc}")
continue
if made.source and not made.source.is_file():
problems.append(f"--vary {dest}={src}: {made.source} is not a file")
elif src and not Path(src).is_file():
problems.append(f"--vary {dest}={src}: not a file")
names = set(BASE_OBSERVABLES) | {f"state:{v}" for v in args.state_var}
if args.frame_hash_every:
names.update(("frame_hashes", "uniform_frames"))
if args.observable not in names:
problems.append(f"--observable {args.observable}: not one of {', '.join(sorted(names))}")
problems += _check_mode_problems(args)
return problems
+3 -3
View File
@@ -186,10 +186,10 @@ class Checker:
self._files(where, entry["profile"], profile, entry.get("files") or [])
header = (entry.get("trigger") or {}).get("header")
if header and self.readers is not None:
self._header(where, header)
self._header(where, header, self.readers)
def _header(self, where: str, header: dict) -> None:
reader = self.readers.get(header["reader"])
def _header(self, where: str, header: dict, readers: dict[str, dict]) -> None:
reader = readers.get(header["reader"])
if reader is None:
self.errors.append(f"{where}: games/headers.yml has no reader {header['reader']}")
return
+141 -108
View File
@@ -31,38 +31,37 @@ Nothing here is written by hand: a second run writes the same bytes.
from __future__ import annotations
import argparse
import functools
import gzip
import hashlib
import json
import posixpath
import sys
from collections.abc import Iterable
from dataclasses import dataclass
from collections.abc import Callable, Iterable
from dataclasses import dataclass, field
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from common import ( # noqa: E402
from common import (
load_emulator_profiles,
load_platform_config,
native_layer,
repository_output_lock,
run_cli,
)
from region import normalize_declared # noqa: E402
from romfolders import ( # noqa: E402
from region import normalize_declared
from romfolders import (
ProfileResolver,
Resolution,
SystemResolver,
folder_names,
load_setups,
)
from artifacts import write_text_atomic # noqa: E402
from safeparse import yaml_load # noqa: E402
from artifacts import write_text_atomic
from safeparse import yaml_load
import install # noqa: E402
import install
FORMAT_VERSION = 1
OUTPUT = Path("install") / "games"
@@ -221,9 +220,8 @@ def fallback_set(
platform_required.get((s, base), True) for s in systems & wanted
)
else:
if systems:
if not systems & wanted:
continue
if systems and not systems & wanted:
continue
declared = profiles.entries_named(profile or "", base)
if not systems and not any(profiles.serves(profile or "", e, system) for e in declared):
continue
@@ -333,6 +331,104 @@ def emulator_profile(row: dict, platform: str, cores: ProfileResolver,
return candidate if any(resolver.equivalents(sid) & declared for sid in systems) else None
@dataclass
class _FallbackTables:
"""The fallback sets of a folder's systems under one core, computed
once per platform."""
profiles: Profiles
tables: dict[str, dict[str, dict]] = field(default_factory=dict)
narrowed: dict = field(default_factory=dict)
def keys(self, platform: str, manifest: dict, required: dict[tuple[str, str], bool],
systems: list[str], chosen: str | None) -> list[str]:
keys = []
table = self.tables.setdefault(platform, {})
for system in systems:
key = f"{system}|{chosen or ''}"
if key not in table:
table[key] = fallback_set(manifest, required, self.profiles, system, chosen, self.narrowed)
keys.append(key)
return keys
@dataclass
class _SetupContext:
resolver: SystemResolver
cores: ProfileResolver
profiles: Profiles
arcade: set[str]
inputs: Inputs
fallbacks: _FallbackTables
manifests: dict[str, dict] = field(default_factory=dict)
required: dict[str, dict[tuple[str, str], bool]] = field(default_factory=dict)
def manifest(self, platform: str) -> dict | None:
if platform and platform not in self.manifests:
path = self.inputs.install / f"{platform}.json"
if path.exists():
self.manifests[platform] = _load_json(path)
self.required[platform] = _platform_required(platform, self.inputs.platforms)
return self.manifests.get(platform)
def _board_defaults(ctx: _SetupContext, row: dict,
fallback_keys: Callable[[str | None], list[str]] | None) -> dict:
boards = {}
for board, spec in sorted((row.get("board_defaults") or {}).items()):
boards[board] = {"core": spec["core"]}
board_profile = ctx.cores.resolve(spec["core"])
if board_profile:
boards[board]["profile"] = board_profile
if board_profile in ctx.arcade:
boards[board]["arcade"] = board_profile
if fallback_keys:
# A card moves between boards, and the installer reads
# it on a computer: each board's core has its set.
boards[board]["fallback"] = fallback_keys(board_profile)
return boards
def _publish_folder(ctx: _SetupContext, row: dict, platform: str, manifest: dict | None,
counts: dict[str, int]) -> dict:
counts["folders"] += 1
profile = (ctx.cores.resolve(row.get("core"))
or emulator_profile(row, platform, ctx.cores, ctx.resolver, ctx.profiles))
resolution = resolve_folder(row, platform, profile, ctx.resolver, ctx.profiles, ctx.arcade)
published: dict = {
"folder": row["folder"],
"systems": resolution.systems,
"basis": resolution.basis,
}
for key in ("name", "aliases", "extensions", "files", "core", "emulator", "note"):
if row.get(key):
published[key] = row[key]
if profile:
published["profile"] = profile
counts["profile"] += 1
if resolution.systems:
counts["resolved"] += 1
fallback_keys = None
if manifest is not None and resolution.systems:
fallback_keys = functools.partial(ctx.fallbacks.keys, platform, manifest, ctx.required[platform],
resolution.systems)
boards = _board_defaults(ctx, row, fallback_keys)
if boards:
published["board_defaults"] = boards
if profile and profile in ctx.arcade:
published["arcade"] = profile
elif row.get("arcade"):
published["arcade"] = True
if fallback_keys:
keys = fallback_keys(profile)
published["fallback"] = keys
if any(ctx.fallbacks.tables[platform][k]["files"] for k in keys):
counts["fallback"] += 1
published["source_ref"] = row["source_ref"]
return published
def build_setups(
setups: dict[str, dict],
resolver: SystemResolver,
@@ -342,80 +438,14 @@ def build_setups(
inputs: Inputs,
) -> tuple[dict[str, dict], dict[str, dict], dict]:
"""Published setup documents, fallback tables per platform, coverage."""
manifests: dict[str, dict] = {}
required: dict[str, dict] = {}
fallbacks: dict[str, dict[str, dict]] = {}
narrowed: dict = {}
ctx = _SetupContext(resolver, cores, profiles, arcade, inputs, _FallbackTables(profiles))
out: dict[str, dict] = {}
coverage: dict[str, dict] = {}
for setup, doc in sorted(setups.items()):
platform = doc.get("platform") or ""
if platform and platform not in manifests:
path = inputs.install / f"{platform}.json"
if path.exists():
manifests[platform] = _load_json(path)
required[platform] = _platform_required(platform, inputs.platforms)
manifest = manifests.get(platform)
folders: list[dict] = []
manifest = ctx.manifest(platform)
counts = {"folders": 0, "resolved": 0, "profile": 0, "fallback": 0}
for row in doc.get("folders", []):
counts["folders"] += 1
profile = (cores.resolve(row.get("core"))
or emulator_profile(row, platform, cores, resolver, profiles))
resolution = resolve_folder(row, platform, profile, resolver, profiles, arcade)
published: dict = {
"folder": row["folder"],
"systems": resolution.systems,
"basis": resolution.basis,
}
for key in ("name", "aliases", "extensions", "files", "core", "emulator", "note"):
if row.get(key):
published[key] = row[key]
if profile:
published["profile"] = profile
counts["profile"] += 1
if resolution.systems:
counts["resolved"] += 1
def fallback_keys(chosen: str | None) -> list[str]:
"""The fallback sets of the folder's systems under one core,
computed once per platform."""
keys = []
table = fallbacks.setdefault(platform, {})
for system in resolution.systems:
key = f"{system}|{chosen or ''}"
if key not in table:
table[key] = fallback_set(manifest, required[platform], profiles, system,
chosen, narrowed)
keys.append(key)
return keys
sets_known = manifest is not None and bool(resolution.systems)
boards = {}
for board, spec in sorted((row.get("board_defaults") or {}).items()):
boards[board] = {"core": spec["core"]}
board_profile = cores.resolve(spec["core"])
if board_profile:
boards[board]["profile"] = board_profile
if board_profile in arcade:
boards[board]["arcade"] = board_profile
if sets_known:
# A card moves between boards, and the installer reads
# it on a computer: each board's core has its set.
boards[board]["fallback"] = fallback_keys(board_profile)
if boards:
published["board_defaults"] = boards
if profile and profile in arcade:
published["arcade"] = profile
elif row.get("arcade"):
published["arcade"] = True
if sets_known:
keys = fallback_keys(profile)
published["fallback"] = keys
if any(fallbacks[platform][k]["files"] for k in keys):
counts["fallback"] += 1
published["source_ref"] = row["source_ref"]
folders.append(published)
folders = [_publish_folder(ctx, row, platform, manifest, counts) for row in doc.get("folders", [])]
out[setup] = {
"format_version": FORMAT_VERSION,
"setup": setup,
@@ -429,7 +459,7 @@ def build_setups(
}
coverage[setup] = counts
published_fallbacks = {
platform: _shared_table(platform, table) for platform, table in sorted(fallbacks.items())
platform: _shared_table(platform, table) for platform, table in sorted(ctx.fallbacks.tables.items())
}
return out, published_fallbacks, coverage
@@ -443,6 +473,32 @@ def _catalogs(directory: Path) -> Iterable[dict]:
yield _load_json(path)
def _add_catalog(doc: dict, catalog: dict) -> None:
regions_table = catalog["regions"]
fields = catalog["fields"]
col = {name: i for i, name in enumerate(fields)}
ident = doc.setdefault("identify", {"sources": [], "regions": [], "games": [], "serials": {}})
region_index: dict[tuple[str, ...], int] = {
tuple(r): i for i, r in enumerate(ident["regions"])
}
def reindex(i: int) -> int:
value = tuple(regions_table[i]) if i is not None and i >= 0 else ()
if value not in region_index:
region_index[value] = len(ident["regions"])
ident["regions"].append(list(value))
return region_index[value]
ident["sources"].append({
k: catalog[k] for k in ("source", "dat", "version", "fetched_from", "licence", "serial_note") if k in catalog
})
for row in catalog["games"]:
region = reindex(row[col["region"]])
ident["games"].append([row[col["crc32"]], row[col["size"]], region, row[col["title"]]])
for serial in row[col["serials"]] if "serials" in col else []:
ident["serials"].setdefault(serial, set()).add(region)
def build_systems(
resolver: SystemResolver,
profiles: Profiles,
@@ -467,30 +523,7 @@ def build_systems(
return docs.setdefault(key, {"format_version": FORMAT_VERSION, "system": key})
for catalog in _catalogs(games / "catalogs"):
doc = doc_for(catalog["system"])
regions_table = catalog["regions"]
fields = catalog["fields"]
col = {name: i for i, name in enumerate(fields)}
ident = doc.setdefault("identify", {"sources": [], "regions": [], "games": [], "serials": {}})
region_index: dict[tuple[str, ...], int] = {
tuple(r): i for i, r in enumerate(ident["regions"])
}
def reindex(i: int) -> int:
value = tuple(regions_table[i]) if i is not None and i >= 0 else ()
if value not in region_index:
region_index[value] = len(ident["regions"])
ident["regions"].append(list(value))
return region_index[value]
ident["sources"].append({
k: catalog[k] for k in ("source", "dat", "version", "fetched_from", "licence", "serial_note") if k in catalog
})
for row in catalog["games"]:
region = reindex(row[col["region"]])
ident["games"].append([row[col["crc32"]], row[col["size"]], region, row[col["title"]]])
for serial in row[col["serials"]] if "serials" in col else []:
ident["serials"].setdefault(serial, set()).add(region)
_add_catalog(doc_for(catalog["system"]), catalog)
for doc in docs.values():
ident = doc.get("identify")
if ident:
+3 -4
View File
@@ -156,9 +156,8 @@ def check_line(record: dict) -> list[str]:
problems.append(f"{rid}: id does not hash the first-layout record ({digest})")
elif record_id(record) != rid:
problems.append(f"{rid}: id does not hash the record ({record_id(record)})")
for key in ("emulator", "subject"):
if not SLUG_PATTERN.match(str(record.get(key, ""))):
problems.append(f"{rid}: {key} {record.get(key)!r} is not a lowercase slug")
problems.extend(f"{rid}: {key} {record.get(key)!r} is not a lowercase slug"
for key in ("emulator", "subject") if not SLUG_PATTERN.match(str(record.get(key, ""))))
return problems
@@ -227,7 +226,7 @@ def read_records(root: Path) -> list[Stored]:
continue
if emulator in CAMPAIGN_FILES:
continue
seen: set[str] = set()
seen: set[str | None] = set()
try:
records = parse_lines(files[path].read_text(encoding="utf-8"), path)
except RecordError as exc:
+46 -58
View File
@@ -252,55 +252,30 @@ def sha1_blob(data: bytes) -> str:
return hashlib.sha1(data).hexdigest()
def classify_file(filepath: str) -> tuple:
"""Determine (Manufacturer, Console) for a file path from a branch.
ARCADE_ROM_PREFIXES = (
"roms/fba/",
"roms/fbneo/",
"roms/mame/",
"roms/mame-libretro/",
"roms/neogeo/",
"roms/naomi/",
"roms/atomiswave/",
"roms/macintosh/",
)
Returns None if the file should be skipped.
"""
name = os.path.basename(filepath)
if name in SKIP_FILES:
return None
ext = os.path.splitext(name)[1].lower()
if ext in SKIP_EXTENSIONS:
def _strip_branch_prefix(filepath: str) -> str | None:
"""The path below its bios/ or arcade roms/ folder, None for any other
roms/ path."""
if filepath.startswith("roms/") and not filepath.startswith(ARCADE_ROM_PREFIXES):
return None
for prefix in ("bios/", "BIOS/", *ARCADE_ROM_PREFIXES):
if filepath.startswith(prefix):
return filepath[len(prefix) :]
return filepath
clean = filepath
for prefix in (
"bios/",
"BIOS/",
"roms/fba/",
"roms/fbneo/",
"roms/mame/",
"roms/mame-libretro/",
"roms/neogeo/",
"roms/naomi/",
"roms/atomiswave/",
"roms/macintosh/",
):
if clean.startswith(prefix):
clean = clean[len(prefix) :]
break
if filepath.startswith("roms/") and not any(
filepath.startswith(p)
for p in (
"roms/fba/",
"roms/fbneo/",
"roms/mame/",
"roms/mame-libretro/",
"roms/neogeo/",
"roms/naomi/",
"roms/atomiswave/",
"roms/macintosh/",
)
):
return None
for prefix, target in PATH_PREFIX_MAP.items():
if clean.startswith(prefix):
return target
def _classify_by_name(name: str, filepath: str) -> tuple[str, str] | None:
if name in BIOS_FILE_MAP:
return BIOS_FILE_MAP[name]
@@ -324,19 +299,33 @@ def classify_file(filepath: str) -> tuple:
if name.endswith(".zip") and filepath.startswith(("roms/", "BIOS/")):
return ("Arcade", "Arcade")
if "saves/" in filepath:
return None
if name.endswith(".chd"):
return None
if name.endswith((".img", ".lst", ".dat")) and "saves/" in filepath:
return None
return None
def classify_file(filepath: str) -> tuple[str, str] | None:
"""Determine (Manufacturer, Console) for a file path from a branch.
Returns None if the file should be skipped.
"""
name = os.path.basename(filepath)
if name in SKIP_FILES:
return None
ext = os.path.splitext(name)[1].lower()
if ext in SKIP_EXTENSIONS:
return None
clean = _strip_branch_prefix(filepath)
if clean is None:
return None
for prefix, target in PATH_PREFIX_MAP.items():
if clean.startswith(prefix):
return target
return _classify_by_name(name, filepath)
def get_subpath(filepath: str, manufacturer: str, console: str) -> str:
"""Get the sub-path within the console directory (for nested files like neocd/*)."""
name = os.path.basename(filepath)
@@ -373,7 +362,7 @@ def extract_from_branches(target: Path, dry_run: bool, existing_hashes: set) ->
continue
result = subprocess.run(
["git", "ls-tree", "-r", "--name-only", ref], capture_output=True, text=True
["git", "ls-tree", "-r", "--name-only", ref], capture_output=True, text=True, check=False
)
files = result.stdout.strip().split("\n")
print(f"\n Branch '{branch}': {len(files)} files")
@@ -551,9 +540,8 @@ def main() -> None:
".gitignore",
}
for d in sorted(source.iterdir()):
if d.name not in known and not d.name.startswith("."):
if d.is_dir():
print(f"\nWARNING: Unmapped directory: {d.name}")
if d.name not in known and not d.name.startswith(".") and d.is_dir():
print(f"\nWARNING: Unmapped directory: {d.name}")
print(f"\nTotal: {moved} files migrated, {len(existing_hashes)} unique hashes")
+22 -14
View File
@@ -41,7 +41,6 @@ from __future__ import annotations
import argparse
import contextlib
import datetime as dt
import fcntl
import hashlib
import json
@@ -62,6 +61,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
import autorun
import campaign
import measurement_records as mr
from autorun import now_iso
from common import (
_norm_system_id,
load_emulator_profiles,
@@ -272,7 +272,7 @@ def so_names(name: str, profile: dict, buildbot: set[str], target: set[str] | No
def choose_cores(config: dict, profiles: dict[str, dict], system: str, buildbot: set[str],
target: set[str] | None) -> list[CoreChoice]:
wanted = _norm_system_id(system)
out = []
out: list[CoreChoice] = []
for name in sorted(resolve_platform_cores(config, profiles, target)):
profile = profiles[name]
if wanted not in {_norm_system_id(s) for s in profile.get("systems") or ()}:
@@ -389,9 +389,8 @@ def map_run(layout: Layout, staged: set[str], rep: dict, profile: dict) -> tuple
else:
kind = "missing_declared" if names else "missing_undeclared"
findings.append({"kind": kind, "path": path, "declared_by": names, "paths": elsewhere})
for item in opened:
if item["path"] in staged and item["entry"] is None:
findings.append({"kind": "unlisted", "path": item["path"], "declared_by": [], "paths": []})
findings.extend({"kind": "unlisted", "path": item["path"], "declared_by": [], "paths": []}
for item in opened if item["path"] in staged and item["entry"] is None)
return opened, findings
@@ -456,10 +455,6 @@ def content_folder(content: campaign.Content, fetch: bool) -> Path:
# One probe: a core, a game, a layout
# --------------------------------------------------------------------------
def now_iso() -> str:
return dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat()
def wait_idle(limit: float = IDLE_WAIT, poll: float = 30.0) -> None:
"""Wait for the load core_probe records under, a quarter of the CPUs.
Extracting a pack loads the host itself for a minute or two."""
@@ -535,10 +530,22 @@ def subject_for(platform: str, install: str, system: str, so: str, content: str)
return f"{mr.PACK_SUBJECT_PREFIX}{subject}"
def probe_one(layout: Layout, platform: str, config: dict, profile: dict, choice: CoreChoice,
core: dict, system: str, content: campaign.Content, load: Path, work: Path) -> dict:
@dataclass(frozen=True)
class ProbeTarget:
"""One core of one system, on the game loaded for it."""
choice: CoreChoice
core: dict
system: str
content: campaign.Content
load: Path
def probe_one(layout: Layout, platform: str, config: dict, profile: dict, target: ProbeTarget,
work: Path) -> dict:
"""Run until the staging is closed. The first run is recorded, and when
the staging grew, the closed one is recorded too and supersedes it."""
choice, core, system, content, load = target.choice, target.core, target.system, target.content, target.load
native = platform_system(config, system)
dests = [f.get("destination") or f.get("name")
for f in ((config.get("systems") or {}).get(native) or {}).get("files") or ()]
@@ -626,7 +633,7 @@ def plan(platform: str, systems: set[str] | None, cores: set[str] | None,
config = load_platform_config(platform, str(ROOT / "platforms"))
profiles = load_emulator_profiles(str(ROOT / "emulators"))
target = load_target_config(platform, TARGETS[platform], str(ROOT / "platforms"))
units = []
units: list[Unit] = []
for system, contents in sorted(load_contents([campaign.CONTENT_FILE, PACK_CONTENT_FILE]).items()):
if systems and system not in systems:
continue
@@ -668,8 +675,9 @@ def run(args: argparse.Namespace) -> int:
continue
for choice in unit.cores:
core = fetch_core(choice.so_name, args.refresh_cores)
line = probe_one(layout, args.platform, config, profiles[choice.emulator], choice,
core, unit.system, unit.content, load, work / "runs")
target = ProbeTarget(choice, core, unit.system, unit.content, load)
line = probe_one(layout, args.platform, config, profiles[choice.emulator], target,
work / "runs")
sealed = append_line(line)
print(f"{args.platform} {install} {unit.system} {choice.so_name}: {line['verdict']}, "
f"{len(line['files_opened'])} opened, {len(line['findings'])} findings, "
+3 -3
View File
@@ -82,9 +82,9 @@ def shown(step: Step) -> str:
def execute(step: Step) -> int:
env = {**os.environ, **step.env}
if not step.then:
return subprocess.run(argv(step.command), cwd=ROOT, env=env).returncode
first = subprocess.run(argv(step.command), cwd=ROOT, env=env, stdout=subprocess.PIPE)
return subprocess.run(argv(step.then), cwd=ROOT, env=env, input=first.stdout).returncode
return subprocess.run(argv(step.command), cwd=ROOT, env=env, check=False).returncode
first = subprocess.run(argv(step.command), cwd=ROOT, env=env, stdout=subprocess.PIPE, check=False)
return subprocess.run(argv(step.then), cwd=ROOT, env=env, input=first.stdout, check=False).returncode
def run(steps: tuple[Step, ...] = STEPS) -> int:
+1125 -779
View File
File diff suppressed because it is too large. Load diff
+95 -78
View File
@@ -56,6 +56,7 @@ import re
import subprocess
import sys
import time
from collections.abc import Callable
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from dataclasses import dataclass
from functools import lru_cache
@@ -220,7 +221,7 @@ def plan_jobs(
for finding in findings:
status = finding.get("status")
area = finding.get("area")
area = str(finding.get("area") or "")
subject = str(finding.get("subject") or "")
if status == "ERROR":
@@ -360,6 +361,96 @@ def _export_refresh(platform: str) -> list[str]:
return [sys.executable, "scripts/export_native.py", "--platform", platform]
def _platform_command(subject: str, registry: dict[str, dict]) -> list[str] | None:
entry = registry.get(subject) or {}
scraper = entry.get("scraper")
if not scraper:
return None
return [
sys.executable,
"-m",
f"scripts.scraper.{scraper}_scraper",
"-o",
f"platforms/{subject}.yml",
*(str(a) for a in entry.get("rescrape_args") or ()),
]
def _target_command(subject: str, registry: dict[str, dict]) -> list[str] | None:
# "<platform> cores" rows list buildbot names without a profile. No
# scraper fixes that, a human writes `cores:` or _overrides.yml.
if subject.endswith(" cores"):
return None
entry = registry.get(subject) or {}
module = entry.get("target_scraper")
if not module:
return None
return [
sys.executable,
"-m",
f"scripts.scraper.targets.{module}_scraper",
"-o",
f"platforms/targets/{subject}.yml",
]
def _data_command(subject: str, registry: dict[str, dict]) -> list[str] | None:
if subject not in _data_dir_keys():
# "_data_dirs.yml" and "buildbot system" name the registry and
# what it does not track yet: a human adds the entry.
return None
return [
sys.executable,
"scripts/refresh_data_dirs.py",
"--key",
subject,
"--force",
]
def _catalog_command(subject: str, registry: dict[str, dict]) -> list[str] | None:
if subject == "mame recipes":
return [
sys.executable,
"-m",
"scripts.scraper.romset_dat_importer",
"--source",
"mame",
"--fetch",
]
if subject == "fbneo recipes":
return [
sys.executable,
"-m",
"scripts.scraper.romset_dat_importer",
"--source",
"fbneo",
"--fetch",
]
if subject in ("no-intro games", "redump games"):
# The game DATs download without a browser, unlike the BIOS ones.
return [
sys.executable,
"-m",
"scripts.scraper.game_dat_importer",
"--source",
subject.split()[0],
"--fetch",
"--refresh",
"--floor",
]
# redump / no-intro / tosec need manual DAT download.
return None
_AREA_COMMANDS: dict[str, Callable[[str, dict[str, dict]], list[str] | None]] = {
"platforms": _platform_command,
"targets": _target_command,
"data": _data_command,
"catalogs": _catalog_command,
}
def _command_for(
area: str, subject: str, registry: dict[str, dict]
) -> list[str] | None:
@@ -369,87 +460,13 @@ def _command_for(
# truth comes first and the original follows (Job.then).
return _truth_refresh(subject)
if area == "platforms":
entry = registry.get(subject) or {}
scraper = entry.get("scraper")
if not scraper:
return None
return [
sys.executable,
"-m",
f"scripts.scraper.{scraper}_scraper",
"-o",
f"platforms/{subject}.yml",
*(str(a) for a in entry.get("rescrape_args") or ()),
]
if area == "targets":
# "<platform> cores" rows list buildbot names without a profile. No
# scraper fixes that, a human writes `cores:` or _overrides.yml.
if subject.endswith(" cores"):
return None
entry = registry.get(subject) or {}
module = entry.get("target_scraper")
if not module:
return None
return [
sys.executable,
"-m",
f"scripts.scraper.targets.{module}_scraper",
"-o",
f"platforms/targets/{subject}.yml",
]
if area == "data":
if subject not in _data_dir_keys():
# "_data_dirs.yml" and "buildbot system" name the registry and
# what it does not track yet: a human adds the entry.
return None
return [
sys.executable,
"scripts/refresh_data_dirs.py",
"--key",
subject,
"--force",
]
if area == "ci" and subject == "install.py pin":
# The pin is the hash of the committed install.py, nothing to judge.
return [sys.executable, "scripts/pin_installer.py"]
if area == "catalogs":
if subject == "mame recipes":
return [
sys.executable,
"-m",
"scripts.scraper.romset_dat_importer",
"--source",
"mame",
"--fetch",
]
if subject == "fbneo recipes":
return [
sys.executable,
"-m",
"scripts.scraper.romset_dat_importer",
"--source",
"fbneo",
"--fetch",
]
if subject in ("no-intro games", "redump games"):
# The game DATs download without a browser, unlike the BIOS ones.
return [
sys.executable,
"-m",
"scripts.scraper.game_dat_importer",
"--source",
subject.split()[0],
"--fetch",
"--refresh",
"--floor",
]
# redump / no-intro / tosec need manual DAT download.
return None
builder = _AREA_COMMANDS.get(area)
if builder:
return builder(subject, registry)
# coreinfo, ci, profiles: never auto-refresh.
return None
+1 -2
View File
@@ -91,8 +91,7 @@ def plan_variants(entries: Iterable[dict], region: str,
local: Callable[[dict], Path | None]) -> dict[str, dict[str, Path]]:
"""The staged files of `full`, `own` and `others`, dest -> file. An entry
the collection does not hold is left out of every variant."""
held = [(entry, local(entry)) for entry in entries]
held = [(entry, path) for entry, path in held if path]
held = [(entry, path) for entry in entries if (path := local(entry))]
full = {entry_dest(e): p for e, p in held}
own = {entry_dest(e): p for e, p in held if region in regions_of(e)}
others = {entry_dest(e): p for e, p in held if region not in regions_of(e)}
+1 -7
View File
@@ -53,12 +53,6 @@ SITE = "https://abdess.github.io/retrobios/"
HANDHELD_PAGE = "wiki/installer/#on-a-handheld-the-retrobios-port"
def _size(count: int) -> str:
if count >= 1024**3:
return f"{count / 1024**3:.1f} GB"
return f"{count / 1024**2:.0f} MB"
def _display(pack: str) -> str:
"""RetroArch_Lakka_v1.22.2_BIOS_Pack.zip reads as RetroArch Lakka v1.22.2."""
return pack.split("_BIOS_Pack", 1)[0].replace("_", " ")
@@ -273,7 +267,7 @@ def render(record: dict, platforms_dir: str, whats_new: str,
folder = folders.get(name)
lines.append(
f"| {_display(name)} | {_link(pack, tag)} |"
f" {_size(pack['extracted_size'])} | {pack['files']:,} |"
f" {release_record.size_text(pack['extracted_size'])} | {pack['files']:,} |"
f" {f'`{folder}`' if folder else '-'} |"
)
lines += [
+3 -3
View File
@@ -196,7 +196,7 @@ def manifest_mismatches(record: dict, install_dir: str | Path) -> list[str]:
return found
def _size(count: int) -> str:
def size_text(count: int) -> str:
if count >= 1024**3:
return f"{count / 1024**3:.1f} GB"
return f"{count / 1024**2:.0f} MB"
@@ -230,8 +230,8 @@ def main() -> int:
return 1
for name, pack in record["packs"].items():
print(
f"{name:<44} download {_size(pack['download_size']):>8}"
f" extracted {_size(pack['extracted_size']):>8}"
f"{name:<44} download {size_text(pack['download_size']):>8}"
f" extracted {size_text(pack['extracted_size']):>8}"
f" {pack['files']:,} files {len(pack['assets'])} asset(s)"
)
mismatches = manifest_mismatches(record, args.install_dir)
+21 -12
View File
@@ -57,6 +57,23 @@ def _name_is(name: bytes, wanted: bytes, compared: int) -> bool:
return True
def _after_reset(data: bytes, reset_compare: int, missing_reset: str) -> int | None:
"""The offset past the RESET entry, or past the last entry searched when
the walk goes on without one, None where the code gives up."""
pos = 0
for _ in range(SEARCH_ENTRIES):
if pos + ENTRY_SIZE > len(data):
return None
name = data[pos:pos + NAME_SIZE]
pos += ENTRY_SIZE
if _name_is(name, b"RESET", reset_compare):
break
else:
if missing_reset == REJECT:
return None
return pos
def walk(data: bytes, spec: dict) -> Romdir | None:
"""The ROM directory walk one fork's LoadBiosVersion runs, or None.
@@ -84,18 +101,10 @@ def walk(data: bytes, spec: dict) -> Romdir | None:
missing_reset = spec.get("missing_reset", ENDS_WALK)
offset_mask = (1 << int(spec.get("offset_width", 64))) - 1
pos = 0
for _ in range(SEARCH_ENTRIES):
if pos + ENTRY_SIZE > size:
return None
name = data[pos:pos + NAME_SIZE]
pos += ENTRY_SIZE
if _name_is(name, b"RESET", reset_compare):
break
else:
if missing_reset == REJECT:
return None
found = _after_reset(data, reset_compare, missing_reset)
if found is None:
return None
pos = found
entry = data[pos - ENTRY_SIZE:pos]
offset = 0
romver: bytes | None = None
+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, and 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, and 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))
+1 -1
View File
@@ -162,7 +162,7 @@ def _ec_mul(k: int, p: tuple[int, int] | None) -> tuple[int, int] | None:
return _INF
result = _INF
addend = p
addend: tuple[int, int] | None = p
while k:
if k & 1:
result = _ec_add(result, addend)
+96 -67
View File
@@ -356,6 +356,95 @@ def resolve_project_word(path: str, trees: Iterable[list[str] | None]) -> str |
return None
def _joined_line(lines: list[str], number: int) -> tuple[str, int, int]:
"""(line, boundary, joined_at) of one scalar line, its wrapped run joined.
boundary is where the line's own text ends, joined_at where the next
line's text starts in the joined line, 0 when nothing was joined.
"""
# A literal block keeps its line breaks, so a citation wrapped after
# `file:` or after a range's comma lost the ranges on the next line
# (gearcoleco `libretro.cpp:` then four ranges). The next line is
# read as the run's continuation, and a run reaching into it is wrapped.
line = lines[number].rstrip()
boundary = len(line)
joined_at = 0
following = lines[number + 1].lstrip() if number + 1 < len(lines) else ""
if PROSE_WRAPPED_RANGE_RE.match(following) and line[-1:].isalnum():
# The break can fall before the colon too: jgenesis wraps
# `.../src/config.rs` then `:76-78,95-99` on the next line.
joined_at = len(line)
line += following
following = ""
# A numbered list after a colon (abuse: `setup.cpp:` then `1. -datadir`)
# is not a range.
if not following[:1].isdigit() or PROSE_LIST_ITEM_RE.match(following):
following = ""
if following and line.endswith(":"):
joined_at = len(line)
line += following
elif following and line.endswith(","):
joined_at = len(line) + 1
line += " " + following
return line, boundary, joined_at
def _prose_events(line: str) -> list[tuple[int, int, re.Match]]:
"""Citations, file names and abbreviated locations of a line, in order."""
return sorted(
[(m.start(), 0, m) for m in PROSE_CITE_RE.finditer(line)]
+ [(m.start(), 1, m) for m in _PROSE_FILE_NAMED_RE.finditer(line)]
+ [(m.start(), 2, m) for m in _PROSE_ABBREVIATED_RE.finditer(line)],
key=lambda event: (event[0], event[1]),
)
def _locate_run(
kind: int, match: re.Match, line: str, lines: list[str], number: int,
known: frozenset[str] | set[str], named: tuple[str, str] | None,
) -> tuple[tuple[str, str, int, tuple[int, int]] | None, tuple[str, str] | None]:
"""(path, role, start, span) of the run an event opens, None when it
opens none, and the file named for the locations after it."""
if kind == 1:
if "://" not in line[max(0, match.start() - 3):match.end()]:
named = (match.group("path"), "")
return None, named
if kind == 2:
if named is None:
return None, named
path, role = named
path_start = match.start()
return (path, role, path_start, (path_start, path_start)), named
found, role, path_start, path_span = _prose_path(line, lines, number, match, known)
if found is None:
return None, named
return (found, role, path_start, path_span), (found, role)
def _run_spans(line: str, match: re.Match) -> tuple[list[tuple[int, int]], int]:
"""Range spans of the run a match opens, and where the run ends."""
spans = [(match.start("range"), match.end("range"))]
end = match.end()
while True:
cont = PROSE_CONT_RE.match(line, end)
if cont is None and (listed := PROSE_CONT_LIST_RE.match(line, end)):
spans.extend(
(item.start(), item.end())
for item in _PROSE_LIST_RANGE_RE.finditer(
line, end, listed.end()
)
)
end = listed.end()
break
if cont is None:
cont = PROSE_CONT_SPACED_RE.match(line, end)
if cont is None:
break
spans.append((cont.start("range"), cont.end("range")))
end = cont.end()
return spans, end
def _prose_runs(
text: str, known: frozenset[str] | set[str] = frozenset()
) -> Iterator[tuple[
@@ -380,79 +469,19 @@ def _prose_runs(
# Where the run wrapped from the line before ends in this one: its
# ranges are that run's, not abbreviated locations of their own.
carried = 0
for number, own in enumerate(lines):
# A literal block keeps its line breaks, so a citation wrapped after
# `file:` or after a range's comma lost the ranges on the next line
# (gearcoleco `libretro.cpp:` then four ranges). The next line is
# read as the run's continuation, and a run reaching into it is wrapped.
line = own.rstrip()
boundary = len(line)
joined_at = 0
following = lines[number + 1].lstrip() if number + 1 < len(lines) else ""
if PROSE_WRAPPED_RANGE_RE.match(following) and line[-1:].isalnum():
# The break can fall before the colon too: jgenesis wraps
# `.../src/config.rs` then `:76-78,95-99` on the next line.
joined_at = len(line)
line += following
following = ""
# A numbered list after a colon (abuse: `setup.cpp:` then `1. -datadir`)
# is not a range.
if not following[:1].isdigit() or PROSE_LIST_ITEM_RE.match(following):
following = ""
if following and line.endswith(":"):
joined_at = len(line)
line += following
elif following and line.endswith(","):
joined_at = len(line) + 1
line += " " + following
for number in range(len(lines)):
line, boundary, joined_at = _joined_line(lines, number)
consumed, carried = carried, 0
events = sorted(
[(m.start(), 0, m) for m in PROSE_CITE_RE.finditer(line)]
+ [(m.start(), 1, m) for m in _PROSE_FILE_NAMED_RE.finditer(line)]
+ [(m.start(), 2, m) for m in _PROSE_ABBREVIATED_RE.finditer(line)],
key=lambda event: (event[0], event[1]),
)
for _start, kind, match in events:
for _start, kind, match in _prose_events(line):
if match.start() >= boundary:
break
if match.start() < consumed:
continue
if kind == 1:
if "://" not in line[max(0, match.start() - 3):match.end()]:
named = (match.group("path"), "")
located, named = _locate_run(kind, match, line, lines, number, known, named)
if located is None:
continue
if kind == 2:
if named is None:
continue
path, role = named
path_start = match.start()
path_span = (path_start, path_start)
else:
path, role, path_start, path_span = _prose_path(
line, lines, number, match, known
)
if path is None:
continue
named = (path, role)
spans = [(match.start("range"), match.end("range"))]
end = match.end()
while True:
cont = PROSE_CONT_RE.match(line, end)
if cont is None and (listed := PROSE_CONT_LIST_RE.match(line, end)):
spans.extend(
(item.start(), item.end())
for item in _PROSE_LIST_RANGE_RE.finditer(
line, end, listed.end()
)
)
end = listed.end()
break
if cont is None:
cont = PROSE_CONT_SPACED_RE.match(line, end)
if cont is None:
break
spans.append((cont.start("range"), cont.end("range")))
end = cont.end()
path, role, path_start, path_span = located
spans, end = _run_spans(line, match)
consumed = end
if end > boundary:
indent = len(lines[number + 1]) - len(lines[number + 1].lstrip())
+46 -36
View File
@@ -27,7 +27,6 @@ from __future__ import annotations
import argparse
import contextlib
import datetime as dt
import hashlib
import json
import os
@@ -49,6 +48,7 @@ from typing import IO
sys.path.insert(0, str(Path(__file__).resolve().parent))
import core_probe as cp
from autorun import now_iso
ROOT = Path(__file__).resolve().parent.parent
CACHE = ROOT / ".cache" / "standalone"
@@ -293,10 +293,6 @@ def installed(emu: Emulator, sha256: str | None, cache: Path = CACHE) -> tuple[d
# One repetition
# --------------------------------------------------------------------------
def now_iso() -> str:
return dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat()
# The X server runs inside the sandbox, on the sandbox's own /tmp: the
# display is private to the run, and the host's /tmp/.X11-unix (read-only
# under WSLg) is never touched. Its fbdir option keeps the screen as an XWD
@@ -338,6 +334,35 @@ def read_lines(stream: IO[bytes], out: list[dict], samples: list) -> None:
out.append({"frame": len(samples), "level": "info", "text": text})
def wait_for_screen(proc: subprocess.Popen, screen_file: Path, logs: list[dict]) -> None:
deadline = time.monotonic() + 30
while not screen_file.exists():
if proc.poll() is not None or time.monotonic() > deadline:
raise cp.ProbeError(f"Xvfb did not start in the sandbox (exit {proc.poll()}): "
f"{' / '.join(line['text'] for line in logs[-5:])}")
time.sleep(0.05)
def sample_screen(proc: subprocess.Popen, screen_file: Path, args: argparse.Namespace,
samples: list[tuple[float, str, bool]], png_dir: Path | None, started: float) -> dict | None:
"""Hash the screen every interval. Returns how the emulator ended, None
while it still runs."""
for index in range(args.samples):
target = started + (index + 1) * args.interval
while time.monotonic() < target and proc.poll() is None:
time.sleep(min(0.05, max(0.0, target - time.monotonic())))
if proc.poll() is not None:
code = proc.returncode
return {"status": code if code >= 0 else None,
"signal": signal.Signals(-code).name if code < 0 else None}
width, height, rgb = parse_xwd(screen_file.read_bytes())
sha1 = hashlib.sha1(rgb).hexdigest()
samples.append((round(time.monotonic() - started, 3), sha1, cp.uniform_frame(rgb, 3)))
if png_dir and not any(p.name.endswith(f"{sha1[:12]}.png") for p in png_dir.iterdir()):
(png_dir / f"{index:04d}-{sha1[:12]}.png").write_bytes(cp.png_bytes(width, height, rgb))
return None
def run_once(args: argparse.Namespace, emu: Emulator, tree: Path, system_dir: Path, scratch: Path,
png_dir: Path | None) -> dict:
home = scratch / "home"
@@ -375,28 +400,9 @@ def run_once(args: argparse.Namespace, emu: Emulator, tree: Path, system_dir: Pa
reader = threading.Thread(target=read_lines, args=(proc.stdout, logs, samples), daemon=True)
reader.start()
try:
deadline = time.monotonic() + 30
while not screen_file.exists():
if proc.poll() is not None or time.monotonic() > deadline:
raise cp.ProbeError(f"Xvfb did not start in the sandbox (exit {proc.poll()}): "
f"{' / '.join(line['text'] for line in logs[-5:])}")
time.sleep(0.05)
wait_for_screen(proc, screen_file, logs)
started = time.monotonic()
ended = None
for index in range(args.samples):
target = started + (index + 1) * args.interval
while time.monotonic() < target and proc.poll() is None:
time.sleep(min(0.05, max(0.0, target - time.monotonic())))
if proc.poll() is not None:
code = proc.returncode
ended = {"status": code if code >= 0 else None,
"signal": signal.Signals(-code).name if code < 0 else None}
break
width, height, rgb = parse_xwd(screen_file.read_bytes())
sha1 = hashlib.sha1(rgb).hexdigest()
samples.append((round(time.monotonic() - started, 3), sha1, cp.uniform_frame(rgb, 3)))
if png_dir and not any(p.name.endswith(f"{sha1[:12]}.png") for p in png_dir.iterdir()):
(png_dir / f"{index:04d}-{sha1[:12]}.png").write_bytes(cp.png_bytes(width, height, rgb))
ended = sample_screen(proc, screen_file, args, samples, png_dir, started)
wall = time.monotonic() - started
finally:
stop(proc)
@@ -608,13 +614,23 @@ def _probe(args: argparse.Namespace, emu: Emulator) -> int:
return 0
def _check_mode_problems(args: argparse.Namespace) -> list[str]:
problems = []
if len({dest for dest, _ in args.vary}) != 1:
problems.append("--vary must name the same DEST in every occurrence")
problems.extend(f"--vary {dest}={src}: not a file"
for dest, src in args.vary if src and not Path(src).is_file())
if args.observable not in OBSERVABLES:
problems.append(f"--observable {args.observable}: not one of {', '.join(OBSERVABLES)}")
return problems
def validate(args: argparse.Namespace) -> list[str]:
problems = []
if not Path(args.content).is_file():
problems.append(f"--content {args.content}: not a file")
for dest, src in args.bios_file:
if not Path(src).is_file():
problems.append(f"--bios-file {dest}={src}: not a file")
problems.extend(f"--bios-file {dest}={src}: not a file"
for dest, src in args.bios_file if not Path(src).is_file())
if args.oracle and not Path(args.oracle).is_file():
problems.append(f"--oracle {args.oracle}: not a file")
if args.samples < 2 or args.interval <= 0:
@@ -630,13 +646,7 @@ def validate(args: argparse.Namespace) -> list[str]:
if args.subject and not re.fullmatch(r"[a-z0-9]+(?:[-_][a-z0-9]+)*", args.subject):
problems.append(f"--subject {args.subject!r}: lowercase letters, digits, - and _ only")
if args.mode == "check":
if len({dest for dest, _ in args.vary}) != 1:
problems.append("--vary must name the same DEST in every occurrence")
for dest, src in args.vary:
if src and not Path(src).is_file():
problems.append(f"--vary {dest}={src}: not a file")
if args.observable not in OBSERVABLES:
problems.append(f"--observable {args.observable}: not one of {', '.join(OBSERVABLES)}")
problems += _check_mode_problems(args)
return problems
+16 -10
View File
@@ -419,9 +419,9 @@ def fetch_file(
return None if text == ABSENT else text.splitlines()
if offline:
raise NotCachedError(f"{repo.slug}@{sha[:8]}:{path} is not in the offline cache")
text = _http_text(content_url(repo, sha, path))
write_cache(target, ABSENT if text is None else text)
return None if text is None else text.splitlines()
fetched = _http_text(content_url(repo, sha, path))
write_cache(target, ABSENT if fetched is None else fetched)
return None if fetched is None else fetched.splitlines()
# How long an answer about a moving reference stays trusted. A branch tip, a
@@ -696,6 +696,15 @@ def _github_graphql(
return payload
def _dig(value: object, *keys: str) -> object:
"""The value under nested keys of a JSON answer, None where one is missing."""
for key in keys:
if not isinstance(value, dict) or key not in value:
return None
value = value[key]
return value
def newest_tag(repo: Repo, cache_dir: str, offline: bool = False) -> str | None:
"""The tag on the newest commit.
@@ -708,10 +717,7 @@ def newest_tag(repo: Repo, cache_dir: str, offline: bool = False) -> str | None:
_NEWEST_TAG_QUERY, {"owner": repo.owner, "name": repo.name},
cache_dir, offline,
)
try:
nodes = payload["data"]["repository"]["refs"]["nodes"]
except (TypeError, KeyError):
nodes = None
nodes = _dig(payload, "data", "repository", "refs", "nodes")
if isinstance(nodes, list):
return nodes[0].get("name") if nodes else None
tags = list_tags(repo, cache_dir, offline)
@@ -911,7 +917,7 @@ def ancestry(
if ahead is None:
return None
if repo.family == "github":
behind = forward.get("behind_by")
behind = forward.get("behind_by") if isinstance(forward, dict) else None
else:
behind = _commits_ahead(
_api(_compare_url(repo, head, base), cache_dir, offline), repo.family
@@ -1132,8 +1138,8 @@ def list_gitlinks(
if len(payload) < TREE_PAGE_SIZE:
break
return links
url = _tree_url(repo, sha)
payload = _api(url, cache_dir, offline) if url else None
tree_url = _tree_url(repo, sha)
payload = _api(tree_url, cache_dir, offline) if tree_url else None
if not isinstance(payload, dict):
return {}
return {
+279 -198
View File
@@ -30,7 +30,10 @@ import zipfile
from collections.abc import Callable, Iterable
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from typing import TYPE_CHECKING, Any, TypedDict
if TYPE_CHECKING:
from typing_extensions import Unpack
sys.path.insert(0, os.path.dirname(__file__))
from common import (
@@ -99,7 +102,7 @@ class ValidationResult:
def __init__(self, filepath: str) -> None:
self.filepath = filepath
self.filename = os.path.basename(filepath)
self.checks = [] # (status, message) tuples
self.checks: list[tuple[str, str]] = [] # (status, message) tuples
self.sha1 = ""
self.md5 = ""
self.crc32 = ""
@@ -410,46 +413,53 @@ def _archive_members(
return described
def validate_file(
filepath: str,
db: dict | None,
platform_hashes: dict,
profile_hashes: dict | None = None,
) -> ValidationResult:
"""Run all validation checks on a file."""
result = ValidationResult(filepath)
@dataclass(frozen=True)
class _Review:
"""One file under review and the tables it is read against."""
filepath: str
db: dict | None
platform_hashes: dict
profile_hashes: dict
@dataclass(frozen=True)
class _Known:
"""What declares the file: a platform's hash, its own check, a profile, its name."""
sha1: bool
md5: bool
other: bool
accepted_by: set[str]
by_profile: set[str] | None
name: bool
@property
def by_platform(self) -> bool:
return bool(self.sha1 or self.md5 or self.other or self.accepted_by)
def _path_problem(filepath: str) -> str:
"""Why the path cannot be reviewed, empty when it can."""
# Whoever opened the pull request chose this path, so its shape is
# settled before anything is read. A symlink to an endless device would
# otherwise be hashed until the job timed out, and a symlink out of the
# checkout would be reported as though its target had been contributed.
if os.path.islink(filepath):
result.add_check(False, "Symlinks are not allowed")
return result
return "Symlinks are not allowed"
if not os.path.exists(filepath):
result.add_check(False, f"File not found: {filepath}. A path is read from the folder "
"the command runs in, or pass --changed to check the files "
"changed under bios/")
return result
return (f"File not found: {filepath}. A path is read from the folder "
"the command runs in, or pass --changed to check the files "
"changed under bios/")
if os.path.isdir(filepath):
result.add_check(False, "Folder with no file in it")
return result
return "Folder with no file in it"
if not os.path.isfile(filepath):
result.add_check(False, "Not a regular file: a device, a pipe or a socket")
return result
return "Not a regular file: a device, a pipe or a socket"
return ""
result.size = os.path.getsize(filepath)
hashes = compute_hashes(filepath)
result.sha1 = hashes["sha1"]
result.md5 = hashes["md5"]
result.crc32 = hashes["crc32"]
ext = os.path.splitext(filepath)[1].lower()
blocked = ext in BLOCKED_EXTENSIONS
def _check_size(result: ValidationResult) -> bool:
"""The size checks, True when the file is too large for git."""
too_large = result.size > MAX_FILE_SIZE
if too_large:
# GitHub refuses a pushed file over 100 MiB, so a pull request cannot
@@ -465,167 +475,179 @@ def validate_file(
result.add_check(False, "File is empty (0 bytes)")
else:
result.add_check(True, f"File size within limits ({result.size:,} bytes)")
return too_large
def _relative_path(filepath: str) -> str:
# Paths are compared as the database writes them, relative to the
# checkout: an absolute path to the file itself read as its duplicate.
relative = filepath
if os.path.isabs(filepath):
candidate = os.path.relpath(filepath, os.getcwd())
if not candidate.startswith(".."):
relative = candidate
return candidate
return filepath
if db:
if result.sha1 in db.get("files", {}):
existing = db["files"][result.sha1]
held_at = {
os.path.normpath(p)
for p in [existing.get("path"), *(existing.get("paths") or [])] if p
}
if os.path.normpath(relative) in held_at:
# The file the database was built from, not a copy of it: a
# PR that regenerated database.json was told each new file
# duplicated itself.
result.add_check(True, "Already in the database at this path")
elif _in_nodedup_dir(relative):
result.add_info(
f"Identical to `{existing['path']}`, kept: this tree is read by path"
)
else:
result.outcome = "held"
result.add_warning(
f"Already held at `{existing['path']}`: nothing to add, "
"leave this copy out of the pull request"
)
else:
result.add_check(True, "Not a duplicate in database")
def _check_duplicate(result: ValidationResult, db: dict, relative: str) -> None:
if result.sha1 not in db.get("files", {}):
result.add_check(True, "Not a duplicate in database")
return
existing = db["files"][result.sha1]
held_at = {
os.path.normpath(p)
for p in [existing.get("path"), *(existing.get("paths") or [])] if p
}
if os.path.normpath(relative) in held_at:
# The file the database was built from, not a copy of it: a
# PR that regenerated database.json was told each new file
# duplicated itself.
result.add_check(True, "Already in the database at this path")
elif _in_nodedup_dir(relative):
result.add_info(
f"Identical to `{existing['path']}`, kept: this tree is read by path"
)
else:
result.outcome = "held"
result.add_warning(
f"Already held at `{existing['path']}`: nothing to add, "
"leave this copy out of the pull request"
)
def _identify(review: _Review, result: ValidationResult, sha256: str) -> _Known:
platform_hashes, profile_hashes = review.platform_hashes, review.profile_hashes
sha1_known = result.sha1 in platform_hashes.get("sha1", set())
md5_known = result.md5 in platform_hashes.get("md5", set())
other_known = (
hashes.get("sha256", "") in platform_hashes.get("sha256", set())
sha256 in platform_hashes.get("sha256", set())
or (result.crc32, result.size) in platform_hashes.get("crc32", set())
)
accepted_by = (
set() if sha1_known or md5_known or other_known
else _platforms_accepting(filepath, result.filename, platform_hashes)
else _platforms_accepting(review.filepath, result.filename, platform_hashes)
)
name_known = result.filename in platform_hashes.get("names", set())
profile_hashes = profile_hashes or {}
by_profile = (
profile_hashes.get("sha1", {}).get(result.sha1)
or profile_hashes.get("sha256", {}).get(hashes.get("sha256", ""))
or profile_hashes.get("sha256", {}).get(sha256)
or profile_hashes.get("md5", {}).get(result.md5)
or profile_hashes.get("crc32", {}).get((result.crc32, result.size))
or profile_hashes.get("crc32", {}).get((result.crc32, None))
)
return _Known(sha1_known, md5_known, other_known, accepted_by, by_profile,
result.filename in platform_hashes.get("names", set()))
if blocked:
# An executable is refused unless an emulator profile pins its exact
# bytes: PICO-8's pico8.exe and SDL2.dll are declared by sha1 from the
# official archive. A weak hash (md5, crc32) never vouches for code.
pinned = (
profile_hashes.get("sha1", {}).get(result.sha1)
or profile_hashes.get("sha256", {}).get(hashes.get("sha256", ""))
)
if pinned:
result.add_check(
True,
f"Executable whose bytes an emulator profile pins by sha1: {', '.join(sorted(pinned))}",
)
else:
result.add_check(False, f"Blocked file extension: {ext}")
# The files of a ZIP no list declares whole, when the upload is one.
members: list[str] | None = None
if sha1_known:
result.add_check(True, "SHA1 matches known platform requirement")
elif md5_known:
result.add_check(True, "MD5 matches known platform requirement")
elif other_known:
result.add_check(True, "Hash matches known platform requirement")
elif accepted_by:
def _check_executable(result: ValidationResult, sha256: str, profile_hashes: dict, ext: str) -> None:
# An executable is refused unless an emulator profile pins its exact
# bytes: PICO-8's pico8.exe and SDL2.dll are declared by sha1 from the
# official archive. A weak hash (md5, crc32) never vouches for code.
pinned = (
profile_hashes.get("sha1", {}).get(result.sha1)
or profile_hashes.get("sha256", {}).get(sha256)
)
if pinned:
result.add_check(
True, "Accepted by the platform's own check: " + ", ".join(sorted(accepted_by))
True,
f"Executable whose bytes an emulator profile pins by sha1: {', '.join(sorted(pinned))}",
)
elif by_profile:
names = sorted(by_profile)
else:
result.add_check(False, f"Blocked file extension: {ext}")
def _check_known(review: _Review, result: ValidationResult, known: _Known, too_large: bool) -> list[str] | None:
"""What declares the file, and the files of a ZIP no list declares
whole, when the upload is one."""
if known.sha1:
result.add_check(True, "SHA1 matches known platform requirement")
elif known.md5:
result.add_check(True, "MD5 matches known platform requirement")
elif known.other:
result.add_check(True, "Hash matches known platform requirement")
elif known.accepted_by:
result.add_check(
True, "Accepted by the platform's own check: " + ", ".join(sorted(known.accepted_by))
)
elif known.by_profile:
names = sorted(known.by_profile)
shown = ", ".join(names[:5]) + (f" and {len(names) - 5} more" if len(names) > 5 else "")
result.add_check(True, f"Hash matches a file the emulator profile declares: {shown}")
elif name_known:
elif known.name:
result.add_warning(
"Filename matches a known requirement but hash differs - may be a variant"
)
else:
result.outcome = "unknown"
members = None if too_large else _archive_members(
filepath, db, platform_hashes, profile_hashes
review.filepath, review.db, review.platform_hashes, review.profile_hashes
)
if members is not None:
# A folder zipped to upload many files at once was hashed as one
# file and its contributor asked where that dump came from.
shown = "; ".join(members[:10]) + (
f"; and {len(members) - 10} more" if len(members) > 10 else ""
)
result.add_warning(
"A ZIP no platform list or emulator profile declares as a whole: "
"add the files it holds, unzipped, not the archive. Inside: "
+ (shown or "nothing")
)
else:
result.add_warning(
"Not recognised: no platform list or emulator profile declares this "
f"file. Say in the {'issue' if too_large else 'pull request'} which "
"emulator reads it, for which system, and where the dump comes from"
)
_report_unknown(result, members, too_large)
return members
return None
normalized = os.path.normpath(relative)
values = (result.sha1, result.md5, hashes.get("sha256", ""))
expected = expected_folders(values, platform_hashes, profile_hashes)
if too_large:
# The file stays out of the pull request, so no folder of bios/ is
# the contributor's to choose: the release asset is placed by hand.
pass
elif normalized.startswith("bios" + os.sep):
parts = normalized.split(os.sep)
here = f"bios/{parts[1]}/{parts[2]}/" if len(parts) >= 4 else ""
makers = {folder.split("/")[1] for folder in expected}
if expected and (len(parts) < 4 or parts[1] not in makers):
# Depth alone passed a PS1 BIOS filed under bios/Nintendo/Game Boy/.
result.add_warning(
"Placed under " + (here or "the bios/ root") + ", while the other files of "
"its system are in " + " or ".join(f"`{f}`" for f in expected)
)
elif len(parts) >= 4:
result.add_check(True, f"Correct placement: bios/{parts[1]}/{parts[2]}/")
else:
result.add_warning("File should be in bios/Manufacturer/Console/ structure")
elif result.outcome == "held" or members is not None:
# Nothing to place: a copy, or an archive whose files go in unzipped.
pass
def _report_unknown(result: ValidationResult, members: list[str] | None, too_large: bool) -> None:
if members is not None:
# A folder zipped to upload many files at once was hashed as one
# file and its contributor asked where that dump came from.
shown = "; ".join(members[:10]) + (
f"; and {len(members) - 10} more" if len(members) > 10 else ""
)
result.add_warning(
"A ZIP no platform list or emulator profile declares as a whole: "
"add the files it holds, unzipped, not the archive. Inside: "
+ (shown or "nothing")
)
else:
# The contributor asks before forking: say where it goes.
spot = placement(
values, result.filename, db, platform_hashes, profile_hashes,
declared=bool(sha1_known or md5_known or other_known or accepted_by or by_profile),
result.add_warning(
"Not recognised: no platform list or emulator profile declares this "
f"file. Say in the {'issue' if too_large else 'pull request'} which "
"emulator reads it, for which system, and where the dump comes from"
)
result.destination = spot.destination(result.sha1)
copies = f". --place copies it to `{result.destination}`" if result.destination else ""
if spot.folders:
result.add_warning(
"File is not under bios/ yet. Its system's files are in "
+ " or ".join(f"`{f}`" for f in spot.folders) + copies
)
elif spot.home:
result.add_warning(
f"File is not under bios/ yet. The collection keeps this name in `{spot.home}`"
+ copies
)
else:
result.add_warning(
"File is not under bios/ yet. Place it in bios/Manufacturer/Console/"
)
def _check_bios_placement(result: ValidationResult, normalized: str, expected: list[str]) -> None:
parts = normalized.split(os.sep)
here = f"bios/{parts[1]}/{parts[2]}/" if len(parts) >= 4 else ""
makers = {folder.split("/")[1] for folder in expected}
if expected and (len(parts) < 4 or parts[1] not in makers):
# Depth alone passed a PS1 BIOS filed under bios/Nintendo/Game Boy/.
result.add_warning(
"Placed under " + (here or "the bios/ root") + ", while the other files of "
"its system are in " + " or ".join(f"`{f}`" for f in expected)
)
elif len(parts) >= 4:
result.add_check(True, f"Correct placement: bios/{parts[1]}/{parts[2]}/")
else:
result.add_warning("File should be in bios/Manufacturer/Console/ structure")
def _suggest_destination(review: _Review, result: ValidationResult, values: tuple[str, ...],
known: _Known) -> None:
# The contributor asks before forking: say where it goes.
spot = placement(
values, result.filename, review.db, review.platform_hashes, review.profile_hashes,
declared=bool(known.by_platform or known.by_profile),
)
result.destination = spot.destination(result.sha1)
copies = f". --place copies it to `{result.destination}`" if result.destination else ""
if spot.folders:
result.add_warning(
"File is not under bios/ yet. Its system's files are in "
+ " or ".join(f"`{f}`" for f in spot.folders) + copies
)
elif spot.home:
result.add_warning(
f"File is not under bios/ yet. The collection keeps this name in `{spot.home}`"
+ copies
)
else:
result.add_warning(
"File is not under bios/ yet. Place it in bios/Manufacturer/Console/"
)
def _check_declared_size(result: ValidationResult, platform_hashes: dict, profile_hashes: dict) -> bool:
"""True when the size fits every declaration of the name."""
declared = [
*platform_hashes.get("sizes", {}).get(result.filename, []),
*profile_hashes.get("sizes", {}).get(result.filename, []),
@@ -639,27 +661,80 @@ def validate_file(
f"Every declaration of {result.filename} expects {shown} bytes, "
f"this file has {result.size:,}: truncated or another file"
)
return size_fits
if (name_known and not (sha1_known or md5_known or other_known or accepted_by)
and not by_profile and size_fits):
owners = name_systems(result.filename, platform_hashes, profile_hashes)
home = _variant_home(db, result.filename, "", set() if len(owners) > 1 else {
d for table in (platform_hashes, profile_hashes or {}) for s in owners
for d in table.get("system_dirs", {}).get(s, ())
} if owners else None)
if not home and normalized.startswith("bios" + os.sep):
# Beside the file, in the folder the contributor chose.
home = os.path.dirname(normalized).replace(os.sep, "/") + "/"
slot = f"{home}.variants/{result.filename}.{result.sha1[:8]}"
if home and not normalized.startswith("bios" + os.sep):
result.destination = slot
if home:
result.add_info(
f"This may be a valid variant. If accepted, it will be placed in `{slot}`"
)
else:
result.add_info("This may be a valid variant of a file the collection lacks")
def _note_variant(review: _Review, result: ValidationResult, normalized: str) -> None:
platform_hashes, profile_hashes = review.platform_hashes, review.profile_hashes
owners = name_systems(result.filename, platform_hashes, profile_hashes)
home = _variant_home(review.db, result.filename, "", set() if len(owners) > 1 else {
d for table in (platform_hashes, profile_hashes) for s in owners
for d in table.get("system_dirs", {}).get(s, ())
} if owners else None)
if not home and normalized.startswith("bios" + os.sep):
# Beside the file, in the folder the contributor chose.
home = os.path.dirname(normalized).replace(os.sep, "/") + "/"
slot = f"{home}.variants/{result.filename}.{result.sha1[:8]}"
if home and not normalized.startswith("bios" + os.sep):
result.destination = slot
if home:
result.add_info(
f"This may be a valid variant. If accepted, it will be placed in `{slot}`"
)
else:
result.add_info("This may be a valid variant of a file the collection lacks")
def validate_file(
filepath: str,
db: dict | None,
platform_hashes: dict,
profile_hashes: dict | None = None,
) -> ValidationResult:
"""Run all validation checks on a file."""
result = ValidationResult(filepath)
problem = _path_problem(filepath)
if problem:
result.add_check(False, problem)
return result
result.size = os.path.getsize(filepath)
hashes = compute_hashes(filepath)
result.sha1 = hashes["sha1"]
result.md5 = hashes["md5"]
result.crc32 = hashes["crc32"]
sha256 = hashes.get("sha256", "")
ext = os.path.splitext(filepath)[1].lower()
too_large = _check_size(result)
relative = _relative_path(filepath)
if db:
_check_duplicate(result, db, relative)
review = _Review(filepath, db, platform_hashes, profile_hashes or {})
known = _identify(review, result, sha256)
if ext in BLOCKED_EXTENSIONS:
_check_executable(result, sha256, review.profile_hashes, ext)
members = _check_known(review, result, known, too_large)
normalized = os.path.normpath(relative)
values = (result.sha1, result.md5, sha256)
if too_large:
# The file stays out of the pull request, so no folder of bios/ is
# the contributor's to choose: the release asset is placed by hand.
pass
elif normalized.startswith("bios" + os.sep):
_check_bios_placement(result, normalized,
expected_folders(values, platform_hashes, review.profile_hashes))
elif result.outcome == "held" or members is not None:
# Nothing to place: a copy, or an archive whose files go in unzipped.
pass
else:
_suggest_destination(review, result, values, known)
size_fits = _check_declared_size(result, platform_hashes, review.profile_hashes)
if known.name and not known.by_platform and not known.by_profile and size_fits:
_note_variant(review, result, normalized)
return result
@@ -734,16 +809,24 @@ class Placement:
return self.folder + self.name
class PlacementOptions(TypedDict, total=False):
"""How placement() tests a path, and the systems and directory a
declaration names."""
exists: Callable[[str], bool]
systems: Iterable[str]
directory: str
def placement(
values: Iterable[str],
filename: str,
db: dict | None,
platform_hashes: dict,
profile_hashes: dict | None,
*,
declared: bool,
exists: Callable[[str], bool] = os.path.exists,
systems: Iterable[str] = (),
directory: str = "",
**options: Unpack[PlacementOptions],
) -> Placement:
"""Where a file goes, by its hashes and its name.
@@ -761,6 +844,9 @@ def placement(
copy by name counts only in a directory of that tail, and a held
directory of that tail is the folder.
"""
exists = options.get("exists", os.path.exists)
systems = options.get("systems", ())
directory = options.get("directory", "")
values = [value for value in values if value]
folders = expected_folders(values, platform_hashes, profile_hashes)
if folders:
@@ -954,11 +1040,7 @@ def get_changed_files() -> list[str]:
"staged, modified and untracked files only",
file=sys.stderr,
)
seen: set[str] = set()
return [
f for f in changed
if f.startswith("bios/") and not (f in seen or seen.add(f)) and os.path.isfile(f)
]
return [f for f in dict.fromkeys(changed) if f.startswith("bios/") and os.path.isfile(f)]
def expand_folders(paths: list[str]) -> list[str]:
@@ -1054,11 +1136,11 @@ def main() -> None:
)
# One output format: --json beside --markdown printed JSON and dropped
# the markdown without a word.
output = parser.add_mutually_exclusive_group()
output.add_argument(
formats = parser.add_mutually_exclusive_group()
formats.add_argument(
"--markdown", action="store_true", help="Output as markdown (for PR comments)"
)
output.add_argument("--json", action="store_true", help="Output as JSON")
formats.add_argument("--json", action="store_true", help="Output as JSON")
parser.add_argument(
"--place", action="store_true",
help="copy each recognised file from outside bios/ to the folder and name "
@@ -1095,21 +1177,20 @@ def main() -> None:
all_passed = all(r.passed for r in results)
if args.json:
output = []
for r in results:
output.append(
{
"file": r.filepath,
"passed": r.passed,
# A file that failed, unread or refused, is not a new one.
"outcome": r.outcome or ("new" if r.passed else "failed"),
"destination": r.destination,
"sha1": r.sha1,
"md5": r.md5,
"size": r.size,
"checks": [{"status": s, "message": m} for s, m in r.checks],
}
)
output = [
{
"file": r.filepath,
"passed": r.passed,
# A file that failed, unread or refused, is not a new one.
"outcome": r.outcome or ("new" if r.passed else "failed"),
"destination": r.destination,
"sha1": r.sha1,
"md5": r.md5,
"size": r.size,
"checks": [{"status": s, "message": m} for s, m in r.checks],
}
for r in results
]
print(json.dumps(output, indent=2))
elif args.markdown:
lines = ["## BIOS Validation Report", ""]
+44 -28
View File
@@ -33,6 +33,13 @@ def _load_json(path: Path) -> object:
return json.load(handle)
def _json_object(path: Path) -> dict:
data = _load_json(path)
if not isinstance(data, dict):
raise ValueError(f"{path}: not a JSON object")
return data
def _validator(name: str) -> Draft202012Validator:
schema = _load_json(SCHEMAS / name)
Draft202012Validator.check_schema(schema)
@@ -63,6 +70,16 @@ def _load_source(path: Path) -> object:
return _SOURCES[key]
def _source_mapping(path: Path) -> dict:
"""A source YAML that holds a mapping, empty when the file is."""
document = _load_source(path)
if not document:
return {}
if not isinstance(document, dict):
raise ValueError(f"{path}: not a mapping")
return document
def _validate_yaml_directory(
directory: Path,
schema_name: str,
@@ -149,12 +166,11 @@ def _config_reads_without_build(path: Path, document: object) -> list[str]:
continue
if read.get("revision") or read.get("binary_sha256"):
continue
for platform in read.get("platforms") or []:
if str(platform) not in builds:
out.append(
f"{path.relative_to(ROOT)}: config_reads[{index}] ({read.get('file')}) "
f"names {platform}, which has no pin_build"
)
out.extend(
f"{path.relative_to(ROOT)}: config_reads[{index}] ({read.get('file')}) "
f"names {platform}, which has no pin_build"
for platform in read.get("platforms") or [] if str(platform) not in builds
)
return out
@@ -272,12 +288,12 @@ def _data_only_source_refs(path: Path, document: object) -> list[str]:
if not isinstance(entry, dict) or not entry.get("source_ref"):
continue
refs = entry["source_ref"]
for ref in refs.values() if isinstance(refs, dict) else [refs]:
if ref and not _ref_cites_code(str(ref)):
out.append(
f"{path.relative_to(ROOT)}: files[{index}] ({entry.get('name')}) "
f"source_ref cites no code that reads the file: {ref}"
)
out.extend(
f"{path.relative_to(ROOT)}: files[{index}] ({entry.get('name')}) "
f"source_ref cites no code that reads the file: {ref}"
for ref in (refs.values() if isinstance(refs, dict) else [refs])
if ref and not _ref_cites_code(str(ref))
)
return out
@@ -310,7 +326,7 @@ def _checks_without_values(path: Path, document: object) -> list[str]:
def _validate_json_files(
paths: list[Path],
schema_name: str,
semantic_check: Callable[[Path, object], list[str]] | None = None,
semantic_check: Callable[[Path, dict], list[str]] | None = None,
) -> list[str]:
validator = _validator(schema_name)
out: list[str] = []
@@ -322,7 +338,8 @@ def _validate_json_files(
continue
validation_errors = _errors(validator, data, str(path.relative_to(ROOT)))
out.extend(validation_errors)
if not validation_errors and semantic_check is not None:
# Every schema a semantic check follows describes an object.
if not validation_errors and semantic_check is not None and isinstance(data, dict):
out.extend(semantic_check(path, data))
return out
@@ -420,11 +437,11 @@ def _unreachable_citations(path: Path, document: object) -> list[str]:
elif isinstance(node, list):
stack.extend(node)
elif isinstance(node, str):
for match in _UNREACHABLE_REF.finditer(node):
out.append(
f"{path.relative_to(ROOT)}: citation names a path outside "
f"any repository: {match.group().strip(' ,;(')}"
)
out.extend(
f"{path.relative_to(ROOT)}: citation names a path outside "
f"any repository: {match.group().strip(' ,;(')}"
for match in _UNREACHABLE_REF.finditer(node)
)
return out
@@ -464,7 +481,7 @@ def _unknown_data_dir_refs() -> list[str]:
for path in source_yaml_paths(directory):
if path.name.startswith("_"):
continue
document = _load_source(path) or {}
document = _source_mapping(path)
systems = document.get("systems")
holders = [document, *(systems.values() if isinstance(systems, dict) else [])]
for holder in holders:
@@ -489,7 +506,7 @@ def _repository_layout_in_profiles() -> list[str]:
"""
out: list[str] = []
for path in source_yaml_paths(ROOT / "emulators"):
document = _load_source(path) or {}
document = _source_mapping(path)
for entry in document.get("files") or []:
if not isinstance(entry, dict):
continue
@@ -855,7 +872,7 @@ def _measurement_errors(root: Path | None = None) -> list[str]:
def _defs_validator(name: str, definition: str) -> Draft202012Validator:
"""A validator for one $defs entry of a schema file."""
schema = _load_json(SCHEMAS / name)
schema = _json_object(SCHEMAS / name)
Draft202012Validator.check_schema(schema)
return Draft202012Validator(
{**schema, "$ref": f"#/$defs/{definition}"}, format_checker=FormatChecker()
@@ -924,13 +941,13 @@ def _arcade_pin_errors() -> list[str]:
code in place, and the installer kept serving it."""
out: list[str] = []
for path in sorted((ROOT / "games" / "arcade").glob("*.json")):
doc = _load_json(path)
doc = _json_object(path)
profile_path = ROOT / "emulators" / f"{doc.get('profile')}.yml"
label = str(path.relative_to(ROOT))
if not profile_path.is_file():
out.append(f"{label}: no profile emulators/{profile_path.name}")
continue
profile = _load_source(profile_path) or {}
profile = _source_mapping(profile_path)
pinned = profile.get("source_commit")
pins = set(pinned.values()) if isinstance(pinned, dict) else {pinned}
commit = (doc.get("source") or {}).get("commit")
@@ -956,7 +973,7 @@ def _games_index_errors() -> list[str]:
if not index_path.exists():
return []
out: list[str] = []
index = _load_json(index_path)
index = _json_object(index_path)
out.extend(_errors(_defs_validator("games-index.schema.json", "index"), index,
str(index_path.relative_to(ROOT))))
kinds = {
@@ -978,9 +995,8 @@ def _games_index_errors() -> list[str]:
if len(data) != entry["size"] or hashlib.sha256(data).hexdigest() != entry["sha256"]:
out.append(f"{label}: size or sha256 differs from index.json")
out.extend(_errors(validator, json.loads(data), label))
for path in sorted(base.rglob("*.json")):
if path != index_path and path not in listed:
out.append(f"{path.relative_to(ROOT)}: not listed in index.json")
out.extend(f"{path.relative_to(ROOT)}: not listed in index.json"
for path in sorted(base.rglob("*.json")) if path != index_path and path not in listed)
return out
+129 -78
View File
@@ -29,6 +29,7 @@ build mode, the way it keys core_version.
from __future__ import annotations
import re
from collections.abc import Callable
from dataclasses import dataclass
import upstream
@@ -175,6 +176,123 @@ def _ancestry(
return relation
@dataclass(frozen=True)
class _Request:
"""One basis read for one build mode, and what its readings carry."""
profile: dict
mode: str
basis: dict
kind: str
stated: str | None
cache_dir: str
offline: bool
profiles: dict | None
recompute: bool
def reading(self, value: str | None, where: str, updates: tuple = ()) -> Reading:
status = MATCH if value == self.stated else DRIFT
return Reading(self.mode, self.kind, self.stated, value, where, status, updates)
def unreadable(self, reason: str) -> Reading:
return Reading(self.mode, self.kind, self.stated, None, reason, UNREADABLE)
def repo_and_pin(self) -> tuple[upstream.Repo, str]:
return _repo_and_pin(self.profile, self.basis, self.mode, self.cache_dir, self.offline)
def _read_none(req: _Request) -> Reading:
if req.recompute:
# A release tagged since the basis was written gives the
# code a version: the advance has to name it.
repo, pin = req.repo_and_pin()
described = upstream.describe(repo, pin, req.cache_dir, req.offline)
if described is not None:
tag, distance = described
return Reading(req.mode, req.kind, req.stated, describe_form(tag, distance, pin),
f"{repo.slug}: tag {tag} is now in "
f"{pin[:7]}'s history", DRIFT)
return req.reading(None, "the code states no version")
def _read_unverified(req: _Request) -> Reading:
return Reading(req.mode, req.kind, req.stated, None, f"not verified: {req.basis.get('why')}",
UNCHECKED)
def _read_package(req: _Request) -> Reading:
artifact = str(req.basis.get("artifact") or "")
if req.basis.get("pattern"):
# An artefact named after its version says it in its name:
# advancemame-0.94.0.tar.gz.
found = read_text_version(artifact, str(req.basis["pattern"]), req.basis.get("format"))
if found is None:
return req.unreadable(f"{artifact}: pattern not found")
return req.reading(found[0], f"named by {artifact}")
return Reading(req.mode, req.kind, req.stated, None, f"read from {artifact}", UNCHECKED)
def _read_alias(req: _Request) -> Reading:
other = (req.profiles or {}).get(str(req.basis.get("of") or ""))
if other is None:
return req.unreadable(f"alias of {req.basis.get('of')}: no such profile")
return req.reading(declared(other, req.mode) if isinstance(other.get("core_version"), dict)
else declared(other, ""), f"alias of {req.basis['of']}")
def _read_file(req: _Request, repo: upstream.Repo, pin: str) -> Reading:
path = str(req.basis.get("path") or "")
lines = upstream.fetch_file(repo, pin, path, req.cache_dir, req.offline)
if lines is None:
return req.unreadable(f"{repo.slug}@{pin[:7]}:{path}: absent")
found = read_text_version("\n".join(lines), str(req.basis.get("pattern") or ""),
req.basis.get("format"))
if found is None:
return req.unreadable(f"{repo.slug}@{pin[:7]}:{path}: pattern not found")
value, line = found
return req.reading(value, f"{repo.slug}@{pin[:7]}:{path}:{line}")
def _read_tag(req: _Request, repo: upstream.Repo, pin: str) -> Reading:
basis = req.basis
if req.recompute:
described = upstream.describe(repo, pin, req.cache_dir, req.offline, basis.get("match"))
if described is None:
return req.unreadable(f"{repo.slug}@{pin[:7]}: no tag in its history")
tag, distance = described
else:
tag, distance = str(basis.get("tag") or ""), basis.get("distance")
commit = upstream.tag_commit(repo, tag, req.cache_dir, req.offline)
if commit is None:
return req.unreadable(f"{repo.slug}: no tag {tag}")
relation = (0, 0) if commit == pin else _ancestry(
repo, commit, pin, req.cache_dir, req.offline)
if relation is None:
return req.unreadable(f"{repo.slug}: {tag}...{pin[:7]} not comparable")
if relation[1]:
return req.unreadable(f"{repo.slug}: tag {tag} is not in {pin[:7]}'s history")
if relation[0] != distance:
return Reading(req.mode, req.kind, req.stated, describe_form(tag, relation[0], pin),
f"{repo.slug}: {pin[:7]} is {relation[0]} commits after "
f"{tag}, the basis says {distance}", DRIFT,
(("distance", relation[0]),))
return req.reading(describe_form(tag, distance, pin),
f"{repo.slug}: tag {tag} + {distance}",
(("tag", tag), ("distance", distance)))
_OFF_FORGE: dict[str, Callable[[_Request], Reading]] = {
"none": _read_none,
"unverified": _read_unverified,
"package": _read_package,
"alias": _read_alias,
}
_ON_FORGE: dict[str, Callable[[_Request, upstream.Repo, str], Reading]] = {
"file": _read_file,
"tag": _read_tag,
}
def read(
profile: dict, mode: str, basis: dict, cache_dir: str, offline: bool,
profiles: dict | None = None, recompute: bool = False,
@@ -185,87 +303,20 @@ def read(
has to: a recorded tag only proves its own distance, and a tag released
between the two pins would go unseen.
"""
stated = declared(profile, mode)
kind = str(basis.get("kind") or "")
def reading(value: str | None, where: str, updates: tuple = ()) -> Reading:
status = MATCH if value == stated else DRIFT
return Reading(mode, kind, stated, value, where, status, updates)
def unreadable(reason: str) -> Reading:
return Reading(mode, kind, stated, None, reason, UNREADABLE)
req = _Request(profile, mode, basis, kind, declared(profile, mode),
cache_dir, offline, profiles, recompute)
try:
if kind == "none":
if recompute:
# A release tagged since the basis was written gives the
# code a version: the advance has to name it.
repo, pin = _repo_and_pin(profile, basis, mode, cache_dir, offline)
described = upstream.describe(repo, pin, cache_dir, offline)
if described is not None:
return Reading(mode, kind, stated, describe_form(*described, pin),
f"{repo.slug}: tag {described[0]} is now in "
f"{pin[:7]}'s history", DRIFT)
return reading(None, "the code states no version")
if kind == "unverified":
return Reading(mode, kind, stated, None, f"not verified: {basis.get('why')}",
UNCHECKED)
if kind == "package":
artifact = str(basis.get("artifact") or "")
if basis.get("pattern"):
# An artefact named after its version says it in its name:
# advancemame-0.94.0.tar.gz.
found = read_text_version(artifact, str(basis["pattern"]), basis.get("format"))
if found is None:
return unreadable(f"{artifact}: pattern not found")
return reading(found[0], f"named by {artifact}")
return Reading(mode, kind, stated, None, f"read from {artifact}", UNCHECKED)
if kind == "alias":
other = (profiles or {}).get(str(basis.get("of") or ""))
if other is None:
return unreadable(f"alias of {basis.get('of')}: no such profile")
return reading(declared(other, mode) if isinstance(other.get("core_version"), dict)
else declared(other, ""), f"alias of {basis['of']}")
repo, pin = _repo_and_pin(profile, basis, mode, cache_dir, offline)
if kind == "file":
path = str(basis.get("path") or "")
lines = upstream.fetch_file(repo, pin, path, cache_dir, offline)
if lines is None:
return unreadable(f"{repo.slug}@{pin[:7]}:{path}: absent")
found = read_text_version("\n".join(lines), str(basis.get("pattern") or ""),
basis.get("format"))
if found is None:
return unreadable(f"{repo.slug}@{pin[:7]}:{path}: pattern not found")
value, line = found
return reading(value, f"{repo.slug}@{pin[:7]}:{path}:{line}")
if kind == "tag":
if recompute:
described = upstream.describe(repo, pin, cache_dir, offline, basis.get("match"))
if described is None:
return unreadable(f"{repo.slug}@{pin[:7]}: no tag in its history")
tag, distance = described
else:
tag, distance = str(basis.get("tag") or ""), basis.get("distance")
commit = upstream.tag_commit(repo, tag, cache_dir, offline)
if commit is None:
return unreadable(f"{repo.slug}: no tag {tag}")
relation = (0, 0) if commit == pin else _ancestry(
repo, commit, pin, cache_dir, offline)
if relation is None:
return unreadable(f"{repo.slug}: {tag}...{pin[:7]} not comparable")
if relation[1]:
return unreadable(f"{repo.slug}: tag {tag} is not in {pin[:7]}'s history")
if relation[0] != distance:
return Reading(mode, kind, stated, describe_form(tag, relation[0], pin),
f"{repo.slug}: {pin[:7]} is {relation[0]} commits after "
f"{tag}, the basis says {distance}", DRIFT,
(("distance", relation[0]),))
return reading(describe_form(tag, distance, pin),
f"{repo.slug}: tag {tag} + {distance}",
(("tag", tag), ("distance", distance)))
off_forge = _OFF_FORGE.get(kind)
if off_forge is not None:
return off_forge(req)
repo, pin = req.repo_and_pin()
on_forge = _ON_FORGE.get(kind)
if on_forge is not None:
return on_forge(req, repo, pin)
except (upstream.UpstreamError, VersionUnreadable) as exc:
return unreadable(str(exc))
return unreadable(f"unknown kind {kind!r}")
return req.unreadable(str(exc))
return req.unreadable(f"unknown kind {kind!r}")
def check(