chore: merge the tooling scripts quality work

This commit is contained in:
Abdessamad Derraz committed 2026-11-17 08:26:04 +01:00
commit c92c14ef44
27 files changed
+1110 -820

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:
+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
+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)
+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
+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