refactor: move pack library code into packs/

This commit is contained in:
Abdessamad Derraz committed 2026-11-18 13:47:31 +01:00
1 parent 4d4052a8ab
commit 0b532366d0
167 files changed
+14476 -13882

No files matched your search

+2 -1
View File
@@ -84,7 +84,8 @@ def find_missing(config: dict, db: dict) -> list[dict]:
the cores need that no platform lists.
"""
from resolve.nativemode import reads_file_contents
from verify import Status, verify_platform
from packs.verdicts import Status
from packs.coverage import verify_platform
result = verify_platform(config, db)
hashed = reads_file_contents(config.get("verification_mode", "existence"))
+2 -2
View File
@@ -144,7 +144,7 @@ def release_pack_labels(root: Path = REPO_ROOT) -> dict[str, str]:
from resolve.grouping import group_identical_platforms
from model.registry import list_release_pack_platforms
from model.platforms import load_platform_config
from generate_pack import _name_part, _platform_pack_stem
from packs.naming import _name_part, _platform_pack_stem
platforms_dir = str(root / "platforms")
pool = list_release_pack_platforms(platforms_dir)
@@ -176,7 +176,7 @@ def build_archive(name: str, output: Path, root: Path = REPO_ROOT) -> Path:
)
# The packs' member writer: imported here, as it loads the whole
# pack builder, which a caller reading ARCHIVES does not need.
from generate_pack import _add_pack_member
from packs.archive import _add_pack_member
members = archive_members(name, root)
output.parent.mkdir(parents=True, exist_ok=True)
+1 -1
View File
@@ -24,7 +24,7 @@ from model.registry import list_registered_platforms
from model.database import load_database
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from cross_reference import FileConsumers
from packs.crossref import FileConsumers
def _entries(profile: dict, db: dict) -> list[dict]:
+3 -3
View File
@@ -60,7 +60,7 @@ from exporter.originals import (
wanted_sources,
)
import pin_installer
import refresh_data_dirs
from packs import datadirs
from core import upstream
from core.cli import InputMissing, require_directory, suggest_names
from model.targets import apply_target_overrides
@@ -1027,10 +1027,10 @@ def check_coreinfo(
def check_data(offline: bool) -> list[Finding]:
if offline:
return [Finding("data", "_data_dirs.yml", SKIPPED, detail="offline")]
registry = refresh_data_dirs.load_registry(str(REPO_ROOT / "platforms" / "_data_dirs.yml"))
registry = datadirs.load_registry(str(REPO_ROOT / "platforms" / "_data_dirs.yml"))
sink = io.StringIO()
with contextlib.redirect_stdout(sink):
results = refresh_data_dirs.refresh_all(registry, dry_run=True)
results = datadirs.refresh_all(registry, dry_run=True)
findings = []
for key, result in sorted(results.items()):
if result is None:
+61
View File
@@ -0,0 +1,61 @@
"""The project's own clone: git output lines and the project's main line."""
from __future__ import annotations
import re
import subprocess
def _git_lines(*args: str) -> list[str] | None:
"""Output lines of a git command, or None when git refuses it."""
result = subprocess.run(["git", *args], capture_output=True, text=True, check=False)
if result.returncode != 0:
return None
return [line for line in result.stdout.splitlines() if line]
PROJECT_URLS = (
"https://github.com/Abdess/retrobios",
"https://github.com/Abdess/retroarch_system",
)
def _repo_key(url: str) -> str:
"""owner/name of a clone URL, whatever its scheme."""
path = url.strip().rstrip("/").removesuffix(".git")
return "/".join(re.split(r"[/:]", path)[-2:]).casefold()
def _project_main_line() -> str | None:
"""The project's main line, fetched when this clone does not hold it.
A fork's clone has origin alone. Once the commit is pushed to the fork's
main, origin/main is HEAD and the diff against it was empty, so --changed
found nothing and exited 0. A remote added as CONTRIBUTING says and never
fetched did the same: upstream/main did not exist and origin/main won.
None leaves the upstream/ and origin/ lines in charge when the clone has
no remote at all and only its uncommitted files can be read.
"""
remotes = _git_lines("remote") or []
if not remotes:
return None
project = {_repo_key(url) for url in PROJECT_URLS}
source = PROJECT_URLS[0]
for remote in remotes:
urls = _git_lines("remote", "get-url", "--all", remote) or []
if any(_repo_key(url) in project for url in urls):
if _git_lines("rev-parse", "--verify", "--quiet", f"{remote}/main"):
return f"{remote}/main"
source = remote
break
fetched = subprocess.run(
["git", "fetch", "--quiet", "--no-tags", source, "main"],
capture_output=True, text=True, check=False,
)
if fetched.returncode != 0:
raise RuntimeError(
f"this clone does not hold the main of {PROJECT_URLS[0]}, and "
f"fetching its main from {source} failed: {fetched.stderr.strip()}"
)
return "FETCH_HEAD"
+15 -1428
View File
File diff suppressed because it is too large. Load diff
+1 -48
View File
@@ -31,52 +31,10 @@ sys.path.insert(0, os.path.dirname(__file__))
from core.hashing import compute_hashes
from core.cli import require_directory
from core.artifacts import write_text_atomic
from model.nodedup import _in_nodedup_dir
DEFAULT_BIOS_DIR = "bios"
# Directories where deduplication must NOT be applied.
NODEDUP_DIRS = {
"RPG Maker",
"ScummVM",
# A zoneinfo tree is addressed by zone name and its aliases are equal
# files by design: US/Samoa is Pacific/Midway.
"tzdata",
# VICE data is addressed by machine directory: C64, C64DTV and SCPU64
# share one keymap, C64 and CBM-II one palette. With the copies removed
# the name step served the C128 keymap to all of them.
"c64-emu",
# PinMAME reads a sound-only parent (gts80s) as its own archive, equal
# byte for byte to the base set. Folding them into the clone map would
# key gts1.zip twice, once for MAME's set and once for PinMAME's.
"PinMAME",
# BBK dictionary ROMs are addressed by model directory, and the OS ROM
# the A4988 folder needs is the one the gam4980 core is given.
"BBK",
# Engine data trees read by path: one sound or one sprite sits under
# several characters, campaigns or episodes, and each copy is opened
# where it lies.
"C-Dogs SDL",
"Ikemen GO",
"Theme Hospital",
"TheXTech",
# Aleph One opens each scenario's Physics Models and the Splitwolf mod
# tree its sounds and maps by path: Marathon 2 and Infinity share one
# Standard.phyA, lwmp/ repeats 182 files across its levels.
"Bungie",
"splitwolf",
# CatacombGL reads each game's folder by name and compares sizes only:
# the Armageddon and Apocalypse intro shapes SHP1, SHP9 to SHP13 are the
# Abyss shareware bytes under the retail names, and each game opens
# its own copy.
"Softdisk",
# MAME's support trees (hash, plugins) are read by path as a whole, and
# two MAME versions share most of their software lists byte for byte.
"mame",
# The Tyrian 2.1 distribution ships netset.pcx and tyrset.pcx with the
# same bytes, and EmuELEC places both names under ports/opentyrian/.
"opentyrian",
}
def path_priority(path: str) -> tuple:
"""Lower score = better candidate to keep as canonical.
@@ -90,11 +48,6 @@ def path_priority(path: str) -> tuple:
return (is_variant, is_mame, is_arcade, len(parts), path)
def _in_nodedup_dir(path: str) -> bool:
parts = Path(path).parts
return any(nodedup in parts for nodedup in NODEDUP_DIRS)
def _is_mame_dir(path: str) -> bool:
"""Check if a path is in a MAME-specific directory."""
parts = Path(path).parts
+1 -1
View File
@@ -136,7 +136,7 @@ def main() -> None:
if not args.refresh_cache:
import contextlib
from refresh_data_dirs import hold_data_dirs
from packs.datadirs import hold_data_dirs
# Removal candidates are proved against data/: a refresh swapping a
# tree mid-walk listed entries only that tree holds as removable.
+1 -1
View File
@@ -19,7 +19,7 @@ from resolve.archives import contents_members, holds_required_members
from resolve.standalone import platform_layouts, standalone_set
from resolve.cores import resolve_platform_cores
from resolve.reconcile import HASH_FIELDS, _hash_values
from slots import _accepted_by_all, _lists_hashes, find_collisions
from resolve.collisions import _accepted_by_all, _lists_hashes, find_collisions
from resolve.validation import opens_by_name, outside_gap_scope
+31 -5427
View File
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -35,10 +35,10 @@ from model.systems import system_index
import archive_build
import release_record
from siteguides import PACKAGE_COMMAND, install_command
from validate_pr import LARGE_FILE_ISSUE_URL
from resolve.review import LARGE_FILE_ISSUE_URL
from model.largefiles import LARGE_FILES_CACHE, load_registered_paths
import pr_checks
from verify import verify_platform
from packs.coverage import verify_platform
def _installer_words() -> ModuleType:
@@ -989,7 +989,7 @@ def main() -> None:
import contextlib
from model.registry import load_data_dir_registry
from refresh_data_dirs import hold_data_dirs
from packs.datadirs import hold_data_dirs
db = load_database(args.db)
+8 -8
View File
@@ -70,7 +70,7 @@ from resolve.layout import runs_standalone
from siterender import SECTION_LABELS, WIKI_SRC_DIR
from core.artifacts import ArtifactLockBusy, artifact_lock
from core.artifacts import json_text as _json_text
from cross_reference import FileConsumers, entry_target, held_copy
from packs.crossref import FileConsumers, entry_target, held_copy
from resolve.nativemode import check_label, digest_algorithm, reads_file_contents
from generate_readme import (
@@ -123,7 +123,7 @@ import sitebootstrap
import sitehandheld
import sitemeasurements
import sitewanted
from validate_pr import load_platform_hashes, load_profile_hashes
from resolve.review import load_platform_hashes, load_profile_hashes
from sitediagrams import local_images, prepare_page, unresolved_images
from sitewrite import (
_record,
@@ -688,7 +688,7 @@ def _pack_version(pack_name: str, platforms: list[str]) -> str:
Read past the platform part the builder writes, not at the last
underscore: AmberELEC_prerelease-20261019_1835 read as 1835.
"""
from generate_pack import platform_pack_prefix
from packs.naming import platform_pack_prefix
stem = pack_name.removesuffix("_BIOS_Pack.zip")
prefix = platform_pack_prefix(
@@ -1231,7 +1231,7 @@ def build_emulator_gap_report(
"""
from model.systems import _norm_system_id
from model.declarations import merged_platform_declarations
from cross_reference import cross_reference as run_cross_reference
from packs.crossref import cross_reference as run_cross_reference
# Enriched with alias resolution, with each declaration's size and slot:
# a name alone settled DOSBox's 32 KiB SC-55 ROM1.BIN on Galaksija's.
@@ -9975,7 +9975,7 @@ def _availability_check(
missing while the gap report called it held would describe a
different collection on two pages of the same site.
"""
from cross_reference import entry_source
from packs.crossref import entry_source
by_name = db.get("indexes", {}).get("by_name", {})
by_name_lower = {k.lower(): k for k in by_name}
@@ -10006,7 +10006,7 @@ def _availability_check(
def _emulator_slots(files: list[dict]) -> list[list[dict]]:
"""The entries of each slot, as verify --emulator and the gaps page
count them, leaving out the slots the app ships."""
from cross_reference import slot_key
from packs.crossref import slot_key
slots: dict[tuple, list[dict]] = {}
for f in files:
@@ -13044,7 +13044,7 @@ def main() -> None:
from model.registry import load_data_dir_registry
from core.artifacts import repository_output_lock
from refresh_data_dirs import hold_data_dirs
from packs.datadirs import hold_data_dirs
# The coverage pages resolve against data/, held while they are read.
# Whatever --docs-dir says, website/src/data and wiki/ are written.
@@ -13131,7 +13131,7 @@ class _SiteRun:
def _load_site_run(args: argparse.Namespace, db: dict, docs: Path, public: Path) -> _SiteRun:
"""The registry, the coverage of every platform and the profiles."""
from model.registry import load_data_dir_registry
from cross_reference import _build_supplemental_index
from packs.crossref import _build_supplemental_index
registry = _load_registry(args.platforms_dir)
+54
View File
@@ -0,0 +1,54 @@
"""Trees of bios/ addressed by path, which deduplication leaves alone."""
from __future__ import annotations
from pathlib import Path
# Directories where deduplication must NOT be applied.
NODEDUP_DIRS = {
"RPG Maker",
"ScummVM",
# A zoneinfo tree is addressed by zone name and its aliases are equal
# files by design: US/Samoa is Pacific/Midway.
"tzdata",
# VICE data is addressed by machine directory: C64, C64DTV and SCPU64
# share one keymap, C64 and CBM-II one palette. With the copies removed
# the name step served the C128 keymap to all of them.
"c64-emu",
# PinMAME reads a sound-only parent (gts80s) as its own archive, equal
# byte for byte to the base set. Folding them into the clone map would
# key gts1.zip twice, once for MAME's set and once for PinMAME's.
"PinMAME",
# BBK dictionary ROMs are addressed by model directory, and the OS ROM
# the A4988 folder needs is the one the gam4980 core is given.
"BBK",
# Engine data trees read by path: one sound or one sprite sits under
# several characters, campaigns or episodes, and each copy is opened
# where it lies.
"C-Dogs SDL",
"Ikemen GO",
"Theme Hospital",
"TheXTech",
# Aleph One opens each scenario's Physics Models and the Splitwolf mod
# tree its sounds and maps by path: Marathon 2 and Infinity share one
# Standard.phyA, lwmp/ repeats 182 files across its levels.
"Bungie",
"splitwolf",
# CatacombGL reads each game's folder by name and compares sizes only:
# the Armageddon and Apocalypse intro shapes SHP1, SHP9 to SHP13 are the
# Abyss shareware bytes under the retail names, and each game opens
# its own copy.
"Softdisk",
# MAME's support trees (hash, plugins) are read by path as a whole, and
# two MAME versions share most of their software lists byte for byte.
"mame",
# The Tyrian 2.1 distribution ships netset.pcx and tyrset.pcx with the
# same bytes, and EmuELEC places both names under ports/opentyrian/.
"opentyrian",
}
def _in_nodedup_dir(path: str) -> bool:
parts = Path(path).parts
return any(nodedup in parts for nodedup in NODEDUP_DIRS)
+1
View File
@@ -0,0 +1 @@
"""Pack building and verification: selection, archives, manifests, coverage, cross-reference."""
+260
View File
@@ -0,0 +1,260 @@
"""Writing pack archives: members, generated files, copied archives, data trees."""
from __future__ import annotations
import contextlib
import os
import shutil
import tempfile
import zipfile
from collections.abc import Iterator, Mapping
from dataclasses import dataclass, field
from pathlib import Path
from core.artifacts import set_plain_mode
from core.deterministic_zip import _FIXED_DATE_TIME
from core.hashing import compute_hashes
from core.paths import sanitize_pack_path
from packs.paths import _has_path_conflict, _register_path, placement_block
def _reject_unknown(function: str, options: Mapping[str, object], known: frozenset[str]) -> None:
"""Refuse a keyword the options do not declare, as a named parameter would."""
for key in options:
if key not in known:
raise TypeError(f"{function}() got an unexpected keyword argument '{key}'")
# Formats that are already compressed: deflating them again took 28 s of the
# RetroArch build for 2.1 GB of members and saved 9.6 MB (0.45 %), 16 GB and
# about 72 MB across all packs. Measured per extension on the 2026-10-20
# packs; .pk3 (3 %), .jpg (6 %), .avi (44 %) and .jar (60 %) still shrink
# and stay deflated. Chosen by name alone, so a pack stays a function of its
# inputs.
_STORED_EXTENSIONS = frozenset({".7z", ".chd", ".ogg", ".pk4", ".png", ".zip"})
def _member_compression(arcname: str) -> int:
"""ZIP_STORED for a member whose format is already compressed."""
if os.path.splitext(arcname)[1].lower() in _STORED_EXTENSIONS:
return zipfile.ZIP_STORED
return zipfile.ZIP_DEFLATED
class PackRecord:
"""A pack build kept in memory: the paths it writes, no archive.
``members`` is every path written, ``files`` the ones the build counts as
the profile's files (archives and loose files, not trees or notes), and
``trees`` the members a platform pack takes from its data directories.
The pipeline builds every emulator pack and every narrowed platform pack
this way and compares them with what verify credits, without reading or
compressing a byte.
"""
def __init__(self) -> None:
self.members: list[str] = []
self.files: list[str] = []
self.trees: list[str] = []
# The collection file each copied member comes from: a split part
# writes a file only where the full pack writes the same bytes.
self.sources: dict[str, str] = {}
def _add_pack_member(
zf: zipfile.ZipFile | PackRecord, source_path: str, arcname: str
) -> None:
"""Add a file to the pack with metadata that does not depend on the build.
ZipFile.write copies the source file's mtime into the member. For a file
this build just produced in tmp/ that is the wall clock, and for a file
from the collection it is whenever the clone was checked out, so a pack
rebuilt from identical inputs differed from the last one although every
byte of content matched: 348 members of the Recalbox pack moved between
two consecutive builds. The content is streamed rather than read whole,
because some members are firmware images of several hundred megabytes.
"""
if isinstance(zf, PackRecord):
zf.members.append(arcname)
zf.sources[arcname] = source_path
return
info = zipfile.ZipInfo(filename=arcname, date_time=_FIXED_DATE_TIME)
info.compress_type = _member_compression(arcname)
# The executable bit is the one permission worth carrying: the RetroDECK
# pack ships the two Voxatron engine binaries, and a user who extracts
# them at 644 cannot run them. Git records the bit, so reading it from
# the source keeps the pack the same from any clone. Nothing else about
# the source's mode reaches the archive.
stat_result = os.stat(source_path)
mode = 0o755 if stat_result.st_mode & 0o111 else 0o644
info.external_attr = (0o100000 | mode) << 16
size = stat_result.st_size
info.file_size = size
with open(source_path, "rb") as source, zf.open(
info, "w", force_zip64=size >= 1 << 31
) as target:
shutil.copyfileobj(source, target, 1024 * 1024)
def _write_generated_member(
zf: zipfile.ZipFile | PackRecord, arcname: str, text: str
) -> None:
"""Write a pack member the builder composes rather than copies.
READMEs, instruction notes and the manifest are produced at build time,
so writestr would stamp them with the wall clock and give the same pack
a different hash on every run. Pinning them to the epoch the archive
rebuilder already uses makes a pack a function of its inputs alone.
"""
if isinstance(zf, PackRecord):
zf.members.append(arcname)
return
info = zipfile.ZipInfo(filename=arcname, date_time=_FIXED_DATE_TIME)
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = 0o100644 << 16
zf.writestr(info, text)
@contextlib.contextmanager
def _writing_pack(zip_path: str) -> Iterator[zipfile.ZipFile]:
"""A pack written beside its final name, swapped in once complete.
Opened on the final name, a rebuild truncated the previous pack at once,
and a build that raised half way still wrote a central directory: a
readable ZIP holding part of the files, which the run then checked and
summed as the pack.
"""
directory = os.path.dirname(zip_path) or "."
fd, scratch = tempfile.mkstemp(
prefix=f".{os.path.basename(zip_path)}.", suffix=".partial", dir=directory
)
os.close(fd)
try:
with zipfile.ZipFile(scratch, "w", zipfile.ZIP_DEFLATED) as zf:
yield zf
set_plain_mode(scratch)
os.replace(scratch, zip_path)
except BaseException:
Path(scratch).unlink(missing_ok=True)
raise
# What the builder writes into a platform pack beside the files it carries.
PACK_DOCUMENTS = ("README.txt", "manifest.json")
@dataclass
class _Placed:
"""The destinations a build has taken, and the folders they open.
``fold`` is whether a case twin of a taken path counts as taken.
"""
fold: bool
destinations: set[str] = field(default_factory=set)
lower: set[str] = field(default_factory=set) # only used when fold=True
parents: set[str] = field(default_factory=set) # parent dirs of added files (path conflict detection)
def take(self, dest: str) -> None:
self.destinations.add(dest)
_register_path(dest, self.destinations, self.parents)
if self.fold:
self.lower.add(dest.lower())
def holds(self, dest: str) -> bool:
return dest in self.destinations or (self.fold and dest.lower() in self.lower)
def conflicts(self, dest: str) -> bool:
return _has_path_conflict(dest, self.destinations, self.parents)
def block(self, dest: str) -> str | None:
return placement_block(dest, self.destinations, self.lower, self.parents, self.fold)
def _extract_zip_to_archive(
source_zip: str,
dest_prefix: str,
target_zf: zipfile.ZipFile | PackRecord,
) -> None:
"""Extract contents of a source ZIP into target ZIP under dest_prefix."""
with zipfile.ZipFile(source_zip, "r") as src:
if isinstance(target_zf, PackRecord):
target_zf.members.extend(
f"{dest_prefix}/{name}" if dest_prefix else name
for name in map(sanitize_pack_path, src.namelist())
if name and not name.endswith("/")
)
target_zf.sources[dest_prefix] = source_zip
return
for info in src.infolist():
if info.is_dir():
continue
clean_name = sanitize_pack_path(info.filename)
if not clean_name:
continue
data = src.read(info.filename)
target_path = f"{dest_prefix}/{clean_name}" if dest_prefix else clean_name
member = zipfile.ZipInfo(
filename=target_path, date_time=_FIXED_DATE_TIME
)
member.compress_type = _member_compression(target_path)
member.external_attr = 0o100644 << 16
target_zf.writestr(member, data)
def _add_zip_to_pack(
source_zip: str,
dest_path: str,
target_zf: zipfile.ZipFile | PackRecord,
file_entry: dict | None = None,
) -> None:
"""Write a source ZIP into the pack, byte for byte.
The pack carries the collection's own bytes, so every member hashes to
the sha1 the install list and the site publish. Rebuilt ZIPs gave about
1,500 archives another hash than the list: an extracted pack then failed
`install.py --check`. The collection's bytes are fixed in git, which keeps
the pack reproducible without a rebuild.
"""
if isinstance(target_zf, PackRecord):
target_zf.members.append(dest_path)
target_zf.sources[dest_path] = source_zip
return
_check_zip_members(source_zip)
_add_pack_member(target_zf, source_zip, dest_path)
def _check_zip_members(source_zip: str) -> None:
"""Refuse an archive whose members fail their own CRC.
Copied as-is "for verify to flag", a damaged archive went into the pack
and nothing flagged it.
"""
try:
with zipfile.ZipFile(source_zip) as zf:
bad = zf.testzip()
except zipfile.BadZipFile as exc:
raise DamagedArchiveError(
f"{source_zip}: {exc}; restore it from git or the release before packing"
) from exc
if bad is not None:
raise DamagedArchiveError(
f"{source_zip}: member {bad} fails its CRC; "
"restore it from git or the release before packing"
)
class DamagedArchiveError(OSError):
"""An archive of the collection whose members fail their own CRC."""
def _same_bytes(path: str, other: str | None) -> bool:
if not other:
return False
if os.path.realpath(path) == os.path.realpath(other):
return True
return compute_hashes(path)["sha1"] == compute_hashes(other)["sha1"]
# Systems whose default filesystems fold case (NTFS, APFS, HFS+).
CASE_FOLDING_OS = frozenset({"windows", "darwin"})
+189
View File
@@ -0,0 +1,189 @@
"""A platform pack cut into one pack per system or per manufacturer."""
from __future__ import annotations
import contextlib
import io
import os
from typing import TYPE_CHECKING
from model.platforms import load_platform_config
from model.profiles import load_emulator_profiles
from packs.archive import PackRecord, _reject_unknown
from packs.emulatorpack import _system_display_name
from packs.extras import _collect_emulator_extras, extras_for_systems as _extras_for_systems
from packs.naming import _name_part, _narrowings, _platform_pack_stem
from packs.platformpack import PackNarrowing, _PartScope, _report_left_out, generate_pack
from resolve.cores import platform_scope_systems
from resolve.gamedata import without_game_data
if TYPE_CHECKING:
from typing_extensions import Unpack
def _group_systems_by_manufacturer(
systems: dict[str, dict],
db: dict,
bios_dir: str,
) -> dict[str, list[str]]:
"""Group system IDs by manufacturer for --split --group-by manufacturer."""
from model.systems import derive_manufacturer
groups: dict[str, list[str]] = {}
for sid, sys_data in systems.items():
mfr = derive_manufacturer(sid, sys_data)
groups.setdefault(mfr, []).append(sid)
return groups
class SplitOptions(PackNarrowing, total=False):
"""The keyword options of generate_split_packs."""
records: dict[str, PackRecord] | None
def _split_extras(config: dict, db: dict, narrowing: PackNarrowing) -> list[dict]:
"""The core extras of every part, collected once (expensive: scans 260+
emulator profiles), then distributed per group by system overlap."""
emu_profiles = narrowing["emu_profiles"] or {}
source = narrowing["source"]
target_cores = narrowing["target_cores"]
base_dest = config.get("base_destination", "")
# Each part cuts the platform's own entries from the full profiles. The
# extras are collected once here, already without the cores' game data.
cut = (
without_game_data(config, emu_profiles, narrowing["data_registry"], target_cores)
if narrowing["no_game_data"] else None
)
if source == "platform":
all_extras = []
elif emu_profiles:
all_extras = _collect_emulator_extras(
cut.config if cut else config, narrowing["emulators_dir"], db,
set(), base_dest, cut.profiles if cut else emu_profiles,
target_cores=target_cores, include_all=(source == "truth"),
)
else:
all_extras = []
if cut is not None and source != "platform":
_report_left_out(cut, systems=set(), cores=True)
return all_extras
def generate_split_packs(
platform_name: str,
platforms_dir: str,
db: dict,
bios_dir: str,
output_dir: str,
group_by: str = "system",
**options: Unpack[SplitOptions],
) -> list[str]:
"""Generate split packs (one ZIP per system or manufacturer).
The parts add up to the full pack: each is built against the full pack's
own placement (``within``). ``records`` builds the parts in memory, keyed
by part name, with no archive written.
"""
_reject_unknown("generate_split_packs", options, SplitOptions.__optional_keys__)
config = load_platform_config(platform_name, platforms_dir)
records = options.get("records")
narrowing: PackNarrowing = {
"emulators_dir": options.get("emulators_dir", "emulators"),
"zip_contents": options.get("zip_contents"),
"data_registry": options.get("data_registry"),
"emu_profiles": options.get("emu_profiles"),
"target_cores": options.get("target_cores"),
"required_only": options.get("required_only", False),
"source": options.get("source", "full"),
"regions": options.get("regions"),
"target_name": options.get("target_name"),
"one_per_slot": options.get("one_per_slot", False),
"offline": options.get("offline"),
"no_game_data": options.get("no_game_data", False),
}
# The split directory carries the same tags as the packs inside it, or two
# differently narrowed runs write into one another.
split_tags = "".join(
tag
for tag, _label in _narrowings(
narrowing["source"], narrowing["regions"], narrowing["target_name"],
narrowing["one_per_slot"], narrowing["required_only"],
no_game_data=narrowing["no_game_data"],
)
)
# Two groupings write different files. Without the tag they accumulate in
# one directory under one SHA256SUMS.txt.
group_tag = "" if group_by == "system" else f"_By{group_by.title()}"
# The parts carry the version, so the directory does too: a rescrape that
# moves the version would otherwise leave the old parts beside the new
# under one SHA256SUMS.txt.
# Named by the stem the full pack reads: assembled here by hand, a '/' in
# a version nested the directory where the check never looked for it.
part_prefix = (
f"{_platform_pack_stem([platform_name], platform_name, platforms_dir)}{split_tags}"
)
split_dir = os.path.join(output_dir, f"{part_prefix}{group_tag}_Split")
if records is None:
os.makedirs(split_dir, exist_ok=True)
emu_profiles = narrowing["emu_profiles"]
if emu_profiles is None:
emu_profiles = load_emulator_profiles(narrowing["emulators_dir"])
narrowing["emu_profiles"] = emu_profiles
full = PackRecord()
with contextlib.redirect_stdout(io.StringIO()):
generate_pack(
platform_name, platforms_dir, db, bios_dir, split_dir,
record=full, **narrowing,
)
def part(pack_name: str, scope: _PartScope) -> str | None:
record = PackRecord() if records is not None else None
zip_path = generate_pack(
platform_name, platforms_dir, db, bios_dir, split_dir,
pack_name=pack_name, record=record, within=full.sources,
**scope, **narrowing,
)
if records is not None and record is not None and zip_path:
records[pack_name] = record
return zip_path
# The systems a core of the target runs: a part per declared system sent
# each one the target drops to a refusal naming it as unknown.
systems = platform_scope_systems(config, emu_profiles, narrowing["target_cores"])
if group_by == "manufacturer":
groups = _group_systems_by_manufacturer(systems, db, bios_dir)
else:
groups = {_system_display_name(sid): [sid] for sid in systems}
all_extras = _split_extras(config, db, narrowing)
results = []
for group_name, group_system_ids in sorted(groups.items()):
group_extras = _extras_for_systems(all_extras, group_system_ids)
zip_path = part(
f"{part_prefix}_{_name_part(group_name, '_')}_BIOS_Pack.zip",
{"system_filter": group_system_ids, "precomputed_extras": group_extras},
)
if zip_path:
results.append(zip_path)
# Extras whose system the platform does not declare, or that name none,
# belong to no group: they go in a part of their own, or the parts would
# not add up to the full pack (4507 of RetroArch's 5430 were left out).
distributed = {
id(fe)
for fe in _extras_for_systems(
all_extras, [s for ids in groups.values() for s in ids]
)
}
undistributed = [fe for fe in all_extras if id(fe) not in distributed]
if undistributed:
zip_path = part(
f"{part_prefix}_Other_Cores_BIOS_Pack.zip",
{"precomputed_extras": undistributed, "extras_only": True},
)
if zip_path:
results.append(zip_path)
return results
+952
View File
@@ -0,0 +1,952 @@
"""A platform's coverage: each declaration resolved and judged as its frontend would."""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, TypedDict
from core.paths import sanitize_pack_path
from core.ziptools import build_zip_contents_index
from model.alternatives import core_file_spares
from model.declarations import OUTER_ROOTS, platform_declarations
from model.profiles import load_emulator_profiles
from model.systems import select_systems
from packs import slots
from packs.crossref import launcher_reads_not_held
from packs.gaps import find_exclusion_notes, find_undeclared_files
from packs.verdicts import (
DEFAULT_BIOS_DIR,
DEFAULT_EMULATORS_DIR,
RELEASE_ASSET_PENDING,
Severity,
Status,
_SEVERITY_ORDER,
_STATUS_ORDER,
_storage_verdict,
compute_severity,
verify_entry_existence,
verify_entry_md5,
verify_entry_sha1,
)
from resolve.categories import BIOS, EntryCategories
from resolve.cores import platform_scope_systems, resolve_platform_cores
from resolve.launchers import launcher_unproven
from resolve.nativemode import digest_algorithm, normalize as normalize_mode, reads_file_contents
from resolve.validation import (
_build_validation_index,
agnostic_substitute,
baseline_verdict,
build_ground_truth,
destination_owners,
validated_choice,
)
if TYPE_CHECKING:
from packs.extras import ExtraResolver
from typing_extensions import Unpack
_UNPLACED_REASONS = {
"outside_bios_folder": "read in a folder the platform keeps outside the BIOS tree",
"no_roms_directory": "read below a roms folder the platform's registry does not name",
"no_emulators_directory": "read in an emulator folder the platform's registry does not describe",
"no_configs_directory": "read below a configs folder the platform's file does not record",
"no_platform_slug": "no platform slug for its system",
"below_platform_folder": "below the folder the platform lists",
"no_save_directory": "read below a save directory the platform keeps in no fixed place",
"no_core_folder": "read below the save directory and the profile names no library_name",
"no_save_system": "read below a save folder per system and no system runs the core there",
}
def _mark_unplaced(config: dict, undeclared: list[dict], profiles: dict) -> None:
"""What the builder cannot place is not in the pack, held or not."""
from packs.extras import unplaceable_extras
unplaced = unplaceable_extras(config, undeclared, profiles)
for u in undeclared:
if u.get("bundled"):
# Installed with the emulator, so already on the user's machine:
# the pack leaves it out, held or not.
u["in_pack"] = False
u["omitted"] = "installed with its emulator"
continue
reason = unplaced.get(
(u.get("emulator", ""), u.get("name", ""), u.get("path") or "")
)
if not reason and u.get("root") in OUTER_ROOTS:
# The pack is extracted into the BIOS folder: the installer
# writes this file into the roms or emulator folder, the pack
# cannot.
u["in_pack"] = False
u["omitted"] = f"read below the {u['root']} folder, which only the installer reaches"
continue
if reason:
u["in_pack"] = False
u["omitted"] = _UNPLACED_REASONS[reason]
_HIDDEN_REASONS = {
"case_twin": "a packed file of the same name in another case takes its place",
"path_conflict": "a packed file occupies its directory",
}
@dataclass(frozen=True)
class _BuilderPass:
"""The arguments the builder's own pass over the core files is run with."""
emulators_dir: str
db: dict
emu_profiles: dict | None
target_cores: set[str] | None
region_drops: set[str] | None
report: list[dict] | None
resolver: ExtraResolver | None
placed_kind: dict[str, str] | None
system_ids: list[str] | None
required_only: bool
def _mark_hidden(
config: dict,
undeclared: list[dict],
shipped: dict[str, str | None],
builder: _BuilderPass,
) -> set[str]:
"""What the builder holds but cannot place beside the files it packed.
Returns the full destinations the builder fills with a core's file.
``builder.report`` is the gap report the caller already computed with the
builder's arguments. Without it the builder's pass computes its own.
"""
from packs.extras import hidden_extras
placed: set[str] = set()
hidden = hidden_extras(
config, builder.emulators_dir, builder.db,
builder.emu_profiles if builder.emu_profiles is not None
else load_emulator_profiles(builder.emulators_dir),
shipped, builder.target_cores, builder.region_drops, placed,
report=builder.report, resolver=builder.resolver, placed_kind=builder.placed_kind,
system_ids=builder.system_ids, required_only=builder.required_only,
)
for u in undeclared:
reason = hidden.get(
(u.get("emulator", ""), u.get("name", ""), u.get("path") or "")
)
if reason and u.get("in_repo") and u.get("in_pack", True):
u["in_pack"] = False
u["omitted"] = _HIDDEN_REASONS[reason]
return placed
def _builder_placement(
packed_order: list[tuple[str, str, str | None]], case_insensitive: bool,
) -> tuple[dict[str, str], dict[str, str | None]]:
"""The platform files the builder writes, and every path it keeps.
The builder walks the systems in name order and skips a path that a
written file blocks as a directory, or the reverse: RetroArch declares
SGB1.sfc and SGB1.sfc/program.rom, and only the first is in the pack.
An entry without a destination (EmuDeck's system:md5 whitelist) is
judged but takes no path. Returns (path -> local copy written there,
path -> copy or None for each slot kept, a user_provided or external one
included).
"""
from packs.paths import _has_path_conflict, _register_path
shipped: dict[str, str] = {}
occupied: dict[str, str | None] = {}
seen: set[str] = set()
folded: set[str] = set()
parents: set[str] = set()
for _sys_id, full, local in sorted(packed_order, key=lambda item: item[0]):
# EmuDeck's system:md5 entries name no file: the builder writes none.
if not full or full.endswith("/"):
continue
if (
full in occupied
or (case_insensitive and full.lower() in folded)
or _has_path_conflict(full, seen, parents)
):
continue
_register_path(full, seen, parents)
folded.add(full.lower())
occupied[full] = local
if local is not None:
shipped[full] = local
return shipped, occupied
def _dest_key(file_entry: dict, sys_id: str) -> str:
"""The path a declaration occupies, as the builder keys its pack."""
dest = sanitize_pack_path(file_entry.get("destination", file_entry.get("name", "")))
return dest or f"{sys_id}/{file_entry.get('name', '')}"
def _twin_index(
verify_systems: dict, db: dict, base_dest: str, zip_contents: dict,
) -> tuple[dict[str, int], dict[int, tuple[str, dict]]]:
"""Which declaration the pack ships at each destination, and every declaration by id."""
# From the module that defines the rule, not the builder's CLI: importing
# generate_pack made every verify depend on its argparse and manifest code.
from resolve.packfiles import preferred_entries as _preferred_entries
preferred_entries = _preferred_entries(
verify_systems, db, DEFAULT_BIOS_DIR, base_dest, False,
zip_contents, True,
)
winners = {
id(fe): (sid, fe)
for sid, system in verify_systems.items()
for fe in system.get("files", [])
}
return preferred_entries, winners
@dataclass(frozen=True)
class _DeclarationResolver:
"""How a platform run resolves its declarations, as the builder does."""
db: dict
zip_contents: dict
data_dir_registry: dict | None
slot_overrides: dict[str, str]
mode: str
platform_profiles: dict
# Which declaration the pack ships at each destination, and every
# declaration by id (_twin_index).
preferred_entries: dict[str, int]
winners: dict[int, tuple[str, dict]]
base_dest: str
def _resolve_declaration(
file_entry: dict, sys_id: str, resolver: _DeclarationResolver,
) -> tuple[str | None, str, str | None]:
"""Resolve a declaration to the file the pack ships at its destination.
When another declaration holds the destination, that one's file is
returned and the evidence reset: the winner's hash match is not this
declaration's, which is hashed against the shipped file.
"""
base_dest = resolver.base_dest
bare = sanitize_pack_path(file_entry.get("destination", file_entry.get("name", "")))
preferred = resolver.preferred_entries.get(f"{base_dest}/{bare}" if base_dest else bare)
held_by, winner = (None, file_entry)
if preferred is not None and preferred != id(file_entry):
held_by, winner = resolver.winners[preferred]
local_path, resolve_status = _resolve_for_platform(
winner, held_by or sys_id, resolver.db, resolver.zip_contents,
resolver.data_dir_registry, resolver.slot_overrides, resolver.mode,
resolver.platform_profiles,
)
return local_path, "" if held_by else resolve_status, held_by
def _twin_unmet(
result: dict,
held_by: str | None,
file_entry: dict | None = None,
sys_id: str = "",
destination: str = "",
) -> bool:
"""Mark a declaration unmet at a path another declaration holds.
The path is answered by the winner's file, which the pack counts once.
This declaration's failure is reported, never folded into the
destination's status. The message names the path, both systems and
what this declaration expects: "is not met at the path coco holds"
named neither the path nor the file wanted there.
"""
if held_by is None or result["status"] == Status.OK:
return False
entry = file_entry or {}
expects = next(
(f" ({h} {str(entry[h]).split(',')[0]})"
for h in ("sha1", "md5", "crc32") if entry.get(h)),
"",
)
owner = sys_id or "this"
result["discrepancy"] = (
f"{destination or result.get('name', '')} is declared for {owner}"
f" and for {held_by}. The {owner} declaration{expects} is not met at"
f" the path, which holds the {held_by} file"
)
# Read by reports that list entries: the destination itself is held, and
# a count by destination does not include this one.
result["settled_by"] = held_by
return True
def _resolve_for_platform(
file_entry: dict,
sys_id: str,
db: dict,
zip_contents: dict,
data_dir_registry: dict | None,
slot_overrides: dict[str, str],
mode: str,
platform_profiles: dict,
) -> tuple[str | None, str]:
"""Resolve one platform entry the way the pack builder does.
The builder's own resolution (packresolve.resolve_declaration), read from
disk and the large-file cache: verify never downloads. A frontend that
never reads the bytes takes the filename-free core's own image.
"""
from resolve.packfiles import pending_release_asset, resolve_declaration, run_is_offline
override = slot_overrides.get(
sanitize_pack_path(file_entry.get("destination", file_entry.get("name", "")))
)
local_path, status = resolve_declaration(
file_entry, db, DEFAULT_BIOS_DIR, zip_contents, data_dir_registry,
override, offline=True,
)
if status in ("not_found", "hash_mismatch") and not run_is_offline():
# Not in the cache, and the release holds a copy that answers the
# declaration: an online build fetches and packs it (resolve_file).
asset = pending_release_asset(file_entry, db)
if asset:
return asset, RELEASE_ASSET_PENDING
if status == "not_found" and not reads_file_contents(mode):
found = agnostic_substitute(file_entry, sys_id, db, platform_profiles)
if found:
return found[0], "agnostic_fallback"
return local_path, status
@dataclass(frozen=True)
class _PlatformRun:
"""The inputs of one verify_platform run, read by each of its stages."""
config: dict
db: dict
emulators_dir: str
emu_profiles: dict | None
profiles: dict
target_cores: set[str] | None
data_dir_registry: dict | None
zip_contents: dict
system_filter: list[str] | None
required_only: bool
mode: str
base_dest: str
def full(self, destination: str) -> str:
return f"{self.base_dest}/{destination}" if self.base_dest else destination
@dataclass
class _PlatformTally:
"""Each declaration's verdict, and the verdicts aggregated by destination."""
run: _PlatformRun
platform: str
resolver: _DeclarationResolver
region_drops: set[str]
validation_index: dict
validation_owners: dict[str, list[tuple[str, str]]]
hle_index: dict[str, bool]
categories: EntryCategories
details: list[dict] = field(default_factory=list)
file_status: dict[str, str] = field(default_factory=dict)
file_required: dict[str, bool] = field(default_factory=dict)
file_severity: dict[str, str] = field(default_factory=dict)
# What each entry is: firmware, a game's data, or a name no core the
# platform runs opens. Only firmware gaps carry a severity.
file_category: dict[str, str] = field(default_factory=dict)
# (system, full destination, local copy) of each declaration the builder
# writes, and None for one whose slot it keeps without a file from the
# collection (user_provided, external). Placed below in the builder's order.
packed_order: list[tuple[str, str, str | None]] = field(default_factory=list)
shipped_keys: set[str] = field(default_factory=set)
results_at: dict[str, list[dict]] = field(default_factory=dict)
def judge(self, sys_id: str, file_entry: dict) -> None:
"""Verify one declaration and add it to its destination's tally."""
destination = sanitize_pack_path(
file_entry.get("destination", file_entry.get("name", ""))
)
if self.region_drops and destination in self.region_drops:
return
local_path, resolve_status, held_by = _resolve_declaration(
file_entry, sys_id, self.resolver,
)
result, local_path = self._verdict(
file_entry, sys_id, local_path, resolve_status, destination,
)
result["system"] = sys_id
result["hle_fallback"] = self.hle_index.get(file_entry.get("name", ""), False)
result["ground_truth"] = build_ground_truth(
file_entry.get("name", ""),
self.validation_index,
)
self.details.append(result)
config = self.run.config
mode = self.run.mode
# Occupied only where the builder ships the declaration: a hash
# the frontend refuses is left out, and the destination stays free
# for a core's file the pack does carry.
if (
local_path
and result["status"] != Status.MISSING
and baseline_verdict(
file_entry, local_path, resolve_status, mode, config.get("hash_rule", "")
)[1] is None
):
self.packed_order.append((sys_id, self.run.full(destination), local_path))
self.shipped_keys.add(_dest_key(file_entry, sys_id))
if _twin_unmet(
result, held_by, file_entry, sys_id, self.run.full(destination),
):
return
self._aggregate(sys_id, file_entry, destination, result)
def _verdict(
self, file_entry: dict, sys_id: str, local_path: str | None,
resolve_status: str, destination: str,
) -> tuple[dict, str | None]:
"""The declaration's result, and the local copy the pack writes for it."""
config = self.run.config
mode = self.run.mode
stored = _storage_verdict(file_entry, emulator_pack=False)
if resolve_status == RELEASE_ASSET_PENDING:
# Counted as an online build counts it, which fetches the
# asset. Under --offline the builder cannot, and neither
# does this report (_resolve_for_platform).
result = {
"name": file_entry.get("name", ""),
"required": file_entry.get("required", True),
"status": Status.OK,
"release_asset": local_path,
"reason": "release asset, fetched when the pack is built",
}
# Written at its path like any held file: keyed to None, it
# stayed out of pack_destinations and step 5 read the pack's
# copy as a file only the pack holds.
self.packed_order.append((sys_id, self.run.full(destination), local_path))
self.shipped_keys.add(_dest_key(file_entry, sys_id))
return result, None
if stored is not None:
# The builder keeps the slot: instructions for a user_provided
# file, the download for an external one, whether it arrives
# or not. No core file goes there.
self.packed_order.append((sys_id, self.run.full(destination), None))
return stored, None
if not reads_file_contents(mode):
return verify_entry_existence(
file_entry,
local_path,
self.validation_index,
self.run.db,
destination,
self.validation_owners,
resolve_status,
config.get("platform", ""),
), local_path
if digest_algorithm(mode) == "sha1":
return verify_entry_sha1(file_entry, local_path), local_path
result = verify_entry_md5(
file_entry, local_path, resolve_status, config.get("hash_rule", "")
)
# Emulator-level validation: informational for platform packs.
# Platform verification (MD5) is the authority. Emulator
# mismatches are reported as discrepancies, not failures.
if result["status"] == Status.OK:
_chosen, disagreement = validated_choice(
file_entry, local_path, self.run.db, self.validation_index, "bios",
digest_algorithm(mode), destination, self.validation_owners,
)
if disagreement:
result["discrepancy"] = f"{self.platform} says OK but {disagreement}"
return result, local_path
def _aggregate(
self, sys_id: str, file_entry: dict, destination: str, result: dict,
) -> None:
# Aggregate by destination, keyed as the builder keys its pack.
# A declaration that finds nothing leaves the path to one that
# holds a file: the builder packs that file there, whatever the
# order the two are read in.
dest = _dest_key(file_entry, sys_id)
self.results_at.setdefault(dest, []).append(result)
required = file_entry.get("required", True)
cur = result["status"]
prev = self.file_status.get(dest)
hle = self.hle_index.get(file_entry.get("name", ""), False)
sev = compute_severity(cur, required, self.run.mode, hle)
explained = self.categories.explain(file_entry, destination, sys_id)
category = explained.pop("category")
result["category"] = category
result["category_evidence"] = explained
if cur != Status.MISSING:
# A held entry is firmware for the counts: its category only
# documents it.
category = BIOS
if self.file_category.get(dest, category) == BIOS:
category = BIOS
self.file_category[dest] = category
if prev is not None and (cur == Status.MISSING) != (prev == Status.MISSING):
if cur == Status.MISSING:
return
del self.file_status[dest], self.file_severity[dest]
prev = None
if prev is None or _STATUS_ORDER.get(cur, 0) > _STATUS_ORDER.get(prev, 0):
self.file_status[dest] = cur
self.file_required[dest] = required
prev_sev = self.file_severity.get(dest)
if prev_sev is None or _SEVERITY_ORDER.get(sev, 0) > _SEVERITY_ORDER.get(
prev_sev, 0
):
self.file_severity[dest] = sev
def settle_groups(self) -> None:
"""RetroBat's group: one file of it held is enough, and the others are
reported OPTIONAL (batocera-systems/Program.cs). None held, each stays
required."""
members: dict[tuple[str, str], list[str]] = {}
for sys_id, system in self.run.config.get("systems", {}).items():
for file_entry in system.get("files", []):
if file_entry.get("group"):
dest = _dest_key(file_entry, sys_id)
if dest in self.file_status:
members.setdefault((sys_id, file_entry["group"]), []).append(dest)
for dests in members.values():
if not any(self.file_status[d] == Status.OK for d in dests):
continue
for dest in dests:
if self.file_status[dest] == Status.MISSING:
self.file_required[dest] = False
self.file_severity[dest] = compute_severity(
Status.MISSING, False, self.run.mode
)
for result in self.results_at.get(dest, []):
result["required"] = False
def credit_placed(self, placed: set[str]) -> None:
"""An existence frontend is satisfied by any file at the path, and the
builder fills a free platform destination with a core's file."""
for dest, status in self.file_status.items():
if status == Status.MISSING and self.run.full(dest) in placed:
self.file_status[dest] = Status.OK
self.file_severity[dest] = Severity.OK
for result in self.results_at.get(dest, []):
result["status"] = Status.OK
def severity_counts(self) -> tuple[dict[str, int], dict[str, list[str]]]:
"""Destinations by severity, and the missing ones that are not firmware."""
counts = {
Severity.OK: 0,
Severity.INFO: 0,
Severity.WARNING: 0,
Severity.CRITICAL: 0,
}
not_firmware: dict[str, list[str]] = {}
for dest, s in self.file_severity.items():
category = self.file_category.get(dest, BIOS)
if category != BIOS and self.file_status.get(dest) == Status.MISSING:
not_firmware.setdefault(category, []).append(dest)
continue
counts[s] = counts.get(s, 0) + 1
return counts, not_firmware
def _cut_game_data(
config: dict,
emu_profiles: dict | None,
emulators_dir: str,
data_dir_registry: dict | None,
target_cores: set[str] | None,
system_filter: list[str] | None,
) -> tuple[dict, dict, list[str]]:
"""The config and profiles of a --no-game-data pack, and what it leaves out."""
from resolve.gamedata import without_game_data
if emu_profiles is None:
emu_profiles = load_emulator_profiles(emulators_dir)
cut = without_game_data(config, emu_profiles, data_dir_registry, target_cores)
config, emu_profiles = cut.config, cut.profiles
systems = config.get("systems", {})
in_scope = set(select_systems(systems, system_filter) if system_filter else systems)
cut.left_out = [
item for item in cut.left_out
if item.layer == "core" or item.system in in_scope
]
return config, emu_profiles, cut.report_lines()
def _required_declarations(verify_systems: dict) -> dict:
return {
sys_id: {
**system,
"files": [
fe for fe in system.get("files", []) if fe.get("required") is not False
],
}
for sys_id, system in verify_systems.items()
}
def _region_pass(
run: _PlatformRun, verify_systems: dict, pack_overrides: dict, regions: list[str],
) -> tuple[set[str], list[str], dict[tuple[str, str, str], str]]:
"""The destinations a region run withdraws, the groups no file answers,
and the destination of each core extra."""
from resolve import regions as resolve_regions
# The builder owns pack composition, so it owns the grouping the region
# pass reads. Grouping the platform files here and the core extras
# there let the two answer differently on one request: the report kept
# every core extra a region run withdraws from the pack.
from packs.extras import platform_region_groups
config = run.config
held: set[str] = set()
region_groups, region_extra_dests = platform_region_groups(
config,
verify_systems,
run.emulators_dir,
run.db,
config.get("base_destination", ""),
run.profiles,
target_cores=run.target_cores,
required_only=run.required_only,
held_out=held,
zip_contents=run.zip_contents,
data_registry=run.data_dir_registry,
slot_overrides=pack_overrides,
)
region_index = resolve_regions.platform_region_index(config, run.profiles, run.target_cores)
region_drops = resolve_regions.resolve_region_drops(
region_groups, region_index, regions, held,
)
# The pack README names these: no file answers the request, so every
# candidate stays. Reported here too, or verify reads all OK for a
# system that has no BIOS for the region asked.
region_fallbacks = resolve_regions.fallback_groups(
region_groups, region_index, regions
)
return region_drops, region_fallbacks, region_extra_dests
def _platform_gaps(
run: _PlatformRun,
occupied: dict[str, str | None],
region_drops: set[str],
region_extra_dests: dict[tuple[str, str, str], str],
validation_index: dict,
validation_owners: dict[str, list[tuple[str, str]]],
) -> tuple[list[dict], set[str], dict[str, str]]:
"""The core files of the pack: the gap report as the builder narrows it,
the destinations it fills, and the category of each."""
config = run.config
# Cross-reference undeclared files, called exactly as the builder calls
# it: its declarations, not the enriched ones (a core file the platform
# also declares under another name is packed at the core's own path, 21
# such files in the RetroArch pack), and no names from inside archives
# or data trees (a loose file whose name exists only as a member of
# naomi2.zip was counted "in pack" while the builder shipped nothing).
undeclared = find_undeclared_files(
config,
run.emulators_dir,
run.db,
run.emu_profiles,
target_cores=run.target_cores,
declared_names=platform_declarations(config, run.db, enrich=False),
)
# The builder's own pass reads the same report: computed once here and
# handed over as it stands now, before the markings below.
report_for_builder = [dict(u) for u in undeclared]
if run.system_filter:
# A system pack carries the extras its systems own.
from packs.extras import report_owned_by_systems
undeclared = report_owned_by_systems(undeclared, run.system_filter)
if run.required_only:
undeclared = [u for u in undeclared if u.get("required") is not False]
if region_drops:
undeclared = [
u
for u in undeclared
if region_extra_dests.get(
(u.get("emulator", ""), u.get("name", ""), u.get("path") or "")
)
not in region_drops
]
if run.required_only:
# One member of a required set, as the builder keeps it.
spares = core_file_spares(undeclared)
undeclared = [u for u in undeclared if id(u) not in spares]
_mark_unplaced(config, undeclared, run.profiles)
from packs.extras import ExtraResolver
placed_kind: dict[str, str] = {}
placed = _mark_hidden(config, undeclared, occupied, _BuilderPass(
run.emulators_dir, run.db, run.emu_profiles, run.target_cores, region_drops,
report_for_builder,
ExtraResolver(
run.db, DEFAULT_BIOS_DIR, run.zip_contents, run.data_dir_registry,
validation_index, validation_owners, profiles=run.profiles,
pending_assets=True,
),
placed_kind,
run.system_filter,
run.required_only,
))
return undeclared, placed, placed_kind
def _profile_coverage(
profiles: dict, verify_systems: dict, file_status: dict[str, str],
validation_index: dict,
) -> tuple[int, int]:
"""Destinations whose file a core validates, and those a profile names."""
gt_filenames = set(validation_index)
profiled_names: set[str] = set()
for profile in profiles.values():
if profile.get("type") in ("launcher", "alias"):
continue
for f in profile.get("files", []):
name = f.get("name", "")
if name:
profiled_names.add(name)
profiled_names.update(f.get("aliases") or [])
dest_to_name: dict[str, str] = {}
for sys_id, system in verify_systems.items():
for fe in system.get("files", []):
dest_to_name.setdefault(_dest_key(fe, sys_id), fe.get("name", ""))
with_validation = sum(
1 for dest in file_status if dest_to_name.get(dest, "") in gt_filenames
)
with_profile = sum(
1 for dest in file_status if dest_to_name.get(dest, "") in profiled_names
)
return with_validation, with_profile
class PlatformNarrowing(TypedDict, total=False):
"""The narrowings of a platform pack verify_platform reports on."""
regions: list[str] | None
system_filter: list[str] | None
no_game_data: bool
required_only: bool
def verify_platform(
config: dict,
db: dict,
emulators_dir: str = DEFAULT_EMULATORS_DIR,
emu_profiles: dict | None = None,
target_cores: set[str] | None = None,
data_dir_registry: dict | None = None,
**narrowing: Unpack[PlatformNarrowing],
) -> dict:
"""Verify all BIOS files for a platform, including cross-reference gaps.
``no_game_data`` reports on the pack built with --no-game-data: the
game data cut as the builder cuts it, and named in ``left_out``.
A region priority list narrows the report to the files a pack built with the
same list would carry, using the same selection function as the builder.
``system_filter`` does the same for a pack built with --system: the
systems it keeps and the core extras those systems own.
``required_only`` reports on the pack built with --required-only: the
declarations, trees and core extras marked ``required: false`` are left
out before any of them takes a path, as the builder leaves them out.
"""
unknown = sorted(set(narrowing) - set(PlatformNarrowing.__annotations__))
if unknown:
raise TypeError(f"verify_platform() got an unexpected keyword argument '{unknown[0]}'")
regions = narrowing.get("regions")
system_filter = narrowing.get("system_filter")
no_game_data = narrowing.get("no_game_data", False)
required_only = narrowing.get("required_only", False)
left_out: list[str] = []
if no_game_data:
config, emu_profiles, left_out = _cut_game_data(
config, emu_profiles, emulators_dir, data_dir_registry, target_cores,
system_filter,
)
# Normalized once: a typo in a platform YAML must not verify with one
# mode and be scored with another.
mode = normalize_mode(config.get("verification_mode"))
platform = config.get("platform", "unknown")
# The builder settles a destination claimed by both layers, and this must read
# the same decision, or the two tools describe different packs.
has_zipped = any(
fe.get("zipped_file")
for sys in config.get("systems", {}).values()
for fe in sys.get("files", [])
)
zip_contents = build_zip_contents_index(db) if has_zipped else {}
# Loaded before the slot overrides: a caller passing no profiles (the
# README's coverage) got no override and reported a discrepancy at a slot
# the pack settles.
profiles = (
emu_profiles
if emu_profiles is not None
else load_emulator_profiles(emulators_dir)
)
base_dest = config.get("base_destination", "")
pack_overrides = slots.pack_overrides(
config, profiles, db, zip_contents, data_dir_registry,
target_cores=target_cores,
)
slot_overrides = {
(key[len(base_dest) + 1:] if base_dest and key.startswith(f"{base_dest}/") else key): path
for key, path in pack_overrides.items()
}
# Build HLE + validation indexes from emulator profiles
# Ground truth comes from the emulators the platform runs. A standalone
# profile that loads a same-named file of its own (ZEsarUX's 48K
# cpc6128.rom against cap32's 32K one) has nothing to say about a
# RetroArch pack, nor does its HLE: dosbox-x's FONT.ROM fallback turned a
# missing required Batocera BIOS into INFO.
plat_cores = resolve_platform_cores(config, profiles)
platform_profiles = {name: profiles[name] for name in plat_cores}
hle_index = {
f.get("name", ""): True
for profile in platform_profiles.values()
for f in profile.get("files", [])
if f.get("hle_fallback")
}
validation_index = _build_validation_index(platform_profiles)
validation_owners = destination_owners(platform_profiles)
verify_systems = platform_scope_systems(config, profiles, target_cores, system_filter)
if required_only:
verify_systems = _required_declarations(verify_systems)
categories = EntryCategories(config, profiles, data_dir_registry)
run = _PlatformRun(
config, db, emulators_dir, emu_profiles, profiles, target_cores,
data_dir_registry, zip_contents, system_filter, required_only, mode, base_dest,
)
region_drops: set[str] = set()
region_fallbacks: list[str] = []
region_extra_dests: dict[tuple[str, str, str], str] = {}
if regions:
region_drops, region_fallbacks, region_extra_dests = _region_pass(
run, verify_systems, pack_overrides, regions,
)
# A destination two systems declare with two hashes ships one file, the
# one the builder prefers. The other declaration is scored against that
# file, as the frontend will score it after installation: RetroDECK's
# xroar component hashes bios/disk.rom and finds the PC-88 ROM.
preferred_entries, winners = _twin_index(
verify_systems, db, base_dest, zip_contents
)
tally = _PlatformTally(
run, platform,
_DeclarationResolver(
db, zip_contents, data_dir_registry, slot_overrides, mode,
platform_profiles, preferred_entries, winners, base_dest,
),
region_drops, validation_index, validation_owners, hle_index, categories,
)
for sys_id, system in verify_systems.items():
for file_entry in system.get("files", []):
tally.judge(sys_id, file_entry)
tally.settle_groups()
shipped, occupied = _builder_placement(
tally.packed_order, bool(config.get("case_insensitive_fs", False))
)
undeclared, placed, placed_kind = _platform_gaps(
run, occupied, region_drops, region_extra_dests, validation_index,
validation_owners,
)
# What the builder places from the cores, one per pack path, by category:
# several entries claim one path (rom.key from three Amiga cores) and the
# builder ships one file there. The category travels on the extra: a copy
# the second pass makes has no gap report entry to look it up by.
packed_extras = {"bios": 0, "game_data": 0}
for category in placed_kind.values():
packed_extras["game_data" if category == "game_data" else "bios"] += 1
if not reads_file_contents(mode):
tally.credit_placed(placed)
counts, not_firmware = tally.severity_counts()
file_status = tally.file_status
# Held but refused: on a hash platform the builder leaves out a file whose
# declared hash the local copy contradicts. Counted apart, so a coverage
# figure never calls present what the pack does not carry.
excluded = sorted(
dest for dest, status in file_status.items()
if status == Status.UNTESTED and dest not in tally.shipped_keys
)
# Count by file status (ok/untested/missing)
status_counts: dict[str, int] = {}
for s in file_status.values():
status_counts[s] = status_counts.get(s, 0) + 1
exclusions = find_exclusion_notes(
config, emulators_dir, emu_profiles, target_cores=target_cores
)
with_validation, with_profile = _profile_coverage(
profiles, verify_systems, file_status, validation_index,
)
total = len(file_status)
# The paths a pack built from this report holds, as written in the ZIP
# (base_destination stripped, as the builder flattens it). The pipeline
# compares this set with the archive: equal counts can hide one file
# credited here and another written there.
from packs.paths import _flat
pack_destinations = sorted(
{_flat(dest, base_dest, True) for dest in shipped} | {
_flat(dest, base_dest, True) for dest in placed
}
)
return {
"platform": platform,
**({"systems": sorted(verify_systems)} if system_filter else {}),
"verification_mode": mode,
"total_files": total,
"pack_destinations": pack_destinations,
"severity_counts": counts,
"status_counts": status_counts,
"missing_not_firmware": {k: sorted(v) for k, v in sorted(not_firmware.items())},
"excluded_files": excluded,
"packed_extras": packed_extras,
"undeclared_files": undeclared,
# Reported apart, never scored: no severity, count or exit code reads it.
"launcher_reads_not_held": launcher_reads_not_held(
{config.get("_key", platform): config}, db, profiles, data_dir_registry
),
# Records a config file does not prove: listed, never consumed.
"launcher_unproven": launcher_unproven({config.get("_key", platform): config}, profiles),
"exclusion_notes": exclusions,
"region_fallbacks": sorted(region_fallbacks),
**({"left_out": left_out} if no_game_data else {}),
# Every tree of the registry answers a declaration by its tail, so
# one that was never refreshed leaves its files missing here while
# an online pack build refreshes it and packs them.
"data_dir_notices": sorted(
key for key, entry in (data_dir_registry or {}).items()
if not os.path.isdir(entry.get("local_cache", ""))
),
"details": tally.details,
"ground_truth_coverage": {
"with_validation": with_validation,
"with_profile": with_profile,
"platform_only": total - with_validation,
"total": total,
"applicable": bool(resolve_platform_cores(config, profiles)),
},
}
File diff suppressed because it is too large. Load diff
+646
View File
@@ -0,0 +1,646 @@
"""The cached data directories: the lock readers hold on them, and their refresh from upstream."""
from __future__ import annotations
import contextlib
import json
import logging
import os
import shutil
import tarfile
import tempfile
import time
import urllib.request
import zipfile
from collections.abc import Callable, Iterator
from pathlib import Path
try:
import yaml
except ImportError:
yaml = None
from core.artifacts import file_lock as _file_lock, set_plain_mode
from core.cli import InputMissing
from core.github import github_token
from model.safeparse import yaml_load
log = logging.getLogger(__name__)
DEFAULT_REGISTRY = "platforms/_data_dirs.yml"
VERSIONS_FILE = "data/.versions.json"
USER_AGENT = "retrobios/1.0"
REQUEST_TIMEOUT = 30
DOWNLOAD_TIMEOUT = 300
# A mirror sometimes answers with a page that is not the archive: the
# buildbot's ScummVM.zip failed CI once as "File is not a zip file" and
# downloaded fine minutes later. Seconds to wait before each retry.
DOWNLOAD_RETRY_WAITS = (5, 20)
_TRANSIENT = (urllib.error.URLError, OSError, tarfile.TarError, zipfile.BadZipFile, EOFError)
def load_registry(registry_path: str = DEFAULT_REGISTRY) -> dict[str, dict]:
if yaml is None:
raise ImportError("PyYAML required: pip install pyyaml")
path = Path(registry_path)
if not path.exists():
raise InputMissing(f"Registry not found: {registry_path}")
with open(path) as f:
data = yaml_load(f) or {}
return data.get("data_directories", {})
def cache_lock(
cache_dir: str | Path, shared: bool = False
) -> contextlib.AbstractContextManager[None]:
"""The lock a refresh holds while it swaps cache_dir.
A reader takes it shared: a pack walking data/sdlpal while another run
swapped the tree shipped part of it, or nothing.
"""
cache_dir = Path(cache_dir)
return _announced_lock(cache_dir.with_name(f".{cache_dir.name}.lock"), shared, cache_dir)
def _wait_message(lock_path: Path, shared: bool, cache_dir: Path) -> str:
"""Who to wait for, and, for a refresh, how not to.
The bare "another run holds it" named neither the lock nor its holder,
and the build waited with no limit.
"""
message = (
f"waiting for {cache_dir}: another run holds {lock_path} "
f"(lsof {lock_path} names it)"
)
if not shared:
message += (
". generate_pack.py --no-refresh-data, or --offline there and in"
" pipeline.py, builds from the cache as it is without waiting"
)
return message
@contextlib.contextmanager
def _announced_lock(lock_path: Path, shared: bool, cache_dir: Path) -> Iterator[None]:
"""file_lock, saying so when it has to wait.
A pipeline holds every cache for its whole run: a refresh started beside
it waited hours with nothing on screen.
"""
try:
import fcntl
except ImportError:
with _file_lock(lock_path, shared=shared):
yield
return
lock_path.parent.mkdir(parents=True, exist_ok=True)
mode = fcntl.LOCK_SH if shared else fcntl.LOCK_EX
with open(lock_path, "a") as handle:
try:
fcntl.flock(handle, mode | fcntl.LOCK_NB)
except BlockingIOError:
log.warning(_wait_message(lock_path, shared, cache_dir))
fcntl.flock(handle, mode)
try:
yield
finally:
fcntl.flock(handle, fcntl.LOCK_UN)
def hold_data_dirs(stack: contextlib.ExitStack, registry: dict) -> None:
"""Hold every cached data directory shared for the life of *stack*.
A pack resolves names against a tree, then copies the file minutes
later. A refresh swapping the tree in between shipped bytes nobody
verified, or died on a file the new tree no longer has. A refresh waits
for the holders. Never called before a refresh in the same process:
the exclusive lock would wait on this one. A cache not yet on disk is
held too: the lock sits beside the tree, and skipped, a refresh could
install the tree after verify ran and before the packs read it.
"""
for entry in registry.values():
cache = entry.get("local_cache", "")
if cache:
stack.enter_context(cache_lock(cache, shared=True))
def _load_versions(versions_path: str = VERSIONS_FILE) -> dict[str, dict]:
path = Path(versions_path)
if not path.exists():
return {}
with open(path) as f:
return json.load(f)
def _save_versions(
versions: dict[str, dict], versions_path: str = VERSIONS_FILE
) -> None:
"""Write the version file whole or not at all.
Truncating in place let a concurrent reader load an empty file and die
on JSONDecodeError. The scratch file sits beside the target so the
rename stays on one filesystem.
"""
path = Path(versions_path)
path.parent.mkdir(parents=True, exist_ok=True)
handle, scratch = tempfile.mkstemp(
dir=path.parent, prefix=f".{path.name}.", suffix=".tmp"
)
try:
with os.fdopen(handle, "w") as f:
json.dump(versions, f, indent=2, sort_keys=True)
f.write("\n")
set_plain_mode(scratch)
os.replace(scratch, path)
except BaseException:
with contextlib.suppress(OSError):
os.unlink(scratch)
raise
def _record_version(key: str, record: dict, versions_path: str) -> None:
"""Set one key under the file lock, so two writers keep both updates."""
path = Path(versions_path)
with _file_lock(path.with_name(f".{path.name}.lock")):
versions = _load_versions(versions_path)
versions[key] = record
_save_versions(versions, versions_path)
def _staging_dir(cache_dir: Path) -> tempfile.TemporaryDirectory:
"""Scratch space beside the cache, on its filesystem.
/tmp is a 4 GB tmpfs here: staging there filled it and turned the
promotion into a copy, during which the cache held a partial tree.
"""
cache_dir.parent.mkdir(parents=True, exist_ok=True)
return tempfile.TemporaryDirectory(
dir=cache_dir.parent, prefix=f".{cache_dir.name}-"
)
def _promote(extract_dir: Path, cache_dir: Path, scratch: Path) -> None:
"""Swap the new tree in by renames alone.
The old tree steps aside into the run's own scratch directory, never a
fixed sibling name another run could be using, and comes back if the
new one cannot be moved in.
"""
previous = scratch / "previous"
if cache_dir.exists():
os.replace(cache_dir, previous)
try:
os.replace(extract_dir, cache_dir)
except BaseException:
if previous.exists() and not cache_dir.exists():
os.replace(previous, cache_dir)
raise
def _api_request(url: str) -> dict:
req = urllib.request.Request(
url,
headers={
"User-Agent": USER_AGENT,
"Accept": "application/json",
},
)
token = github_token()
if token and "github" in url:
req.add_header("Authorization", f"token {token}")
with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as resp:
return json.loads(resp.read())
def _parse_repo_from_url(source_url: str) -> tuple[str, str, str]:
"""Extract (host_type, owner, repo) from a tarball URL.
Returns host_type as 'github' or 'gitlab'.
"""
if "github.com" in source_url:
# https://github.com/owner/repo/archive/{version}.tar.gz
parts = source_url.split("github.com/")[1].split("/")
return "github", parts[0], parts[1]
if "gitlab.com" in source_url:
parts = source_url.split("gitlab.com/")[1].split("/")
return "gitlab", parts[0], parts[1]
raise ValueError(f"Unsupported host in URL: {source_url}")
def get_remote_sha(source_url: str, version: str) -> str | None:
"""Fetch the current commit SHA for a branch/tag from GitHub or GitLab."""
try:
host_type, owner, repo = _parse_repo_from_url(source_url)
except ValueError:
log.warning("cannot parse repo from URL: %s", source_url)
return None
try:
if host_type == "github":
url = f"https://api.github.com/repos/{owner}/{repo}/commits/{version}"
data = _api_request(url)
return data["sha"]
else:
encoded = f"{owner}%2F{repo}"
url = f"https://gitlab.com/api/v4/projects/{encoded}/repository/branches/{version}"
data = _api_request(url)
return data["commit"]["id"]
except (urllib.error.URLError, KeyError, OSError) as exc:
log.warning(
"failed to fetch remote SHA for %s/%s@%s: %s", owner, repo, version, exc
)
return None
class NothingExtractedError(Exception):
"""An archive that yields no file for the cache.
Promoting it replaced the cache with an empty directory, recorded the new
version and reported success, so the next run read "up to date" and the
packs left without the directory.
"""
def _is_safe_tar_member(member: tarfile.TarInfo, dest: Path) -> bool:
"""Reject path traversal, absolute paths, and symlinks in tar members."""
if member.issym() or member.islnk():
return False
if member.name.startswith("/") or ".." in member.name.split("/"):
return False
resolved = (dest / member.name).resolve()
dest_str = str(dest.resolve()) + os.sep
return str(resolved).startswith(dest_str) or str(resolved) == str(dest.resolve())
def _download_and_extract(
source_url: str,
source_path: str,
local_cache: str,
exclude: list[str] | None = None,
measured: Callable[[int], None] | None = None,
) -> int:
"""Download tarball, extract source_path subtree to local_cache.
Returns the number of files extracted. measured receives the size of
the archive downloaded.
"""
exclude = exclude or []
cache_dir = Path(local_cache)
with _staging_dir(cache_dir) as tmpdir:
tarball_path = Path(tmpdir) / "archive.tar.gz"
log.info("downloading %s", source_url)
req = urllib.request.Request(source_url, headers={"User-Agent": USER_AGENT})
with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp, open(tarball_path, "wb") as f:
while True:
chunk = resp.read(65536)
if not chunk:
break
f.write(chunk)
if measured is not None:
measured(tarball_path.stat().st_size)
log.info("extracting %s -> %s", source_path, local_cache)
prefix = source_path.rstrip("/") + "/"
file_count = 0
with tarfile.open(tarball_path, "r:gz") as tf:
extract_dir = Path(tmpdir) / "extract"
extract_dir.mkdir()
for member in tf.getmembers():
if not member.name.startswith(prefix) and member.name != source_path:
continue
rel = member.name[len(prefix) :]
if not rel:
continue
# skip excluded subdirectories
top_component = rel.split("/")[0]
if top_component in exclude:
continue
if not _is_safe_tar_member(member, extract_dir):
log.warning("skipping unsafe tar member: %s", member.name)
continue
# rewrite member name to relative path
member_copy = tarfile.TarInfo(name=rel)
member_copy.size = member.size
member_copy.mode = member.mode
member_copy.type = member.type
if member.isdir():
(extract_dir / rel).mkdir(parents=True, exist_ok=True)
elif member.isfile():
dest_file = extract_dir / rel
dest_file.parent.mkdir(parents=True, exist_ok=True)
src = tf.extractfile(member)
if src is None:
continue
with src, open(dest_file, "wb") as dst:
shutil.copyfileobj(src, dst)
file_count += 1
if not file_count:
raise NothingExtractedError(f"no file under {source_path} in the archive")
_promote(extract_dir, cache_dir, Path(tmpdir))
return file_count
def _download_and_extract_zip(
source_url: str,
local_cache: str,
exclude: list[str] | None = None,
strip_components: int = 0,
measured: Callable[[int], None] | None = None,
) -> int:
"""Download ZIP, extract to local_cache. Returns file count.
strip_components removes N leading path components from each entry
(like tar --strip-components). Useful when a ZIP has a single root
directory that should be flattened.
"""
exclude = exclude or []
cache_dir = Path(local_cache)
with _staging_dir(cache_dir) as tmpdir:
zip_path = Path(tmpdir) / "archive.zip"
log.info("downloading %s", source_url)
req = urllib.request.Request(source_url, headers={"User-Agent": USER_AGENT})
with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp, open(zip_path, "wb") as f:
while True:
chunk = resp.read(65536)
if not chunk:
break
f.write(chunk)
if measured is not None:
measured(zip_path.stat().st_size)
extract_dir = Path(tmpdir) / "extract"
extract_dir.mkdir()
file_count = 0
with zipfile.ZipFile(zip_path) as zf:
for info in zf.infolist():
if info.is_dir():
continue
name = info.filename
if ".." in name or name.startswith("/"):
continue
# strip leading path components
parts = name.split("/")
if strip_components > 0:
if len(parts) <= strip_components:
continue
parts = parts[strip_components:]
name = "/".join(parts)
# skip excludes (check against stripped path)
top = parts[0] if parts else ""
if top in exclude:
continue
dest = extract_dir / name
dest.parent.mkdir(parents=True, exist_ok=True)
with zf.open(info) as src, open(dest, "wb") as dst:
shutil.copyfileobj(src, dst)
file_count += 1
if not file_count:
raise NothingExtractedError("the archive holds no file to extract")
# The old tree is stepped aside rather than deleted: removing it
# first and then failing to move the new one in left the cache with
# nothing at all, and the next run reads that as "never fetched".
_promote(extract_dir, cache_dir, Path(tmpdir))
return file_count
def _measure_archive(source_url: str) -> int | None:
"""The size of the archive at source_url, read by streaming it: a
tarball GitHub builds on request is sent without a Content-Length."""
req = urllib.request.Request(source_url, headers={"User-Agent": USER_AGENT})
size = 0
try:
with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp:
while chunk := resp.read(65536):
size += len(chunk)
except _TRANSIENT as exc:
log.warning("could not measure %s: %s", source_url, exc)
return None
return size or None
def _record_archive_size(key: str, entry: dict, versions_path: str) -> None:
"""Record the archive size of a tree current since before it was kept.
The installer announces a tree's download as that size: a tarball
whose tree is 10 KB is a download of 21 MB. Measured, not refetched,
so the tree the packs carry stays the one recorded.
"""
path = Path(versions_path)
with _file_lock(path.with_name(f".{path.name}.lock")):
versions = _load_versions(versions_path)
record = versions.get(key)
if record is None or "archive_size" in record:
return
version = entry.get("version", "master")
size = _measure_archive(entry["source_url"].format(version=version))
if size is None:
return
with _file_lock(path.with_name(f".{path.name}.lock")):
versions = _load_versions(versions_path)
if key in versions and "archive_size" not in versions[key]:
versions[key]["archive_size"] = size
_save_versions(versions, versions_path)
log.info("[%s] archive size recorded: %d bytes", key, size)
def _get_remote_etag(source_url: str) -> str | None:
"""HEAD request to get ETag or Last-Modified for freshness check."""
try:
req = urllib.request.Request(
source_url, method="HEAD", headers={"User-Agent": USER_AGENT}
)
with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as resp:
return resp.headers.get("ETag") or resp.headers.get("Last-Modified") or ""
except (urllib.error.URLError, OSError):
return None
def _short_tag(tag: str | None) -> str:
"""A commit sha or ETag cut for a log line, quotes dropped first: a
quoted ETag cut at 12 characters kept its opening quote only."""
if not tag:
return "none"
return tag.strip().removeprefix("W/").strip('"')[:12] or "none"
def refresh_entry(
key: str,
entry: dict,
*,
force: bool = False,
dry_run: bool = False,
versions_path: str = VERSIONS_FILE,
) -> bool | None:
"""Refresh a single data directory entry.
Returns True if the entry was refreshed (or would be in dry-run mode).
The decision and the swap run under one lock per directory: a run that
waited for another session re-reads the version it recorded and finds
nothing left to do.
The exclusive lock waits for every reader, and a pipeline reads the
trees for its whole run: a second build sat on "waiting" for a tree the
remote check would have found current. The check is made first without
it, and only a tree to replace waits.
"""
if dry_run:
return _refresh_entry(key, entry, force, dry_run, versions_path)
if not force:
needs, _remote, cached_tag = _decide(key, entry, False, versions_path)
if needs is None:
return None
if not needs:
log.info("[%s] up to date (tag: %s)", key, _short_tag(cached_tag))
_record_archive_size(key, entry, versions_path)
return False
with cache_lock(entry["local_cache"]):
return _refresh_entry(key, entry, force, dry_run, versions_path)
def _decide(
key: str, entry: dict, force: bool, versions_path: str
) -> tuple[bool | None, str | None, str | None]:
"""(whether the tree needs a refresh, the remote tag read, the recorded
tag). None when the remote could not be read."""
version = entry.get("version", "master")
cached = _load_versions(versions_path).get(key, {})
cached_tag = cached.get("sha") or cached.get("etag")
if force or not Path(entry["local_cache"]).exists():
return True, None, cached_tag
if entry.get("source_type", "tarball") == "zip":
remote_tag = _get_remote_etag(entry["source_url"].format(version=version))
else:
remote_tag = get_remote_sha(entry["source_url"], version)
if remote_tag is None:
log.warning("[%s] could not check remote, skipping", key)
return None, None, cached_tag
return remote_tag != cached_tag, remote_tag, cached_tag
def _refresh_entry(
key: str, entry: dict, force: bool, dry_run: bool, versions_path: str
) -> bool | None:
source_type = entry.get("source_type", "tarball")
version = entry.get("version", "master")
source_url = entry["source_url"].format(version=version)
local_cache = entry["local_cache"]
exclude = entry.get("exclude", [])
needs_refresh, remote_tag, cached_tag = _decide(key, entry, force, versions_path)
if needs_refresh is None:
return None
if not needs_refresh:
log.info("[%s] up to date (tag: %s)", key, _short_tag(cached_tag))
return False
if dry_run:
if remote_tag is not None:
reason = f"cached: {_short_tag(cached_tag)}, remote: {_short_tag(remote_tag)}"
elif force:
reason = "forced"
else:
reason = "not cached"
log.info("[%s] would refresh (type: %s, %s)", key, source_type, reason)
return True
if remote_tag is None:
# Read before the download. A release published in between then
# leaves an older tag on newer content, which the next run refreshes.
# Read after, it left a newer tag on older content, trusted for good.
if source_type == "zip":
remote_tag = _get_remote_etag(source_url)
else:
remote_tag = get_remote_sha(entry["source_url"], version)
archive_sizes: list[int] = []
def fetch() -> int:
archive_sizes.clear()
if source_type == "zip":
return _download_and_extract_zip(
source_url, local_cache, exclude, entry.get("strip_components", 0),
measured=archive_sizes.append,
)
source_path = entry["source_path"].format(version=version)
return _download_and_extract(
source_url, source_path, local_cache, exclude, measured=archive_sizes.append
)
# An archive that reads but holds nothing under the path is the same on
# every try: only a failed or unreadable download is tried again.
for attempt, wait in enumerate((*DOWNLOAD_RETRY_WAITS, None), start=1):
try:
file_count = fetch()
break
except NothingExtractedError as exc:
log.warning("[%s] download failed: %s", key, exc)
return None
except _TRANSIENT as exc:
if wait is None:
log.warning("[%s] download failed after %d tries: %s", key, attempt, exc)
return None
log.warning("[%s] download failed (%s), trying again in %d s", key, exc, wait)
time.sleep(wait)
record = {"sha": remote_tag or "", "version": version}
if archive_sizes:
record["archive_size"] = archive_sizes[-1]
_record_version(key, record, versions_path)
log.info("[%s] refreshed: %d files extracted to %s", key, file_count, local_cache)
return True
def refresh_all(
registry: dict[str, dict],
*,
force: bool = False,
dry_run: bool = False,
versions_path: str = VERSIONS_FILE,
platform: str | None = None,
) -> dict[str, bool | None]:
"""Refresh all entries in the registry.
If platform is set, only refresh entries whose for_platforms
includes that platform (or entries with no for_platforms restriction).
Returns a dict mapping key -> True when refreshed, False when already up
to date, None when the refresh failed. A single boolean conflated the last
two, so a run that reached no remote at all exited 0 like a run with
nothing to do.
"""
results = {}
for key, entry in registry.items():
allowed = entry.get("for_platforms")
if platform and allowed and platform not in allowed:
continue
results[key] = refresh_entry(
key,
entry,
force=force,
dry_run=dry_run,
versions_path=versions_path,
)
if any(results.values()):
# A cache the resolver indexed in this process has changed under it.
from resolve.datadirs import forget_data_dir_index
forget_data_dir_index()
return results
+400
View File
@@ -0,0 +1,400 @@
"""The data directory trees a pack carries, and the cores that read them."""
from __future__ import annotations
import json
import os
import zipfile
from collections.abc import Iterable, Iterator
from pathlib import Path
from typing import TYPE_CHECKING, TypedDict
from core.hashing import compute_hashes
from model.declarations import declared_root
from model.profiles import entry_system_ids, installed_data_refs
from model.systems import _norm_system_id
from packs.archive import PackRecord, _add_pack_member, _reject_unknown
from packs.datadirs import cache_lock
from packs.extras import prefixed_destination
from packs.paths import MEDIA_MARKER, _has_path_conflict, _register_path, lands_on_android
from resolve.cores import resolve_platform_cores as _platform_cores
from resolve.layout import core_system_dirs
from resolve.standalone import platform_layouts, standalone_set
from resolve.validation import deliverable, read_from_system_dir
if TYPE_CHECKING:
from typing_extensions import Unpack
def pack_markers(
platform_name: str, target_name: str | None, platforms_dir: str
) -> tuple[str, ...]:
"""The empty files a pack carries for the systems it is unzipped on,
as named before flattening: the .nomedia of a pack for Android."""
from model.targets import list_available_targets
names = [t["name"] for t in list_available_targets(platform_name, platforms_dir)]
return (MEDIA_MARKER,) if lands_on_android(names, target_name) else ()
def core_data_trees(
config: dict,
profiles: dict[str, dict],
platform_name: str,
data_registry: dict | None,
target_cores: set[str] | None = None,
) -> list[dict]:
"""The data directories the platform's cores read, as tree references.
A profile's ``data_directories`` reach the pack of every platform that
runs the core as a libretro core, below the system directory it hands
the core (and the build's own folder, ``pack_structure``), as the
emulator pack lays them out. Left out: a tree the platform's package
installs, for this core or another reading the same tree
(``installed_data_refs``), one the build bundles or the platform never
opens (``deliverable``), and one whose registry entry names the
platforms it serves (``for_platforms``) without this one. A standalone build reads its data below its own folder, which a
tree's destination does not describe, so its trees stay out, as does a
tree read beside the content (``load_from``).
Each reference carries the profile's systems (``source_systems``, as a
core extra does), which --system and --split narrow on.
"""
if not data_registry:
return []
installed = installed_data_refs(platform_name)
handed = standalone_set(config)
# Relative to base_destination, which the members are written under. A
# platform with none writes its BIOS folder into every destination, and
# the trees go there as the core extras do.
root = declared_root(config)
trees: list[dict] = []
seen: dict[tuple[str, str], int] = {}
for core in sorted(_platform_cores(config, profiles, target_cores)):
profile = profiles[core]
if all(standalone for _view, standalone in platform_layouts(core, profile, handed)):
continue
declared = [t for t in profile.get("data_directories") or [] if isinstance(t, dict)]
directories = core_system_dirs(core, profile, handed)
structure = str((profile.get("pack_structure") or {}).get("libretro") or "")
for tree in deliverable(declared, False, platform_name):
if not read_from_system_dir(tree):
continue
ref = str(tree.get("ref") or "")
entry = data_registry.get(ref)
if entry is None or ref in installed:
continue
allowed = entry.get("for_platforms")
if allowed and platform_name not in allowed:
continue
for directory in [""] if directories is None else directories:
destination = prefixed_destination("/".join(
part.strip("/")
for part in (directory, structure, str(tree.get("destination") or ""))
if part.strip("/")
), root) or root
if (ref, destination) in seen:
# One tree, read by a second core: the manifest says both
# (tree_readers), the pack writes it once.
first = trees[seen[(ref, destination)]]
if core not in first["readers"]:
first["readers"].append(core)
continue
seen[(ref, destination)] = len(trees)
trees.append({
"ref": ref,
"destination": destination,
"required": tree.get("required"),
"core": core,
"readers": [core],
"source_systems": entry_system_ids(tree, profile),
})
return trees
def _in_data_cache(path: str, data_registry: dict | None) -> bool:
"""Whether a resolved file lies in one of the data directory caches."""
real = os.path.realpath(path)
return any(
real.startswith(os.path.realpath(entry["local_cache"]) + os.sep)
for entry in (data_registry or {}).values()
if entry.get("local_cache")
)
def _tree_references(
pack_systems: dict, core_trees: Iterable[dict],
) -> Iterator[tuple[tuple[str, ...], dict]]:
"""(systems, reference) for each tree a pack carries: those its systems
declare, then those its cores read."""
for sys_id, system in sorted(pack_systems.items()):
for dd in system.get("data_directories", []):
yield (sys_id,), dd
for tree in core_trees:
yield tuple(tree["source_systems"]), tree
class _TreeWalkOptions(TypedDict, total=False):
"""The keyword options of _data_directory_members."""
refs_out: dict | None
required_only: bool
core_trees: Iterable[dict]
reclaim: dict[str, str] | None
def _carried_tree(dd: dict, data_registry: dict | None, platform_name: str) -> str | None:
"""The cache folder of a tree reference the pack carries, or None."""
ref_key = dd.get("ref", "")
if not ref_key or not data_registry or ref_key not in data_registry:
return None
if ref_key in installed_data_refs(platform_name):
return None
entry = data_registry[ref_key]
allowed = entry.get("for_platforms")
if allowed and platform_name not in allowed:
return None
local_path = entry.get("local_cache", "")
if not local_path or not os.path.isdir(local_path):
print(
f" WARNING: data directory '{ref_key}' not cached at {local_path} (run refresh_data_dirs.py)"
)
_MISSING_DATA_DIRS.add(ref_key)
return None
return local_path
def _tree_files(local_path: str, dd_prefix: str) -> Iterator[tuple[str, str]]:
"""(source, destination) of every file of a cached tree."""
for root, _dirs, filenames in os.walk(local_path):
for fname in filenames:
src = os.path.join(root, fname)
rel = os.path.relpath(src, local_path)
yield src, f"{dd_prefix}/{rel}" if dd_prefix else rel
def _data_directory_members(
pack_systems: dict,
data_registry: dict | None,
platform_name: str,
base_dest: str,
case_insensitive: bool,
seen_destinations: set,
seen_lower: set,
seen_parents: set,
**options: Unpack[_TreeWalkOptions],
) -> Iterator[tuple[str, str]]:
"""Yield (source, destination) for the cached data directories a
platform's systems declare, then those its cores read (``core_trees``,
from core_data_trees).
``reclaim`` maps a destination already taken to the cache file it was
resolved to: the manifest found the platform's entry there and cannot
list it as a file, so the tree yields it once more and the installer
gets it from the tree's archive.
``refs_out``, when given, maps each yielded destination to
(registry key, system ids, directory destination, whether the core
needs the tree), for the manifest.
These are not BIOS and carry no hash of their own: they are whole
trees an emulator reads, refreshed from upstream, so what ships is
whatever the cache holds. The pack and the install manifest both read
this, the first to write the files and the second to count them.
``required_only`` leaves out a tree declared ``required: false``, one the
core runs without, as it leaves out such a file.
"""
_reject_unknown("_data_directory_members", options, _TreeWalkOptions.__optional_keys__)
refs_out = options.get("refs_out")
reclaim = options.get("reclaim")
required_only = options.get("required_only", False)
core_trees = options.get("core_trees", ())
# Data directories from _data_dirs.yml
for systems, dd in _tree_references(pack_systems, core_trees):
needed = dd.get("required") is not False
if required_only and not needed:
continue
local_path = _carried_tree(dd, data_registry, platform_name)
if local_path is None:
continue
ref_key = dd.get("ref", "")
dd_dest = dd.get("destination", "")
dd_prefix = f"{base_dest}/{dd_dest}" if base_dest and dd_dest else base_dest or dd_dest
# Held while the caller writes what is yielded: a refresh swapping
# the tree waits until the walk is done.
with cache_lock(local_path, shared=True):
for src, full in _tree_files(local_path, dd_prefix):
if reclaim and full in reclaim and (
os.path.normpath(reclaim[full]) == os.path.normpath(src)
):
del reclaim[full]
elif full in seen_destinations or (
full.lower() in seen_lower and case_insensitive
) or _has_path_conflict(full, seen_destinations, seen_parents):
continue
else:
seen_destinations.add(full)
_register_path(full, seen_destinations, seen_parents)
if case_insensitive:
seen_lower.add(full.lower())
if refs_out is not None:
refs_out[full] = (ref_key, systems, dd_prefix, needed)
yield src, full
def _pack_data_tree(
zf: zipfile.ZipFile | PackRecord,
local_cache: str,
dd_dest: str,
seen_destinations: set[str],
seen_parents: set[str],
seen_lower: set[str],
packed_at: dict[str, str] | None = None,
) -> int:
"""Write one data directory into an emulator pack, under its shared lock.
A refresh swaps the tree by rename. Without the lock a walk half done
read the old tree and wrote files of the new one. ``packed_at`` records
each member, so a later profile asking for the same bytes there is
served rather than reported missing.
"""
added = 0
with cache_lock(local_cache, shared=True):
for root, _dirs, filenames in os.walk(local_cache):
for fname in filenames:
src = os.path.join(root, fname)
rel = os.path.relpath(src, local_cache)
full = f"{dd_dest}/{rel}" if dd_dest else rel
if full.lower() in seen_lower or _has_path_conflict(
full, seen_destinations, seen_parents
):
continue
seen_destinations.add(full)
_register_path(full, seen_destinations, seen_parents)
seen_lower.add(full.lower())
_add_pack_member(zf, src, full)
if packed_at is not None:
packed_at[full.lower()] = src
added += 1
return added
# Data directories a pack needed and the cache did not hold. The pack is
# written without them, so the run cannot exit as if it were complete: a
# refresh refused by a quota left the PPSSPP pack with 2 files, exit 0.
_MISSING_DATA_DIRS: set[str] = set()
def tree_readers(pack_systems: dict, core_trees: Iterable[dict]) -> dict[str, list[str]]:
"""The cores that read each tree, for a tree only cores read. A tree a
platform system declares is the system's, whatever core runs it, and
gets no entry. Every reference counts: two cores reading one tree yield
its files once."""
cores: dict[str, set[str]] = {}
declared: set[str] = set()
for _systems, dd in _tree_references(pack_systems, core_trees):
ref = str(dd.get("ref") or "")
if dd.get("core"):
cores.setdefault(ref, set()).update(str(core) for core in dd.get("readers") or [dd["core"]])
else:
declared.add(ref)
return {ref: sorted(names) for ref, names in cores.items() if ref not in declared}
def _tree_group(
ref: str, prefix: str, entry: dict, base_dest: str, versions: dict[str, dict[str, dict]],
) -> dict:
"""The manifest record of one data directory, before its files.
``versions`` caches each .versions.json read, by path.
"""
version = str(entry.get("version", "master"))
dest = prefix
if base_dest and (dest == base_dest or dest.startswith(base_dest + "/")):
dest = dest[len(base_dest):].lstrip("/")
group: dict = {
"ref": ref,
"dest": dest,
"url": str(entry.get("source_url", "")).format(version=version),
"type": "zip" if entry.get("source_type") == "zip" else "tarball",
"systems": [],
"files": {},
}
if group["type"] == "zip":
group["strip_components"] = int(entry.get("strip_components", 0))
else:
group["source_path"] = str(entry.get("source_path", "")).format(version=version)
if entry.get("exclude"):
group["exclude"] = [str(e) for e in entry["exclude"]]
cache = entry.get("local_cache")
if cache:
recorded = Path(cache).parent / ".versions.json"
if str(recorded) not in versions:
try:
versions[str(recorded)] = json.loads(recorded.read_text())
except FileNotFoundError:
versions[str(recorded)] = {}
size = versions[str(recorded)].get(ref, {}).get("archive_size")
if isinstance(size, int) and size > 0:
group["archive_size"] = size
return group
def _manifest_data_directories(
members: list[tuple[str, str]],
refs: dict[str, tuple[str, tuple[str, ...], str, bool]],
registry: dict,
base_dest: str,
readers: dict[str, list[str]] | None = None,
platform_systems: Iterable[str] | None = None,
) -> list[dict]:
"""Each data directory the pack carries, as the installer rebuilds it.
The source archive and the rule that maps its members onto the tree
(strip_components for a ZIP, source_path for a tarball, exclude) come
from _data_dirs.yml, the same refresh_data_dirs applies. Every file
carries the sha1 and size the cache holds, so a member the source
changed since is refused rather than installed. archive_size is the
size of the archive refresh_data_dirs last downloaded, what fetching
the tree costs: a tarball whose tree is 10 KB is a download of 21 MB.
``systems`` are the platform's ids (``platform_systems``) the tree's
systems normalize to, as a core extra's are: a tree no platform system
serves has none, and goes with the files of no system, as the pack
built with --system puts it in the part of its own. FBNeo's cheats
carried sega-megadrive where RetroArch's list says sega-mega-drive.
``optional`` marks a tree every core reading it runs without
(``required: false``): install.py --required-only leaves it out, as the
pack built with --required-only does. ``cores`` names the cores that
read a tree no platform system declares (``readers``): an install for
the games of a card keeps it only when its plan runs one of them.
"""
grouped: dict[tuple[str, str], dict] = {}
versions: dict[str, dict[str, dict]] = {}
by_norm: dict[str, list[str]] = {}
for sys_id in sorted(platform_systems or ()):
by_norm.setdefault(_norm_system_id(sys_id), []).append(sys_id)
for src, full in members:
ref, systems, prefix, needed = refs[full]
if platform_systems is not None:
systems = tuple(own for sid in systems for own in by_norm.get(_norm_system_id(sid), ()))
key = (ref, prefix)
group = grouped.get(key)
if group is None:
group = grouped[key] = _tree_group(
ref, prefix, registry.get(ref, {}), base_dest, versions
)
if needed:
group["needed"] = True
group["systems"].extend(s for s in systems if s not in group["systems"])
rel = full[len(prefix):].lstrip("/") if prefix else full
hashes = compute_hashes(src, frozenset({"sha1"}))
group["files"][rel] = {"sha1": hashes["sha1"], "size": os.path.getsize(src)}
trees = []
for key in sorted(grouped):
group = grouped[key]
if not group.pop("needed", False):
group["optional"] = True
if readers and group["ref"] in readers:
group["cores"] = readers[group["ref"]]
trees.append(group)
return trees
+762
View File
@@ -0,0 +1,762 @@
"""Coverage of one emulator or one system, as the emulator reads its files."""
from __future__ import annotations
import os
import sys
from collections.abc import Callable
from dataclasses import dataclass, field
from core.cli import suggest_names
from core.hashing import compute_hashes
from core.paths import REPO_ROOT
from core.ziptools import build_zip_contents_index
from model.alternatives import set_requirements, settle_sets, slot_set_keys
from model.profiles import (
ProfileSelectionError,
entry_serves_systems,
load_emulator_profiles,
profiles_for_systems,
select_emulator_profiles,
)
from model.registry import load_data_dir_registry
from model.systems import system_index
from packs.verdicts import (
DEFAULT_BIOS_DIR,
RELEASE_ASSET_PENDING,
Severity,
Status,
_SEVERITY_ORDER,
_STATUS_ORDER,
_emulator_severity,
_storage_verdict,
)
from resolve.archives import archive_entry, archive_is_optional
from resolve.directories import expand_directory_entries
from resolve.validation import (
_build_validation_index,
build_ground_truth,
deliverable,
validated_choice,
with_archive_members,
)
# The repository's platforms wherever the script runs from, for library calls
# that pass no directory.
_REPO_PLATFORMS = str(REPO_ROOT / "platforms")
def _effective_validation_label(details: list[dict], validation_index: dict) -> str:
"""Determine the bracket label for the report.
Returns the union of all check types used, e.g. [crc32+existence+size].
"""
all_checks: set[str] = set()
has_files = False
for d in details:
fname = d.get("name", "")
if d.get("note"):
continue # skip informational entries (empty profiles)
has_files = True
entry = validation_index.get(fname)
if entry:
all_checks.update(entry["checks"])
else:
all_checks.add("existence")
if not has_files:
return "existence"
return "+".join(sorted(all_checks))
def _select_profiles(
profile_names: list[str],
all_profiles: dict,
standalone: bool,
) -> list[tuple[str, dict]]:
"""Resolve the named profiles, stopping the run on a bad name."""
try:
return select_emulator_profiles(profile_names, all_profiles, standalone)
except ProfileSelectionError as exc:
print(f"Error: {exc}", file=sys.stderr)
sys.exit(1)
_HASH_CONTRADICTED = "declared hash contradicted by the local file"
# Reduced in the order generate_emulator_pack chooses, so the
# destination's status is the one the pack reports: a slot it
# fills with a contradicted copy, or counts as refused by the
# core, is not missing because another alternative is absent.
_SLOT_PREFERENCE: tuple[Callable[[tuple], bool], ...] = (
lambda a: a[0]["status"] == Status.OK,
lambda a: a[0]["status"] == Status.UNTESTED
and a[0].get("reason") == _HASH_CONTRADICTED,
lambda a: a[0]["status"] != Status.MISSING,
)
def _emulator_files(
emu_name: str,
profile: dict,
db: dict,
standalone: bool,
all_profiles: dict,
system_ids: list[str] | None,
required_only: bool,
region_drops: set[str],
) -> list[dict]:
"""The entries of a profile the emulator pack carries."""
from packs.extras import expand_agnostic_entries
from packs.paths import _resolve_destination
files = expand_agnostic_entries(
expand_directory_entries(
deliverable(profile.get("files", []), standalone),
db,
standalone,
),
emu_name, profile, db, standalone, all_profiles,
)
if system_ids:
files = [fe for fe in files if entry_serves_systems(fe, profile, system_ids)]
if required_only:
optional_archives = {
fe["archive"] for fe in files
if fe.get("archive")
and archive_is_optional(archive_entry(fe["archive"], files), fe["archive"], files)
}
files = [
fe for fe in files
if fe.get("archive") not in optional_archives
and (fe.get("archive") or fe.get("required") is not False)
]
if region_drops:
# Loose files only, as the emulator pack: an archive ships whole,
# and dropping kronos' regional stvbios.zip members rebuilt the
# archive here from 4 of its 14 members and changed its required.
files = [
fe
for fe in files
if fe.get("archive")
or _resolve_destination(fe, standalone) not in region_drops
]
return files
def _archive_result(
archive: str, required: bool, local_path: str | None, resolve_status: str,
) -> dict:
"""The verdict on an archive unit, from its resolution."""
if local_path and resolve_status == "hash_mismatch":
# Same policy as the loose-file branch below: the name
# matched while the bytes contradict the hash the profile
# declares on the container. Reporting it covered says the
# collection holds an archive it does not.
return {
"name": archive,
"status": Status.UNTESTED,
"required": required,
"path": local_path,
"reason": "declared hash contradicted by the local file",
}
if local_path:
result = {
"name": archive,
"status": Status.OK,
"required": required,
"path": local_path,
}
if resolve_status == RELEASE_ASSET_PENDING:
result["release_asset"] = local_path
return result
return {
"name": archive,
"status": Status.MISSING,
"required": required,
}
PlacedResult = tuple[str, dict, bool, bool, list[dict]]
@dataclass
class _EmulatorPack:
"""The emulator pack as verify_emulator retraces it, and its report."""
db: dict
standalone: bool
required_only: bool
validation_index: dict
zip_contents: dict
data_registry: dict | None
details: list[dict] = field(default_factory=list)
# Members of a set another member fills, or that the set's first member
# stands for: not missing, and out of every count.
set_members: list[dict] = field(default_factory=list)
file_status: dict[str, str] = field(default_factory=dict)
file_severity: dict[str, str] = field(default_factory=dict)
dest_to_name: dict[str, str] = field(default_factory=dict)
data_dir_notices: list[str] = field(default_factory=list)
# The paths the emulator pack writes a profile file to. A copy whose hash
# the profile contradicts is written too (UNTESTED here, a DISCREPANCY in
# the pack), so the status alone does not say what the pack holds.
packed_dests: set[str] = field(default_factory=set)
# The emulator pack walks profiles in name order and keeps the first
# file at a path, folding case: a later profile's different file there
# (zesarux pentagon.rom after speccy's PENTAGON.ROM) is not in the pack.
sha1_by_path: dict = field(init=False)
# Destination -> (file packed there, its profile, the path as written).
# Archives and data trees take paths too, before and after the loose
# files of their profile, as the pack writes them.
placed: dict[str, tuple[str | None, str, str]] = field(default_factory=dict)
placed_files: set[str] = field(default_factory=set)
placed_parents: set[str] = field(default_factory=set)
content_ids: dict[str, str | None] = field(default_factory=dict)
def __post_init__(self) -> None:
self.sha1_by_path = {
entry.get("path"): sha1 for sha1, entry in self.db.get("files", {}).items()
}
def pending(self, entry: dict, local_path: str | None, status: str) -> tuple[str | None, str]:
from resolve.packfiles import pending_release_asset, run_is_offline
# Read from disk and the cache, as _resolve_for_platform does: a
# release asset the cache lacks is fetched by an online build
# (generate_emulator_pack resolves with offline=offline).
if status in ("not_found", "hash_mismatch") and not run_is_offline():
asset = pending_release_asset(entry, self.db)
if asset:
return asset, RELEASE_ASSET_PENDING
return local_path, status
def content_id(self, path: str | None) -> str | None:
if not path:
return None
if path not in self.content_ids:
self.content_ids[path] = self.sha1_by_path.get(path) or (
compute_hashes(path)["sha1"] if os.path.isfile(path) else None
)
return self.content_ids[path]
def block(self, dest: str) -> str | None:
from packs.paths import placement_block
return placement_block(
dest, self.placed_files, set(self.placed), self.placed_parents, True
)
def occupy(self, dest: str, path: str | None, owner: str) -> None:
from packs.paths import _register_path
if self.block(dest):
return
self.placed[dest.lower()] = (path, owner, dest)
_register_path(dest, self.placed_files, self.placed_parents)
def occupy_trees(self, emu_name: str, profile: dict) -> None:
"""The profile's data trees follow its files in the pack, which
writes them even when the system filter leaves it no file:
bluemsx's Machines/ tree holds msx-emu's coleco.rom path in a
--system colecovision pack."""
for dd in deliverable(profile.get("data_directories", []), self.standalone):
if self.required_only and dd.get("required") is False:
continue
cache = (self.data_registry or {}).get(dd.get("ref", ""), {}).get("local_cache", "")
if not cache or not os.path.isdir(cache):
continue
dd_dest = dd.get("destination", "")
structure = profile.get("pack_structure")
prefix = (
structure.get("standalone" if self.standalone else "libretro", "")
if structure else ""
)
if prefix:
dd_dest = f"{prefix}/{dd_dest}" if dd_dest else prefix
for root, _dirs, names in os.walk(cache):
for fname in names:
src = os.path.join(root, fname)
rel = os.path.relpath(src, cache).replace(os.sep, "/")
self.occupy(f"{dd_dest}/{rel}" if dd_dest else rel, src, emu_name)
def note_data_dirs(self, profile: dict) -> None:
# Check data directories (only notice if not cached)
for dd in deliverable(
profile.get("data_directories", []), self.standalone
):
if self.required_only and dd.get("required") is False:
continue
ref = dd.get("ref", "")
if not ref:
continue
if self.data_registry and ref in self.data_registry:
cache_path = self.data_registry[ref].get("local_cache", "")
if cache_path and os.path.isdir(cache_path):
continue # cached, no notice needed
self.data_dir_notices.append(ref)
def verify_profile(
self, emu_name: str, profile: dict, files: list[dict], spares: set[str],
) -> None:
"""Verify one profile's entries and add them to the report."""
self.note_data_dirs(profile)
if not files:
self.details.append(
{
"name": f"({emu_name})",
"status": Status.OK,
"required": False,
"system": "",
"note": f"No files needed for {profile.get('emulator', emu_name)}",
"ground_truth": [],
}
)
self.occupy_trees(emu_name, profile)
return
# Each destination's outcome, settled by set once the profile is
# read: an archive unit is a member like a loose file (Kronos reads
# kronos/stvbios.zip, else stvbios.zip).
placed_results = self._archive_results(emu_name, profile, files, spares)
self._place_loose(emu_name, self._loose_results(emu_name, files), placed_results)
self._settle(emu_name, profile, placed_results)
self.occupy_trees(emu_name, profile)
def _archive_results(
self, emu_name: str, profile: dict, files: list[dict], spares: set[str],
) -> list[PlacedResult]:
# Verify archives as units (e.g., neogeo.zip, aes.zip)
from packs.paths import _archive_destination
from resolve.packfiles import resolve_file
placed_results: list[PlacedResult] = []
seen_archives: set[str] = set()
for file_entry in files:
archive = file_entry.get("archive")
if not archive or archive in seen_archives:
continue
seen_archives.add(archive)
own_entry = archive_entry(archive, files)
# Where the pack puts it: an archive_prefix or pack_structure
# moves it, and a loose same-named entry is another file.
dest = _archive_destination(
archive, profile.get("archive_prefix", ""),
profile.get("pack_structure"), self.standalone,
)
if dest in spares:
continue
local_path, resolve_status = self.pending(own_entry, *resolve_file(
own_entry,
self.db,
DEFAULT_BIOS_DIR,
self.zip_contents,
data_dir_registry=self.data_registry,
offline=True,
))
required = any(
f.get("archive") == archive and f.get("required", True)
for f in files
)
result = _archive_result(archive, required, local_path, resolve_status)
result["system"] = file_entry.get("system", "")
result["hle_fallback"] = False
result["ground_truth"] = build_ground_truth(archive, self.validation_index)
result["destination"] = dest
block = self.block(dest)
if block and local_path and result["status"] != Status.MISSING:
other_path, owner, other_dest = self.placed.get(dest.lower(), (None, "", ""))
if block == "path_conflict" or self.content_id(local_path) != self.content_id(other_path):
# The pack serves the other profile's file here: this
# archive is not in it, whatever this profile resolves.
result["status"] = Status.MISSING
result["reason"] = (
"a packed file occupies its directory" if block == "path_conflict"
else f"the pack holds {owner}'s {other_dest} at this path"
)
elif local_path:
self.occupy(dest, local_path, emu_name)
self.packed_dests.add(dest)
placed_results.append((dest, result, required, False, [own_entry]))
return placed_results
def _loose_results(
self, emu_name: str, files: list[dict],
) -> dict[str, list[tuple[dict, bool, bool, dict]]]:
from packs.paths import _resolve_destination
from resolve.packfiles import resolve_file
# Results of this emulator, by destination. Several entries of one
# profile on one destination are the releases the code accepts
# there (a shareware and a retail HOG, each GRP in a size table):
# holding one of them fills the slot, and the others are not gaps.
emu_results: dict[str, list[tuple[dict, bool, bool, dict]]] = {}
for file_entry in files:
# Skip archive members (verified as archive units above)
if file_entry.get("archive"):
continue
dest_hint = file_entry.get("path", "")
# The emulator pack's resolution, release assets included.
local_path, resolve_status = self.pending(file_entry, *resolve_file(
{**with_archive_members(file_entry, files), "source_profile": emu_name},
self.db,
DEFAULT_BIOS_DIR,
self.zip_contents,
dest_hint=dest_hint,
data_dir_registry=self.data_registry,
offline=True,
))
if resolve_status in ("not_found", "user_provided", "external"):
local_path = None
name = file_entry.get("name", "")
required = file_entry.get("required", True)
hle = file_entry.get("hle_fallback", False)
result = self._loose_result(
file_entry, name, required, local_path, resolve_status, emu_name,
)
result["system"] = file_entry.get("system", "")
result["hle_fallback"] = hle
result["ground_truth"] = build_ground_truth(name, self.validation_index)
# The slot the emulator pack places this entry in: standalone_path
# under --standalone, the sanitised path.
dest = _resolve_destination(file_entry, self.standalone) or name
emu_results.setdefault(dest, []).append((result, required, hle, file_entry))
return emu_results
def _loose_result(
self, file_entry: dict, name: str, required: bool, local_path: str | None,
resolve_status: str, emu_name: str,
) -> dict:
"""The verdict on a loose profile entry, from its resolution."""
stored = _storage_verdict(file_entry, emulator_pack=True)
if stored is not None:
return stored
if resolve_status == RELEASE_ASSET_PENDING:
return {
"name": name,
"status": Status.OK,
"required": required,
"path": local_path,
"release_asset": local_path,
"reason": "release asset, fetched when the pack is built",
}
if not local_path:
result = {"name": name, "status": Status.MISSING, "required": required}
# An entry the profile documents as unsourceable is absent by
# design: a per-user key, a slot the user fills, a dump nobody
# has made. Counting it beside a file somebody could still
# find invites the wrong repair: dropping the flag, or
# chasing a vendor's whole install tree.
unsourceable = file_entry.get("unsourceable")
if unsourceable:
result["unsourceable"] = (
unsourceable if isinstance(unsourceable, str) else ""
)
return result
# Apply emulator validation
# Judged by this emulator's own entries, as it runs its check,
# through the selection the emulator pack makes.
chosen, disagreement = validated_choice(
file_entry, local_path, self.db, self.validation_index, DEFAULT_BIOS_DIR,
None, emulators={emu_name},
)
if disagreement:
return {
"name": name,
"status": Status.UNTESTED,
"required": required,
"path": local_path,
"reason": disagreement.split(" says ", 1)[-1],
}
if chosen != local_path:
return {
"name": name,
"status": Status.OK,
"required": required,
"path": chosen,
}
if resolve_status == "hash_mismatch":
# Nothing in validation: caught it, but the name matched
# while the bytes contradict the hash the profile
# declares. That is a different file wearing the right
# name (config.ini and ROM collide across systems), so
# calling it covered reports the collection as holding
# something it does not. Validation runs first because it
# names the specific field that disagrees.
return {
"name": name,
"status": Status.UNTESTED,
"required": required,
"path": local_path,
"reason": "declared hash contradicted by the local file",
}
return {
"name": name,
"status": Status.OK,
"required": required,
"path": local_path,
}
def _place_loose(
self, emu_name: str,
emu_results: dict[str, list[tuple[dict, bool, bool, dict]]],
placed_results: list[PlacedResult],
) -> None:
for dest, alternatives in emu_results.items():
# What the emulator pack places here: an accepted file, else a
# file whose hash the profile contradicts. A refused copy is held
# but never packed.
slot_entries = [a[3] for a in alternatives]
kept = _preferred_alternatives(alternatives)
packed = next(
(a[0].get("path") for a in kept
if a[0]["status"] == Status.OK and a[0].get("path")),
None,
) or next(
(a[0].get("path") for a in kept
if a[0]["status"] == Status.UNTESTED
and a[0].get("reason") == _HASH_CONTRADICTED and a[0].get("path")),
None,
)
held = packed or next(
(a[0].get("path") for a in kept
if a[0]["status"] != Status.MISSING and a[0].get("path")),
None,
)
block = self.block(dest)
block_reason = ""
if block and held is not None:
block_reason = self._block_reason(dest, block, held)
elif not block and packed is not None:
self.occupy(dest, packed, emu_name)
self.packed_dests.add(dest)
for result, required, hle, _file_entry in kept:
if block_reason and result["status"] != Status.MISSING:
result["status"] = Status.MISSING
result["reason"] = block_reason
result["destination"] = dest
placed_results.append((dest, result, required, hle, slot_entries))
def _block_reason(self, dest: str, block: str, held: str) -> str:
other_path, owner, other_dest = self.placed.get(dest.lower(), (None, "", ""))
same = self.content_id(held) is not None and self.content_id(held) == self.content_id(
other_path
)
if block == "path_conflict":
return "a packed file occupies its directory"
if block == "case_twin":
return (
f"packed only as {other_dest}, from {owner}"
if same
else f"the pack holds {owner}'s {other_dest} at this path"
)
if not same:
return f"the pack holds {owner}'s {other_dest} at this path"
return ""
def _settle(self, emu_name: str, profile: dict, placed_results: list[PlacedResult]) -> None:
# A set the code takes one member of is one need: once a member is
# in the pack the others are not missing, and a set nobody holds is
# one gap under its first member. Settled per profile, before the
# destinations of several profiles are merged.
excused, standing = settle_sets([
(
slot_set_keys(emu_name, entries),
entries[0],
result["status"] == Status.OK
or (result["status"] == Status.UNTESTED
and result.get("reason") == _HASH_CONTRADICTED),
)
for _dest, result, _required, _hle, entries in placed_results
], lambda key: set_requirements(profile).get(key[1], True))
for position, (dest, result, required, hle, _fe) in enumerate(placed_results):
if position in excused and result["status"] == Status.MISSING:
self.set_members.append(result)
continue
if position in standing:
result["alternatives"] = standing[position].others
result["required"] = required = standing[position].required
self.details.append(result)
# Aggregate by destination (path if available, else name)
self.dest_to_name[dest] = result["name"]
cur = result["status"]
prev = self.file_status.get(dest)
if prev is None or _STATUS_ORDER.get(cur, 0) > _STATUS_ORDER.get(
prev, 0
):
self.file_status[dest] = cur
sev = _emulator_severity(cur, required, hle)
prev_sev = self.file_severity.get(dest)
if prev_sev is None or _SEVERITY_ORDER.get(
sev, 0
) > _SEVERITY_ORDER.get(prev_sev, 0):
self.file_severity[dest] = sev
def _preferred_alternatives(
alternatives: list[tuple[dict, bool, bool, dict]],
) -> list[tuple[dict, bool, bool, dict]]:
"""The one alternative the emulator pack places at a destination."""
if len(alternatives) > 1:
for keep in _SLOT_PREFERENCE:
chosen = [a for a in alternatives if keep(a)]
if chosen:
return chosen[:1]
return alternatives
def verify_emulator(
profile_names: list[str],
emulators_dir: str,
db: dict,
standalone: bool = False,
regions: list[str] | None = None,
platforms_dir: str = _REPO_PLATFORMS,
system_ids: list[str] | None = None,
required_only: bool = False,
) -> dict:
"""Verify files for specific emulator profiles.
A region priority list narrows the report the same way a pack built with the
same list would be narrowed, through the emulator pack's own drop set.
`system_ids` keeps the entries of those systems, as the system pack does.
`required_only` reports on the pack built with --required-only: a loose
file or tree marked ``required: false`` is left out, and an archive when
it and every member it carries are optional, as the builder leaves them.
"""
from packs.paths import _resolve_destination
# Also load aliases for redirect messages
all_profiles = load_emulator_profiles(emulators_dir, skip_aliases=False)
selected = _select_profiles(profile_names, all_profiles, standalone)
# The member index only answers a zipped_file entry, and decompressing
# every archive took 23 of the 24 seconds of a run that had none.
zip_contents = (
build_zip_contents_index(db)
if any(f.get("zipped_file") for _name, profile in selected
for f in profile.get("files") or [])
else {}
)
# Build validation index from selected profiles only
selected_profiles = dict(selected)
validation_index = _build_validation_index(selected_profiles)
data_registry = load_data_dir_registry(platforms_dir)
pack = _EmulatorPack(
db, standalone, required_only, validation_index, zip_contents, data_registry,
)
# The emulator pack withdraws these, and the report withdraws the same.
region_drops: set[str] = set()
if regions:
from packs.extras import emulator_region_drops
region_drops = emulator_region_drops(
selected, standalone, regions, required_only, db=db,
zip_contents=zip_contents, data_registry=data_registry,
)
for emu_name, profile in sorted(selected):
files = _emulator_files(
emu_name, profile, db, standalone, all_profiles, system_ids,
required_only, region_drops,
)
spares: set[str] = set()
if required_only:
from packs.extras import emulator_required_spares
spares = emulator_required_spares(
emu_name, profile, files, standalone, region_drops, db,
validation_index, zip_contents, data_registry=data_registry,
)
files = [
fe for fe in files
if fe.get("archive") or _resolve_destination(fe, standalone) not in spares
]
pack.verify_profile(emu_name, profile, files, spares)
counts = {
Severity.OK: 0,
Severity.INFO: 0,
Severity.WARNING: 0,
Severity.CRITICAL: 0,
}
for s in pack.file_severity.values():
counts[s] = counts.get(s, 0) + 1
status_counts: dict[str, int] = {}
for s in pack.file_status.values():
status_counts[s] = status_counts.get(s, 0) + 1
label = _effective_validation_label(pack.details, validation_index)
gt_filenames = set(validation_index)
total = len(pack.file_status)
with_validation = sum(
1 for dest in pack.file_status if pack.dest_to_name.get(dest, "") in gt_filenames
)
return {
"emulators": [n for n, _ in selected],
"verification_mode": label,
"total_files": total,
# The paths the emulator pack fills with the profile's files, for the
# pipeline's comparison with the pack built in memory.
"pack_destinations": sorted(pack.packed_dests),
"severity_counts": counts,
"status_counts": status_counts,
"details": pack.details,
"set_members": pack.set_members,
"data_dir_notices": sorted(set(pack.data_dir_notices)),
"ground_truth_coverage": {
"with_validation": with_validation,
"platform_only": total - with_validation,
"total": total,
},
}
def verify_system(
system_ids: list[str],
emulators_dir: str,
db: dict,
standalone: bool = False,
regions: list[str] | None = None,
platforms_dir: str = _REPO_PLATFORMS,
required_only: bool = False,
) -> dict:
"""Verify files for all emulators supporting given system IDs."""
profiles = load_emulator_profiles(emulators_dir)
matching = profiles_for_systems(profiles, system_ids, standalone)
if not matching:
all_systems: set[str] = set()
for p in profiles.values():
all_systems.update(p.get("systems", []))
if standalone:
print(
f"No standalone emulators found for system(s): {', '.join(system_ids)}",
file=sys.stderr,
)
else:
print(
f"No emulators found for system(s): {', '.join(system_ids)}",
file=sys.stderr,
)
# --list-systems merges spellings that differ in case or separator:
# the hint counted 579 spellings for the 532 lines it prints.
print(suggest_names(system_ids, sorted(all_systems), "--list-systems",
listed=len(system_index(profiles))),
file=sys.stderr)
sys.exit(1)
return verify_emulator(
matching, emulators_dir, db, standalone, regions=regions,
platforms_dir=platforms_dir, system_ids=system_ids, required_only=required_only,
)
+642
View File
@@ -0,0 +1,642 @@
"""Packs for one emulator or one system."""
from __future__ import annotations
import contextlib
import functools
import os
import shutil
import sys
import tempfile
import zipfile
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, TypedDict
from core.cli import suggest_names
from core.paths import REPO_ROOT
from core.ziptools import build_zip_contents_index
from model.alternatives import settle_sets, slot_set_keys
from model.profiles import (
ProfileSelectionError,
entry_serves_systems,
load_emulator_profiles,
profiles_for_systems,
select_emulator_profiles,
)
from model.registry import load_data_dir_registry
from model.systems import MANUFACTURER_PREFIXES, system_index
from packs.archive import (
PackRecord,
_Placed,
_add_pack_member,
_add_zip_to_pack,
_reject_unknown,
_same_bytes,
_write_generated_member,
_writing_pack,
)
from packs.datatrees import _MISSING_DATA_DIRS, _pack_data_tree
from packs.extras import emulator_region_drops, emulator_required_spares, expand_agnostic_entries
from packs.naming import _bounded_join, _bounded_pack_name, _name_part, _narrowings
from packs.paths import _archive_destination, _resolve_destination
from resolve import packfiles as packresolve
from resolve.archives import archive_entry, archive_is_optional
from resolve.directories import expand_directory_entries
from resolve.packfiles import download_external, resolve_file
from resolve.validation import (
_build_validation_index,
deliverable,
validated_choice,
with_archive_members,
)
if TYPE_CHECKING:
from typing_extensions import Unpack
if TYPE_CHECKING:
# What a destination came to: its entries, whether it was filled, and the
# report to make if no other member of its set fills it.
_Outcome = tuple[list[dict], bool, "Callable[[], None] | None"]
class EmulatorPackOptions(TypedDict, total=False):
"""The keyword options of generate_emulator_pack."""
zip_contents: dict | None
offline: bool | None
platforms_dir: str | None
pack_name: str | None
system_ids: list[str] | None
final_dir: str | None
record: PackRecord | None
@dataclass
class _EmulatorPackBuild:
"""One emulator pack being written, and what each destination came to."""
db: dict
bios_dir: str
standalone: bool
required_only: bool
zip_contents: dict
data_registry: dict
validation_index: dict
region_drops: set[str]
all_profiles: dict
zf: zipfile.ZipFile | PackRecord
offline: bool | None = None
system_ids: list[str] | None = None
record: PackRecord | None = None
total_files: int = 0
data_files: int = 0
missing_files: list[str] = field(default_factory=list)
rejected_files: list[str] = field(default_factory=list)
discrepancies: list[str] = field(default_factory=list)
unsourceable_files: list[str] = field(default_factory=list)
instruction_files: list[str] = field(default_factory=list)
placed: _Placed = field(default_factory=lambda: _Placed(True))
seen_hashes: set[str] = field(default_factory=set) # SHA1 dedup for same file, different path
# Loose file packed at each folded destination, to tell a profile asking
# for the same file there from one asking for other bytes.
packed_at: dict[str, str] = field(default_factory=dict)
# A destination is missing once, however many profiles ask for it:
# verify --emulator counts by destination.
missing_at: set[str] = field(default_factory=set)
data_dir_notices: list[str] = field(default_factory=list)
def report_missing(self, name: str, destination: str) -> None:
if destination not in self.missing_at:
self.missing_at.add(destination)
self.missing_files.append(name)
def _add(self, local_path: str, dest: str, fe: dict | None) -> None:
"""Write a loose file or an archive at dest and count it."""
if fe is not None and local_path.endswith(".zip"):
_add_zip_to_pack(local_path, dest, self.zf, fe)
else:
_add_pack_member(self.zf, local_path, dest)
self.placed.take(dest)
self.total_files += 1
if self.record is not None:
self.record.files.append(dest)
def pack_profile(self, emu_name: str, profile: dict) -> None:
pack_structure = profile.get("pack_structure")
files = expand_agnostic_entries(
expand_directory_entries(
deliverable(profile.get("files", []), self.standalone),
self.db,
self.standalone,
),
emu_name, profile, self.db, self.standalone, self.all_profiles,
)
if self.system_ids:
files = [
fe for fe in files if entry_serves_systems(fe, profile, self.system_ids)
]
if not files and not profile.get("data_directories"):
print(f" No files needed for {profile.get('emulator', emu_name)}")
# What each destination came to, settled by set once the
# profile is read: a member another member fills is not missing,
# and a set nobody holds is reported once (alternatives.py). An
# archive unit is a member like a loose file.
outcomes: list[_Outcome] = []
spares = emulator_required_spares(
emu_name, profile, files, self.standalone, self.region_drops, self.db,
self.validation_index, self.zip_contents, data_registry=self.data_registry,
) if self.required_only else set()
# Pack archives as units
archive_prefix = profile.get("archive_prefix", "")
for archive_name in sorted({fe["archive"] for fe in files if fe.get("archive")}):
archive_dest = _archive_destination(
archive_name, archive_prefix, pack_structure, self.standalone
)
own_entry = archive_entry(archive_name, files)
if self.required_only and archive_is_optional(own_entry, archive_name, files):
continue
if archive_dest in spares:
continue
outcomes.append(self._pack_archive(own_entry, archive_name, archive_dest))
for dest, alternatives in self._slots(files, spares).items():
outcome = self._pack_slot(emu_name, files, dest, alternatives)
if outcome is not None:
outcomes.append(outcome)
excused, _standing = settle_sets([
(slot_set_keys(emu_name, entries), entries[0], fills)
for entries, fills, _report in outcomes
])
for position, (_entries, _fills, report) in enumerate(outcomes):
if report is not None and position not in excused:
report()
self._pack_trees(profile, pack_structure)
def _pack_archive(self, own_entry: dict, archive_name: str, archive_dest: str) -> _Outcome:
local_path, status = resolve_file(
own_entry,
self.db,
self.bios_dir,
self.zip_contents,
data_dir_registry=self.data_registry,
offline=self.offline,
)
taken = archive_dest.lower() in self.placed.lower
if taken or self.placed.conflicts(archive_dest):
# Another profile's file holds this path. The same archive
# asked for twice is served. Anything else leaves this
# profile without its archive, which used to pass in
# silence: a neocdz.zip lacking 000-lo.lo shipped as the
# one the second core needs.
if not (taken and local_path and _same_bytes(
local_path, self.packed_at.get(archive_dest.lower())
)):
return ([own_entry], False, functools.partial(
self.report_missing, archive_name, archive_dest
))
return ([own_entry], True, None)
if local_path and status not in ("not_found",):
self._add(local_path, archive_dest, own_entry)
self.packed_at[archive_dest.lower()] = local_path
return ([own_entry], True, None)
return ([own_entry], False, functools.partial(
self.report_missing, archive_name, archive_dest
))
def _slots(self, files: list[dict], spares: set) -> dict[str, list[dict]]:
# Pack individual files (skip archive members). The entries of one
# profile on one destination are the releases the code accepts
# there (raze's seven SW.GRP): the first one the core accepts
# fills the slot, as verify --emulator credits it, and the slot
# has one outcome however many alternatives it lists.
slots: dict[str, list[dict]] = {}
for fe in files:
if self.required_only and fe.get("required") is False:
continue
if fe.get("archive"):
continue
dest = _resolve_destination(fe, self.standalone)
if not dest or dest in spares:
continue
if self.region_drops and dest in self.region_drops:
continue
slots.setdefault(dest, []).append(fe)
return slots
def _write_instructions(self, provided: dict, dest: str) -> None:
# Instructions, not a file: written beside the slot the
# user fills, and counted apart from what the pack holds.
self.placed.take(dest)
instr = provided.get("instructions", "Please provide this file manually.")
folder = dest.rsplit("/", 1)[0] + "/" if "/" in dest else ""
_write_generated_member(
self.zf,
f"{folder}INSTRUCTIONS_{provided['name']}.txt",
f"File needed: {provided['name']}\n\n{instr}\n",
)
# verify --emulator counts an unsourceable one as such.
(self.unsourceable_files if provided.get("unsourceable") else self.instruction_files).append(
provided["name"]
)
def _choose(
self, emu_name: str, files: list[dict], alternatives: list[dict],
) -> tuple[tuple[dict, str, str | None] | None, str | None, str | None]:
"""The alternative the core accepts, with the refusal of the first
one it turned away and that copy."""
fallback: tuple[dict, str, str | None] | None = None
refusal: str | None = None
refused_path: str | None = None
for fe in alternatives:
local_path, status = resolve_file(
{**with_archive_members(fe, files), "source_profile": emu_name},
self.db,
self.bios_dir,
self.zip_contents,
dest_hint=fe.get("path", ""),
data_dir_registry=self.data_registry,
offline=self.offline,
)
if status == "external":
return (fe, "", "external"), refusal, refused_path
if status in ("not_found", "user_provided") or not local_path:
continue
# The file verify --emulator credits is the one shipped:
# a dump the core's own check rejects gives way to a held
# one it accepts (azahar's otp.bin, dolphin's dsp_rom.bin).
better, disagreement = validated_choice(
fe, local_path, self.db, self.validation_index, self.bios_dir, None,
emulators={emu_name},
)
if disagreement:
reason = disagreement.split(" says ", 1)[-1]
refusal = refusal or f"{fe['name']}: {reason}"
refused_path = refused_path or local_path
continue
if better != local_path:
return (fe, better, None), refusal, refused_path
if status == "hash_mismatch":
# Not a check the core runs, so the file still serves,
# but it is not the dump the profile documents.
fallback = fallback or (fe, local_path, "mismatch")
continue
return (fe, local_path, None), refusal, refused_path
return fallback, refusal, refused_path
def _pack_slot(
self, emu_name: str, files: list[dict], dest: str, alternatives: list[dict],
) -> _Outcome | None:
# Name order, first file wins, case folded: verify replays
# the rule and reports a later profile's file as missing.
block = self.placed.block(dest)
provided = next(
(fe for fe in alternatives if fe.get("storage") == "user_provided"),
None,
)
if provided is not None:
if not block:
self._write_instructions(provided, dest)
return None
chosen, refusal, refused_path = self._choose(emu_name, files, alternatives)
if block:
held = (
chosen[1] if chosen is not None and chosen[2] != "external"
else None if chosen is not None else refused_path
)
if chosen is not None or held is not None:
if block == "taken" and held and _same_bytes(
held, self.packed_at.get(dest.lower())
):
# The file already at this path, asked for twice.
return (alternatives, True, None)
return (alternatives, False, functools.partial(
self.report_missing, alternatives[0]["name"], dest
))
if chosen is None:
return self._unfilled(alternatives, dest, refusal)
fe, local_path, how = chosen
if how == "external":
return self._pack_external(fe, dest, alternatives)
if how == "mismatch":
self.discrepancies.append(
f"{fe['name']}: not the dump the {emu_name} profile declares"
)
# SHA1 dedup: skip if same physical file AND same destination
# (but allow same file to be packed under different destinations,
# e.g., IPL.bin in GC/USA/ and GC/EUR/ from same source)
dedup_key_hash = f"{os.path.realpath(local_path)}:{dest}"
if dedup_key_hash not in self.seen_hashes:
self.seen_hashes.add(dedup_key_hash)
self._add(local_path, dest, fe)
self.packed_at[dest.lower()] = local_path
return (alternatives, True, None)
def _unfilled(self, alternatives: list[dict], dest: str, refusal: str | None) -> _Outcome:
if refusal:
self.rejected_files.append(refusal)
return (alternatives, False, None)
if all(fe.get("unsourceable") for fe in alternatives):
return (alternatives, False, functools.partial(
self.unsourceable_files.append, alternatives[0]["name"]
))
return (alternatives, False, functools.partial(
self.report_missing, alternatives[0]["name"], dest
))
def _pack_external(self, fe: dict, dest: str, alternatives: list[dict]) -> _Outcome:
file_ext = os.path.splitext(fe["name"])[1] or ""
with tempfile.NamedTemporaryFile(
delete=False, suffix=file_ext, dir=packresolve.scratch_dir()
) as tmp:
tmp_path = tmp.name
try:
# Built in memory, nothing is fetched: verify --emulator
# cannot fetch either and reports the file missing.
if self.record is None and download_external(fe, tmp_path):
self._add(tmp_path, dest, None)
return (alternatives, True, None)
return (alternatives, False, functools.partial(
self.missing_files.append, fe["name"]
))
finally:
if os.path.exists(tmp_path):
os.unlink(tmp_path)
def _pack_trees(self, profile: dict, pack_structure: dict | None) -> None:
# The trees after the files, as in a platform pack: a dump the
# profile declares wins over the copy a tree bundles at the same
# path (Dolphin's real dsp_rom.bin over Sys/GC's free one).
# A tree only one build reads follows that build, like a file.
required_only = self.required_only
for dd in deliverable(
profile.get("data_directories", []), self.standalone
):
if required_only and dd.get("required") is False:
continue
ref_key = dd.get("ref", "")
if not ref_key or not self.data_registry or ref_key not in self.data_registry:
if ref_key:
self.data_dir_notices.append(ref_key)
continue
local_cache = self.data_registry[ref_key].get("local_cache", "")
if not local_cache or not os.path.isdir(local_cache):
self.data_dir_notices.append(ref_key)
continue
dd_dest = dd.get("destination", "")
if pack_structure:
mode_key = "standalone" if self.standalone else "libretro"
prefix = pack_structure.get(mode_key, "")
if prefix:
dd_dest = f"{prefix}/{dd_dest}" if dd_dest else prefix
self.data_files += _pack_data_tree(
self.zf, local_cache, dd_dest, self.placed.destinations,
self.placed.parents, self.placed.lower, self.packed_at,
)
def nothing_needed(self) -> bool:
return self.total_files + self.data_files == 0 and not (
self.missing_files or self.rejected_files or self.instruction_files
or self.unsourceable_files
)
def report(self, shown: str) -> None:
# Report. The members of data trees are counted apart: verify --emulator
# counts the profile's files, and folding 3500 tree members into the
# same number made the two impossible to compare.
parts = [f"{self.total_files} files packed"]
if self.data_files:
parts.append(f"{self.data_files} from data directories")
if self.missing_files:
parts.append(f"{len(self.missing_files)} missing")
if self.rejected_files:
parts.append(f"{len(self.rejected_files)} refused by the core")
if self.unsourceable_files:
parts.append(f"{len(self.unsourceable_files)} unsourceable")
if self.instruction_files:
parts.append(f"{len(self.instruction_files)} to provide")
print(f" {shown}: {', '.join(parts)}")
for name in self.missing_files:
print(f" MISSING: {name}")
for name in self.unsourceable_files:
print(f" UNSOURCEABLE: {name}")
for name in self.instruction_files:
print(f" TO PROVIDE: {name} (instructions in the pack)")
for line in self.rejected_files:
print(f" REFUSED: {line}")
for line in self.discrepancies:
print(f" DISCREPANCY: {line}")
for ref in sorted(set(self.data_dir_notices)):
print(
f" Note: data directory '{ref}' required but not included (use refresh_data_dirs.py)"
)
_MISSING_DATA_DIRS.update(self.data_dir_notices)
def generate_emulator_pack(
profile_names: list[str],
emulators_dir: str,
db: dict,
bios_dir: str,
output_dir: str,
standalone: bool = False,
*,
required_only: bool = False,
regions: list[str] | None = None,
**options: Unpack[EmulatorPackOptions],
) -> str | None:
"""Generate a ZIP pack for specific emulator profiles.
Returns the path, "" when no file is needed (verify --emulator reports
0/0 OK), None on failure.
`pack_name` is the caller's own file name: the system pack names its
archive after the system, and joining 23 SNES emulator names went past
the 255 bytes a file name may hold. `system_ids` keeps only the entries
of those systems, as a platform pack narrows core extras. `final_dir`
is where the caller moves the archive, the path the report names.
`record` builds the pack in memory instead (PackRecord): nothing is
written or read, and the paths are kept on it.
"""
_reject_unknown("generate_emulator_pack", options, EmulatorPackOptions.__optional_keys__)
all_profiles = load_emulator_profiles(emulators_dir, skip_aliases=False)
zip_contents = options.get("zip_contents")
if zip_contents is None:
zip_contents = build_zip_contents_index(db)
try:
selected = select_emulator_profiles(profile_names, all_profiles, standalone)
except ProfileSelectionError as exc:
print(f"Error: {exc}", file=sys.stderr)
return None
record = options.get("record")
# ZIP naming
display_names = [_name_part(p.get("emulator", n)) for n, p in selected]
validation_index = _build_validation_index(dict(selected))
narrow_tags = "".join(
tag
for tag, _label in _narrowings(
"full", regions, None, False, required_only, standalone
)
)
zip_name = options.get("pack_name") or _bounded_pack_name(
display_names, [n for n, _p in selected], f"{narrow_tags}_BIOS_Pack.zip"
)
zip_path = os.path.join(output_dir, zip_name)
if record is None:
os.makedirs(output_dir, exist_ok=True)
data_registry = load_data_dir_registry(
options.get("platforms_dir") or str(REPO_ROOT / "platforms")
)
region_drops: set[str] = (
emulator_region_drops(
selected, standalone, regions, required_only, db,
zip_contents=zip_contents, data_registry=data_registry,
)
if regions
else set()
)
with (
contextlib.nullcontext(record) if record is not None
else _writing_pack(zip_path)
) as zf:
build = _EmulatorPackBuild(
db, bios_dir, standalone, required_only, zip_contents, data_registry,
validation_index, region_drops, all_profiles, zf,
offline=options.get("offline"), system_ids=options.get("system_ids"), record=record,
)
for emu_name, profile in sorted(selected):
build.pack_profile(emu_name, profile)
# Remove empty ZIP (no files packed and no missing = nothing to ship)
if record is None and build.nothing_needed():
os.unlink(zip_path)
# What verify --emulator reports as 0/0 OK: no file is needed, so
# no pack is written and the run succeeds. Printed with the path,
# the run named a file it had just removed and exited 1.
print(f" {', '.join(display_names)}: no file needed, no pack written")
return ""
final_dir = options.get("final_dir")
build.report(os.path.join(final_dir, zip_name) if final_dir else zip_path)
return None if build.nothing_needed() else zip_path
class SystemPackOptions(TypedDict, total=False):
"""The keyword options of generate_system_pack."""
required_only: bool
regions: list[str] | None
offline: bool | None
platforms_dir: str | None
def generate_system_pack(
system_ids: list[str],
emulators_dir: str,
db: dict,
bios_dir: str,
output_dir: str,
standalone: bool = False,
zip_contents: dict | None = None,
**options: Unpack[SystemPackOptions],
) -> str | None:
"""Generate a ZIP pack for all emulators supporting given system IDs.
Returns the path, "" when no file is needed, None on failure.
"""
_reject_unknown("generate_system_pack", options, SystemPackOptions.__optional_keys__)
required_only = options.get("required_only", False)
regions = options.get("regions")
offline = options.get("offline")
platforms_dir = options.get("platforms_dir")
profiles = load_emulator_profiles(emulators_dir)
matching = profiles_for_systems(profiles, system_ids, standalone)
if not matching:
all_systems: set[str] = set()
for p in profiles.values():
all_systems.update(p.get("systems", []))
if standalone:
print(
f"No standalone emulators found for system(s): {', '.join(system_ids)}",
file=sys.stderr,
)
else:
print(
f"No emulators found for system(s): {', '.join(system_ids)}",
file=sys.stderr,
)
# --list-systems merges spellings that differ in case or separator:
# the hint counted 579 spellings for the 532 lines it prints.
print(suggest_names(system_ids, sorted(all_systems), "--list-systems",
listed=len(system_index(profiles))),
file=sys.stderr)
return None
# Named like the platform's --system tag: one spelling of a system is
# one file name, and one selection.
sys_display = _bounded_join(
[_system_display_name(sid) for sid in system_ids], list(system_ids)
)
# Built in a scratch directory: under its emulator name in output_dir it
# overwrote, then carried away, an --emulator pack already there.
os.makedirs(output_dir, exist_ok=True)
# Every dimension goes through the one list: keeping only the region
# tag made --system X --required-only overwrite the pack built without it.
tags = "".join(
tag
for tag, _label in _narrowings(
"full", regions, None, False, required_only, standalone=standalone
)
)
# The selection mode is part of the name: `--system sega-triforce`
# and `--emulator triforce` both wrote Triforce_BIOS_Pack.zip, and
# the second run replaced the first without a word.
final_name = f"{sys_display}_System{tags}_BIOS_Pack.zip"
scratch = tempfile.mkdtemp(prefix=".system-", dir=output_dir)
try:
result = generate_emulator_pack(
matching,
emulators_dir,
db,
bios_dir,
scratch,
standalone,
zip_contents=zip_contents,
required_only=required_only,
regions=regions,
offline=offline,
platforms_dir=platforms_dir,
pack_name=final_name,
system_ids=system_ids,
final_dir=output_dir,
)
if not result:
return result
new_path = os.path.join(output_dir, final_name)
os.replace(result, new_path)
return new_path
finally:
shutil.rmtree(scratch, ignore_errors=True)
def _system_display_name(system_id: str) -> str:
"""Convert system ID to display name for ZIP naming."""
s = system_id.lower().replace("_", "-")
for prefix in MANUFACTURER_PREFIXES:
if s.startswith(prefix):
s = s[len(prefix) :]
break
parts = s.split("-")
return "_".join(p.title() for p in parts if p)
@@ -26,7 +26,7 @@ from model.declarations import OUTER_ROOTS, outer_layout
from core.paths import sanitize_pack_path
from resolve.content import declares_shape, shape_fits, size_fits
from resolve.validation import deliverable, read_from_save_dir, read_from_system_dir
from packpaths import libretro_systems, save_destination, save_layout
from packs.paths import libretro_systems, save_destination, save_layout
from resolve.regions import FILE_GROUP
if TYPE_CHECKING:
@@ -329,7 +329,7 @@ class ExtraResolver:
def resolve(self, fe: dict, dest: str) -> tuple[str | None, str, str]:
"""(local copy or None, resolver status, the core's disagreement)."""
from packresolve import pending_release_asset, resolve_file, run_is_offline
from resolve.packfiles import pending_release_asset, resolve_file, run_is_offline
from resolve.validation import core_size_refusal, validated_choice
local_path, status = resolve_file(
@@ -410,7 +410,7 @@ def hidden_extras(
``required_only`` are the builder's for a --source truth or a
--required-only pack: an optional extra is skipped before it takes a path.
"""
from packpaths import _register_path, placement_block
from packs.paths import _register_path, placement_block
reject_unknown("hidden_extras", options, HiddenOptions.__optional_keys__)
report = options.get("report")
@@ -1402,7 +1402,7 @@ def undeclared_report(
"""The gap report _collect_emulator_extras reads, for a caller that
collects the extras more than once with these arguments: the region
grouping and the pack or manifest phase 2 each computed it in full."""
from verify import find_undeclared_files
from packs.gaps import find_undeclared_files
return find_undeclared_files(
config, emulators_dir, db, emu_profiles, target_cores=target_cores,
@@ -2123,7 +2123,7 @@ def _ships(
Resolved with the builder's own inputs: without the data directories,
AmberELEC's bluemsx config.ini read as missing while the pack held it.
"""
from packresolve import resolve_declaration
from resolve.packfiles import resolve_declaration
from resolve.validation import baseline_verdict
path, status = resolve_declaration(
@@ -2322,7 +2322,7 @@ def emulator_region_drops(
emulator pack resolves with.
"""
from resolve import regions as resolve_regions
from packpaths import _resolve_destination
from packs.paths import _resolve_destination
from resolve.validation import _build_validation_index, filter_files_by_mode
region_index = resolve_regions.build_region_index(dict(selected))
@@ -2370,7 +2370,7 @@ def emulator_required_spares(
stvbios.zip. The pack and verify --emulator both read this."""
from model.alternatives import groups_of, rank_in, required_groups
from resolve.archives import archive_entry
from packpaths import _archive_destination, _resolve_destination
from packs.paths import _archive_destination, _resolve_destination
reject_unknown("emulator_required_spares", options, SpareOptions.__optional_keys__)
data_registry = options.get("data_registry")
@@ -2415,7 +2415,7 @@ def _emulator_ships(
directories, dolphin-mmjr2's nwc24msg.cfg read as missing while the pack
held it.
"""
from packresolve import resolve_file
from resolve.packfiles import resolve_file
from resolve.validation import validated_choice, with_archive_members
local, status = resolve_file(
+239
View File
@@ -0,0 +1,239 @@
"""Built packs checked against their platform and given their manifest."""
from __future__ import annotations
import json
import os
import shutil
import sys
import tempfile
import zipfile
from collections.abc import Iterable
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, TypedDict
from core.artifacts import set_plain_mode
from model.registry import list_registered_platforms
from model.targets import load_target_config
from packs.archive import _reject_unknown, _write_generated_member
from packs.integrity import generate_sha256sums, verify_pack, verify_pack_against_platform
from packs.naming import _expected_pack_names, _narrows_contents, _pack_archives
from packs.scope import annotate_pack_systems
if TYPE_CHECKING:
from typing_extensions import Unpack
def _baseline_shortfall(excluded: int, absent: int) -> list[str]:
"""Why a verified pack holds fewer baseline files than the platform declares."""
parts = []
if excluded:
parts.append(f"{excluded} unsafe excluded")
if absent:
parts.append(f"{absent} not in the collection")
return parts
def inject_manifest(zip_path: str, manifest: dict) -> None:
"""Inject manifest.json into an existing ZIP pack.
The pack is rewritten beside its final name and swapped in, as
_writing_pack builds it: appending in place rewrites the central
directory last, so a process killed in between left an unreadable ZIP
where a valid pack had been.
"""
manifest_json = json.dumps(manifest, indent=2, ensure_ascii=False)
with zipfile.ZipFile(zip_path, "r") as zf:
has_manifest = "manifest.json" in zf.namelist()
directory = os.path.dirname(zip_path) or "."
fd, scratch = tempfile.mkstemp(
prefix=f".{os.path.basename(zip_path)}.", suffix=".partial", dir=directory
)
os.close(fd)
try:
if not has_manifest:
# Append to a copy. Append mode defaults to ZIP_STORED, which
# would leave the manifest uncompressed and give the same pack
# two different byte layouts depending on the path taken here.
shutil.copyfile(zip_path, scratch)
with zipfile.ZipFile(scratch, "a", zipfile.ZIP_DEFLATED) as zf:
_write_generated_member(zf, "manifest.json", manifest_json)
else:
with zipfile.ZipFile(zip_path, "r") as src, \
zipfile.ZipFile(scratch, "w", zipfile.ZIP_DEFLATED) as dst:
for item in src.infolist():
if item.filename == "manifest.json":
continue
dst.writestr(item, src.read(item.filename))
_write_generated_member(dst, "manifest.json", manifest_json)
set_plain_mode(scratch)
os.replace(scratch, zip_path)
except BaseException:
Path(scratch).unlink(missing_ok=True)
raise
def _target_cores_for(
platform_name: str, target_name: str | None, platforms_dir: str
) -> set[str] | None:
"""Cores a target leaves available, or None when no target was asked for.
Called on a platform the build already packed under the target, so the
target is known to it: a platform without one is left out of the run.
"""
if not target_name:
return None
return load_target_config(platform_name, target_name, platforms_dir)
class FinalizeOptions(TypedDict, total=False):
"""The keyword options of verify_and_finalize_packs."""
platforms_dir: str
skip_conformance: bool
data_registry: dict | None
regions: list[str] | None
target_name: str | None
emulators_dir: str
no_game_data: bool
pack_systems_by_name: dict[str, dict] | None
built: Iterable[str] | None
@dataclass(frozen=True)
class _FinalizeSettings:
"""FinalizeOptions with their defaults."""
platforms_dir: str = "platforms"
skip_conformance: bool = False
data_registry: dict | None = None
regions: list[str] | None = None
target_name: str | None = None
emulators_dir: str = "emulators"
no_game_data: bool = False
pack_systems_by_name: dict[str, dict] | None = None
built: Iterable[str] | None = None
def _conforms(zip_path: str, pname: str, db: dict, opts: _FinalizeSettings) -> bool:
"""Stage 2 for one platform of a pack: extract and verify against its
config. Prints the platform's line and its errors."""
(
p_ok,
_total,
_matched,
p_errors,
bl_checked,
bl_present,
core_checked,
core_present,
bl_excluded,
bl_absent,
) = verify_pack_against_platform(
zip_path,
pname,
opts.platforms_dir,
db=db,
emulators_dir=opts.emulators_dir,
regions=opts.regions,
data_registry=opts.data_registry,
target_cores=_target_cores_for(pname, opts.target_name, opts.platforms_dir),
no_game_data=opts.no_game_data,
)
status = "OK" if p_ok else "FAILED"
exclusion_note = "".join(
f", {part}" for part in _baseline_shortfall(bl_excluded, bl_absent)
)
print(
f" platform {pname}: {bl_present}/{bl_checked} baseline present"
f"{exclusion_note}, "
f"{core_present}/{core_checked} cores present, {status}"
)
if not p_ok:
for err in p_errors:
print(f" {err}")
return p_ok
def verify_and_finalize_packs(
output_dir: str,
db: dict,
**options: Unpack[FinalizeOptions],
) -> bool:
"""Verify all packs, inject manifests, generate SHA256SUMS.
pack_systems_by_name gives, per pack file name, the systems its
manifest.json records (pack_systems).
``built`` names the packs this run wrote, and only those are verified
and get a manifest. A pack another run left in the directory was
reopened, recompressed and given a manifest without its pack_systems,
which made the installer refuse to narrow it. None takes every pack.
Two-stage verification:
1. Hash check against database.json (integrity)
2. Extract + verify against platform config (conformance)
Returns True if all packs pass verification.
"""
_reject_unknown("verify_and_finalize_packs", options, FinalizeOptions.__optional_keys__)
opts = _FinalizeSettings(**options)
all_ok = True
# Map ZIP names to platform names
# By the exact name this run's reduction gives a platform's pack, never by
# substring: a _Custom or regional pack left by another run was judged
# against this run's expectation and failed it.
registered = list_registered_platforms(opts.platforms_dir)
expected = _expected_pack_names(
registered, opts.platforms_dir, opts.regions, opts.target_name,
no_game_data=opts.no_game_data,
)
packs = _pack_archives(output_dir)
if opts.built is not None:
packs = [name for name in packs if name in set(opts.built)]
pack_to_platform: dict[str, list[str]] = {}
for name in packs:
for pname in registered:
if name in expected[pname]:
pack_to_platform.setdefault(name, []).append(pname)
failing: list[str] = []
for name in packs:
zip_path = os.path.join(output_dir, name)
# Stage 1: database integrity
ok, manifest = verify_pack(zip_path, db, data_registry=opts.data_registry)
summary = manifest["summary"]
status = "OK" if ok else "ERRORS"
print(
f" verify {name}: {summary['verified']}/{summary['total_files']} verified, "
f"{summary['untracked']} untracked, {summary['errors']} errors [{status}]"
)
if not ok:
for err in manifest["errors"]:
print(f" ERROR: {err}")
all_ok = False
failing.append(name)
annotate_pack_systems(manifest, (opts.pack_systems_by_name or {}).get(name))
inject_manifest(zip_path, manifest)
# Stage 2: platform conformance (extract + verify)
# Skipped for filtered/split/custom packs (intentionally partial)
if opts.skip_conformance:
continue
if _narrows_contents(name):
continue
for pname in pack_to_platform.get(name, []):
if not _conforms(zip_path, pname, db, opts):
all_ok = False
failing.append(f"{name} ({pname})")
generate_sha256sums(output_dir)
if failing:
# Named at the end, where a 4,000-line log is read, and on stderr.
print(f"ERROR: packs failed verification: {', '.join(failing)}", file=sys.stderr)
return all_ok
+703
View File
@@ -0,0 +1,703 @@
"""Files the cores load that a platform does not declare, and why some are left out."""
from __future__ import annotations
import functools
from collections.abc import Callable, Mapping
from dataclasses import dataclass, field
from model.alternatives import set_fields, set_keys, set_requirements, settle_sets
from model.declarations import OUTER_ROOTS, platform_declarations, platform_declared_contents
from model.profiles import PROFILE_IDENTITY_FIELDS, entry_system_ids, load_emulator_profiles
from packs.paths import core_save_folder
from resolve.archives import archive_entry, archive_members
from resolve.cores import resolve_platform_cores
from resolve.directories import expand_directory_entries
from resolve.launchers import LauncherLayer, declared_destinations, held_record
from resolve.layout import runs_standalone, system_dir_path
from resolve.localfile import resolve_local_file
from resolve.nativemode import hash_mismatch_excludes_file
from resolve.ownership import _foreign_tree, _owner_tokens
from resolve.standalone import platform_layouts, standalone_set as platform_standalone_set
from resolve.validation import (
_parse_validation,
case_folded_slots,
core_size_refusal,
declaration_settles,
installed_with_emulator,
outside_gap_scope,
read_from_save_dir,
same_slot_entries,
unread_on,
with_archive_members,
)
def _build_expected(file_entry: dict, checks: list[str]) -> dict:
"""Extract expected validation values from an emulator profile file entry."""
expected: dict = {}
if not checks:
return expected
if "size" in checks:
for key in ("size", "min_size", "max_size", "size_multiple"):
if file_entry.get(key) is not None:
expected[key] = file_entry[key]
for hash_type in ("crc32", "md5", "sha1", "sha256"):
if hash_type in checks and file_entry.get(hash_type):
expected[hash_type] = file_entry[hash_type]
adler_val = file_entry.get("known_hash_adler32") or file_entry.get("adler32")
if adler_val:
expected["adler32"] = adler_val
return expected
def _in_foreign_tree(db: dict, owners: set[str], sha1: str) -> bool:
"""Whether the collection keeps this sha1 in another emulator's tree."""
return _foreign_tree(db.get("files", {}).get(sha1, {}).get("path", ""), owners)
def _name_in_index(
name: str,
by_name: dict,
by_path_suffix: dict | None = None,
data_names: set[str] | None = None,
by_name_lower: dict[str, str] | None = None,
foreign: Callable[[str], bool] | None = None,
) -> bool:
"""Check if a name is resolvable in the database indexes or data directories.
*foreign* tells a copy in another emulator's tree from the sha1 of a
name: matched in another casing, such a copy is not the asker's, as in
resolve_local_file's case-insensitive step.
"""
# Strip trailing slash for directory-type entries (e.g. nestopia/samples/foo/)
name = name.rstrip("/")
if name in by_name:
return True
basename = name.rsplit("/", 1)[-1] if "/" in name else name
if basename != name and basename in by_name:
return True
if by_name_lower:
for key in {name.lower(), basename.lower()}:
if key in by_name_lower and not (
foreign and all(foreign(s) for s in by_name[by_name_lower[key]])
):
return True
if by_path_suffix and name in by_path_suffix:
return True
if data_names:
if name in data_names or name.lower() in data_names:
return True
if basename != name and (
basename in data_names or basename.lower() in data_names
):
return True
return False
def _candidate_verdict(
file_entry: dict,
fname: str,
is_standalone: bool,
include_all: bool,
declared_names: Mapping[str, list[tuple[int | None, str]]] | set[str],
dest: str = "",
folded_slots: frozenset[str] = frozenset(),
declared_contents: Mapping[str, set[str]] | None = None,
) -> str:
"""Whether a profile entry can be a gap, and whether it is settled.
Three answers. "keep" means it is a candidate. "settled" means something
has answered for it (the platform declares it, or the profile documents
it as unsourceable), so the same requirement reached from another profile
must not be reconsidered. "skip" means it does not apply in this context,
which leaves it open for a profile where it does: the same file can be
libretro-only here and standalone-only there.
"""
if file_entry.get("unsourceable"):
return "settled"
if outside_gap_scope(file_entry, is_standalone):
return "skip"
if not include_all and declaration_settles(
file_entry, fname, declared_names, dest, folded_slots, declared_contents
):
return "settled"
return "keep"
def _identity_of(entry: dict) -> dict:
"""The fields that tell a profile's file apart from a same-named one."""
return {
field: entry.get(field)
for field in PROFILE_IDENTITY_FIELDS
if entry.get(field) not in (None, "", [])
}
def _gap_destination(f: dict, fname: str, is_standalone: bool, save_root: bool) -> str:
"""The destination a gap entry is keyed and reported at."""
# One destination rule for the dedup key and for the entry: a
# standalone build without standalone_path falls back on path.
# The key used to skip that fallback, so clk's Acorn/basic.rom and
# Electron/basic.rom both keyed as "basic.rom" under Batocera's
# standalone clk and the second was dropped.
# A file the libretro build reads below the save directory is
# placed there, apart from the system directory the platform
# lays out: no declaration of the BIOS tree answers for it.
if is_standalone:
return f.get("standalone_path") or f.get("path") or fname
if save_root:
return f.get("path") or fname
return system_dir_path(f, f.get("path") or fname)
def _region_key(f: dict) -> tuple[str, ...]:
raw_regions = f.get("region") or []
return tuple(
str(value) for value in (
raw_regions if isinstance(raw_regions, list) else [raw_regions]
)
)
SetRecord = tuple[tuple, dict, bool, "tuple[dict, dict | None] | None"]
@dataclass
class _GapScan:
"""What find_undeclared_files reads and gathers while it walks the cores."""
config: dict
db: dict
data_names: set[str] | None
include_all: bool
declared_names: Mapping[str, list[tuple[int | None, str]]]
folded_slots: frozenset[str]
declared_contents: Mapping[str, set[str]]
# Whether the builder drops a file whose local copy contradicts its
# declared hash, which decides if such a copy counts as held here.
shipped_on_mismatch: bool
launcher_layer: LauncherLayer
by_name: dict = field(init=False)
by_name_lower: dict[str, str] = field(init=False)
by_path_suffix: dict = field(init=False)
launcher_candidates: list[tuple[str, bool, dict, dict]] = field(default_factory=list)
# Each grouped requirement met, as (set keys, entry, fills, (reported
# entry, the entry it is a claim on)): settled once every core is read.
set_records: list[SetRecord] = field(default_factory=list)
undeclared: list[dict] = field(default_factory=list)
seen_files: set[tuple] = field(default_factory=set)
# Key -> the entry reported for it. A later profile reading the same
# requirement is kept on that entry rather than counted again: a pack
# built without the first profile still has to name the file.
reported: dict[tuple, dict] = field(default_factory=dict)
# Track archives: archive_name -> {in_repo, emulator, files: [...], ...}
archive_entries: dict[tuple, dict] = field(default_factory=dict)
def __post_init__(self) -> None:
self.by_name = self.db.get("indexes", {}).get("by_name", {})
self.by_name_lower = {k.lower(): k for k in self.by_name}
self.by_path_suffix = self.db.get("indexes", {}).get("by_path_suffix", {})
def scan_file(self, emu_name: str, layout: dict, is_standalone: bool, f: dict) -> None:
"""Consider one profile entry of one build as a gap."""
fname = f.get("name", "")
save_root = read_from_save_dir(f, is_standalone)
dest = _gap_destination(f, fname, is_standalone, save_root)
region_key = _region_key(f)
# Same-name requirements at different paths, for different systems,
# or in distinct variant groups are not interchangeable.
seen_key = (
fname,
f.get("archive"),
dest,
f.get("system"),
f.get("selection_slot"),
region_key,
# Below the save directory each core is handed a folder
# of its own: two cores reading hiscore.dat there read
# two files.
("save", core_save_folder(layout)) if save_root
else (f["root"],) if f.get("root") in OUTER_ROOTS
# In the emulator's own folder: no other core reads it.
else ("emulator", emu_name) if f.get("unplaced") else None,
)
config = self.config
if not fname or unread_on(f, config.get("_key", "")):
return
first = self.reported.get(seen_key)
duplicate = seen_key in self.seen_files
if duplicate and (first is None or first["profile"] == emu_name):
return
outer = save_root or f.get("root") in OUTER_ROOTS
# Nor does it answer for one read below the roms directory.
verdict = _candidate_verdict(
f, fname, is_standalone, self.include_all,
{} if outer else self.declared_names,
dest, self.folded_slots,
None if outer else self.declared_contents,
)
if verdict == "settled":
self.seen_files.add(seen_key)
if (self.launcher_layer and not f.get("unsourceable") and not outer
and not f.get("unplaced")):
self.launcher_layer.declared_elsewhere(emu_name, is_standalone, f)
# Answered by the platform's own declaration, which its
# report covers: the set it belongs to is spoken for.
self.set_records.append((set_keys((emu_name, is_standalone), f), f, True, None))
return
if verdict == "skip":
return
archive = f.get("archive")
self.seen_files.add(seen_key)
if archive:
self._count_archive_member(emu_name, layout, is_standalone, f, region_key)
return
in_repo = self._held(emu_name, layout, f, fname, dest)
entry = self._gap_entry(emu_name, layout, f, fname, dest, in_repo, save_root)
if self.launcher_layer and not outer:
# One read outside the BIOS tree is still served where a
# launcher links that very file: RetroDECK links Cemu's
# keys.txt to bios/cemu/keys.txt.
self.launcher_candidates.append((emu_name, is_standalone, f, entry))
keys = set_keys((emu_name, is_standalone), f)
if duplicate and first is not None:
first.setdefault("other_claims", []).append(entry)
self.set_records.append((keys, f, in_repo, (entry, first)))
return
self.reported[seen_key] = entry
self.undeclared.append(entry)
self.set_records.append((keys, f, in_repo, (entry, None)))
def _count_archive_member(
self, emu_name: str, layout: dict, is_standalone: bool, f: dict,
region_key: tuple[str, ...],
) -> None:
archive = f["archive"]
archive_key = (
archive,
f.get("system_dir"),
f.get("system"),
f.get("selection_slot"),
region_key,
is_standalone,
)
if archive_key not in self.archive_entries:
in_repo = _name_in_index(
archive, self.by_name, self.by_path_suffix, self.data_names,
self.by_name_lower,
)
self.archive_entries[archive_key] = {
"profile": emu_name,
"emulator": layout.get("emulator", emu_name),
"systems": entry_system_ids(f, layout),
"system": f.get("system"),
"region": f.get("region"),
"selection_slot": f.get("selection_slot"),
"name": archive,
"archive": archive,
"path": system_dir_path(f, archive),
"required": False,
"hle_fallback": False,
"category": f.get("category", "bios"),
"in_repo": in_repo,
"note": "",
"checks": [],
"source_ref": None,
"expected": {},
"archive_file_count": 0,
"archive_required_count": 0,
"members": archive_members(archive, layout.get("files", [])),
}
if f.get("system_dir"):
self.archive_entries[archive_key]["system_dir"] = f["system_dir"]
# The archive's own declaration names its sets: an
# archive is a member like a loose file.
own = archive_entry(archive, layout.get("files", []))
self.archive_entries[archive_key].update(set_fields(own, layout))
self.set_records.append((
set_keys((emu_name, is_standalone), own), own, in_repo,
(self.archive_entries[archive_key], None),
))
entry = self.archive_entries[archive_key]
entry["archive_file_count"] += 1
if f.get("required", False):
entry["archive_required_count"] += 1
entry["required"] = True
def _held(self, emu_name: str, layout: dict, f: dict, fname: str, dest: str) -> bool:
"""Whether the collection holds the file as the builder would ship it."""
# Resolution: name, then path basename
# storage: release names where the bytes are served from, not
# that the collection holds them: resolved like any file.
# Resolved as the asker, as the builder's ExtraResolver does:
# another casing of the name in another emulator's tree is
# not this emulator's file (dosbox-x's et4000.bin and pcem's
# et4000.BIN).
owned = {**f, "source_profile": emu_name}
if self.shipped_on_mismatch and (f.get("md5") or f.get("sha1")):
# The entry states what its content should be and the builder
# drops a copy that contradicts it, so content decides here
# too. A name match would not do: generic names collide across
# systems, and answering yes on one describes a pack that will
# not contain the file.
_lp, _st = resolve_local_file(owned, self.db, dest_hint=dest)
return _lp is not None and _st != "hash_mismatch"
in_repo = self._held_by_name(owned, f, fname, dest)
if in_repo and "size" in _parse_validation(f.get("validation")):
# On any platform the core measures what it opens: a
# copy it turns away by its own size check is not
# held for it, the rule the builder's lookup applies
# (packextras.ExtraResolver). The Apple IIGS' 128 KB
# ROM is not Basilisk II's ROM.
_lp, _st = resolve_local_file(owned, self.db, dest_hint=dest)
if core_size_refusal(
f, _lp, same_slot_entries(layout.get("files"), fname, dest)
):
in_repo = False
return in_repo
def _held_by_name(self, owned: dict, f: dict, fname: str, dest: str) -> bool:
foreign = functools.partial(_in_foreign_tree, self.db, _owner_tokens(owned))
in_repo = _name_in_index(
fname, self.by_name, self.by_path_suffix, self.data_names, self.by_name_lower,
foreign,
)
if not in_repo and dest != fname:
path_base = dest.rsplit("/", 1)[-1]
in_repo = _name_in_index(
path_base, self.by_name, self.by_path_suffix, self.data_names,
self.by_name_lower, foreign,
)
if in_repo and not any(
f.get(h) for h in ("sha1", "md5", "crc32", "sha256")
):
# A name alone answers nothing when every copy of that
# name fails the size the code checks: the resolver
# rejects them all. NanoBoyAdvance's 16 KB bios.bin met
# only PCem's and QEMU's PC BIOS images of that name.
# The fallback below then decides as for any mismatch.
_lp, _st = resolve_local_file(owned, self.db, dest_hint=dest)
if _st == "hash_mismatch":
in_repo = False
if not in_repo:
# Hash fallback: the repo may hold the content under a
# different filename (exos21.rom vs exos21.bin).
#
# A copy contradicting the declared hash counts as held
# only where the builder would ship it. Under existence
# the frontend never opens the file, so the pack carries
# it and reports the divergence. Under a digest mode the
# frontend would reject it, the builder leaves it out, and
# calling it available here would describe a pack that
# does not contain it.
_lp, _st = resolve_local_file(owned, self.db, dest_hint=dest)
in_repo = _st != "not_found" and _lp is not None
if in_repo and _st == "hash_mismatch" and self.shipped_on_mismatch:
in_repo = False
return in_repo
def _gap_entry(
self, emu_name: str, layout: dict, f: dict, fname: str, dest: str,
in_repo: bool, save_root: bool,
) -> dict:
checks = _parse_validation(f.get("validation"))
entry = {
"profile": emu_name,
"emulator": layout.get("emulator", emu_name),
"systems": entry_system_ids(f, layout),
"system": f.get("system"),
"region": f.get("region"),
"selection_slot": f.get("selection_slot"),
"name": fname,
"path": dest,
"required": f.get("required", False),
"hle_fallback": f.get("hle_fallback", False),
"bundled": installed_with_emulator(f, self.config.get("_key", "")),
"category": f.get("category", "bios"),
"in_repo": in_repo,
"note": f.get("note", ""),
"checks": sorted(checks) if checks else [],
**set_fields(f, layout),
"source_ref": f.get("source_ref"),
"expected": _build_expected(f, checks),
**_identity_of(f),
"sha1": f.get("sha1"),
"md5": f.get("md5"),
}
if f.get("contents"):
entry["contents"] = f["contents"]
if save_root:
entry["root"] = "save"
folder = core_save_folder(layout)
if folder is not None:
entry["core_folder"] = folder
elif f.get("system_dir"):
entry["system_dir"] = f["system_dir"]
members = with_archive_members(f, layout.get("files", [])).get("members")
if members:
entry["members"] = members
if f.get("layout_path"):
entry["layout_path"] = f["layout_path"]
if f.get("unprefixed"):
entry["unprefixed"] = True
if f.get("unplaced"):
entry["unplaced"] = f["unplaced"]
elif f.get("root") in OUTER_ROOTS:
# Read below the roms directory (ROCKNIX's roms/pico-8)
# or in an emulator folder (RetroBat's emulators/pico8).
entry["root"] = f["root"]
return entry
def find_undeclared_files(
config: dict,
emulators_dir: str,
db: dict,
emu_profiles: dict | None = None,
target_cores: set[str] | None = None,
data_names: set[str] | None = None,
include_all: bool = False,
declared_names: Mapping[str, list[tuple[int | None, str]]] | None = None,
) -> list[dict]:
"""Find files needed by cores but not declared in platform config.
declared_names overrides the default enriched declarations from
platform_declarations. Pass the strict ones (YAML names only) when
building packs so alias-only names still get packed.
"""
if declared_names is None:
declared_names = platform_declarations(config, db)
folded_slots = case_folded_slots(config, declared_names)
declared_contents = platform_declared_contents(config, db)
profiles = (
emu_profiles
if emu_profiles is not None
else load_emulator_profiles(emulators_dir)
)
relevant = resolve_platform_cores(config, profiles, target_cores=target_cores)
standalone_set = platform_standalone_set(config)
# What the platform's own launchers open, matched to the cores it runs:
# the one decision the builder and this report both read.
launcher_layer = LauncherLayer(
config, profiles, relevant, db, declared_destinations(config)
)
scan = _GapScan(
config, db, data_names, include_all, declared_names, folded_slots,
declared_contents,
hash_mismatch_excludes_file(config.get("verification_mode")),
launcher_layer,
)
for emu_name, profile in sorted(profiles.items()):
if profile.get("type") in ("launcher", "alias"):
continue
if emu_name not in relevant:
continue
# A filename-agnostic profile is served by the scan (packextras), all
# but the entries its layout reads outside the BIOS tree: those are
# named here, or a launcher folder drops them without a word
# (ARMSX2's arcade/proverb.zip once ROCKNIX binds bios/armsx2).
agnostic = profile.get("bios_mode") == "agnostic"
for layout, is_standalone in platform_layouts(emu_name, profile, standalone_set):
for f in expand_directory_entries(
layout.get("files", []), db, is_standalone
):
if agnostic and not f.get("unplaced"):
continue
scan.scan_file(emu_name, layout, is_standalone, f)
undeclared = scan.undeclared
settled: set[int] = set()
if launcher_layer:
added, settled = launcher_layer.settle(
scan.launcher_candidates, lambda report: held_record(report, db)
)
undeclared = [u for u in undeclared if id(u) not in settled]
undeclared.extend(added)
undeclared.extend(sorted(scan.archive_entries.values(), key=lambda e: e["name"]))
return _split_bundled_claims(
_settle_core_sets(undeclared, scan.set_records, settled, profiles)
)
def _split_bundled_claims(undeclared: list[dict]) -> list[dict]:
"""A file one emulator installs itself, another reads from the pack.
The first profile reading a requirement hosts the claims of the others,
and a host installed with its emulator is left out of the pack with all
of them: DraStic brings its own usrcheat.dat, and ROCKNIX's DSPerate,
which reads the same file, lost it wherever DraStic runs too. Built for
a board without DraStic, the pack carried it.
"""
out: list[dict] = []
for entry in undeclared:
claims = entry.get("other_claims") or []
rest = [c for c in claims if not c.get("bundled")]
if not entry.get("bundled") or not rest:
out.append(entry)
continue
own = [c for c in claims if c.get("bundled")]
kept = {k: v for k, v in entry.items() if k != "other_claims"}
if own:
kept["other_claims"] = own
promoted = dict(rest[0])
if rest[1:]:
promoted["other_claims"] = rest[1:]
out += [kept, promoted]
return out
def _settle_core_sets(
undeclared: list[dict],
records: list[tuple[tuple, dict, bool, tuple[dict, dict | None] | None]],
launcher_settled: set[int],
profiles: dict[str, dict],
) -> list[dict]:
"""The core complement with each set of alternatives settled.
A member the collection lacks is dropped when another member is held,
declared by the platform or placed by its launcher, and a set nobody
holds keeps one entry, its first member, naming the others. A claim
another profile shares stays: its own core may need that very file.
"""
# Archive units rank first among equals, as the builder orders them.
grouped = sorted(
(r for r in records if r[0]),
key=lambda r: not (r[3] is not None and r[3][0].get("archive")),
)
if not grouped:
return undeclared
excused, standing = settle_sets([
(keys, f, fills or (ref is not None and id(ref[0]) in launcher_settled))
for keys, f, fills, ref in grouped
], lambda key: set_requirements(profiles.get(key[0][0], {})).get(key[1], True))
declared_sets = {
key for keys, _f, _fills, ref in grouped if ref is None for key in keys
}
dropped: set[int] = set()
for position, (keys, _f, _fills, ref) in enumerate(grouped):
if ref is None:
continue
entry, host = ref
required_keys = [k for k in keys if k[1] in entry.get("required_groups", ())]
if required_keys and all(k in declared_sets for k in required_keys):
# The platform declares a member of each of its required sets:
# under --required-only that declaration carries them.
entry["set_declared"] = True
if position in standing:
entry["alternatives"] = standing[position].others
entry["required"] = standing[position].required
if position not in excused:
continue
if host is not None:
host["other_claims"] = [c for c in host.get("other_claims", []) if c is not entry]
if not host["other_claims"]:
del host["other_claims"]
else:
dropped.add(id(entry))
out: list[dict] = []
for entry in undeclared:
if id(entry) not in dropped:
out.append(entry)
continue
# Another core reading the same requirement still needs it.
claims = entry.get("other_claims") or []
if claims:
promoted = dict(claims[0])
if claims[1:]:
promoted["other_claims"] = claims[1:]
out.append(promoted)
return out
def find_exclusion_notes(
config: dict,
emulators_dir: str,
emu_profiles: dict | None = None,
target_cores: set[str] | None = None,
) -> list[dict]:
"""Document why certain emulator files are intentionally excluded.
Reports:
- Launchers (BIOS managed by standalone emulator)
- Standalone-only files (not needed in libretro mode)
- Frozen snapshots with files: [] (code doesn't load .info firmware)
- Files covered by data_directories
"""
profiles = (
emu_profiles
if emu_profiles is not None
else load_emulator_profiles(emulators_dir)
)
platform_systems = set()
for sys_id in config.get("systems", {}):
platform_systems.add(sys_id)
relevant = resolve_platform_cores(config, profiles, target_cores=target_cores)
notes = []
for emu_name, profile in sorted(profiles.items()):
emu_systems = set(profile.get("systems", []))
# Match by core resolution OR system intersection (documents all potential emulators)
if emu_name not in relevant and not (emu_systems & platform_systems):
continue
emu_display = profile.get("emulator", emu_name)
if profile.get("type") == "launcher":
notes.append(
{
"emulator": emu_display,
"reason": "launcher",
"detail": profile.get(
"exclusion_note", "BIOS managed by standalone emulator"
),
}
)
continue
# Profile-level exclusion note (frozen snapshots, etc.)
exclusion_note = profile.get("exclusion_note")
if exclusion_note:
notes.append(
{
"emulator": emu_display,
"reason": "exclusion_note",
"detail": exclusion_note,
}
)
continue
# Count standalone-only files, but only report as excluded if the
# platform does NOT use this emulator in standalone mode
standalone_set = platform_standalone_set(config)
is_standalone = runs_standalone(emu_name, profile, standalone_set)
if not is_standalone:
standalone_files = [
f for f in profile.get("files", []) if f.get("mode") == "standalone"
]
if standalone_files:
names = [f["name"] for f in standalone_files[:3]]
more = (
f" +{len(standalone_files) - 3}"
if len(standalone_files) > 3
else ""
)
notes.append(
{
"emulator": emu_display,
"reason": "standalone_only",
"detail": f"{len(standalone_files)} files for standalone mode only ({', '.join(names)}{more})",
}
)
return notes
@@ -10,9 +10,9 @@ from collections import Counter
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, TypedDict
from verify import DEFAULT_BIOS_DIR
from packs.verdicts import DEFAULT_BIOS_DIR
from core.artifacts import _build_timestamp
from packpaths import MEDIA_MARKER, _has_path_conflict
from packs.paths import MEDIA_MARKER, _has_path_conflict
from core.ziptools import build_zip_contents_index
from core.ziptools import check_inside_zip
from resolve.nativemode import digest_algorithm
@@ -28,12 +28,12 @@ import io
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
import os
from packextras import platform_region_groups
from packpaths import _flat
from packs.extras import platform_region_groups
from packs.paths import _flat
from resolve.nativemode import reads_file_contents
from resolve import regions as resolve_regions
import slots
from packresolve import resolve_declaration, resolve_file
from packs import slots
from resolve.packfiles import resolve_declaration, resolve_file
from resolve.categories import BIOS, EntryCategories
from resolve.gamedata import without_game_data
from resolve.cores import resolve_platform_cores
@@ -615,7 +615,7 @@ def _builder_extras(
refuses, is left free, since the builder then places a core's file
there: taken by the refused file, that core file was never compared.
"""
from packextras import ExtraResolver, hidden_extras
from packs.extras import ExtraResolver, hidden_extras
from resolve.validation import _build_validation_index, destination_owners
config, emu_profiles = expect.config, expect.emu_profiles
+868
View File
@@ -0,0 +1,868 @@
"""The install manifest of a platform."""
from __future__ import annotations
import contextlib
import io
import os
from collections.abc import Callable, Iterator
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, TypedDict
from core.artifacts import _build_timestamp
from core.paths import REPO_ROOT, sanitize_pack_path
from model.declarations import OUTER_ROOTS, declared_root, outer_layout
from model.platforms import load_platform_config
from model.profiles import load_emulator_profiles
from model.registry import load_data_dir_registry
from model.safeparse import yaml_load
from model.systems import platform_system_names
from packs import slots
from packs.archive import CASE_FOLDING_OS, PACK_DOCUMENTS, _Placed, _reject_unknown
from packs.datatrees import (
_data_directory_members,
_in_data_cache,
_manifest_data_directories,
core_data_trees,
pack_markers,
tree_readers,
)
from packs.extras import (
_collect_emulator_extras,
extra_region_key,
save_entry_fields,
save_manifest_dest,
undeclared_report,
)
from packs.manifestcores import (
_downloaded_cores,
_manifest_core_entries,
_manifest_core_index,
_manifest_selection,
_offered_boards,
)
from packs.manifestentry import (
MANIFEST_OUTER_FIELDS,
_ClaimContext,
_attach_claims,
_manifest_dest_of,
_manifest_entry,
_record_absent,
_record_slot_choices,
_record_unplaceable,
)
from packs.manifestselect import SelectionIndex
from packs.paths import save_layout
from packs.scope import platform_list_version, system_titles
from packs.standalone import _standalone_copies, _standalone_layouts
from resolve.contentlayout import TARGET_KEY
from resolve.cores import filter_systems_by_target, resolve_platform_cores as _platform_cores
from resolve.gamedata import GAME_DATA, is_game_data, platform_game_data, without_game_data
from resolve.nativemode import digest_algorithm, reads_file_contents
from resolve.packfiles import preferred_entries as _preferred_entries, resolve_declaration
from resolve.validation import (
_build_validation_index,
agnostic_substitute,
baseline_verdict,
destination_owners,
validated_choice,
)
if TYPE_CHECKING:
from typing_extensions import Unpack
if TYPE_CHECKING:
# How a manifest settles a platform declaration: the copy served, or None
# and why not.
_Settle = Callable[[dict, str, str, "str | None"], "tuple[str | None, str]"]
class InstallListOptions(TypedDict, total=False):
"""The keyword options of generate_install_list, which it hands to
generate_manifest."""
emulators_dir: str
zip_contents: dict | None
emu_profiles: dict | None
target_cores: set[str] | None
source: str
regions: list[str] | None
target_name: str | None
offline: bool | None
required_only: bool
data_registry: dict | None
fold_case: bool | None
no_game_data: bool
one_per_slot: bool
class ManifestOptions(InstallListOptions, total=False):
"""The keyword options of generate_manifest."""
known_slot_choices: dict | None
build_out: dict | None
@dataclass(frozen=True)
class _ManifestSettings:
"""ManifestOptions with their defaults."""
emulators_dir: str = "emulators"
zip_contents: dict | None = None
emu_profiles: dict | None = None
target_cores: set[str] | None = None
source: str = "full"
regions: list[str] | None = None
target_name: str | None = None
offline: bool | None = None
required_only: bool = False
data_registry: dict | None = None
fold_case: bool | None = None
no_game_data: bool = False
one_per_slot: bool = False
known_slot_choices: dict | None = None
build_out: dict | None = None
@dataclass
class _ManifestBuild:
"""One install manifest being listed: its files, omissions and the slots
they take, settled by the rules the pack builder follows."""
platform_name: str
platforms_dir: str
db: dict
bios_dir: str
opts: _ManifestSettings
config: dict
emu_profiles: dict
zip_contents: dict
data_registry: dict
game_entries: set[int]
install_section: dict
repo_root: str
pack_systems: dict
manifest_profiles: dict = field(default_factory=dict)
manifest_validation: dict = field(default_factory=dict)
manifest_owners: dict = field(default_factory=dict)
game_destinations: set[str] = field(default_factory=set)
placed: _Placed = field(init=False)
# Destination -> (entry, full destination, manifest destination) of each
# platform file, for the core claims a target build would fall back on.
platform_entries: dict[str, tuple[dict, str, str]] = field(default_factory=dict)
# Full destination -> the platform systems declaring it. A file's
# `systems` also names the systems whose cores read it there. A pack built
# for a target keeps the file only while a declaring system stays.
declared_by: dict[str, set[str]] = field(default_factory=dict)
manifest_files: list[dict] = field(default_factory=list)
omitted_by_destination: dict[str, dict] = field(default_factory=dict)
total_size: int = 0
# Sizes of the files the pack carries and the installer cannot fetch: the
# collection does not index them, a data directory cache answered.
pack_only_sizes: list[int] = field(default_factory=list)
# Platform entries resolved into a data directory cache: destination ->
# (cache file, size). Settled once the trees are walked.
cache_held: dict[str, tuple[str, int]] = field(default_factory=dict)
rename_notes: set[str] = field(default_factory=set)
slot_choices: dict = field(default_factory=dict)
slot_overrides: dict[str, str] = field(default_factory=dict)
undeclared: list[dict] | None = None
region_drops: set[str] = field(default_factory=set)
selection: SelectionIndex | None = None
builder_held: set[str] = field(default_factory=set)
declarations: dict[str, dict[str, list[dict]]] = field(default_factory=dict)
data_members: list[tuple[str, str]] = field(default_factory=list)
data_directories: list[dict] = field(default_factory=list)
def __post_init__(self) -> None:
self.placed = _Placed(self.case_insensitive)
@property
def base_dest(self) -> str:
return self.config.get("base_destination", "")
@property
def case_insensitive(self) -> bool:
return self.config.get("case_insensitive_fs", False)
@property
def verification_mode(self) -> str:
return self.config.get("verification_mode", "existence")
@property
def fields(self) -> SelectionIndex:
assert self.selection is not None
return self.selection
def manifest_destination(self, full_destination: str) -> str:
return _manifest_dest_of(full_destination, self.base_dest)
def record_omission(
self,
full_destination: str,
file_entry: dict,
system_id: str,
reason: str,
cores: list[str] | None,
) -> None:
# A core extra (cores given) is keyed as the region pass keys it.
bare = (
sanitize_pack_path(file_entry.get("destination", file_entry.get("name", "")))
if cores is None else extra_region_key(file_entry, declared_root(self.config))
)
self.omitted_by_destination[full_destination] = {
**self._omission_dest(full_destination, file_entry),
"name": str(file_entry.get("name") or ""),
"system": system_id,
"required": bool(file_entry.get("required", True)),
"reason": reason,
"cores": cores,
# An omission keeps its region groups, as the builder groups it:
# a requested file the collection lacks answers the request
# without displacing a held fallback (resolve_region_drops,
# held). One the builder holds and the installer cannot fetch
# does displace it in the pack, so it says so, and the installer
# drops the same fallback.
**self.fields.fields(bare, str(file_entry.get("name") or "")),
**({"held": True} if bare in self.builder_held else {}),
**(
{"category": GAME_DATA}
if (bare in self.game_destinations if cores is None else is_game_data(file_entry))
else {}
),
}
def _omission_dest(self, full_destination: str, file_entry: dict) -> dict:
# Read in the emulator's own folder, outside the BIOS tree: dest is
# the path the emulator reads, relative to that folder.
if file_entry.get("unplaced"):
return {"dest": sanitize_pack_path(file_entry.get("path") or ""),
"root": "emulator"}
if file_entry.get("root") in OUTER_ROOTS:
return {"dest": sanitize_pack_path(
file_entry.get("destination") or file_entry.get("path") or ""
), "root": file_entry["root"]}
if file_entry.get("root") == "save":
return {"dest": save_manifest_dest(file_entry), **save_entry_fields(file_entry)}
return {"dest": self.manifest_destination(full_destination)}
def kept_declarations(self) -> Iterator[tuple[str, dict, str, str]]:
"""(system, entry, destination, full destination) of each platform
declaration this manifest keeps, in the builder's order."""
opts = self.opts
for sys_id, system in sorted(self.pack_systems.items()):
for file_entry in system.get("files", []):
if opts.required_only and file_entry.get("required") is False:
continue
dest = sanitize_pack_path(file_entry.get("destination", file_entry["name"]))
if not dest:
continue
if self.region_drops and dest in self.region_drops:
continue
full_dest = f"{self.base_dest}/{dest}" if self.base_dest else dest
yield sys_id, file_entry, dest, full_dest
def declaration_order(self, full_dest: str) -> list[tuple[list[str], dict, str]]:
"""The declarations answering a destination as its systems drop.
A pack built for a target loses the systems no available core
reads, and the next declaration takes the destination by the
same rule: RetroArch's bare nintendo-ds dsi_bios9.bin once the
pinned nintendo-dsi one is gone.
"""
remaining = dict(self.declarations.get(full_dest, {}))
order: list[tuple[list[str], dict, str]] = []
while remaining:
winner = _preferred_entries(
{sid: {"files": fes} for sid, fes in remaining.items()},
self.db, self.bios_dir, self.base_dest, self.opts.required_only,
self.zip_contents, self.opts.offline,
).get(full_dest)
first_sys, first = next(
(sid, fe) for sid, fes in sorted(remaining.items()) for fe in fes
if winner is None or id(fe) == winner
)
systems = sorted(
sid for sid, fes in remaining.items()
if any(fe is first for fe in fes)
)
order.append((systems, first, first_sys))
for sid in systems:
del remaining[sid]
return order
def list_baseline(self, settle: _Settle) -> None:
"""Phase 1: the platform's own files."""
# The same destination can be declared by more than one system, bare
# in one and hash-constrained in another. The builder lets the
# constrained sibling claim it. Without the same rule here the
# manifest named whatever answered to the name, so the pack and the
# installer disagreed about which file a destination means.
# Decided among the declarations this manifest keeps, as the pack
# does. A manifest carries no data directories.
preferred_entries = _preferred_entries(
self.pack_systems, self.db, self.bios_dir, self.base_dest,
self.opts.required_only, self.zip_contents, self.opts.offline,
)
for sys_id, file_entry, _dest, full_dest in self.kept_declarations():
self.declarations.setdefault(full_dest, {}).setdefault(sys_id, []).append(
file_entry
)
for sys_id, file_entry, dest, full_dest in self.kept_declarations():
self.declared_by.setdefault(full_dest, set()).add(sys_id)
preferred = preferred_entries.get(full_dest)
if preferred is not None and id(file_entry) != preferred:
continue
if self.placed.holds(full_dest) or self.placed.conflicts(full_dest):
continue
if file_entry.get("storage", "embedded") == "user_provided":
self._list_instructions(file_entry, sys_id, full_dest)
continue
local_path, status = settle(
file_entry, sys_id, dest, self.slot_overrides.get(full_dest)
)
if local_path is None:
self.record_omission(full_dest, file_entry, sys_id, status, None)
continue
self._list_declared(file_entry, sys_id, dest, full_dest, local_path, settle)
def _list_instructions(self, file_entry: dict, sys_id: str, full_dest: str) -> None:
self.record_omission(
full_dest,
file_entry,
sys_id,
"user_provided",
None,
)
# The pack writes the instructions in the slot's place
# and holds it: one more member than the files listed.
instructions = file_entry.get(
"instructions", "Please provide this file manually."
)
self.pack_only_sizes.append(len(
f"File needed: {file_entry['name']}\n\n{instructions}\n".encode()
))
self.placed.take(full_dest)
def _list_declared(
self,
file_entry: dict,
sys_id: str,
dest: str,
full_dest: str,
local_path: str,
settle: _Settle,
) -> None:
entry, file_size = _manifest_entry(
local_path, dest, None, self.db, self.repo_root,
self.fields.fields(dest, file_entry["name"]),
)
if entry is not None and dest in self.game_destinations:
entry["category"] = GAME_DATA
if entry is not None and self.opts.target_cores is None:
order = self.declaration_order(full_dest)
if full_dest in self.slot_choices or len(order) > 1:
_record_slot_choices(
entry, self.slot_choices.get(full_dest, []), order,
settle, dest, self.db, self.repo_root,
)
if entry is None:
self.record_omission(full_dest, file_entry, sys_id, "not_found", None)
if file_size and full_dest not in self.placed.destinations:
if _in_data_cache(local_path, self.data_registry):
self.cache_held[full_dest] = (local_path, file_size)
else:
self.pack_only_sizes.append(file_size)
self.placed.take(full_dest)
return
self.manifest_files.append(entry)
self.platform_entries[full_dest] = (entry, full_dest, dest)
self.omitted_by_destination.pop(full_dest, None)
self.total_size += file_size
self.placed.take(full_dest)
def claim_context(self) -> _ClaimContext:
return _ClaimContext(
self.db, self.bios_dir, self.zip_contents, self.opts.offline,
self.opts.required_only, self.manifest_validation, self.manifest_owners,
self.repo_root, self.data_registry,
)
def list_core_files(self) -> None:
"""Phase 2: core complement (emulator extras)."""
opts = self.opts
unplaceable: list[dict] = []
baseline_claims: dict[str, dict] = {}
absent: list[dict] = []
if opts.source != "platform":
core_files = _collect_emulator_extras(
self.config,
opts.emulators_dir,
self.db,
self.placed.destinations,
self.base_dest,
self.emu_profiles,
target_cores=opts.target_cores,
include_all=(opts.source == "truth"),
unplaceable=unplaceable,
baseline_claims=baseline_claims,
absent=absent,
undeclared=self.undeclared,
)
else:
core_files = []
_record_unplaceable(unplaceable, self.record_omission, self.config, self.emu_profiles)
_record_absent(
absent, self.config, self.base_dest, self.region_drops, opts.required_only,
self.placed.destinations, self.omitted_by_destination, self.record_omission,
)
self.total_size += _manifest_core_entries(
core_files, self.config, self.db, self.bios_dir, self.base_dest, self.repo_root,
self.zip_contents, opts.offline,
region_drops=self.region_drops, case_insensitive=self.case_insensitive,
seen_destinations=self.placed.destinations, seen_lower=self.placed.lower,
seen_parents=self.placed.parents, manifest_files=self.manifest_files,
omitted_by_destination=self.omitted_by_destination,
record_omission=self.record_omission, pack_only_sizes=self.pack_only_sizes,
selection=self.fields, required_only=opts.required_only,
validation_index=self.manifest_validation, owners=self.manifest_owners,
data_registry=self.data_registry, profiles=self.emu_profiles,
)
self._settle_claims(baseline_claims)
def _settle_claims(self, baseline_claims: dict[str, dict]) -> None:
ctx = self.claim_context()
for key, (entry, full_dest, dest) in self.platform_entries.items():
declared = self.declared_by.get(full_dest, set())
if declared and declared != set(entry.get("systems") or []):
entry["declared_in"] = sorted(declared)
claims = baseline_claims.get(key, {}).get("other_claims")
if claims and any(not is_game_data(claim) for claim in claims):
# A core reads this path as firmware: a pack without game data
# still fills it.
entry.pop("category", None)
if claims:
_attach_claims(entry, claims, ctx, dest, dest)
# A platform omission narrows like a platform file: by the systems
# declaring it, which can be fewer than the ones whose cores read it.
for full_dest, omission in self.omitted_by_destination.items():
declared = self.declared_by.get(full_dest, set())
if (
omission.get("cores") is None
and declared
and declared != set(omission.get("systems") or [])
):
omission["declared_in"] = sorted(declared)
def list_data_directories(self) -> list[int]:
"""Phase 3: data directories, and the sizes the pack alone holds.
They are not files of the collection: the installer fetches each
from its source archive and keeps the members whose hash the list
below records, the same tree the pack carries.
"""
opts = self.opts
required_only = opts.required_only
data_refs: dict[str, tuple[str, tuple[str, ...], str, bool]] = {}
reclaim = {full: path for full, (path, _size) in self.cache_held.items()}
core_trees = ([] if opts.source == "platform"
else core_data_trees(self.config, self.emu_profiles, self.platform_name,
self.data_registry, opts.target_cores))
self.data_members = list(_data_directory_members(
self.pack_systems, self.data_registry, self.platform_name, self.base_dest,
self.case_insensitive, self.placed.destinations, self.placed.lower,
self.placed.parents, refs_out=data_refs, required_only=required_only,
core_trees=core_trees,
reclaim=reclaim,
))
# A platform entry found in a tree the pack carries is that tree's member:
# the installer rebuilds it from the tree's archive. One found in a tree
# the pack does not carry stays omitted, held by the pack alone.
for full_dest, (_path, size) in self.cache_held.items():
if full_dest in reclaim:
self.pack_only_sizes.append(size)
else:
self.omitted_by_destination.pop(full_dest, None)
self.data_directories = _manifest_data_directories(
self.data_members, data_refs, self.data_registry or {}, self.base_dest,
tree_readers(self.pack_systems, core_trees), self.pack_systems,
)
return self.pack_only_sizes + [os.path.getsize(src) for src, _dest in self.data_members]
def result(self, data_sizes: list[int]) -> dict:
opts, config, pack_systems = self.opts, self.config, self.pack_systems
manifest_files, platform_name = self.manifest_files, self.platform_name
omitted = self.omitted_by_destination
# The pack is unzipped into the BIOS folder: an entry the installer puts
# in the roms, emulators or configs folder is in its list, not in the ZIP.
outer = [e for e in manifest_files if e.get("root") in OUTER_ROOTS]
core_names, system_cores = _manifest_core_index(
config, self.emu_profiles, manifest_files, list(omitted.values())
)
result: dict = {
"manifest_version": 2,
"source": opts.source,
"regions": list(opts.regions or []),
# A target-filtered manifest is only distinguishable from the full one
# by its filename, so it records the filter the way regions does.
# Absent on an unfiltered manifest rather than empty, to leave the
# twelve default files byte-identical.
**({"target": opts.target_name} if opts.target_name else {}),
# Every game data file below says so: the installer's --no-game-data
# relies on it, and refuses a list that does not record categories.
"categorized": True,
# The entries a slot decides carry `slot`, which --one-per-slot
# reads: without this mark the installer refuses it.
"slot_fields": True,
**({"no_game_data": True} if opts.no_game_data else {}),
"platform": platform_name,
"display_name": config.get("platform", platform_name),
"version": platform_list_version(config, platform_name),
"generated": _build_timestamp(self.db),
"base_destination": self.base_dest,
"detect": self.install_section.get("detect", []),
"standalone_copies": _standalone_copies(
self.install_section.get("standalone_copies", []), self.manifest_profiles,
manifest_files,
),
"total_files": len(manifest_files),
"total_size": self.total_size,
"pack_files": (
len(manifest_files) - len(outer) + len(data_sizes) + len(PACK_DOCUMENTS)
+ len(self.rename_notes)
+ len(pack_markers(platform_name, opts.target_name, self.platforms_dir))
),
"pack_size": self.total_size - sum(int(e.get("size") or 0) for e in outer)
+ sum(data_sizes),
"total_omitted": len(omitted),
"omitted_files": sorted(
omitted.values(), key=lambda entry: entry["dest"]
),
"core_names": core_names,
**({"downloaded_cores": downloaded} if (downloaded := _downloaded_cores(
config, self.emu_profiles, core_names, self.platforms_dir,
)) else {}),
**({"offered_boards": offered} if (offered := _offered_boards(
config, self.emu_profiles, core_names,
[*manifest_files, *omitted.values()],
)) else {}),
"system_cores": system_cores,
# The names the platform itself gives its systems (Batocera's psx),
# which --system accepts beside the ids.
"system_names": platform_system_names(config, list(pack_systems)),
"system_titles": system_titles(manifest_files, omitted.values()),
"files": manifest_files,
}
if self.data_directories:
result["data_directories"] = self.data_directories
self._outer_directories(result)
return result
def _outer_directories(self, result: dict) -> None:
for root in OUTER_ROOTS:
layout = outer_layout(self.config, root) or {}
if layout and any(entry.get("root") == root
for entry in [*self.manifest_files, *result["omitted_files"]]):
# Where the installer finds the folder: relative to the folder
# holding the BIOS folder, which the platform names bios_folder.
result[f"{root}_directory"] = {
key: layout[key] for key in MANIFEST_OUTER_FIELDS if key in layout
}
saved = [entry for entry in self.manifest_files if entry.get("root") == "save"]
if saved:
save = save_layout(self.config)
result["save_directory"] = {"folder": save.folder, "by_core": save.by_core}
if save.by_system:
# The launcher writes the directory at each launch, one folder
# per system: each dest starts with that folder.
result["save_directory"]["by_system"] = True
def _start_manifest(
platform_name: str,
platforms_dir: str,
db: dict,
bios_dir: str,
registry_path: str,
opts: _ManifestSettings,
) -> tuple[_ManifestBuild, dict]:
"""The manifest's configuration and scope, and the profiles before the
game data cut."""
config = load_platform_config(platform_name, platforms_dir)
if opts.fold_case is not None:
config = {**config, "case_insensitive_fs": opts.fold_case}
if opts.target_name:
config = {**config, TARGET_KEY: opts.target_name}
zip_contents = {} if opts.zip_contents is None else opts.zip_contents
emu_profiles = opts.emu_profiles
if emu_profiles is None:
emu_profiles = load_emulator_profiles(opts.emulators_dir)
data_registry = opts.data_registry
if data_registry is None:
data_registry = load_data_dir_registry(platforms_dir)
full_profiles = emu_profiles
game_entries: set[int] = set()
if opts.no_game_data:
cut = without_game_data(config, emu_profiles, data_registry, opts.target_cores)
config, emu_profiles = cut.config, cut.profiles
else:
game_entries = platform_game_data(config, emu_profiles, data_registry)
# Load registry for install metadata
registry: dict = {}
if os.path.exists(registry_path):
with open(registry_path) as f:
registry = yaml_load(f) or {}
plat_registry = registry.get("platforms", {}).get(platform_name, {})
plat_cores = _platform_cores(config, emu_profiles) if opts.target_cores else None
pack_systems = filter_systems_by_target(
config.get("systems", {}),
emu_profiles,
opts.target_cores,
platform_cores=plat_cores,
)
build = _ManifestBuild(
platform_name, platforms_dir, db, bios_dir, opts, config, emu_profiles,
zip_contents, data_registry, game_entries, plat_registry.get("install", {}),
str(REPO_ROOT), pack_systems,
)
build.manifest_profiles = {
name: emu_profiles[name]
for name in _platform_cores(config, emu_profiles)
}
build.manifest_validation = _build_validation_index(build.manifest_profiles)
build.manifest_owners = destination_owners(build.manifest_profiles)
_settle_manifest_scope(build)
return build, full_profiles
def _settle_manifest_scope(build: _ManifestBuild) -> None:
"""Game data destinations, slot choices and the region selection."""
opts, config, emu_profiles = build.opts, build.config, build.emu_profiles
# A destination is game data when every declaration of it is: a firmware
# declaration of the same path keeps it in a pack built without game data.
declared_kinds: dict[str, set[bool]] = {}
for system in build.pack_systems.values():
for fe in system.get("files", []):
bare = sanitize_pack_path(fe.get("destination", fe.get("name", "")))
if bare:
declared_kinds.setdefault(bare, set()).add(id(fe) in build.game_entries)
build.game_destinations = {d for d, kinds in declared_kinds.items() if kinds == {True}}
# The full manifest records every core's answer at a contested slot, so a
# target narrowed from it gets what that target's own pack serves.
whole = opts.target_cores is None and opts.source != "platform" and bool(emu_profiles)
# The truth list read inside this run takes the choices already made.
build.slot_choices = (
opts.known_slot_choices if opts.known_slot_choices is not None and whole
else slots.slot_choices(config, emu_profiles, build.db, build.zip_contents,
build.data_registry)
if whole else {}
)
# Derived from the same choices: computed twice, it was 8% of a run.
build.slot_overrides = slots.pack_overrides(
config, emu_profiles, build.db, build.zip_contents, build.data_registry,
target_cores=opts.target_cores, source=opts.source,
choices=build.slot_choices if whole else None,
)
# Read by the region grouping and by phase 2 with the same arguments.
build.undeclared = (
undeclared_report(
config, opts.emulators_dir, build.db, emu_profiles, opts.target_cores,
include_all=(opts.source == "truth"),
)
if opts.source != "platform"
else None
)
build.region_drops, build.selection, build.builder_held = _manifest_selection(
config, build.pack_systems, opts.emulators_dir, build.db, build.base_dest,
emu_profiles, opts.target_cores, opts.source,
required_only=opts.required_only, regions=opts.regions,
undeclared=build.undeclared, zip_contents=build.zip_contents,
data_registry=build.data_registry, slot_overrides=build.slot_overrides,
one_per_slot=opts.one_per_slot,
)
def generate_manifest(
platform_name: str,
platforms_dir: str,
db: dict,
bios_dir: str,
registry_path: str,
**options: Unpack[ManifestOptions],
) -> dict:
"""Generate a JSON manifest for a platform (same resolution as generate_pack).
Returns a dict ready for JSON serialization with file inventory,
install hints, and download metadata. ``fold_case`` overrides the
platform's ``case_insensitive_fs``, for the case variants below.
A file that is a game's data, not firmware, carries ``"category":
"game_data"``, so the installer can leave it out as the builder does
under ``no_game_data``. Firmware carries no category.
One build: generate_install_list adds what --source truth and
--standalone read. `build_out` receives the slot choices and the
profiles this build read, which that second build takes over.
"""
_reject_unknown("generate_manifest", options, ManifestOptions.__optional_keys__)
opts = _ManifestSettings(**options)
build, full_profiles = _start_manifest(
platform_name, platforms_dir, db, bios_dir, registry_path, opts
)
config, verification_mode = build.config, build.verification_mode
def settle(
file_entry: dict, sys_id: str, dest: str, override: str | None
) -> tuple[str | None, str]:
"""The file served once the slot is settled, or None and why not."""
local_path, status = resolve_declaration(
file_entry,
db,
bios_dir,
build.zip_contents,
build.data_registry,
override,
offline=opts.offline,
)
if status == "not_found" and not reads_file_contents(verification_mode):
found = agnostic_substitute(file_entry, sys_id, db, build.manifest_profiles)
if found:
local_path, status = found[0], "agnostic_fallback"
if os.path.basename(local_path) != file_entry.get("name", ""):
# The pack explains the rename in a note of its own.
build.rename_notes.add(file_entry.get("name", ""))
# The builder's verdict: a hash platform omits what its frontend
# would reject, a zipped_file archive included when the member is
# missing whatever the outer resolution said. An existence
# platform never reads the bytes.
status, refusal = baseline_verdict(
file_entry, local_path, status, verification_mode,
config.get("hash_rule", ""),
)
if refusal or status in ("not_found", "external"):
return None, "hash_mismatch" if refusal else status
# The variant the pack ships when an emulator rejects the
# resolved file: the installer must place the same bytes.
local_path, _disagreement = validated_choice(
file_entry, local_path, db, build.manifest_validation, bios_dir,
digest_algorithm(verification_mode), dest, build.manifest_owners,
)
return local_path, status
if opts.source != "truth":
build.list_baseline(settle)
build.list_core_files()
result = build.result(build.list_data_directories())
detect = build.install_section.get("detect", [])
if build.case_insensitive and opts.fold_case is None and any(
d.get("os") not in CASE_FOLDING_OS for d in detect
):
# RetroArch also runs where case is kept: there Mesen-CE opens
# bios.col and np2kai np2kai/2608_bd.wav, which the folded list
# serves only as BIOS.col and 2608_BD.WAV. The installer adds these
# where the directory keeps case, while the pack, extracted on Windows
# or macOS too, stays folded.
kept = generate_manifest(
platform_name, platforms_dir, db, bios_dir, registry_path,
emulators_dir=opts.emulators_dir, zip_contents=build.zip_contents,
emu_profiles=full_profiles, target_cores=opts.target_cores, source=opts.source,
regions=opts.regions, target_name=opts.target_name, offline=opts.offline,
required_only=opts.required_only, data_registry=build.data_registry,
fold_case=False, no_game_data=opts.no_game_data,
)
folded = {entry["dest"] for entry in build.manifest_files}
folded_lower = {dest.lower() for dest in folded}
variants = [
entry for entry in kept["files"]
if entry["dest"] not in folded and entry["dest"].lower() in folded_lower
]
if variants:
result["case_variants"] = variants
if opts.build_out is not None:
opts.build_out.update(slot_choices=build.slot_choices, profiles=build.manifest_profiles)
return result
def generate_install_list(
platform_name: str,
platforms_dir: str,
db: dict,
bios_dir: str,
registry_path: str,
standalone_out: dict | None = None,
**options: Unpack[InstallListOptions],
) -> dict:
"""The list install.py reads: the full manifest, the files and omissions
the --source truth build holds apart from it, and the emulators with a
standalone build. `standalone_out` receives, per such emulator, what
`--emulator X --standalone` packs, written apart from the list
(install/standalone/<platform>.json) and fetched only by a run given
--standalone.
A manifest narrowed by a target, a case fold or --one-per-slot is no
list install.py reads by default and gets neither.
"""
settings = _ManifestSettings(**options)
built: dict = {}
result = generate_manifest(platform_name, platforms_dir, db, bios_dir, registry_path,
build_out=built, **options)
if (settings.source != "full" or settings.target_cores is not None
or settings.fold_case is not None or settings.one_per_slot):
return result
truth_options: InstallListOptions = {**options, "source": "truth"}
with contextlib.redirect_stdout(io.StringIO()):
truth = generate_manifest(
platform_name, platforms_dir, db, bios_dir, registry_path,
**truth_options, known_slot_choices=built["slot_choices"],
)
_mark_truth(result, truth)
layouts = _standalone_layouts(
built["profiles"], settings.emulators_dir, db, bios_dir,
settings.zip_contents or {}, settings.offline, platforms_dir, result,
)
if layouts:
result["standalone_builds"] = sorted(layouts)
if standalone_out is not None:
standalone_out.update(layouts)
return result
def _truth_key(entry: dict) -> tuple:
"""What tells one entry from another, as the installer's _entry_key."""
root = entry.get("root")
cores = tuple(entry.get("cores") or []) if root == "emulator" else ()
return (str(entry.get("dest")), root, cores)
def _mark_truth(result: dict, truth: dict) -> None:
"""What `--source truth` installs, carried in the full list.
The truth list holds what the emulator profiles prove is read. A file of
the full list it does not hold, by destination and content, is marked
`"truth": false`, and what only the truth list holds is `truth_files`.
Omissions compare by destination. The installer then rebuilds the
truth list from the full one, and a list without `truth_files` is one
published before, on which `--source truth` is refused.
"""
held = {(_truth_key(entry), entry.get("sha1")) for entry in truth["files"]}
full = {(_truth_key(entry), entry.get("sha1")) for entry in result["files"]}
for entry in result["files"]:
if (_truth_key(entry), entry.get("sha1")) not in held:
entry["truth"] = False
result["truth_files"] = [
entry for entry in truth["files"]
if (_truth_key(entry), entry.get("sha1")) not in full
]
absent = {_truth_key(entry) for entry in truth["omitted_files"]}
listed = {_truth_key(entry) for entry in result["omitted_files"]}
for entry in result["omitted_files"]:
if _truth_key(entry) not in absent:
entry["truth"] = False
result["truth_omitted"] = [
entry for entry in truth["omitted_files"] if _truth_key(entry) not in listed
]
+464
View File
@@ -0,0 +1,464 @@
"""The manifest's core entries and the scope a manifest selects."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, TypedDict
from core.paths import sanitize_pack_path
from model.alternatives import core_file_spares
from model.declarations import OUTER_ROOTS, ROMS_ROOT, declared_root
from model.profiles import upstream_profile_index
from model.targets import list_available_targets, load_target_config
from packs.archive import _reject_unknown
from packs.extras import (
ExtraResolver,
_detect_extras_prefix,
_extra_system_ids,
extra_full_destination,
extra_region_key,
platform_region_groups,
save_entry_fields,
save_manifest_dest,
)
from packs.manifestentry import (
_ClaimContext,
_attach_claims,
_claim_cores,
_claim_platform_omission,
_manifest_dest_of,
_manifest_entry,
)
from packs.manifestselect import SelectionIndex
from packs.paths import _register_path, placement_block
from packs.platformpack import _slot_drops
from resolve import regions as resolve_regions, slot as slot_mod
from resolve.contentlayout import TARGET_KEY, _core_key, content_folder_boards
from resolve.cores import (
downloadable_on,
downloaded_only_profiles,
resolve_platform_cores as _platform_cores,
system_core_reach,
)
from resolve.gamedata import GAME_DATA, is_game_data
if TYPE_CHECKING:
from typing_extensions import Unpack
class _CoreEntryState(TypedDict):
"""What _manifest_core_entries reads and fills of the manifest being listed."""
region_drops: set
case_insensitive: bool
seen_destinations: set
seen_lower: set
seen_parents: set
manifest_files: list
omitted_by_destination: dict
record_omission: Callable[..., None]
pack_only_sizes: list[int]
selection: SelectionIndex
class _CoreEntryParts(_CoreEntryState, total=False):
"""_CoreEntryState and the optional keywords of _manifest_core_entries."""
required_only: bool
validation_index: dict | None
owners: dict | None
data_registry: dict | None
profiles: dict | None
@dataclass
class _CoreEntryLister:
"""Lists a platform's core extras into the manifest, one at a time."""
config: dict
base_dest: str
ctx: _ClaimContext
state: _CoreEntryParts
resolver: ExtraResolver
total_size: int = 0
extras_pfx: str = field(init=False)
def __post_init__(self) -> None:
self.extras_pfx = _detect_extras_prefix(self.config, self.base_dest)
def region_key(self, fe: dict) -> str:
return extra_region_key(fe, declared_root(self.config))
def region_dropped(self, fe: dict) -> bool:
drops = self.state["region_drops"]
return bool(drops) and self.region_key(fe) in drops
def list_extra(self, fe: dict) -> None:
state = self.state
dest = sanitize_pack_path(fe.get("destination", fe["name"]))
if not dest:
return
region_key = self.region_key(fe)
if state["region_drops"] and region_key in state["region_drops"]:
return
full_dest = extra_full_destination(fe, self.extras_pfx)
if not full_dest:
return
if (
state["case_insensitive"]
and full_dest not in state["seen_destinations"]
and full_dest.lower() in state["seen_lower"]
):
self._join_spelling(fe, full_dest, dest)
return
if placement_block(
full_dest, state["seen_destinations"], state["seen_lower"], state["seen_parents"],
state["case_insensitive"],
):
return
# The builder's own lookup (ExtraResolver): the data directories, the
# copy the emulator accepts, and the size its code checks. Without
# the data directories blueMSX's MSX2P.rom named a different dump
# than the one its pack carried.
local_path, status, _disagreement = self.resolver.resolve(fe, dest)
if not local_path:
self._omit(fe, full_dest, status)
return
self._list_held(fe, dest, full_dest, region_key, local_path)
def _join_spelling(self, fe: dict, full_dest: str, dest: str) -> None:
# One file under two spellings: BlastEm opens 32X_M_BIOS.bin and
# PicoDrive 32X_M_BIOS.BIN. The second core's claim joins the
# entry kept, or a pack built without the first core loses the
# file the installer would still have to place. Collisions are
# rare, so the entry is looked up only when one happens.
save_root = fe.get("root") == "save"
folded = (
save_manifest_dest(fe) if save_root
else _manifest_dest_of(full_dest, self.base_dest)
).lower()
held = next(
(e for e in self.state["manifest_files"]
if e["dest"].lower() == folded
and (e.get("root") == "save") == save_root),
None,
)
if held is not None and held.get("cores") is not None:
_attach_claims(held, [fe], self.ctx, dest, held["dest"])
def _omit(self, fe: dict, full_dest: str, reason: str) -> None:
source_emu = fe.get("source_profile") or fe.get("source_emulator", "")
if not _claim_platform_omission(
self.state["omitted_by_destination"].get(full_dest), source_emu
):
systems = _extra_system_ids(fe)
self.state["record_omission"](
full_dest, fe, systems[0] if systems else "", reason, _claim_cores(fe),
)
def _list_held(
self, fe: dict, dest: str, full_dest: str, region_key: str, local_path: str,
) -> None:
state = self.state
source_emu = fe.get("source_profile") or fe.get("source_emulator", "")
save_root = fe.get("root") == "save"
# Manifest dests are relative to base_destination. Keep the inferred
# extras prefix when it is an internal layout dir (RetroDECK bios/).
# A file read below the save directory is written relative to the
# directory the core is handed, and says so (save_entry_fields).
outer_root = fe.get("root") if fe.get("root") in OUTER_ROOTS else None
if save_root:
manifest_dest = save_manifest_dest(fe)
elif outer_root:
# Relative to the roms or emulators folder the entry names.
manifest_dest = dest
else:
manifest_dest = _manifest_dest_of(full_dest, self.base_dest)
entry, file_size = _manifest_entry(
local_path, manifest_dest, [source_emu] if source_emu else [],
self.ctx.db, self.ctx.repo_root,
state["selection"].fields(region_key, fe.get("name", "")),
)
if entry is not None and save_root:
entry.update(save_entry_fields(fe))
elif entry is not None and outer_root:
entry["root"] = outer_root
if entry is None:
self._omit(fe, full_dest, "not_found")
if file_size:
state["pack_only_sizes"].append(file_size)
return
if is_game_data(fe) and all(
is_game_data(claim) for claim in fe.get("other_claims", [])
):
entry["category"] = GAME_DATA
_attach_claims(entry, fe.get("other_claims", []), self.ctx, dest, manifest_dest)
state["manifest_files"].append(entry)
displaced = state["omitted_by_destination"].pop(full_dest, None)
if displaced and displaced.get("cores"):
# A core that wants this slot and has nothing held: a pack built
# without the cores served here leaves the slot to it, missing,
# and the installer narrowing to those cores has to say so too.
entry.setdefault("absent_claims", []).append(
{k: v for k, v in displaced.items() if k not in ("dest", "held")}
)
self.total_size += file_size
state["seen_destinations"].add(full_dest)
_register_path(full_dest, state["seen_destinations"], state["seen_parents"])
if state["case_insensitive"]:
state["seen_lower"].add(full_dest.lower())
def _manifest_core_entries(
core_files: list,
config: dict,
db: dict,
bios_dir: str,
base_dest: str,
repo_root: str,
zip_contents: dict | None,
offline: bool | None,
**state: Unpack[_CoreEntryParts],
) -> int:
"""Add the files a platform's cores need but its list does not name.
The installer fetches by hash, so an entry records the copy this
repository holds rather than the value the profile declares: an
upstream hash carried by no local file leaves the entry with no URL.
Returns the bytes added.
"""
_reject_unknown(
"_manifest_core_entries", state,
_CoreEntryParts.__required_keys__ | _CoreEntryParts.__optional_keys__,
)
required_only = state.get("required_only", False)
ctx = _ClaimContext(
db, bios_dir, zip_contents, offline, required_only,
state.get("validation_index"), state.get("owners"), repo_root,
state.get("data_registry"),
)
lister = _CoreEntryLister(
config, base_dest, ctx, state,
ExtraResolver(
db, bios_dir, zip_contents, ctx.data_registry, ctx.validation_index or {},
ctx.owners, offline, profiles=state.get("profiles"),
),
)
spares = core_file_spares(core_files, lister.region_dropped) if required_only else set()
for fe in core_files:
if required_only and (fe.get("required") is False or id(fe) in spares):
continue
lister.list_extra(fe)
return lister.total_size
class _SelectionOptions(TypedDict, total=False):
"""The keyword options of _manifest_selection."""
required_only: bool
regions: list[str] | None
undeclared: list[dict] | None
zip_contents: dict | None
data_registry: dict | None
slot_overrides: dict[str, str] | None
one_per_slot: bool
def _manifest_selection(
config: dict,
pack_systems: dict,
emulators_dir: str,
db: dict,
base_dest: str,
emu_profiles: dict,
target_cores: set[str] | None,
source: str,
**options: Unpack[_SelectionOptions],
) -> tuple[set[str], SelectionIndex, set[str]]:
"""Destinations a region list and --one-per-slot remove, the groups the
installer replays, and the destinations the builder holds.
Grouped as the pack groups them, so a region or a slot the installer
decides on the full manifest withdraws what `--region` and
`--one-per-slot` withdraw from the pack.
"""
_reject_unknown("_manifest_selection", options, _SelectionOptions.__optional_keys__)
required_only = options.get("required_only", False)
regions = options.get("regions")
one_per_slot = options.get("one_per_slot", False)
extras: list[dict] = []
held: set[str] = set()
region_groups, _extra_dests = platform_region_groups(
config,
pack_systems,
emulators_dir,
db,
base_dest,
emu_profiles,
target_cores=target_cores,
include_extras=(source != "platform"),
include_all=(source == "truth"),
required_only=required_only,
extras_out=extras,
held_out=held,
undeclared=options.get("undeclared"),
zip_contents=options.get("zip_contents"),
data_registry=options.get("data_registry"),
slot_overrides=options.get("slot_overrides"),
)
region_index = resolve_regions.platform_region_index(
config, emu_profiles, target_cores
)
drops = (
resolve_regions.resolve_region_drops(region_groups, region_index, regions, held)
if regions
else set()
)
if one_per_slot:
drops = drops | _slot_drops(
config, emu_profiles, target_cores, region_groups, drops, held
)[0]
return drops, SelectionIndex.build(
region_groups, region_index, pack_systems, extras, required_only,
extras_prefix=declared_root(config),
slot_claims=slot_mod.platform_slot_claims(config, emu_profiles, target_cores),
), held
def _offered_boards(
config: dict,
profiles: dict[str, dict],
core_names: dict[str, list[str]],
entries: list[dict],
) -> dict[str, list[dict]]:
"""The roms folders each profile is offered for on some boards only,
each with those boards, aliases included, where the manifest places a
file of that profile.
ROCKNIX writes uae4arm for roms/amiga under the devices it builds it for
(emulators/package.mk:188), and a board's core list names uae4arm when
another folder offers it there. The pack builder reads the board from
the config (TARGET_KEY) and `install.py --target` reads its answer here.
A manifest built for one board needs none.
"""
if config.get(TARGET_KEY):
return {}
pairs = content_folder_boards(config)
if all(on is None for on in pairs.values()):
return {}
from resolve.launchers import _roms_place
by_key: dict[str, set[str]] = {}
for name, claimants in upstream_profile_index(profiles).items():
by_key.setdefault(_core_key(name), set()).update(claimants)
free = {
(profile, folder) for (core, folder), on in pairs.items() if on is None
for profile in by_key.get(core, ())
}
found: dict[tuple[str, str, str], set[str]] = {}
for (core, folder), on in pairs.items():
where = _roms_place(config, folder) if on is not None else None
if where is None:
continue
for profile in by_key.get(core, ()):
if profile in core_names and (profile, folder) not in free:
found.setdefault((profile, where[0], where[1]), set()).update(on)
# An entry below the roms root names it, one in the install tree none.
trees = {ROMS_ROOT: ROMS_ROOT, None: "install"}
placed = {
(profile, trees[entry.get("root")], str(entry.get("dest", "")).rpartition("/")[0])
for entry in entries if entry.get("root") in trees
for copy in [entry, *entry.get("alternatives", [])]
for profile in copy.get("cores") or []
}
result: dict[str, list[dict]] = {}
for (profile, tree, folder), boards in sorted(found.items()):
if not any(
p == profile and t == tree and (d == folder or d.startswith(f"{folder}/"))
for p, t, d in placed
):
continue
result.setdefault(profile, []).append(
{"root": tree, "folder": folder, "boards": sorted(boards)}
)
return result
def _downloaded_cores(
config: dict,
profiles: dict[str, dict],
core_names: dict[str, list[str]],
platforms_dir: str,
) -> dict[str, list[str]]:
"""The cores only the platform's RetroArch downloader brings, each with
the boards, aliases included, whose downloader offers it.
A target list names the board's standalone amiberry and the buildbot's
amiberry core alike, so the installer cannot tell from the name whether
the board reaches the core. `resolve_platform_cores` decides it, and
`install.py --target` reads its answer here.
"""
reached = {
profile: names
for profile, names in downloaded_only_profiles(config, profiles).items()
if profile in core_names
}
if not reached:
return {}
platform = str(config.get("_key") or "")
boards: dict[str, list[str]] = {profile: [] for profile in reached}
for target in list_available_targets(platform, platforms_dir):
cores = load_target_config(platform, target["name"], platforms_dir)
if cores is None:
continue
for profile, names in reached.items():
if downloadable_on(cores, names):
boards[profile] += [target["name"], *target.get("aliases", [])]
return {profile: sorted(names) for profile, names in sorted(boards.items())}
def _manifest_core_index(
config: dict,
profiles: dict[str, dict],
files: list[dict],
omitted: list[dict],
) -> tuple[dict[str, list[str]], dict[str, list[str]]]:
"""What the installer needs to narrow by a list of core names.
A target list, or the cores found installed, names cores the way the
buildbot does, and a file names the profile that reads it: `core_names`
gives each profile the other names it goes by, and names every core the
platform runs, one that reads no file included: a core found installed
that the list does not name is one it has no profile for. `system_cores`
gives each platform system the cores whose presence keeps it, as
`filter_systems_by_target` decides. A system absent from it is kept
whatever is available.
"""
runs = _platform_cores(config, profiles)
reach = system_core_reach(config.get("systems", {}), profiles, runs)
system_cores = {
sys_id: sorted(cores) for sys_id, cores in sorted(reach.items())
if cores is not None
}
named = {
c for entry in [*files, *omitted]
for copy in [entry, *entry.get("alternatives", []), *entry.get("slot_choices", [])]
for c in copy.get("cores") or []
}
named |= {c for cores in system_cores.values() for c in cores}
named |= set(runs)
aliases: dict[str, set[str]] = {profile: set() for profile in named & set(runs)}
for name, claimants in upstream_profile_index(profiles, include_aliases=True).items():
for profile in claimants & named:
if name != profile:
aliases.setdefault(profile, set()).add(name)
core_names = {profile: sorted(names) for profile, names in sorted(aliases.items())}
return core_names, system_cores
+477
View File
@@ -0,0 +1,477 @@
"""One file's manifest entry: where it is fetched, its hashes, the claims on it."""
from __future__ import annotations
import functools
import os
from collections.abc import Callable
from dataclasses import dataclass
from core.hashing import compute_hashes
from core.paths import sanitize_pack_path
from model.declarations import OUTER_ROOTS, declared_root
from model.largefiles import asset_name, load_registered_paths, published_asset_name
from packs.extras import (
_detect_extras_prefix,
_extra_system_ids,
extra_full_destination,
extra_region_key,
save_manifest_dest,
)
from resolve.packfiles import resolve_file
from resolve.validation import validated_choice
@functools.cache
def _registered(repo_root: str) -> frozenset[str]:
"""The paths a repository's .gitignore registers as release assets, read
by the parser the fetcher and the release check use, once per root."""
return frozenset(load_registered_paths(os.path.join(repo_root, ".gitignore")))
def _is_release_asset(local_path: str, repo_root: str) -> bool:
"""Whether the installer fetches this file from the large-files release.
The repository serves every committed file from its raw URL. Only the
files kept out of git live as release assets, and .gitignore is the
ledger of those. Size is not the criterion: a committed file over 50 MB
is still served by the repository, and announcing it as a release asset
sends the installer to an asset nobody uploaded.
"""
return _repo_relative(local_path, repo_root) in _registered(repo_root)
def _repo_relative(local_path: str, repo_root: str) -> str:
try:
return os.path.relpath(local_path, repo_root)
except ValueError:
return ""
def _release_asset_name(local_path: str, repo_root: str) -> str:
"""The large-files asset install.py downloads for a gitignored file.
The name GitHub serves, not the one uploaded: a space in the path came
back as a 404 for an installer asking for it verbatim.
"""
return published_asset_name(
asset_name(_repo_relative(local_path, repo_root), sorted(_registered(repo_root)))
)
def _get_repo_path(sha1: str, db: dict) -> str:
"""Get the repo path for a file by SHA1 lookup."""
entry = db.get("files", {}).get(sha1, {})
return entry.get("path", "")
# The database the index was built from, held so its identity stays its own.
_DB_SHA1_BY_PATH: list[tuple[dict, dict[str, str]]] = []
def _db_sha1_by_path(db: dict) -> dict[str, str]:
"""Path -> sha1 of the database, built once per database."""
if _DB_SHA1_BY_PATH and _DB_SHA1_BY_PATH[0][0] is db:
return _DB_SHA1_BY_PATH[0][1]
index = {
os.path.normpath(entry["path"]): sha1
for sha1, entry in db.get("files", {}).items()
if entry.get("path")
}
_DB_SHA1_BY_PATH[:] = [(db, index)]
return index
# The hashes a manifest entry records, and each file's once verified.
_MANIFEST_HASHES = frozenset({"sha1", "sha256"})
_STABLE_HASHES: dict[tuple, dict] = {}
def _stable_hashes(local_path: str, db: dict) -> dict:
"""The file's hashes, held against the scan that built the database.
A manifest entry is what every installer downloads and checks against.
Under load this host has hashed a 252 MB DSi NAND to a sha1 no file
holds, twice and the same way, so recomputing alone proves nothing: the
database scanned the same path, and a manifest that disagrees with it is
refused rather than published.
"""
stat = os.stat(local_path)
expected = _db_sha1_by_path(db).get(os.path.normpath(local_path))
# Keyed by what was checked, the sha1 this database expects there, never
# by id(db): a database freed and replaced at the same address answered
# with hashes verified against the first one.
key = (os.path.normpath(local_path), stat.st_size, stat.st_mtime_ns, expected)
known = _STABLE_HASHES.get(key)
if known is not None:
# Verified against the scan once: twelve manifests name a file up
# to a dozen times, and rehashing it each time spent 163 s of 218.
return known
hashes = compute_hashes(local_path, _MANIFEST_HASHES)
for _attempt in range(2):
if expected is None or hashes["sha1"] == expected:
_STABLE_HASHES[key] = hashes
return hashes
# Read from disk again: the cached digest is the one in doubt, and a
# retry through the cache answered with it without a second read.
hashes = compute_hashes(local_path, _MANIFEST_HASHES, cache=False)
raise RuntimeError(
f"{local_path}: sha1 {hashes['sha1']} contradicts the database scan "
f"({expected}). Rehash the file or regenerate database.json"
)
def _manifest_entry(
local_path: str | None,
dest: str,
cores: list[str] | None,
db: dict,
repo_root: str,
selection_fields: dict,
) -> tuple[dict | None, int]:
"""The download record of a resolved file, and the size it occupies.
The installer fetches by hash, so the entry records the copy this
repository holds: an upstream hash carried by no local file resolves to
no URL. An entry needs somewhere to be fetched from, and a file the
database does not index (a data directory, a copy added since the last
scan, a hash computed wrong) has neither a repo path nor a release
asset. None then, so the caller records an omission instead of a dead
entry that makes the installer refuse the whole manifest.
`selection_fields` carries what the installer narrows on.
"""
sha1 = ""
sha256 = ""
file_size = 0
if local_path and os.path.exists(local_path):
file_size = os.path.getsize(local_path)
hashes = _stable_hashes(local_path, db)
sha1 = hashes["sha1"]
sha256 = hashes["sha256"]
repo_path = _get_repo_path(sha1, db) if sha1 else ""
is_release_asset = _is_release_asset(local_path or "", repo_root)
if not repo_path and not is_release_asset:
return None, file_size
entry: dict = {
"dest": dest,
"sha1": sha1,
"sha256": sha256,
"size": file_size,
"repo_path": repo_path,
"cores": cores,
**selection_fields,
}
if local_path and is_release_asset:
entry["storage"] = "release"
entry["release_asset"] = _release_asset_name(local_path, repo_root)
# The installer writes what it downloads with the umask's mode, but a program
# (RetroDECK's pico8, vox) has to stay runnable. The git mode cannot say:
# hundreds of MAME archives carry an execute bit nothing reads.
if local_path and _is_program(local_path):
entry["executable"] = True
return entry, file_size
_PROGRAM_MAGIC = (
b"\x7fELF",
b"#!",
b"\xcf\xfa\xed\xfe",
b"\xce\xfa\xed\xfe",
b"\xca\xfe\xba\xbe",
)
def _is_program(path: str) -> bool:
"""An ELF or Mach-O binary, or a script with an interpreter line."""
with open(path, "rb") as handle:
head = handle.read(4)
return any(head.startswith(magic) for magic in _PROGRAM_MAGIC)
@dataclass(frozen=True)
class _ClaimContext:
"""How a manifest resolves and judges the copy a core claim names."""
db: dict
bios_dir: str
zip_contents: dict | None
offline: bool | None
required_only: bool
validation_index: dict | None
owners: dict | None
repo_root: str
data_registry: dict | None = None
def _attach_claims(
entry: dict,
claims: list[dict],
ctx: _ClaimContext,
dest: str,
manifest_dest: str,
) -> None:
"""Every other core that reads this destination, in the order the builder
meets them: a pack built without the earlier cores, or without the
platform system that declares the file, carries the first remaining
one's copy.
A claim joins the copy just before it when the bytes agree and starts an
alternative otherwise. It never joins an earlier copy, which would let it
win over a core the builder tries first. Only a core's first claim can
win: its later ones are reached only when that one is. A platform entry
names no core, so its first claim always starts an alternative.
"""
claimed = set(entry["cores"] or [])
for claim in claims:
claim_emu = claim.get("source_profile") or claim.get("source_emulator", "")
if not claim_emu or claim_emu in claimed:
continue
claimed.add(claim_emu)
if ctx.required_only and claim.get("required") is False:
continue
claim_path, claim_status = resolve_file(
claim, ctx.db, ctx.bios_dir, ctx.zip_contents,
dest_hint=claim.get("destination", ""),
data_dir_registry=ctx.data_registry, offline=ctx.offline,
)
if claim_status in ("not_found", "external", "user_provided") or not claim_path:
# Nothing held for this core: narrowed to it without the cores
# served above, the slot is a file left out (installer replays it).
entry.setdefault("absent_claims", []).append(
_absent_claim(claim, claim_emu, claim_status)
)
continue
claim_path, _ = validated_choice(
claim, claim_path, ctx.db, ctx.validation_index or {}, ctx.bios_dir, None,
claim.get("layout_path") or dest, ctx.owners,
)
copy, _size = _manifest_entry(
claim_path, manifest_dest, [claim_emu], ctx.db, ctx.repo_root, {}
)
if copy is None:
continue
alternatives = entry.setdefault("alternatives", [])
last = alternatives[-1] if alternatives else entry
if last["cores"] is not None and copy["sha1"] == last["sha1"]:
if claim_emu not in last["cores"]:
last["cores"].append(claim_emu)
continue
del copy["dest"]
alternatives.append(copy)
if not entry.get("alternatives"):
entry.pop("alternatives", None)
def _absent_claim(claim: dict, claim_emu: str, claim_status: str) -> dict:
"""The omission a claim with nothing held stands for."""
systems = _extra_system_ids(claim)
return {
"name": str(claim.get("name") or ""),
"system": systems[0] if systems else "",
"required": bool(claim.get("required", True)),
"reason": (
claim_status
if claim_status in ("not_found", "external", "user_provided")
else "not_found"
),
"cores": [claim_emu],
}
def _record_slot_choices(
entry: dict,
choices: list[tuple[str, str | None]],
declarations: list[tuple[list[str], dict, str]],
settle: Callable[[dict, str, str, str | None], tuple[str | None, str]],
dest: str,
db: dict,
repo_root: str,
) -> None:
"""Record what a pack built for fewer cores serves at a platform destination.
`slot_choices` lists, in the order slots decides, the cores whose claim
settles the slot and the copy it serves, a choice without a copy leaving
the platform's answer. `declared_choices` is the platform's answer by the
declaring systems that remain, in the order the builder takes them.
Nothing is recorded where every narrowing gets the entry's own copy.
"""
def download(file_entry: dict, sys_id: str, override: str | None) -> dict | None:
local_path, _status = settle(file_entry, sys_id, dest, override)
if local_path is None:
return None
copy, _size = _manifest_entry(local_path, dest, None, db, repo_root, {})
if copy is None:
return None
return {k: v for k, v in copy.items() if k not in ("dest", "cores")}
declared: list[dict] = []
for systems, file_entry, sys_id in declarations:
copy = download(file_entry, sys_id, None)
if copy is None:
# An omission is not a copy the installer can switch to.
return
if declared and declared[-1]["sha1"] == copy["sha1"]:
declared[-1]["systems"].extend(systems)
else:
declared.append({**copy, "systems": list(systems)})
_systems, first, first_sys = declarations[0]
recorded: list[dict] = []
seen: set[str] = set()
for emulator, path in choices:
if emulator in seen:
continue
seen.add(emulator)
copy = {} if path is None else download(first, first_sys, path)
if copy is None:
return
if recorded and recorded[-1].get("sha1") == copy.get("sha1"):
recorded[-1]["cores"].append(emulator)
else:
recorded.append({**copy, "cores": [emulator]})
while recorded and "sha1" not in recorded[-1]:
recorded.pop()
if not recorded and len(declared) == 1:
return
if recorded:
entry["slot_choices"] = recorded
entry["declared_choices"] = declared
def _manifest_dest_of(full_dest: str, base_dest: str) -> str:
"""A pack destination as the manifest writes it, below base_destination."""
if base_dest and full_dest.startswith(f"{base_dest}/"):
return full_dest[len(base_dest) + 1:]
return full_dest
def _claim_platform_omission(held: dict | None, emulator: str) -> bool:
"""Record a core's claim on a destination the platform already omits.
The platform's own omission stands while one of its declaring systems
does. A pack built without them falls to the first core claiming the
path, as for a file present. Overwriting the record lost the platform's
claim: a target without that core dropped an omission its pack reports.
"""
if held is None or held.get("cores") is not None:
return False
if emulator:
claims = held.setdefault("alternatives", [])
if {"cores": [emulator]} not in claims:
claims.append({"cores": [emulator]})
return True
def _claim_cores(fe: dict) -> list[str]:
"""The cores an extra and the claims folded onto it name: an omission
names every core reading the file, as a list built for one of them
would."""
names = {
claim.get("source_profile") or claim.get("source_emulator", "")
for claim in (fe, *fe.get("other_claims", []))
}
return sorted(name for name in names if name)
def _record_absent(
absent: list[dict],
config: dict,
base_dest: str,
region_drops: set,
required_only: bool,
seen_destinations: set,
omitted_by_destination: dict,
record_omission: Callable[..., None],
) -> None:
"""A file a core needs that the collection does not hold is an omission.
Left out of both lists, DevilutionX's diabdat.mpq and dhewm3's
pak000-004 reached no safety notice: the installer said everything
was verified and the game refused to start.
"""
extras_pfx = _detect_extras_prefix(config, base_dest)
for fe in absent:
if required_only and fe.get("required") is False:
continue
dest = sanitize_pack_path(fe.get("destination", fe.get("name", "")))
if not dest or (
region_drops and extra_region_key(fe, declared_root(config)) in region_drops
):
continue
full_dest = extra_full_destination(fe, extras_pfx)
if not full_dest or full_dest in seen_destinations:
continue
source_emu = fe.get("source_profile") or fe.get("source_emulator", "")
held = omitted_by_destination.get(full_dest)
if held is not None:
# Another core reads the same missing file there (Raze and
# EDuke32 both open NAPALM.GRP): one omission names them all.
claimed = held.get("cores")
if (held.get("reason") == "not_found" and claimed and source_emu
and source_emu not in claimed):
held["cores"] = sorted([*claimed, source_emu])
continue
systems = _extra_system_ids(fe)
record_omission(
full_dest, fe, systems[0] if systems else "", "not_found",
[source_emu] if source_emu else [],
)
# What a manifest's roms_directory and emulators_directory carry: the BIOS
# folder's name, for the roms root its place relative to the BIOS folder
# (romfolders roms_root.from_bios), and for emulator folders the places the
# launcher searches, the one a missing folder is created at, and the config
# file whose key moves a folder.
MANIFEST_OUTER_FIELDS = ("bios_folder", "from_bios", "searched", "default", "config")
def _record_unplaceable(
unplaceable: list[dict],
record_omission: Callable[..., None],
config: dict,
profiles: dict[str, dict],
) -> None:
"""Held by the collection, nowhere to put it on this platform.
Said in the manifest, where RomM's DOSBox Pure ROMs were simply absent.
One place read by several cores is one omission naming them all.
"""
# The emulator's own folder is the one the platform installs the name
# it lists into: RetroPie puts amiberry 5.7.2 and 6.3.3, one per board,
# both in $md_inst of its amiberry package.
platform_names = {
str(c) for key in ("cores", "standalone_cores")
if isinstance(config.get(key), list) for c in config[key]
}
def folder(profile: str) -> str:
names = {profile, *map(str, (profiles.get(profile) or {}).get("cores") or [])}
return min(names & platform_names, default=profile)
grouped: dict[str, tuple[dict, list[str]]] = {}
for u in unplaceable:
where = u.get("path") or u.get("name", "")
# The profile key, the name a target's core list and the
# installer's narrowing match: the display name matched none.
core = u.get("profile") or u.get("emulator", "")
if u.get("unplaced"):
key = f"emulator:{folder(core)}:{where}"
elif u.get("root") in OUTER_ROOTS:
key = f"{u['root']}:{where}"
elif u.get("root") == "save":
key = f"save:{save_manifest_dest(u)}"
else:
key = where
held, cores = grouped.setdefault(key, (u, []))
if core and core not in cores:
cores.append(core)
if u.get("required", True) and not held.get("required", True):
grouped[key] = ({**held, "required": True}, cores)
for key, (u, cores) in grouped.items():
record_omission(
# Keyed apart from the BIOS tree's paths, which a file read below
# the save directory or in the emulator's folder can repeat.
key, u, u.get("system") or "",
u.get("unplaceable", "no_platform_slug"), sorted(cores),
)
@@ -21,7 +21,7 @@ from resolve import regions as resolve_regions
from resolve import slot as slot_mod
from model.systems import _norm_system_id
from core.paths import sanitize_pack_path
from packextras import (
from packs.extras import (
_kept,
_serving_system_ids,
extra_region_groups,
+243
View File
@@ -0,0 +1,243 @@
"""A pack built from a list of hashes."""
from __future__ import annotations
import hashlib
import os
import sys
from dataclasses import dataclass
from typing import TYPE_CHECKING, TypedDict
from model.platforms import load_platform_config
from model.profiles import ProfileSelectionError, load_emulator_profiles, select_emulator_profiles
from packs.archive import _add_pack_member, _reject_unknown, _writing_pack
from packs.naming import _name_part, _narrowings
from packs.paths import _resolve_destination
from resolve.packfiles import resolve_file, sha1_for_hash
if TYPE_CHECKING:
from typing_extensions import Unpack
def _entry_for_file(candidates: list[dict], held: dict) -> dict:
"""The declaration a held file answers when several share its name.
BBKEmu declares 8.BIN once per model. The last one won, and the A4980
dump went to the A4988 folder. The declared hash decides, then the
destination the collection's own path ends with, then the last one.
"""
def declared(fe: dict, key: str) -> set[str]:
value = fe.get(key)
values = value if isinstance(value, list) else str(value or "").split(",")
return {str(v).strip().lower() for v in values if str(v).strip()}
for fe in candidates:
if any(
str(held.get(key, "")).lower() in declared(fe, key)
for key in ("sha1", "md5", "sha256", "crc32")
if held.get(key)
):
return fe
held_paths = [str(held.get("path", ""))] + [str(p) for p in held.get("paths") or []]
for fe in candidates:
tail = str(fe.get("path") or fe.get("destination") or "").lower()
if tail and any(path.lower().endswith("/" + tail) for path in held_paths):
return fe
return candidates[-1]
class Md5PackOptions(TypedDict, total=False):
"""The keyword options of generate_md5_pack: the layout to follow."""
platform_name: str | None
platforms_dir: str | None
emulator_name: str | None
emulators_dir: str | None
standalone: bool
@dataclass(frozen=True)
class _Md5Settings:
"""Md5PackOptions with their defaults."""
platform_name: str | None = None
platforms_dir: str | None = None
emulator_name: str | None = None
emulators_dir: str | None = None
standalone: bool = False
@dataclass(frozen=True)
class _Md5Layout:
"""Where a hash-selected pack puts each file: the declarations by
lowercased name, the platform's base destination, and the pack's name."""
index: dict[str, list[dict]]
base_dest: str
context_name: str
def _md5_layout(opts: _Md5Settings) -> _Md5Layout | None:
"""The platform or emulator layout a hash list is packed in, or None
when the emulator named is refused."""
platform_name = opts.platform_name
platforms_dir = opts.platforms_dir
emulator_name = opts.emulator_name
emulators_dir = opts.emulators_dir
plat_file_index: dict[str, list[dict]] = {}
base_dest = ""
plat_display = "Custom"
if platform_name and platforms_dir:
config = load_platform_config(platform_name, platforms_dir)
base_dest = config.get("base_destination", "")
plat_display = config.get("platform", platform_name)
for system in config.get("systems", {}).values():
for fe in system.get("files", []):
plat_file_index.setdefault(fe.get("name", "").lower(), []).append(fe)
emu_display = ""
if emulator_name and emulators_dir:
profiles = load_emulator_profiles(emulators_dir, skip_aliases=False)
# The same gate as --emulator, unknown names included: a typo or a
# buildbot name gave a generic pack in the layout of no emulator. A
# core with no standalone build has no standalone layout either.
try:
(_name, profile), = select_emulator_profiles(
[emulator_name], profiles, opts.standalone
)
except ProfileSelectionError as exc:
print(f"Error: {exc}", file=sys.stderr)
return None
emu_display = profile.get("emulator", emulator_name)
for fe in profile.get("files", []):
plat_file_index.setdefault(fe.get("name", "").lower(), []).append(fe)
for alias in fe.get("aliases", []):
plat_file_index.setdefault(alias.lower(), []).append(fe)
context_name = plat_display if platform_name else (emu_display or "Custom")
return _Md5Layout(plat_file_index, base_dest, context_name)
def _md5_pack_name(
context_name: str, hashes: list[tuple[str, str]], opts: _Md5Settings,
) -> str:
"""The file name of a hash-selected pack."""
# The selection mode is part of the name, as for --system: BizHawk is
# both a platform and a profile display name, and the two layouts
# (Firmware/ under the platform, the profile's paths under the core)
# wrote one file, the second run replacing the first without a word.
mode_part = (
"_Emulator" if opts.emulator_name and not opts.platform_name else ""
)
# --standalone changes the destination layout, so a run with it must not
# take the name of a run without it.
custom_tags = "".join(
tag
for tag, _label in _narrowings(
"full", None, None, False, False, standalone=opts.standalone
)
)
# The hash list is what chooses the content: two lists under one name
# overwrote each other in the same output directory.
selection = hashlib.sha1(
"\n".join(sorted(f"{kind}:{value.lower()}" for kind, value in hashes)).encode()
).hexdigest()[:8]
return (
f"{_name_part(context_name, '_')}{mode_part}_Custom_{selection}{custom_tags}"
"_BIOS_Pack.zip"
)
def _md5_destination(entry: dict, layout: _Md5Layout, opts: _Md5Settings) -> str:
"""Where a held file goes in a hash-selected pack."""
name = entry.get("name", "")
aliases = entry.get("aliases") or []
paths = entry.get("paths") or []
dest = name
matched_fe = None
for lookup_name in [name] + aliases:
if lookup_name.lower() in layout.index:
matched_fe = _entry_for_file(layout.index[lookup_name.lower()], entry)
break
if matched_fe:
if opts.emulator_name:
# Laid out as the emulator pack lays it out: its path and
# its standalone_path, which --standalone has to reach.
dest = _resolve_destination(matched_fe, opts.standalone)
else:
dest = matched_fe.get("destination", matched_fe.get("name", name))
elif paths:
dest = paths[0]
if layout.base_dest and not dest.startswith(layout.base_dest):
return f"{layout.base_dest}/{dest}"
return dest
def generate_md5_pack(
hashes: list[tuple[str, str]],
db: dict,
bios_dir: str,
output_dir: str,
zip_contents: dict | None = None,
**options: Unpack[Md5PackOptions],
) -> str | None:
"""Build a pack from an explicit list of hashes with layout context."""
files_db = db.get("files", {})
if zip_contents is None:
zip_contents = {}
_reject_unknown("generate_md5_pack", options, Md5PackOptions.__optional_keys__)
opts = _Md5Settings(**options)
layout = _md5_layout(opts)
if layout is None:
return None
zip_path = os.path.join(output_dir, _md5_pack_name(layout.context_name, hashes, opts))
os.makedirs(output_dir, exist_ok=True)
packed: list[tuple[str, str]] = []
not_in_repo: list[tuple[str, str]] = []
not_in_db: list[str] = []
seen: set[str] = set()
with _writing_pack(zip_path) as zf:
for hash_type, hash_val in hashes:
sha1 = sha1_for_hash(hash_type, hash_val, db)
if not sha1:
not_in_db.append(hash_val)
continue
entry = files_db[sha1]
name = entry.get("name", "")
full_dest = _md5_destination(entry, layout, opts)
if full_dest in seen:
continue
seen.add(full_dest)
fe_for_resolve = {"name": name, "sha1": sha1, "md5": entry.get("md5", "")}
local_path, status = resolve_file(
fe_for_resolve, db, bios_dir, zip_contents
)
if status == "not_found" or not local_path:
not_in_repo.append((name, hash_val))
continue
_add_pack_member(zf, local_path, full_dest)
packed.append((name, hash_val))
total = len(hashes)
print(f"\nPacked {len(packed)}/{total} requested files")
for name, h in packed:
print(f" PACKED: {name} ({h[:16]}...)")
for name, h in not_in_repo:
print(f" NOT IN REPO: {name} ({h[:16]}...)")
for h in not_in_db:
print(f" NOT IN DB: {h}")
if not packed:
if os.path.exists(zip_path):
os.unlink(zip_path)
return None
return zip_path
+346
View File
@@ -0,0 +1,346 @@
"""The names of pack archives and manifests, built from every narrowing."""
from __future__ import annotations
import hashlib
import os
import re
from model import region
from model.platforms import load_platform_config
from model.registry import list_release_pack_platforms
from model.systems import MANUFACTURER_PREFIXES
from model.targets import build_target_cores_cache, canonical_target_name, platform_files_target
from packs import parts as packs_parts
from resolve.grouping import group_identical_platforms
def _narrowings(
source: str,
regions: list[str] | None,
target_name: str | None,
one_per_slot: bool,
required_only: bool,
standalone: bool = False,
no_game_data: bool = False,
) -> list[tuple[str, str]]:
"""Every dimension that narrows a pack, as (filename tag, plain label).
The pack name and the pack README are both built from this list, so a new
way of narrowing a pack cannot reach users nameless or unannounced. Order
is the filename order and must not change: it is what existing archives
are called.
"""
applied: list[tuple[str, str]] = []
if source == "platform":
applied.append(("_Platform", "only what the platform declares"))
elif source == "truth":
applied.append(("_Truth", "only what emulator profiles require"))
if regions:
pretty = ", ".join(
" ".join(w.title() for w in slug.split("-")) for slug in regions
)
applied.append(
(f"_{region.region_tag(regions)}", f"region priority {pretty}")
)
if target_name:
applied.append(
(f"_{_target_tag(target_name)}", f"cores available on {target_name}")
)
if one_per_slot:
applied.append(("_OnePerSlot", "one BIOS per system and region"))
if standalone:
applied.append(("_Standalone", "standalone mode files only"))
if required_only:
applied.append(("_Required", "required files only"))
if no_game_data:
applied.append(("_NoGameData", "firmware only, game data left out"))
return applied
def _target_tag(target_name: str) -> str:
"""Filename tag for a hardware target.
Without it a targeted pack takes the same name as the full one and
overwrites it.
"""
return "".join(
part.title() for part in re.split(r"[-_\s]+", target_name.strip()) if part
)
def _platform_target(
platform_name: str, target: str | None, platforms_dir: str
) -> str | None:
"""The target as this platform files it, the name its artifacts carry.
Named once for the whole run, a target two platforms file differently
(rpi4: Batocera's bcm2711, Recalbox's rpi4_64) kept the typed name under
--all and took the platform's own under --platform, so --verify-packs
looked for a pack the --all build had named otherwise. A platform that
does not file the target is packed whole under --all, and its name
claims no narrowing: BizHawk_..._Switch_BIOS_Pack.zip was the full pack.
"""
if not target or not platform_files_target(platform_name, target, platforms_dir):
return None
return canonical_target_name([platform_name], target, platforms_dir)
def _system_tag(system_filter: list[str] | None) -> str:
"""Filename tag for a pack limited to some systems, empty for all."""
if not system_filter:
return ""
display_parts = []
for sid in system_filter:
s = sid.lower().replace("_", "-")
for prefix in MANUFACTURER_PREFIXES:
if s.startswith(prefix):
s = s[len(prefix) :]
break
display_parts.append("_".join(p.title() for p in s.split("-") if p))
return "_" + _bounded_join(display_parts, system_filter)
# A system list long enough to push a pack name past this falls back to the
# first system, a count and a digest of the list.
MAX_SYSTEM_TAG_BYTES = 120
def _bounded_join(parts: list[str], keys: list[str]) -> str:
"""Parts joined while they fit, else the first, a count and a digest.
Thirty systems joined made a 261-byte file name and the ZIP could not
be opened. The digest keeps two different selections apart. The joiner
is one no part holds: with "_", sega-dreamcast + arcade and
sega-dreamcast-arcade both named Dreamcast_Arcade, and the second build
replaced the first.
"""
joined = "+".join(parts)
if len(joined.encode("utf-8")) <= MAX_SYSTEM_TAG_BYTES:
return joined
digest = hashlib.sha1("\n".join(sorted(keys)).encode("utf-8")).hexdigest()[:8]
return f"{parts[0]}_and_{len(parts) - 1}_more_{digest}"
_UNSAFE_IN_NAME = re.compile(r'[/\\:*?"<>|]')
def _name_part(text: str, space: str = "") -> str:
"""A display name made safe to stand in a file name.
'FinalBurn Neo (CPS-1/CPS-2)' named a directory that did not exist, and a
Windows user cannot write ':' or '?' either.
"""
return _UNSAFE_IN_NAME.sub("-", text.replace(" ", space))
def _platform_pack_stem(
group_platforms: list[str], representative: str, platforms_dir: str
) -> str:
"""Platform part of a pack name, version included.
A group of identical platforms shares one pack named after all of them,
and the builder and --verify-packs both read the name from here.
"""
rep_cfg = load_platform_config(representative, platforms_dir)
version = rep_cfg.get("version", rep_cfg.get("dat_version", ""))
version_tag = f"_{_name_part(str(version))}" if version else ""
return platform_pack_prefix(group_platforms, representative, platforms_dir) + version_tag
def platform_pack_prefix(
group_platforms: list[str], representative: str, platforms_dir: str
) -> str:
"""Platform part of a pack name without the version.
The site reads a pack's version back by removing this prefix: a version
may hold an underscore (AmberELEC prerelease-20261019_1835).
"""
if len(group_platforms) <= 1:
rep_cfg = load_platform_config(representative, platforms_dir)
return _name_part(rep_cfg.get("platform", representative), "_")
names = [
load_platform_config(p, platforms_dir).get("platform", p)
for p in group_platforms
]
return "_".join(_name_part(n) for n in names)
def _platform_pack_name(
platform_name: str,
platforms_dir: str,
narrowings: list[tuple[str, str]],
system_filter: list[str] | None,
pack_name: str | None = None,
) -> str:
"""File name of a platform pack: stem, narrowing tags, system tag.
A caller naming the pack itself (a --split part) is taken at its word.
"""
if pack_name:
return pack_name
stem = _platform_pack_stem([platform_name], platform_name, platforms_dir)
tags = "".join(tag for tag, _label in narrowings)
return f"{stem}{tags}_BIOS_Pack{_system_tag(system_filter)}.zip"
# A file name holds 255 bytes on every filesystem a pack is written to,
# and the margin leaves room for the split part suffix and a scratch prefix.
MAX_PACK_NAME_BYTES = 200
def _bounded_pack_name(display_names: list[str], keys: list[str], suffix: str) -> str:
"""The emulator pack's file name, its emulators joined while they fit.
Past the limit the name keeps the first emulator, says how many more the
pack holds, and carries a digest of the selection so two different
selections never share a file.
"""
joined = "_".join(display_names) + suffix
if len(joined.encode("utf-8")) <= MAX_PACK_NAME_BYTES:
return joined
digest = hashlib.sha1("\n".join(sorted(keys)).encode("utf-8")).hexdigest()[:8]
return f"{display_names[0]}_and_{len(display_names) - 1}_more_{digest}{suffix}"
def _expected_pack_names(
platforms: list[str],
platforms_dir: str,
regions: list[str] | None,
target_name: str | None,
variants: tuple[tuple[str, bool], ...] = (("full", False),),
no_game_data: bool = False,
) -> dict[str, set[str]]:
"""Exact pack file names --verify-packs may check, per platform.
Rebuilt from the name builder, never matched by substring: a substring
picks the full pack when a regional or targeted one was asked for, or a
narrowed pack when the full one was. A platform answers to its own name
and to the name of the group it shares a pack with. ``variants`` lists
the (source, required_only) combinations the run built.
"""
def narrow_tags(platform_name: str) -> list[str]:
named = _platform_target(platform_name, target_name, platforms_dir)
return [
"".join(
tag
for tag, _label in _narrowings(
source, regions, named, False, required, no_game_data=no_game_data
)
)
for source, required in variants
]
names: dict[str, set[str]] = {
p: {
f"{_platform_pack_stem([p], p, platforms_dir)}{tags}_BIOS_Pack.zip"
for tags in narrow_tags(p)
}
for p in platforms
}
# Groups depend on which platforms a run built: the release packs of
# --all.
pool = list_release_pack_platforms(platforms_dir)
cache = None
if target_name:
try:
cache, pool = build_target_cores_cache(
pool, target_name, platforms_dir, is_all=True
)
except ValueError:
# No platform has the target: no pack was built under it.
return names
for group, representative in group_identical_platforms(
pool, platforms_dir, cache
):
if len(group) < 2:
continue
stem = _platform_pack_stem(group, representative, platforms_dir)
for tags in narrow_tags(representative):
for p in group:
if p in names:
names[p].add(f"{stem}{tags}_BIOS_Pack.zip")
return names
def _content_narrowing_tags() -> tuple[str, ...]:
"""Tags naming a pack that holds fewer files than the platform declares.
Read from the name builder rather than retyped, so the two cannot drift.
Region and target are absent on purpose: both are handed to the check
itself, which narrows its expectation instead of skipping it.
"""
# (source, one_per_slot, required_only), one dimension at a time.
dimensions = (
("platform", False, False),
("truth", False, False),
("full", True, False),
("full", False, True),
)
tags: list[str] = []
for source, one_per_slot, required_only in dimensions:
tags.extend(
tag
for tag, _label in _narrowings(source, None, None, one_per_slot, required_only)
)
return tuple(tags)
_CONTENT_NARROWING_TAGS = _content_narrowing_tags()
def _narrows_contents(pack_name: str) -> bool:
"""True when a pack holds fewer files than the platform declares.
A source-restricted or required-only build is narrower by design, so the
full platform expectation does not apply to it and conformance is skipped.
Region is not listed: the region filter is passed to the check itself, and
a hardware target is passed the same way.
"""
return any(f"{tag}_" in pack_name for tag in _CONTENT_NARROWING_TAGS)
def _pack_variant(pack_name: str) -> tuple[str, bool] | None:
"""The (source, required_only) a pack was built as, read from its name.
None for a one-per-slot pack, whose slot choice the check does not
replay. The tags come from the name builder, as for _narrows_contents.
"""
def tagged(**dimension: object) -> bool:
tags = [
tag for tag, _label in _narrowings(
str(dimension.get("source", "full")), None, None,
bool(dimension.get("one_per_slot", False)),
bool(dimension.get("required_only", False)),
)
]
return all(f"{tag}_" in pack_name for tag in tags)
if tagged(one_per_slot=True):
return None
source = next(
(s for s in ("platform", "truth") if tagged(source=s)), "full"
)
return source, tagged(required_only=True)
def _pack_archives(output_dir: str) -> list[str]:
"""The ZIPs of a directory that are packs.
A part of a split pack holds a share of a platform by design and was
checked against the whole when it was cut: judged as a pack it would
fail conformance, and injecting a manifest would change published bytes.
Every name the builder gives holds `_BIOS_Pack`, then the system tag of
a --system platform pack (`_BIOS_Pack_Playstation.zip`): build_port.py
wrote its launcher archives (RetroBIOS.zip) to the same dist/, and
taking every ZIP rewrote them with a manifest after build_port had
printed their hashes.
"""
return sorted(
name
for name in os.listdir(output_dir)
if _PACK_NAME.search(name) and not packs_parts.is_part(name)
)
_PACK_NAME = re.compile(r"_BIOS_Pack(?:_[^/]+)?\.zip$")
+297
View File
@@ -0,0 +1,297 @@
"""A pack too large for one release asset, written as several ZIPs of whole files."""
from __future__ import annotations
import io
import re
import struct
import zipfile
import zlib
from pathlib import Path
# "Each file included in a release must be under 2 GiB."
ASSET_LIMIT = 2 * 1024**3
PACK_SUFFIX = "_BIOS_Pack.zip"
_PART_NAME = re.compile(r"^(?P<stem>.+_BIOS_Pack)\.part(?P<index>\d+)of(?P<count>\d+)\.zip$")
_MARKER_NAME = re.compile(r"^(?P<stem>.+_BIOS_Pack)\.part(?P<index>\d+)of(?P<count>\d+)\.txt$")
# Sizes are written at a fixed width, so a marker's length, and with it the
# size of its own part, does not depend on the sizes it records.
_SIZE_WIDTH = 13
_LOCAL = struct.Struct("<4s2B4HL2L2H")
_CENTRAL = struct.Struct("<4s4B4HL2L5H2L")
_END = struct.Struct("<4s4H2LH")
_LOCAL_SIG = b"PK\x03\x04"
_CENTRAL_SIG = b"PK\x01\x02"
_END_SIG = b"PK\x05\x06"
_DATA_DESCRIPTOR = 0x08
_UTF8_NAME = 0x800
_CHUNK = 1024 * 1024
_MAX_ENTRIES = 0xFFFF
_MAX_FIELD = 0xFFFFFFFF
def is_part(name: str) -> bool:
"""Whether a file name is one part of a split pack."""
return _PART_NAME.match(name) is not None
def pack_of(name: str) -> str:
"""The pack a published file belongs to, a part folded into its archive."""
part = _PART_NAME.match(name)
return f"{part['stem']}.zip" if part else name
def part_name(pack_name: str, index: int, count: int) -> str:
return f"{pack_name[: -len('.zip')]}.part{index}of{count}.zip"
def marker_name(pack_name: str, index: int, count: int) -> str:
return f"{pack_name[: -len('.zip')]}.part{index}of{count}.txt"
def is_marker(name: str) -> bool:
"""Whether an archive member is the marker a split writes in each part."""
return _MARKER_NAME.match(name) is not None
def marker_text(pack_name: str, index: int, sizes: list[int]) -> bytes:
"""The marker of part *index* of a pack published in ``len(sizes)`` parts.
Plain text a person can read, in a form install.py parses back: the
lines that matter are `pack:`, `part:` and one `file:` per part.
"""
count = len(sizes)
lines = [
"RetroBIOS split pack",
f"This folder holds part {index} of {count} of {pack_name}.",
"Every part is needed: extract them all into this same folder.",
"The installer's --check names a part missing from the folder.",
"",
f"pack: {pack_name}",
f"part: {index} of {count}",
]
lines += [
f"file: {size:>{_SIZE_WIDTH}} {part_name(pack_name, number, count)}"
for number, size in enumerate(sizes, 1)
]
return ("\n".join(lines) + "\n").encode("utf-8")
def _marker_weight(pack_name: str, index: int, count: int) -> int:
name = len(marker_name(pack_name, index, count).encode("utf-8"))
body = len(marker_text(pack_name, index, [0] * count))
return _LOCAL.size + name + body + _CENTRAL.size + name
def _name_bytes(info: zipfile.ZipInfo) -> bytes:
encoding = "utf-8" if info.flag_bits & _UTF8_NAME else "cp437"
return info.orig_filename.encode(encoding)
def _weight(info: zipfile.ZipInfo) -> int:
"""Bytes a member adds to a part: both headers and its stored data."""
name = len(_name_bytes(info))
return _LOCAL.size + name + info.compress_size + _CENTRAL.size + name
def plan_parts(
members: list[zipfile.ZipInfo], limit: int, reserve: int = 0
) -> list[list[zipfile.ZipInfo]]:
"""Fill each part in archive order, up to the limit less *reserve*."""
parts: list[list[zipfile.ZipInfo]] = [[]]
floor = _END.size + reserve
size = floor
for info in members:
weight = _weight(info)
if floor + weight >= limit:
raise ValueError(
f"{info.filename} needs {weight:,} bytes, more than a part of "
f"{limit:,} can hold"
)
if info.compress_size > _MAX_FIELD or info.file_size > _MAX_FIELD:
raise ValueError(f"{info.filename} needs ZIP64, which a part does not use")
if size + weight >= limit or len(parts[-1]) >= _MAX_ENTRIES - 1:
parts.append([])
size = floor
parts[-1].append(info)
size += weight
return parts
def _dos_stamp(info: zipfile.ZipInfo) -> tuple[int, int]:
year, month, day, hour, minute, second = info.date_time
return (
(hour << 11) | (minute << 5) | (second // 2),
((year - 1980) << 9) | (month << 5) | day,
)
def _data_offset(source: io.BufferedReader, info: zipfile.ZipInfo) -> int:
"""Where a member's stored bytes begin, read from its own local header."""
source.seek(info.header_offset)
header = _LOCAL.unpack(source.read(_LOCAL.size))
if header[0] != _LOCAL_SIG:
raise ValueError(f"{info.filename}: no local header at its offset")
return info.header_offset + _LOCAL.size + header[10] + header[11]
def _marker_info(name: str, body: bytes) -> zipfile.ZipInfo:
info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0))
info.compress_type = zipfile.ZIP_STORED
info.CRC = zlib.crc32(body)
info.compress_size = info.file_size = len(body)
info.create_system = 3
info.external_attr = (0o100000 | 0o644) << 16
return info
def _write_part(
source: io.BufferedReader, members: list[zipfile.ZipInfo], dest: Path,
marker: tuple[str, bytes],
) -> None:
directory = []
marker_info = _marker_info(*marker)
with open(dest, "wb") as out:
for info in [marker_info, *members]:
name = _name_bytes(info)
flags = info.flag_bits & ~_DATA_DESCRIPTOR
dos_time, dos_date = _dos_stamp(info)
offset = out.tell()
out.write(
_LOCAL.pack(
_LOCAL_SIG, info.extract_version, info.reserved, flags,
info.compress_type, dos_time, dos_date, info.CRC,
info.compress_size, info.file_size, len(name), 0,
)
)
out.write(name)
if info is marker_info:
out.write(marker[1])
remaining = 0
else:
source.seek(_data_offset(source, info))
remaining = info.compress_size
while remaining:
chunk = source.read(min(_CHUNK, remaining))
if not chunk:
raise ValueError(f"{info.filename}: the pack ends inside it")
out.write(chunk)
remaining -= len(chunk)
directory.append(
_CENTRAL.pack(
_CENTRAL_SIG, info.create_version, info.create_system,
info.extract_version, info.reserved, flags,
info.compress_type, dos_time, dos_date, info.CRC,
info.compress_size, info.file_size, len(name), 0, 0, 0,
info.internal_attr, info.external_attr, offset,
)
+ name
)
start = out.tell()
for record in directory:
out.write(record)
out.write(
_END.pack(
_END_SIG, 0, 0, len(directory), len(directory),
out.tell() - start, start, 0,
)
)
def _identity(archive: zipfile.ZipFile) -> list[tuple[str, int, int]]:
return [
(info.filename, info.CRC, info.file_size)
for info in archive.infolist()
if not is_marker(info.filename)
]
def marker_weight(pack_name: str, count: int) -> int:
"""Bytes the largest marker of a pack in *count* parts adds to its part."""
return max(_marker_weight(pack_name, index, count) for index in (1, count))
def _plan_with_markers(
pack_name: str, members: list[zipfile.ZipInfo], limit: int
) -> list[list[zipfile.ZipInfo]]:
"""Plan the parts with room for the marker each one carries.
The marker lists every part, so its length grows with their count: the
plan is made again until the count it assumed is the count it gives.
"""
count = 1
while True:
reserve = marker_weight(pack_name, count)
plan = plan_parts(members, limit, reserve)
if len(plan) <= count:
return plan
count = len(plan)
def split_pack(zip_path: Path, limit: int = ASSET_LIMIT) -> list[Path]:
"""Replace a pack at or over the limit by parts that each fit under it.
Returns the files to publish. The pack is removed only once every part
has been read back in full and the parts together list exactly its
members, so a failure leaves the pack as it was and no part behind.
"""
zip_path = Path(zip_path)
if zip_path.stat().st_size < limit:
return [zip_path]
with zipfile.ZipFile(zip_path) as archive:
members = archive.infolist()
expected = _identity(archive)
taken = [info.filename for info in members if is_marker(info.filename)]
if taken:
raise ValueError(f"{zip_path.name} already holds {taken[0]}, a part marker name")
plan = _plan_with_markers(zip_path.name, members, limit)
count = len(plan)
parts = [
zip_path.with_name(part_name(zip_path.name, index, count))
for index in range(1, count + 1)
]
sizes = [
_END.size + _marker_weight(zip_path.name, index, count)
+ sum(_weight(info) for info in chosen)
for index, chosen in enumerate(plan, 1)
]
try:
with open(zip_path, "rb") as source:
for index, (dest, chosen) in enumerate(zip(parts, plan), 1):
marker = (marker_name(zip_path.name, index, count),
marker_text(zip_path.name, index, sizes))
_write_part(source, chosen, dest, marker)
if dest.stat().st_size != sizes[index - 1]:
raise ValueError(
f"{dest.name} is {dest.stat().st_size:,} bytes, its marker "
f"says {sizes[index - 1]:,}"
)
found: list[tuple[str, int, int]] = []
for dest in parts:
with zipfile.ZipFile(dest) as archive:
damaged = archive.testzip()
if damaged:
raise ValueError(f"{dest.name}: {damaged} does not read back")
found.extend(_identity(archive))
if dest.stat().st_size >= limit:
raise ValueError(f"{dest.name} reached the limit of {limit:,} bytes")
if found != expected:
raise ValueError(f"the parts of {zip_path.name} do not add up to it")
except (OSError, ValueError, zipfile.BadZipFile):
for dest in parts:
dest.unlink(missing_ok=True)
raise
zip_path.unlink()
return parts
def split_directory(directory: Path, limit: int = ASSET_LIMIT) -> list[Path]:
"""Split every pack of a directory that needs it. Returns what to publish."""
published: list[Path] = []
for path in sorted(Path(directory).glob(f"*{PACK_SUFFIX}")):
published.extend(split_pack(path, limit))
return published
File renamed without changes.
File diff suppressed because it is too large. Load diff
@@ -7,7 +7,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING, TypedDict
from packextras import reject_unknown
from packs.extras import reject_unknown
from model.region import label as region_label
from siteguides import INSTALL_PS1, INSTALL_SH, pack_manual
+635
View File
@@ -0,0 +1,635 @@
"""Verify results printed for a person, per platform and per emulator."""
from __future__ import annotations
from collections import Counter
from packs.verdicts import Severity, Status
from resolve.categories import BIOS
from resolve.nativemode import reads_file_contents
def _format_ground_truth_aggregate(ground_truth: list[dict]) -> str:
"""Format ground truth as a single aggregated line.
Example: beetle_psx [md5], pcsx_rearmed [existence]
"""
parts = []
for gt in ground_truth:
checks_label = "+".join(gt["checks"]) if gt["checks"] else "existence"
parts.append(f"{gt['emulator']} [{checks_label}]")
return ", ".join(parts)
def _format_ground_truth_verbose(ground_truth: list[dict]) -> list[str]:
"""Format ground truth as one line per core with expected values and source ref.
Example: handy validates crc32=0d973c9d,size=512 [lynx/rom.h:48-49]
"""
lines = []
for gt in ground_truth:
checks_label = "+".join(gt["checks"]) if gt["checks"] else "existence"
expected = gt.get("expected", {})
if expected:
vals = ",".join(f"{k}={v}" for k, v in sorted(expected.items()))
part = f"{gt['emulator']} validates {vals}"
else:
part = f"{gt['emulator']} validates {checks_label}"
if gt.get("source_ref"):
part += f" [{gt['source_ref']}]"
lines.append(part)
return lines
def _print_ground_truth(gt: list[dict], verbose: bool) -> None:
"""Print ground truth lines for a file entry."""
if not gt:
return
if verbose:
for line in _format_ground_truth_verbose(gt):
print(f" {line}")
else:
print(f" {_format_ground_truth_aggregate(gt)}")
def _discrepancy_keys(details: list[dict]) -> set[str]:
"""The DISCREPANCY lines _print_detail_entries prints for these details.
A file already reported MISSING or UNTESTED on its own ground is not
printed again as a discrepancy, and is not counted as one either.
"""
shown = {
f"{d['system']}/{d['name']}"
for d in details
if d["status"] == Status.MISSING
or (d["status"] == Status.UNTESTED and not d.get("discrepancy"))
}
return {
key
for d in details
if d.get("discrepancy")
and (key := f"{d['system']}/{d['name']}") not in shown
}
# A platform entry that is not firmware, as the report names it.
_NOT_FIRMWARE = {
"game_data": "game data",
"unread": "no core the platform runs opens it",
}
def category_evidence_text(evidence: dict) -> str:
"""One line saying what establishes a missing entry's category."""
if evidence.get("read_by"):
groups: dict[bool, list[str]] = {True: [], False: []}
for reader in evidence["read_by"]:
refs = [
f"{e['name']} at {e['source_ref']}" if e.get("source_ref") else e["name"]
for e in reader.get("entries", [])
]
groups[bool(reader.get("runs_system"))].append(
f"{reader['emulator']} ({', '.join(refs)})" if refs
else f"{reader['emulator']} (by {reader['proof']})"
)
if not groups[True]:
return "read by " + ", ".join(groups[False])
text = "read by " + ", ".join(groups[True])
if groups[False]:
text += ", also named by " + ", ".join(groups[False])
return text
examined = evidence.get("cores_examined") or []
cores = f"cores examined: {', '.join(examined)}" if examined else "no core examined"
if evidence.get("unsettled"):
return f"no reader found, not settled: {evidence['unsettled']} ({cores})"
return f"no reader found ({cores})"
def _print_category_evidence(detail: dict) -> None:
evidence = detail.get("category_evidence")
if evidence:
print(f" {category_evidence_text(evidence)}")
def _print_detail_entries(details: list[dict], seen: set[str], verbose: bool) -> None:
"""Print UNTESTED, MISSING, and DISCREPANCY entries from verification details."""
_print_untested_details(details, seen, verbose)
_print_missing_details(details, seen, verbose)
_print_discrepancy_details(details, seen, verbose)
if verbose:
_print_ok_details(details, seen)
def _print_untested_details(details: list[dict], seen: set[str], verbose: bool) -> None:
for d in details:
if d["status"] != Status.UNTESTED:
continue
if d.get("discrepancy"):
# Reported below with the ground for it: a declaration
# unmet at a path another declaration holds.
continue
key = f"{d['system']}/{d['name']}"
if key in seen:
continue
seen.add(key)
req = "required" if d.get("required", True) else "optional"
hle = ", HLE available" if d.get("hle_fallback") else ""
reason = d.get("reason", "")
print(f" UNTESTED ({req}{hle}): {key}: {reason}")
_print_ground_truth(d.get("ground_truth", []), verbose)
def _print_missing_details(details: list[dict], seen: set[str], verbose: bool) -> None:
for d in details:
if d["status"] != Status.MISSING:
continue
key = f"{d['system']}/{d['name']}"
if key in seen:
continue
label = _NOT_FIRMWARE.get(d.get("category", BIOS))
if label:
# Counted on their own line, named on request.
if verbose:
seen.add(key)
print(f" MISSING ({label}): {key}")
_print_category_evidence(d)
continue
seen.add(key)
req = "required" if d.get("required", True) else "optional"
hle = ", HLE available" if d.get("hle_fallback") else ""
print(f" MISSING ({req}{hle}): {key}")
if verbose:
_print_category_evidence(d)
_print_ground_truth(d.get("ground_truth", []), verbose)
def _print_discrepancy_details(details: list[dict], seen: set[str], verbose: bool) -> None:
for d in details:
disc = d.get("discrepancy")
if disc:
key = f"{d['system']}/{d['name']}"
if key in seen:
continue
seen.add(key)
print(f" DISCREPANCY: {key}: {disc}")
_print_ground_truth(d.get("ground_truth", []), verbose)
def _print_ok_details(details: list[dict], seen: set[str]) -> None:
for d in details:
if d["status"] != Status.OK:
continue
key = f"{d['system']}/{d['name']}"
if key in seen:
continue
seen.add(key)
gt = d.get("ground_truth", [])
if gt:
req = "required" if d.get("required", True) else "optional"
print(f" OK ({req}): {key}")
for line in _format_ground_truth_verbose(gt):
print(f" {line}")
def _print_undeclared_entry(
u: dict, prefix: str, verbose: bool, repeated: frozenset[str] = frozenset()
) -> None:
"""Print a single undeclared file entry with its validation checks.
A name in ``repeated`` is read at more than one path, and the line names
the path: two identical lines told no one there were two slots to fill.
"""
name = u["path"] if u["name"] in repeated and u.get("path") else u["name"]
arc_count = u.get("archive_file_count")
if arc_count:
name_label = f"{name} ({arc_count} file{'s' if arc_count != 1 else ''})"
else:
name_label = name
if u.get("alternatives") and not u.get("in_repo"):
name_label += f" (or {', '.join(u['alternatives'])})"
print(f" {prefix}: {u['emulator']} needs {name_label}")
checks = u.get("checks", [])
if checks:
if verbose:
expected = u.get("expected", {})
if expected:
vals = ",".join(f"{k}={v}" for k, v in sorted(expected.items()))
ref_part = f" [{u['source_ref']}]" if u.get("source_ref") else ""
print(f" validates {vals}{ref_part}")
else:
checks_label = "+".join(checks)
ref_part = f" [{u['source_ref']}]" if u.get("source_ref") else ""
print(f" validates {checks_label}{ref_part}")
else:
# A bare "[size]" under the entry said nothing to a reader.
print(f" validates {'+'.join(checks)}")
def _split_undeclared(undeclared: list[dict]) -> tuple[list[dict], list[dict], list[dict]]:
"""Game data, firmware the pack places, firmware it holds but cannot place.
Everything that is not game data is firmware the core loads, archives
included: a bios_zip sat in neither list, so a required one that was
missing was never printed.
"""
game_data = [u for u in undeclared if u.get("category", "bios") == "game_data"]
firmware = [u for u in undeclared if u.get("category", "bios") != "game_data"]
unplaced = [u for u in firmware if u["in_repo"] and not u.get("in_pack", True)]
placed = [u for u in firmware if u.get("in_pack", True)]
return game_data, placed, unplaced
def _core_required_missing(bios_files: list[dict]) -> list[dict]:
"""Core files a core cannot run without, absent from the collection.
A file bundled with the emulator (DaedalusX64's n64.psh, the shader
library its renderer installs beside the binary) arrives with it: the
collection does not hold it by design, and listing it as missing sent
readers after a file every install already has.
"""
return [
u
for u in bios_files
if u["required"] and not u["in_repo"] and not u.get("hle_fallback")
and not u.get("bundled")
]
def _repeated_names(entries: list[dict]) -> frozenset[str]:
"""Names more than one of ``entries`` carries."""
counts = Counter(u["name"] for u in entries)
return frozenset(name for name, count in counts.items() if count > 1)
def _omission_reasons(entries: list[dict]) -> str:
"""Each reason a held file was left out, with its count when several.
Printing the first entry's reason for the whole count named one cause
for 412 RomM files when 20 carried it.
"""
counts = Counter(u.get("omitted", "not placed") for u in entries)
if len(counts) == 1:
return next(iter(counts))
ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
return ", ".join(f"{count} {reason}" for reason, count in ranked)
def _print_undeclared_section(result: dict, verbose: bool) -> None:
"""Print cross-reference section for undeclared files used by cores."""
undeclared = result.get("undeclared_files", [])
# The pack's core copies can come from no gap entry: recalbox
# --system nec-pc-engine packs six root syscard copies for geargrafx
# with an empty gap report, and returning here hid them.
packed = result.get("packed_extras")
if not undeclared and not (packed and any(packed.values())):
return
game_data, bios_files, unplaced = _split_undeclared(undeclared)
# A file installed with its emulator is never collected, firmware or
# game data, required or not: cross_reference counts it apart. The
# firmware already left the pack lists (_mark_unplaced), the game data
# did not, and Abuse's three bundled data files read as missing.
bundled = [u for u in undeclared if not u["in_repo"] and u.get("bundled")]
game_data = [u for u in game_data if u["in_repo"] or not u.get("bundled")]
req_not_in_repo = _core_required_missing(bios_files)
req_hle_not_in_repo = [
u
for u in bios_files
if u["required"] and not u["in_repo"] and u.get("hle_fallback")
]
req_in_repo = [u for u in bios_files if u["required"] and u["in_repo"]]
opt_in_repo = [u for u in bios_files if not u["required"] and u["in_repo"]]
opt_not_in_repo = [u for u in bios_files if not u["required"] and not u["in_repo"]]
# The builder's count, one file per pack path, when the platform pass
# replayed it. Counting entries said 1130 for RetroArch, 48 more than the
# pack holds: rom.key alone was claimed by three Amiga cores.
core_in_pack = (
packed["bios"] if packed is not None else len(req_in_repo) + len(opt_in_repo)
)
core_missing_req = len(req_not_in_repo) + len(req_hle_not_in_repo)
core_missing_opt = len(opt_not_in_repo)
# Required gaps are always named below, the optional ones on request.
listed = "" if verbose or not core_missing_opt else " (--verbose lists them)"
print(
f" Core files: {core_in_pack} in pack, {core_missing_req} required missing, "
f"{core_missing_opt} optional missing{listed}"
)
# The missing files follow the line that counts them: printed after the
# held-but-not-packed line, they read as files installed with their emulator.
repeated = _repeated_names(req_not_in_repo + req_hle_not_in_repo + opt_not_in_repo)
for u in req_not_in_repo:
_print_undeclared_entry(u, "MISSING (required)", verbose, repeated)
for u in req_hle_not_in_repo:
_print_undeclared_entry(u, "MISSING (required, HLE fallback)", verbose, repeated)
if verbose:
for u in opt_not_in_repo:
_print_undeclared_entry(u, "MISSING (optional)", verbose, repeated)
if bundled:
# The required firmware is named, as a missing one would be. The
# rest (shaders, runtime libraries, engine data) on request.
shown = bundled if verbose else [
u for u in bundled
if u["required"] and u.get("category", "bios") != "game_data"
]
named = sorted({u["name"] for u in shown})
# The required firmware alone read as the whole count: 14 names
# for 154 entries, nothing saying the rest existed.
hidden = len({u["name"] for u in bundled}) - len(named)
more = f"{hidden} more, " if named else ""
items = named + ([f"{more}--verbose lists them"] if hidden else [])
print(
f" Bundled with their emulator, not collected: {len(bundled)}"
+ (f" ({', '.join(items)})" if items else "")
)
if unplaced:
print(f" Core files held but not packed: {len(unplaced)} "
f"({_omission_reasons(unplaced)})")
if game_data or (packed and packed.get("game_data")):
gd_missing = [u for u in game_data if not u["in_repo"]]
gd_packed = (
packed["game_data"] if packed is not None
else sum(1 for u in game_data if u["in_repo"] and u.get("in_pack", True))
)
gd_unplaced = [u for u in game_data if u["in_repo"] and not u.get("in_pack", True)]
if gd_missing or gd_packed or gd_unplaced:
listed = "" if verbose or not gd_missing else " (--verbose lists them)"
print(f" Game data: {gd_packed} in pack, {len(gd_missing)} missing{listed}")
if verbose:
repeated = _repeated_names(gd_missing)
for u in gd_missing:
_print_undeclared_entry(u, "MISSING (game data)", verbose, repeated)
if gd_unplaced:
print(
f" Game data held but not packed: {len(gd_unplaced)} "
f"({_omission_reasons(gd_unplaced)})"
)
def _print_launcher_unproven(result: dict, verbose: bool) -> None:
"""Launcher records resting on a config file the code does not prove."""
rows = result.get("launcher_unproven") or []
if not rows:
return
listed = "" if verbose else " (--verbose lists them)"
print(f" Launcher records unproven: {len(rows)}{listed}")
if not verbose:
return
for row in rows:
print(f" [{row['index']}] {row['emulator']} {row['kind']}: {row['passes_to']}")
for link in row["missing"]:
print(f" missing {link}")
def _print_launcher_reads(result: dict, verbose: bool) -> None:
"""Names the platform's launch code reads that the collection lacks."""
every = result.get("launcher_reads_not_held") or []
rows = [r for r in every if not r.get("unsourceable")]
unsourceable = [r for r in every if r.get("unsourceable")]
listed = "" if verbose else " (--verbose lists them)"
if rows:
print(f" Launcher reads, not held: {len(rows)}{listed}")
if unsourceable:
print(f" Launcher reads, unsourceable: {len(unsourceable)}{listed}")
if not verbose:
return
for row in unsourceable:
print(f" {row['name']} [{', '.join(row['emulators'])}]: {row['unsourceable']}")
for row in rows:
kinds = ", ".join(sorted({r["kind"] for r in row["readers"]}))
casing = f", held as {row['held_as']}" if row.get("held_as") else ""
print(f" {row['name']} [{', '.join(row['emulators'])}, {kinds}{casing}]")
for reader in row["readers"]:
print(f" {reader['emulator']}: {reader['source_ref']}")
def _platform_summary_parts(result: dict) -> list[str]:
"""The counts of a platform's first report line, in its mode's terms."""
mode = result["verification_mode"]
total = result["total_files"]
c = result["severity_counts"]
ok_count = c[Severity.OK]
problems = total - ok_count
if not reads_file_contents(mode):
parts = [f"{ok_count}/{total} present"]
if problems:
missing = c.get(Severity.WARNING, 0) + c.get(Severity.CRITICAL, 0)
optional_missing = c.get(Severity.INFO, 0)
if missing:
parts.append(f"{missing} missing")
if optional_missing:
parts.append(f"{optional_missing} optional missing")
return parts
sc = result.get("status_counts", {})
untested = sc.get(Status.UNTESTED, 0)
missing = sc.get(Status.MISSING, 0)
parts = [f"{ok_count}/{total} OK"]
if untested:
parts.append(f"{untested} untested")
if missing:
parts.append(f"{missing} missing")
return parts
def _print_release_assets(details: list[dict]) -> None:
fetched = sorted({d["name"] for d in details if d.get("release_asset")})
if fetched:
# Counted present: an online build downloads them. --offline counts
# them missing, as an offline build leaves them out.
shown = ", ".join(fetched[:10]) + (f" (+{len(fetched) - 10})" if len(fetched) > 10 else "")
print(f" Release assets fetched when the pack is built ({len(fetched)}): {shown}")
def _print_platform_notices(result: dict, verbose: bool) -> None:
"""What the counts leave unsaid: uncached trees, cuts, region and category gaps."""
uncached = result.get("data_dir_notices") or []
if uncached and result.get("status_counts", {}).get(Status.MISSING):
shown = ", ".join(uncached[:10]) + (f" (+{len(uncached) - 10})" if len(uncached) > 10 else "")
print(
f" Data directories not cached ({len(uncached)}), their files count missing "
f"until refresh_data_dirs.py runs (an online pack build refreshes them): {shown}"
)
for line in result.get("left_out") or []:
print(f" {line}")
fallbacks = result.get("region_fallbacks") or []
if fallbacks:
from packs.readme import _group_label
print(f" No BIOS for the requested regions, all kept ({len(fallbacks)}): "
+ ", ".join(_group_label(g) for g in fallbacks))
not_firmware = result.get("missing_not_firmware") or {}
if not_firmware:
counts = ", ".join(
f"{len(dests)} {_NOT_FIRMWARE[category]}"
for category, dests in not_firmware.items()
)
listed = "" if verbose else " (--verbose lists them)"
print(f" Missing, not firmware: {counts}{listed}")
def _print_platform_coverage(result: dict, verbose: bool) -> None:
# The same notes come back for every platform running these cores and
# filled 985 of the 1114 lines of verify --all: counted, listed on ask.
exclusions = result.get("exclusion_notes", [])
if exclusions and verbose:
print(f" No external files ({len(exclusions)}):")
for ex in exclusions:
print(f" {ex['emulator']}: {ex['detail']} [{ex['reason']}]")
elif exclusions:
print(f" No external files: {len(exclusions)} cores (--verbose lists them)")
gt_cov = result.get("ground_truth_coverage")
if gt_cov and not gt_cov.get("applicable", True):
# MiSTer declares no core by design: its BiosDB is the answer, and
# the site shows "-" for it rather than a 0% gap.
print(" Ground truth: not applicable, the platform runs no profiled core")
elif gt_cov and gt_cov["total"] > 0:
# Rounded, as the site rounds: truncated, RetroArch read 20% here
# and 21% there for one measure.
pct = round(gt_cov["with_validation"] * 100 / gt_cov["total"])
print(
f" Ground truth: {gt_cov['with_validation']}/{gt_cov['total']} files have emulator validation ({pct}%)"
)
no_profile = gt_cov["total"] - gt_cov.get("with_profile", gt_cov["with_validation"])
if no_profile:
print(f" {no_profile} platform-only (no emulator profile)")
def print_platform_result(
result: dict, group: list[str], verbose: bool = False
) -> None:
mode = result["verification_mode"]
label = " / ".join(group)
if result.get("systems"):
label += f" ({', '.join(result['systems'])})"
parts = _platform_summary_parts(result)
print(f"{label}: {', '.join(parts)} [{mode}]")
_print_release_assets(result["details"])
_print_platform_notices(result, verbose)
seen_details: set[str] = set()
_print_detail_entries(result["details"], seen_details, verbose)
_print_undeclared_section(result, verbose)
_print_launcher_reads(result, verbose)
_print_launcher_unproven(result, verbose)
_print_platform_coverage(result, verbose)
def _emulator_summary_parts(result: dict) -> list[str]:
total = result["total_files"]
ok_count = result["severity_counts"][Severity.OK]
sc = result.get("status_counts", {})
untested = sc.get(Status.UNTESTED, 0)
missing = sc.get(Status.MISSING, 0)
# Counted by slot, as missing is: xash3d's thirteen unsourceable
# pak0.pak and liblist.gam were three names and ten "missing".
missing_slots: dict[str, bool] = {}
for d in result["details"]:
if d["status"] == Status.MISSING:
slot = d.get("destination") or d["name"]
missing_slots[slot] = missing_slots.get(slot, True) and "unsourceable" in d
unsourceable = sum(missing_slots.values())
parts = [f"{ok_count}/{total} OK"]
if untested:
parts.append(f"{untested} untested")
if missing - unsourceable > 0:
parts.append(f"{missing - unsourceable} missing")
if unsourceable:
parts.append(f"{unsourceable} unsourceable")
return parts
def _print_emulator_ground_truth(gt: list[dict], verbose: bool) -> None:
if gt:
if verbose:
for line in _format_ground_truth_verbose(gt):
print(f" {line}")
else:
print(f" {_format_ground_truth_aggregate(gt)}")
def _print_emulator_problems(details: list[dict], seen: set[str], verbose: bool) -> None:
"""The UNTESTED, MISSING and UNSOURCEABLE lines of an emulator report."""
for d in details:
if d["status"] == Status.UNTESTED:
if d["name"] in seen:
continue
seen.add(d["name"])
req = "required" if d.get("required", True) else "optional"
hle = ", HLE available" if d.get("hle_fallback") else ""
reason = d.get("reason", "")
print(f" UNTESTED ({req}{hle}): {d['name']}: {reason}")
_print_emulator_ground_truth(d.get("ground_truth", []), verbose)
for d in details:
if d["status"] == Status.MISSING and "unsourceable" not in d:
if d["name"] in seen:
continue
seen.add(d["name"])
req = "required" if d.get("required", True) else "optional"
hle = ", HLE available" if d.get("hle_fallback") else ""
others = d.get("alternatives")
either = f" (or {', '.join(others)})" if others else ""
print(f" MISSING ({req}{hle}): {d['name']}{either}")
_print_emulator_ground_truth(d.get("ground_truth", []), verbose)
for d in details:
if d["status"] == Status.MISSING and "unsourceable" in d:
if d["name"] in seen:
continue
seen.add(d["name"])
why = d.get("unsourceable") or "documented as unobtainable"
print(f" UNSOURCEABLE: {d['name']}: {why}")
def _print_emulator_ok(details: list[dict], seen: set[str]) -> None:
for d in details:
if d["status"] == Status.OK:
if d["name"] in seen:
continue
seen.add(d["name"])
gt = d.get("ground_truth", [])
if gt:
req = "required" if d.get("required", True) else "optional"
print(f" OK ({req}): {d['name']}")
for line in _format_ground_truth_verbose(gt):
print(f" {line}")
def print_emulator_result(result: dict, verbose: bool = False) -> None:
"""Print verification result for emulator/system mode."""
label = " + ".join(result["emulators"])
mode = result["verification_mode"]
parts = _emulator_summary_parts(result)
print(f"{label}: {', '.join(parts)} [{mode}]")
fetched = sorted({d["name"] for d in result["details"] if d.get("release_asset")})
if fetched:
shown = ", ".join(fetched[:10]) + (f" (+{len(fetched) - 10})" if len(fetched) > 10 else "")
print(f" Release assets fetched when the pack is built ({len(fetched)}): {shown}")
seen: set[str] = set()
_print_emulator_problems(result["details"], seen, verbose)
for d in result["details"]:
if d.get("note"):
print(f" {d['note']}")
if verbose:
_print_emulator_ok(result["details"], seen)
for ref in result.get("data_dir_notices", []):
print(
f" Note: data directory '{ref}' required but not included (use refresh_data_dirs.py)"
)
gt_cov = result.get("ground_truth_coverage")
if gt_cov and gt_cov["total"] > 0:
pct = round(gt_cov["with_validation"] * 100 / gt_cov["total"])
print(
f" Ground truth: {gt_cov['with_validation']}/{gt_cov['total']} files have emulator validation ({pct}%)"
)
if gt_cov["platform_only"]:
print(f" {gt_cov['platform_only']} without declared validation")
+109
View File
@@ -0,0 +1,109 @@
"""The systems a pack covers, with the titles a person reads."""
from __future__ import annotations
from collections.abc import Iterable
def platform_list_version(config: dict, platform: str) -> str:
"""The version of the list a platform's YAML transcribes: the release
tag the scraper read, or for a list kept on a branch with no release,
the date of the commit it pinned. load_platform_config never passes a
parent's version to a child, Lakka is not RetroArch v1.22.2.
The installer compares it with the version a machine runs, so a missing
value is refused rather than written as a stand-in.
"""
version = str(config.get("version") or "").strip()
if not version:
raise ValueError(
f"{platform}: the platform YAML records no version of its own"
)
return version
def system_titles(*entry_lists: Iterable[dict]) -> dict[str, str]:
"""The name a person reads for each system the entries carry.
Batocera names PlayStation `psx` and the installer showed
`sony-playstation (psx)`: neither is what a beginner looks for. The
title is the one the site prints, so a system reads the same on its
page and in the installer. A system the site cannot name is left out,
and the installer shows its id: the site build refuses such a system,
so only a test fixture reaches here with one.
"""
from siterender import system_name
ids = {
sys_id
for entries in entry_lists for entry in entries
for sys_id in entry.get("systems") or []
}
titles: dict[str, str] = {}
for sys_id in sorted(ids):
try:
titles[sys_id] = system_name(sys_id)
except KeyError:
continue
return titles
def pack_systems(install_manifest: dict, targets: dict | None = None) -> dict:
"""What a pack's manifest.json records of its systems, from the install
list built with the same choices: each file's systems, by its path in
the pack, and the names a person reads for them.
A pack recorded none: the installer refused --system with a pack alone
("the file list comes from an older release") and offered no Choose
systems, the route of a handheld without Wi-Fi.
The install list itself and the platform's cores per board (targets, as
install/targets/ publishes them) ride along: with the pack alone, a
board was never applied and --target was refused, and a Batocera RPi4
card took 8.9 GB where its board reads 5.8.
"""
files = install_manifest.get("files", [])
entries = [*files, *install_manifest.get("omitted_files", [])]
# What the install list narrows by, the installer's recorded_axes: with
# the pack alone it names that list as the way to --core and --region
# only when the list records them. It named install/misterfpga.json for
# --core, a list that records no core.
records = {"systems"} if any("systems" in entry for entry in entries) else set()
if any(copy.get("cores") for entry in files
for copy in [entry, *entry.get("alternatives", []),
*entry.get("slot_choices", [])]):
records.add("cores")
if records or any("regions" in entry for entry in entries):
records.add("regions")
systems = {
"files": {entry["dest"]: list(entry.get("systems") or [])
for entry in files if "systems" in entry},
"system_titles": dict(install_manifest.get("system_titles") or {}),
"system_names": dict(install_manifest.get("system_names") or {}),
"list_records": sorted(records),
}
# The version of the platform's list, which the installer compares with
# the one the machine runs when it has the pack alone.
if install_manifest.get("version"):
systems["list_version"] = install_manifest["version"]
systems["install_list"] = install_manifest
if targets is not None:
systems["targets"] = targets
return systems
def annotate_pack_systems(manifest: dict, systems: dict | None) -> None:
"""Write pack_systems into a pack's manifest: a systems list on each
file the install list names, the titles and names beside."""
if not systems:
return
for entry in manifest.get("files", []):
held = systems["files"].get(entry["path"])
if held is not None:
entry["systems"] = held
for key in ("system_titles", "system_names"):
if systems.get(key):
manifest[key] = systems[key]
for key in ("list_records", "list_version", "install_list", "targets"):
if key in systems:
manifest[key] = systems[key]
+643
View File
@@ -0,0 +1,643 @@
"""Who decides what goes at a destination: the platform's claim against the emulator profile's."""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
from core.hashing import parse_md5_list
from model.profiles import entry_system_ids
from resolve import nativemode
from resolve.archives import archive_entry, holds_required_members
from resolve.collisions import _accepted_by_all, _content_sha1, _lists_hashes, _normalize
from resolve.cores import resolve_platform_cores
from resolve.layout import system_dir_path
from resolve.localfile import resolution_is_hash_exact, resolve_local_file
from resolve.packfiles import preferred_entries
from resolve.standalone import platform_layouts, standalone_set as platform_standalone_set
from resolve.validation import (
content_alternatives,
outside_gap_scope,
read_from_save_dir,
with_archive_members,
)
if TYPE_CHECKING:
from packs.extras import ExtraPlacement
# A profile entry can prove a slot without declaring a hash: Dolphin names no
# checksum for the GameCube boot ROM because its source names none, and the
# proof is then the path the repository stores the file at.
# A profile entry that names an exact size, for a file the code reads in
# full (no hash to declare), is proven by a held copy of that size: the
# platform's xmil/IPLROM.X1T pinned the 2 KiB X1 font where xmil reads a
# 32 KiB Turbo IPL, and a name-only claim could not contest it.
SIZE_EXACT = "size_exact"
PROVEN_STATUSES = frozenset({"path_exact", "members_held", SIZE_EXACT})
def _size_the_code_reads(entry: dict, local: str | None) -> bool:
"""Whether a name-resolved copy has the exact size the entry declares."""
size = entry.get("size")
if not local or not isinstance(size, int) or size <= 0:
return False
try:
return os.path.getsize(local) == size
except OSError:
return False
# A core that reads ROMs inside an archive proves the archive by its members:
# FBNeo's neocdz.zip is any copy holding neocd.bin and 000-lo.lo by crc.
MEMBERS_HELD = "members_held"
@dataclass
class Claim:
"""One layer's answer to what belongs at a destination."""
origin: str
destination: str
name: str
emulator: str = ""
entry: dict = field(default_factory=dict)
local_path: str | None = None
status: str = ""
# A core that identifies its firmware by content reads no file by this
# name: any dump it takes for the same system and region answers for it.
accepts: tuple[dict, ...] = ()
@property
def is_proven(self) -> bool:
"""Whether the claim rests on evidence rather than on a bare name."""
return resolution_is_hash_exact(self.status) or self.status in PROVEN_STATUSES
@dataclass
class Conflict:
"""Two proven claims on one destination that resolve to different files."""
destination: str
platform_claim: Claim
profile_claims: list[Claim]
@property
def emulators(self) -> list[str]:
return sorted({c.emulator for c in self.profile_claims if c.emulator})
def files_read(self) -> list[tuple[str | None, list[str], str]]:
"""Each file the profiles want here, with the emulators reading it
and the proof of the first claim on it.
One file stood for every claim: Recalbox's neocdz.zip line gave
geolith the archive fbneo reads, not the one geolith pins.
"""
files: dict[str | None, tuple[list[str], str]] = {}
for claim in self.profile_claims:
emulators, status = files.setdefault(claim.local_path, ([], claim.status))
if claim.emulator and claim.emulator not in emulators:
emulators.append(claim.emulator)
return [(path, sorted(emus), status) for path, (emus, status) in files.items()]
def platform_claims(
config: dict,
db: dict,
base_dest: str = "",
zip_contents: dict | None = None,
data_dir_registry: dict | None = None,
) -> list[Claim]:
"""What the platform YAML says belongs at each of its destinations."""
claims: list[Claim] = []
for system in (config.get("systems") or {}).values():
for entry in system.get("files") or []:
if not isinstance(entry, dict):
continue
dest = entry.get("destination") or entry.get("name") or ""
if not dest:
continue
full = f"{base_dest}/{dest}" if base_dest else dest
local, status = resolve_local_file(
entry,
db,
zip_contents,
dest_hint=dest,
data_dir_registry=data_dir_registry,
)
claims.append(
Claim(
origin="platform",
destination=full,
name=entry.get("name", ""),
entry=entry,
local_path=local,
status=status,
)
)
return claims
def profile_claims(
profiles: dict,
db: dict,
base_dest: str = "",
standalone_cores: set[str] | None = None,
zip_contents: dict | None = None,
data_dir_registry: dict | None = None,
config: dict | None = None,
) -> list[Claim]:
"""What each emulator profile says belongs at each destination it names.
With the platform's config, a claim sits where the pack puts the core's
file (ExtraPlacement): under RetroDECK's bios/, under RomM's system
folder. A file the platform cannot place claims nothing.
A file can exist in one build of an emulator and not the other, and the
two builds read from different directories. The mode is decided per
emulator, not per pack: a platform runs some of its emulators as libretro
cores and others standalone, naming the latter in ``standalone_cores``.
An entry the standalone build alone loads does not address a platform
running that emulator as a core, and where it does, the destination is
``standalone_path``. This is the gate verify already applies.
"""
standalone_cores = standalone_cores or set()
placement = None
if config is not None:
from packs.extras import ExtraPlacement
placement = ExtraPlacement(config, base_dest, profiles)
claims: list[Claim] = []
for emu_name, profile in sorted(profiles.items()):
if profile.get("type") in ("launcher", "alias"):
continue
# The gap report skips a filename-agnostic profile whole: the builder
# carries its scan candidates, never its named entries.
if profile.get("bios_mode") == "agnostic":
continue
for layout, is_standalone in platform_layouts(emu_name, profile, standalone_cores):
claims.extend(
_archive_claims(
emu_name, layout, is_standalone, db, base_dest, placement,
zip_contents, data_dir_registry,
)
)
for entry in layout.get("files") or []:
if not isinstance(entry, dict):
continue
# The same rule as the gap report and the builder: an entry the
# pack never carries (a placeholder, a filename-agnostic scan)
# arbitrates nothing. One read below the save directory sits
# outside the BIOS tree, where no platform declares a file.
if outside_gap_scope(entry, is_standalone) or read_from_save_dir(
entry, is_standalone
) or entry.get("unplaced"):
continue
# A member of a romset is not a file at the BIOS root: the archive
# holding it occupies the destination (_archive_claims). Claiming
# the member put FBNeo's msx.zip contents loose at the root.
if entry.get("archive"):
continue
dest = (
(entry.get("standalone_path") or entry.get("path"))
if is_standalone
else system_dir_path(entry, entry.get("path") or entry.get("name") or "")
) or entry.get("name") or ""
if not dest:
continue
if placement is None:
full = f"{base_dest}/{dest}" if base_dest else dest
else:
placed = placement.place(
{
"profile": emu_name,
"system": entry.get("system"),
"systems": entry_system_ids(entry, layout),
},
dest,
)
if placed is None:
continue
full = placed[1]
# The owner's own copy is the one the builder ships.
local, status = resolve_local_file(
{
**with_archive_members(entry, layout.get("files") or []),
"source_profile": emu_name,
},
db,
zip_contents,
dest_hint=dest,
data_dir_registry=data_dir_registry,
)
if status == "name_exact" and _size_the_code_reads(entry, local):
status = SIZE_EXACT
accepts = tuple(content_alternatives(entry, layout))
claims.append(
Claim(
origin="profile",
destination=full,
name=entry.get("name", ""),
emulator=emu_name,
entry=entry,
local_path=local,
status=status,
accepts=accepts,
)
)
return claims
def _archive_claims(
emu_name: str,
profile: dict,
is_standalone: bool,
db: dict,
base_dest: str,
placement: ExtraPlacement | None,
zip_contents: dict | None,
data_dir_registry: dict | None,
) -> list[Claim]:
"""The archives a core reads its ROMs from, where the builder places them.
The archive sits at the root and, for a core that reads a directory of
its own (archive_prefix), under it as well. The claim is proven when the
copy holds every member the core requires.
"""
files = [
entry for entry in profile.get("files") or []
if isinstance(entry, dict)
and not outside_gap_scope(entry, is_standalone)
and not read_from_save_dir(entry, is_standalone)
and not entry.get("unplaced")
]
prefix = profile.get("archive_prefix", "")
claims: list[Claim] = []
for archive in sorted({entry["archive"] for entry in files if entry.get("archive")}):
entry = archive_entry(archive, files)
members = entry.get("members")
if not members:
continue
member = next(f for f in files if f.get("archive") == archive)
system = member.get("system")
if member.get("system_dir"):
entry = {**entry, "system_dir": member["system_dir"]}
root = system_dir_path(entry, archive)
for dest in (root, f"{prefix}/{archive}") if prefix else (root,):
if placement is None:
full = f"{base_dest}/{dest}" if base_dest else dest
else:
placed = placement.place({"profile": emu_name, "system": system}, dest)
if placed is None:
continue
full = placed[1]
local, status = resolve_local_file(
{**entry, "source_profile": emu_name},
db,
zip_contents,
dest_hint=dest,
data_dir_registry=data_dir_registry,
)
if (
local
and not resolution_is_hash_exact(status)
and holds_required_members(local, members)
):
status = MEMBERS_HELD
claims.append(
Claim(
origin="profile",
destination=full,
name=archive,
emulator=emu_name,
entry=entry,
local_path=local,
status=status,
)
)
return claims
def checked_by_path(mode: str, entry: dict, rule: str = "") -> bool:
"""Whether the frontend checks this declaration by its path alone.
Whether a frontend reads the bytes is a property of the platform, but
what it compares them with is the entry's: Batocera skips an empty md5
(batocera-systems:1088), and EmuDeck declares neocdz.zip with no hash at
all. Such an entry is a path, in an md5 platform as in an existence one.
A member pinned inside an archive is content.
"""
if not nativemode.reads_file_contents(mode):
return True
if entry.get("zipped_file"):
return False
if rule == nativemode.SIZE_AND_ANY_HASH:
fields: tuple[str, ...] = ("md5", "sha1", "crc32")
else:
fields = (nativemode.digest_algorithm(mode) or "",)
return not any(
parse_md5_list(entry.get(name)) if name == "md5" else entry.get(name)
for name in fields
)
def _claim_rank(claim: Claim) -> int:
"""How strongly a platform claim speaks for what the pack ships."""
if resolution_is_hash_exact(claim.status):
return 2
return 1 if claim.is_proven else 0
def _slot_claims(
config: dict,
profiles: dict,
db: dict,
base_dest: str,
standalone_cores: set[str] | None,
zip_contents: dict | None,
data_dir_registry: dict | None,
) -> tuple[dict[str, Claim], dict[str, list[Claim]]]:
"""The platform claim and the proven profile claims at each destination."""
fold = bool(config.get("case_insensitive_fs", False))
# The builder's own choice among declarations sharing a destination,
# read from the same function: the most accepting archive for zipped_file
# members, then md5_exact. A rule of its own here compared profiles with
# a file the pack does not ship (Batocera adam_fdc.zip).
shipped = set(
preferred_entries(
config.get("systems") or {}, db, "bios", base_dest, False,
zip_contents, True,
).values()
)
by_dest: dict[str, Claim] = {}
for claim in platform_claims(
config, db, base_dest, zip_contents, data_dir_registry
):
key = _normalize(claim.destination, fold)
held = by_dest.get(key)
if held is not None and id(held.entry) in shipped:
continue
# A bare sibling met first must not stand for the destination: it
# would hide the contradiction with the file actually shipped.
if (
held is None
or id(claim.entry) in shipped
or _claim_rank(claim) > _claim_rank(held)
):
by_dest[key] = claim
# Grouped before judging: a profile may declare several revisions that are
# all acceptable at one destination, and the platform choosing one of them
# is agreement, not contradiction. Only a destination where no profile
# claim at all matches what ships is a disagreement.
# A platform claim resting on a bare name, or on a pin no local file
# matches, asserts nothing about content. Where the frontend never reads
# the bytes, a proven profile claim then decides: RetroArch's neocdz.zip
# pins an md5 nobody holds, and the primary shipped without the 000-lo.lo
# geolith and FBNeo read inside it. Decided per entry: EmuDeck, an md5
# platform, declares the same archive with no hash.
mode = config.get("verification_mode", "existence")
rule = config.get("hash_rule", "")
by_slot: dict[str, list[Claim]] = {}
for claim in profile_claims(
profiles, db, base_dest, standalone_cores, zip_contents, data_dir_registry,
config=config,
):
key = _normalize(claim.destination, fold)
platform = by_dest.get(key)
if platform is None or not claim.is_proven:
continue
if claim.status == SIZE_EXACT and (
not platform.local_path
or _size_the_code_reads(claim.entry, platform.local_path)
):
# A size proves a claim only against a file of another size.
continue
if not platform.is_proven and not (
platform.local_path and checked_by_path(mode, platform.entry, rule)
):
continue
by_slot.setdefault(key, []).append(claim)
return by_dest, by_slot
def find_conflicts(
config: dict,
profiles: dict,
db: dict,
base_dest: str = "",
standalone_cores: set[str] | None = None,
zip_contents: dict | None = None,
data_dir_registry: dict | None = None,
) -> list[Conflict]:
"""Destinations where a proven profile claim contradicts what ships.
Only proven claims are compared. A claim resolved by filename alone
asserts nothing about content and cannot contradict anything.
"""
by_dest, by_slot = _slot_claims(
config, profiles, db, base_dest, standalone_cores, zip_contents,
data_dir_registry,
)
# A declaration that lists several accepted hashes is satisfied by any of
# them: Recalbox names both scph1001.bin revisions, and mesence names
# four BS-X dumps among which System.dat pins one. The resolver stops on
# the first it finds, so the paths differ while both layers agree.
disputed = {
key: claims
for key, claims in by_slot.items()
if not any(_satisfies(c, by_dest[key], db) for c in claims)
}
return [
Conflict(
destination=by_dest[key].destination,
platform_claim=by_dest[key],
profile_claims=claims,
)
for key, claims in sorted(disputed.items())
]
# Why a decision went the way it did. Not the mode's own name: the mode is
# spelt in one place only, and nativemode answers whether it reads content.
SERVES_BOTH = "path_only_check"
ADDRESSEE = "addressee"
FRONTEND_CHECKS_CONTENT = "frontend_checks_content"
@dataclass
class Decision:
"""Which claim a pack should honour at a contested destination, and why."""
conflict: Conflict
winner: Claim
reason: str
@property
def serves_both(self) -> bool:
"""Whether honouring the winner still satisfies the other layer."""
return self.reason == SERVES_BOTH
def pack_overrides(
config: dict,
profiles: dict,
db: dict,
zip_contents: dict | None = None,
data_dir_registry: dict | None = None,
target_cores: set[str] | None = None,
source: str = "full",
choices: dict[str, list[tuple[str, str | None]]] | None = None,
) -> dict[str, str]:
"""Full pack destination -> the file a platform pack serves there instead.
Where a source-verified profile contradicts the scraped baseline on one
destination, the pack answers to the platform it is built for. In
existence mode the frontend never reads the bytes, so serving the
emulator's file satisfies both. The ZIP builder, the install manifest and
verify all read this: two of them deciding alone gave the one-line
installer different bytes than the ZIP. ``choices`` is slot_choices
for the same arguments when the caller already holds it.
"""
# A baseline-only pack serves what the platform declares, and a target's
# pack answers to the cores that hardware builds: DuckStation does not
# exist on any RetroArch target and still replaced its scph5000.bin.
if not profiles or source == "platform":
return {}
cores = set(resolve_platform_cores(config, profiles, target_cores=target_cores))
overrides: dict[str, str] = {}
if choices is None:
choices = slot_choices(config, profiles, db, zip_contents, data_dir_registry)
for destination, ordered in choices.items():
path = next((path for emulator, path in ordered if emulator in cores), None)
if path:
overrides[destination] = path
return overrides
def slot_choices(
config: dict,
profiles: dict,
db: dict,
zip_contents: dict | None = None,
data_dir_registry: dict | None = None,
) -> dict[str, list[tuple[str, str | None]]]:
"""Destination -> (core, the file it has served there) in decision order.
A pack built for a set of cores serves the first choice whose core is in
it, None standing for the platform's own answer. No core in it leaves
the platform's answer too. The order is arbitrate's: a core agreeing with
the platform settles the slot whatever else is present, then the
strongest proof decides. Read for one core set by pack_overrides and
recorded whole in the install manifest, so a target narrowed from the
full manifest gets the bytes the target's own pack carries.
"""
mode = config.get("verification_mode", "existence")
rule = config.get("hash_rule", "")
platform_profiles = {
name: profiles[name] for name in resolve_platform_cores(config, profiles)
}
by_dest, by_slot = _slot_claims(
config,
platform_profiles,
db,
config.get("base_destination", ""),
platform_standalone_set(config),
zip_contents,
data_dir_registry,
)
choices: dict[str, list[tuple[str, str | None]]] = {}
for key, claims in sorted(by_slot.items()):
platform = by_dest[key]
# Where the frontend compares a hash, the platform's file stays.
if not checked_by_path(mode, platform.entry, rule):
continue
agree = [_satisfies(c, platform, db) for c in claims]
agreeing = [c for c, ok in zip(claims, agree) if ok]
others = sorted(
(c for c, ok in zip(claims, agree) if not ok),
key=lambda claim: (-_claim_rank(claim), claims.index(claim)),
)
if not others:
continue
choices[platform.destination] = [
*((c.emulator, None) for c in agreeing),
*((c.emulator, c.local_path) for c in others),
]
return choices
def _strongest(claims: list[Claim]) -> Claim:
"""The profile claim with the strongest proof, the first emulator breaking ties.
yaps2 pins its GameIndex.yaml by sha1 while armsx2 and lrps2 only match a
path: alphabetical order served armsx2's copy to all three.
"""
return max(claims, key=lambda claim: (_claim_rank(claim), -claims.index(claim)))
def arbitrate(
conflict: Conflict, mode: str, addressee: str = "platform", rule: str = "",
) -> Decision:
"""Decide a contested destination for the pack being built.
A pack answers to whoever asked for it. A platform pack must leave the
frontend's own check green, because a user reading red concludes the pack
is broken. A pack built for one emulator answers to that emulator. The
other layer is served as well whenever the destination allows it.
In ``existence`` mode the frontend only looks for a path, so the emulator's
file satisfies both sides at once and there is nothing to trade away. In a
content-checking mode the two answers cannot share one path, and the pack's
addressee decides. The loss is reported rather than absorbed: only the
platform's own list can change what its frontend accepts there.
"""
profile = _strongest(conflict.profile_claims)
if addressee == "emulator":
return Decision(conflict, profile, ADDRESSEE)
if checked_by_path(mode, conflict.platform_claim.entry, rule):
return Decision(conflict, profile, SERVES_BOTH)
return Decision(conflict, conflict.platform_claim, FRONTEND_CHECKS_CONTENT)
def _satisfies(profile: Claim, platform: Claim, db: dict) -> bool:
"""Whether the two layers agree on what ships at this destination.
They agree when they resolve to the same bytes, when the platform's own
hash list accepts the profile's file, or when the profile's accepts the
platform's. A contradiction needs both lists to reject the other side.
A core found by content (found_by: content) reads no file by the
destination's name, so any dump it takes for the same system and region
settles the slot: DuckStation takes Batocera's scph1001.bin v2.0, which its profile
labels scph1001_v20.bin.
"""
if profile.local_path == platform.local_path:
return True
# Two paths can hold one content: AmberELEC's bluemsx declarations
# resolve into the data/bluemsx cache, the profile's into bios/.
if profile.local_path and platform.local_path:
shipped = _content_sha1(platform.local_path, db)
if shipped is not None and shipped == _content_sha1(profile.local_path, db):
return True
members = profile.entry.get("members")
if members and platform.local_path:
return holds_required_members(platform.local_path, members)
if (
profile.local_path
and _lists_hashes(platform.entry)
and _accepted_by_all(profile.local_path, [platform.entry], db)
):
return True
if platform.local_path and any(
_lists_hashes(label) and _accepted_by_all(platform.local_path, [label], db)
for label in profile.accepts
):
return True
return bool(
platform.local_path
and _lists_hashes(profile.entry)
and _accepted_by_all(platform.local_path, [profile.entry], db)
)
+242
View File
@@ -0,0 +1,242 @@
"""Files a standalone emulator reads where the platform places them."""
from __future__ import annotations
import contextlib
import io
import re
from pathlib import PurePosixPath
from core.paths import REPO_ROOT
from packs.archive import PackRecord
from packs.emulatorpack import generate_emulator_pack
from packs.manifestentry import _manifest_entry
def _placed_copies(copies: list[dict], dests: list[str]) -> list[dict]:
"""Each standalone copy with the path this manifest gives its file.
The registry names one path per file for every platform (one anchor),
while each manifest places the file its own way: EmuDeck installs
aes_keys.txt at the root and Batocera prod.keys under switch/, so the
installer looked for Citra/sysdata/aes_keys.txt, found nothing and
copied nothing. `file` stays as written, since it also lays out a custom
emulator root. `source` says where the installed file is.
"""
by_name: dict[str, list[str]] = {}
for dest in dests:
by_name.setdefault(dest.rsplit("/", 1)[-1].casefold(), []).append(dest)
placed: list[dict] = []
for copy in copies:
wanted = copy.get("file")
if not wanted or wanted in dests:
placed.append(copy)
continue
tail = [d for d in dests if d.endswith("/" + wanted)]
if tail:
# The file whose path carries the least on top of the tail.
shortest = min(len(d) for d in tail)
tail = [d for d in tail if len(d) == shortest]
else:
tail = by_name.get(wanted.rsplit("/", 1)[-1].casefold(), [])
placed.append({**copy, "source": tail[0]} if len(tail) == 1 else copy)
return placed
# data_root keys of the profiles, as the copy targets name each system.
_DATA_ROOT_SYSTEMS = {"linux": "linux", "macos": "darwin", "windows": "windows",
"android": "android"}
def _data_root_target(system: str, text: str) -> str | None:
"""A profile's data_root on one system as a copy target, or None when it
names no place a run can find: a folder beside an executable, a working
directory, a folder picked in the app. Of `A, else B` the alternative
under the home is kept, the default the registry's targets write.
"""
for choice in (part.strip() for part in text.split(", else ")):
if "<" in choice:
continue
if system == "windows" and re.match(r"^%[A-Za-z0-9_()]+%/", choice):
return choice.replace("/", "\\")
if system == "android" and choice.startswith("Android/data/"):
return "$EXTERNAL_STORAGE/" + choice
if system in ("linux", "darwin"):
if choice.startswith("~/"):
return "$HOME/" + choice[2:]
if choice.startswith("$HOME/"):
return choice
return None
def _one_content(held: list[str], entries: dict[str, dict], emulator: str) -> list[str]:
"""The one dest a copy reads when every held dest carries the same bytes.
Unchanged when the contents differ: the name then designates nothing.
"""
if len({entries[dest].get("sha1") for dest in held}) != 1:
return held
own = [dest for dest in held if emulator in (entries[dest].get("cores") or ())]
return [min(own or held, key=lambda dest: (dest.count("/"), len(dest), dest))]
def _profile_roots(profile: dict) -> dict[str, str]:
"""The data_root of each system the profile names a findable place for."""
return {
_DATA_ROOT_SYSTEMS[key]: target
for key, value in (profile.get("data_root") or {}).items()
if key in _DATA_ROOT_SYSTEMS and isinstance(value, dict)
and (target := _data_root_target(_DATA_ROOT_SYSTEMS[key], value.get("path", "")))
}
def _copy_source(
entry: dict,
by_tail: dict[str, list[str]],
entries: dict[str, dict] | None,
profile_name: str,
) -> str | None:
"""The manifest dest a profile entry's standalone copy is taken from."""
standalone = entry.get("standalone_path")
if (not standalone or standalone.endswith("/") or entry.get("mode") == "libretro"
or entry.get("type") == "directory" or entry.get("found_by") == "content"):
return None
held = by_tail.get(entry.get("path") or entry["name"], [])
if len(held) > 1 and entries is not None:
held = _one_content(held, entries, profile_name)
if len(held) != 1:
return None
return held[0]
def _profile_copies(
profiles: dict[str, dict], dests: list[str], declared: list[dict],
entries: dict[str, dict] | None = None,
) -> list[dict]:
"""The standalone copies the emulator profiles document: each file with
a standalone_path, into the data_root of each system that names a place.
The registry's list was kept by hand for eight emulators, while the
profiles give the folder of 61 with the code that builds it: a machine
with standalone Cemu only got none of its keys. A target the registry
already gives for the same name is left to it, and a file the manifest
does not carry, or carries under the save directory, has no source. A
file found by content (found_by) sits wherever the folder the user set
for the scan points: Amiberry reads its ROMs from rom_path, which
amiberry.conf moves, so its name under data_root proves nothing.
``entries`` maps each dest to its manifest entry: one file carried at
two paths with the same bytes is one source, the copy whose cores name
the emulator, else the shortest path. DuckStation's ps2_scph50006.bin
sits at the BIOS root and under pcsx2/bios/ for the libretro PS2 cores.
"""
from fnmatch import fnmatch
taken: list[tuple[str, str, str, bool]] = []
for copy in declared:
name = copy.get("pattern") or PurePosixPath(copy.get("file", "")).name
for system, targets in (copy.get("targets") or {}).items():
taken += [(system, target, name, "pattern" in copy) for target in targets]
def covered(system: str, target: str, name: str) -> bool:
return any(
system == t_system and target == t_target
and (fnmatch(name, t_name) if is_pattern else name == t_name)
for t_system, t_target, t_name, is_pattern in taken
)
by_tail: dict[str, list[str]] = {}
for dest in dests:
parts = dest.split("/")
for start in range(len(parts)):
by_tail.setdefault("/".join(parts[start:]), []).append(dest)
copies: list[dict] = []
for profile_name in sorted(profiles):
profile = profiles[profile_name]
roots = _profile_roots(profile)
if not roots:
continue
for entry in profile.get("files", []):
source = _copy_source(entry, by_tail, entries, profile_name)
if source is None:
continue
where = PurePosixPath(entry["standalone_path"])
placed: dict[str, list[str]] = {}
for system, root in roots.items():
sep = "\\" if system == "windows" else "/"
target = root if str(where.parent) == "." else (
root + sep + str(where.parent).replace("/", sep))
if not covered(system, target, where.name):
placed[system] = [target]
if not placed:
continue
copy = {"file": source, "targets": placed}
if where.name != PurePosixPath(source).name:
copy["as"] = where.name
copies.append(copy)
return copies
def _standalone_copies(
declared: list[dict], profiles: dict[str, dict], manifest_files: list[dict],
) -> list[dict]:
"""A manifest's standalone copies: the registry's, placed where this
manifest puts each file, then the ones the profiles document. A platform
whose registry entry declares none gets none."""
if not declared:
return []
kept = [entry for entry in manifest_files if entry.get("root") != "save"]
dests = [entry["dest"] for entry in kept]
entries = {entry["dest"]: entry for entry in kept}
return _placed_copies(declared, dests) + _profile_copies(profiles, dests, declared, entries)
STANDALONE_DIR = "standalone"
def _standalone_layouts(
profiles: dict[str, dict],
emulators_dir: str,
db: dict,
bios_dir: str,
zip_contents: dict,
offline: bool | None,
platforms_dir: str,
result: dict,
) -> dict[str, list]:
"""Per emulator with a standalone build, the files `--emulator X
--standalone` packs, at the destinations that build reads.
Built by the emulator pack itself, in memory. A file whose content the
list already carries is written as [dest, sha1], its download read from
that entry. Another is written whole. A data tree member is left to the
list's data directories.
"""
repo_root = str(REPO_ROOT)
known = {
copy["sha1"]
for entry in [*result["files"], *result.get("truth_files", [])]
for copy in [entry, *entry.get("alternatives", []), *entry.get("slot_choices", [])]
if copy.get("sha1") and (copy.get("repo_path") or copy.get("release_asset"))
}
layouts: dict[str, list] = {}
for name, profile in sorted(profiles.items()):
if "standalone" not in str(profile.get("type", "")):
continue
record = PackRecord()
with contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()):
generate_emulator_pack(
[name], emulators_dir, db, bios_dir, "", standalone=True,
zip_contents=zip_contents, offline=offline,
platforms_dir=platforms_dir, record=record,
)
items: list = []
for member in record.files:
entry, _size = _manifest_entry(
record.sources.get(member), member, [name], db, repo_root, {}
)
if entry is None:
continue
items.append([member, entry["sha1"]] if entry["sha1"] in known else entry)
layouts[name] = items
return layouts
+108
View File
@@ -0,0 +1,108 @@
"""The per-target core lists the installer reads."""
from __future__ import annotations
import json
import os
import sys
from pathlib import Path
from core.artifacts import write_text_atomic
from model.safeparse import yaml_load
from model.targets import load_target_config
def generate_target_manifests(targets_dir: str, output_dir: str) -> None:
"""Convert target YAMLs to installer JSON manifests."""
os.makedirs(output_dir, exist_ok=True)
targets_path = Path(targets_dir)
if not targets_path.is_dir():
print(f"No targets directory at {targets_dir}", file=sys.stderr)
return
count = 0
for yml_file in sorted(targets_path.glob("*.yml")):
if yml_file.name.startswith("_"):
continue
result = target_list(yml_file)
out_path = Path(output_dir) / f"{yml_file.stem}.json"
write_text_atomic(out_path, json.dumps(result, indent=2, sort_keys=True) + "\n")
count += 1
print(f" {yml_file.stem}: {len(result)} targets")
print(f"Generated {count} target manifest(s) in {output_dir}")
def target_list(yml_file: Path) -> dict[str, list[str] | dict | None]:
"""A platform's cores per hardware target, as install/targets/ publishes
them and a pack carries them: aliases included, overrides applied."""
targets_path = yml_file.parent
with open(yml_file) as f:
data = yaml_load(f) or {}
targets = data.get("targets", {})
if not isinstance(targets, dict):
raise ValueError(f"{yml_file}: targets must be a mapping")
# The pack builder accepts the aliases declared in _overrides.yml, so
# --target switch works there. Emitting only canonical names left the
# installer rejecting the same word and, worse, carrying on with every
# file instead: the user asked for a filter and got the full pack.
overrides_path = targets_path / "_overrides.yml"
alias_map: dict[str, list[str]] = {}
platform_overrides: dict = {}
if overrides_path.is_file():
with open(overrides_path) as f:
all_overrides = yaml_load(f) or {}
platform_overrides = (
all_overrides.get(yml_file.stem, {}).get("targets", {}) or {}
)
for tname, ovr in platform_overrides.items():
names = [a for a in (ovr or {}).get("aliases", []) if isinstance(a, str)]
if names:
alias_map[tname] = names
result: dict[str, list[str] | dict | None] = {}
for target_name, target_info in targets.items():
if not isinstance(target_name, str) or not target_name:
raise ValueError(f"{yml_file}: target names must be non-empty strings")
if not isinstance(target_info, dict):
raise ValueError(f"{yml_file}: target {target_name!r} must be a mapping")
cores = target_info.get("cores")
if cores is None:
result[target_name] = None
continue
if (
not isinstance(cores, list)
or any(not isinstance(core, str) or not core for core in cores)
or len(cores) != len(set(cores))
):
raise ValueError(
f"{yml_file}: target {target_name!r} cores must be unique "
"non-empty strings"
)
# The builder's own reading, overrides included: a list published
# another way makes the installer serve what the pack does not.
# An empty list is a board with no core, not one with every core.
resolved = load_target_config(
yml_file.stem, target_name, str(targets_path.parent)
)
listed = None if resolved is None else sorted(resolved)
images = target_info.get("images")
# The image names a card's board file holds (Batocera writes
# anbernic-rg35xx-plus for the h700 target): the installer reads
# the board of a card prepared on a computer through them.
result[target_name] = (
{"cores": listed, "images": images}
if images and listed is not None else listed
)
for target_name, names in alias_map.items():
if target_name not in result:
continue
for alias in names:
if alias in result:
raise ValueError(
f"{yml_file}: alias {alias!r} collides with a target name"
)
# An alias names the board, not its images.
held = result[target_name]
result[alias] = held["cores"] if isinstance(held, dict) else held
return result
+290
View File
@@ -0,0 +1,290 @@
"""Per-file verdicts and their severity, in each platform's native mode."""
from __future__ import annotations
from core.hashing import compute_hashes, md5sum, parse_md5_list
from core.ziptools import check_inside_zip
from resolve.nativemode import SIZE_AND_ANY_HASH, reads_file_contents
from resolve.validation import (
check_file_validation,
existence_discrepancy,
frontend_digest_matches,
validated_choice,
)
DEFAULT_BIOS_DIR = "bios"
DEFAULT_EMULATORS_DIR = "emulators"
class Status:
OK = "ok"
UNTESTED = "untested" # file present, hash not confirmed: a warning, never --strict
MISSING = "missing"
# A declaration whose file is a release asset the cache does not hold yet:
# an online build fetches it, verify reads the database record instead.
RELEASE_ASSET_PENDING = "release_asset_pending"
class Severity:
CRITICAL = "critical" # required file missing or bad hash (Recalbox RED)
WARNING = "warning" # optional missing or hash mismatch (Recalbox YELLOW)
INFO = "info" # optional missing on existence-only platform
OK = "ok" # file verified
_STATUS_ORDER = {Status.OK: 0, Status.UNTESTED: 1, Status.MISSING: 2}
_SEVERITY_ORDER = {
Severity.OK: 0,
Severity.INFO: 1,
Severity.WARNING: 2,
Severity.CRITICAL: 3,
}
def verify_entry_existence(
file_entry: dict,
local_path: str | None,
validation_index: dict[str, dict] | None = None,
db: dict | None = None,
destination: str = "",
owners: dict | None = None,
resolve_status: str = "",
platform_display: str = "",
) -> dict:
"""RetroArch verification: path_is_valid(), a file that exists is OK.
The result names the collection file found, as the hash modes do."""
name = file_entry.get("name", "")
required = file_entry.get("required", True)
if not local_path:
return {"name": name, "status": Status.MISSING, "required": required}
result = {"name": name, "status": Status.OK, "required": required, "path": local_path}
if resolve_status == "hash_mismatch":
# The frontend reads no bytes, so the file stays, and the declared hash
# it contradicts is reported, as the pack does.
result["discrepancy"] = existence_discrepancy(
file_entry, local_path, platform_display
)
return result
if not validation_index:
return result
if db:
# The pack ships the variant this returns, so a disagreement it
# settles is not reported.
_chosen, disagreement = validated_choice(
file_entry, local_path, db, validation_index, "bios", None,
destination, owners,
)
else:
check = check_file_validation(local_path, name, validation_index)
disagreement = f"{', '.join(check[1])} says {check[0]}" if check else None
if disagreement:
result["discrepancy"] = f"file present (OK) but {disagreement}"
return result
def _verify_zipped_md5(
base: dict, local_path: str, zipped_file: str, md5_list: list[str],
) -> dict:
"""The md5 check of an entry naming the ROM inside its ZIP (zipped_file)."""
found_in_zip = False
had_error = False
for md5_candidate in md5_list or [""]:
result = check_inside_zip(local_path, zipped_file, md5_candidate)
if result == Status.OK:
return {**base, "status": Status.OK, "path": local_path}
if result == "error":
had_error = True
elif result != "not_in_zip":
found_in_zip = True
if had_error and not found_in_zip:
return {
**base,
"status": Status.UNTESTED,
"path": local_path,
"reason": f"{local_path} read error",
}
if not found_in_zip:
return {
**base,
"status": Status.UNTESTED,
"path": local_path,
"reason": f"{zipped_file} not found inside ZIP",
}
return {
**base,
"status": Status.UNTESTED,
"path": local_path,
"reason": f"{zipped_file} MD5 mismatch inside ZIP",
}
def verify_entry_md5(
file_entry: dict,
local_path: str | None,
resolve_status: str = "",
hash_rule: str = "",
) -> dict:
"""MD5 verification -Batocera md5sum + Recalbox multi-hash + Md5Composite.
Under SIZE_AND_ANY_HASH (RomM) the size and any one declared hash decide.
"""
name = file_entry.get("name", "")
expected_md5 = file_entry.get("md5", "")
zipped_file = file_entry.get("zipped_file")
required = file_entry.get("required", True)
base = {"name": name, "required": required}
# One parse for verify, the builder and the pack check: Recalbox writes
# md5 in uppercase, and a copy that lowercased only comma lists judged
# a single uppercase value differently from the others.
md5_list = parse_md5_list(expected_md5)
if not local_path:
return {**base, "status": Status.MISSING}
if hash_rule == SIZE_AND_ANY_HASH:
if frontend_digest_matches(file_entry, local_path, "md5", hash_rule):
return {**base, "status": Status.OK, "path": local_path}
return {
**base,
"status": Status.UNTESTED,
"path": local_path,
"reason": "the declared size and at least one declared hash must match",
}
if zipped_file:
return _verify_zipped_md5(base, local_path, zipped_file, md5_list)
if not md5_list:
if resolve_status == "hash_mismatch":
# No md5 to compare does not mean nothing was compared: the entry
# declares a sha1 or a crc32 the local file contradicts, and the
# builder drops it for exactly that. Reporting OK here said the
# collection holds bytes it does not.
return {
**base,
"status": Status.UNTESTED,
"path": local_path,
"reason": "declared hash contradicted by the local file",
}
return {**base, "status": Status.OK, "path": local_path}
if resolve_status == "md5_exact":
return {**base, "status": Status.OK, "path": local_path}
# The builder's comparison, so the two count the same files as held.
if frontend_digest_matches(file_entry, local_path, "md5"):
return {**base, "status": Status.OK, "path": local_path}
actual_md5 = md5sum(local_path)
return {
**base,
"status": Status.UNTESTED,
"path": local_path,
"reason": f"expected {md5_list[0][:12]}... got {actual_md5[:12]}...",
}
def verify_entry_sha1(
file_entry: dict,
local_path: str | None,
) -> dict:
"""SHA1 verification -BizHawk firmware hash check."""
name = file_entry.get("name", "")
expected_sha1 = file_entry.get("sha1", "")
required = file_entry.get("required", True)
base = {"name": name, "required": required}
if not local_path:
return {**base, "status": Status.MISSING}
if not expected_sha1:
return {**base, "status": Status.OK, "path": local_path}
hashes = compute_hashes(local_path)
actual_sha1 = hashes["sha1"].lower()
if actual_sha1 == expected_sha1.lower():
return {**base, "status": Status.OK, "path": local_path}
return {
**base,
"status": Status.UNTESTED,
"path": local_path,
"reason": f"expected {expected_sha1[:12]}... got {actual_sha1[:12]}...",
}
def _emulator_severity(status: str, required: bool, hle_fallback: bool) -> str:
"""Severity when the emulator's own code is the check.
A file present but refused by the core's validation, or a different dump
than the one the profile declares, is not a file the core runs with:
read in existence mode it counted OK, and `verify --emulator` announced
1/1 OK above the line that said the core would refuse it.
"""
if status == Status.UNTESTED:
return Severity.WARNING
return compute_severity(status, required, "existence", hle_fallback)
def compute_severity(
status: str,
required: bool,
mode: str,
hle_fallback: bool = False,
) -> str:
"""Map (status, required, verification_mode, hle_fallback) -> severity.
Based on native platform behavior + emulator HLE capability:
- RetroArch (existence): required+missing = warning, optional+missing = info
- Batocera/Recalbox/RetroBat/EmuDeck (md5): hash-based verification
- BizHawk (sha1): same severity rules as md5
- hle_fallback: core works without this file via HLE -> always INFO when missing
"""
if status == Status.OK:
return Severity.OK
# HLE fallback: core works without this file regardless of platform requirement
if hle_fallback and status == Status.MISSING:
return Severity.INFO
if not reads_file_contents(mode):
if status == Status.MISSING:
return Severity.WARNING if required else Severity.INFO
return Severity.OK
# md5 mode (Batocera, Recalbox, RetroBat, EmuDeck)
if status == Status.MISSING:
return Severity.CRITICAL if required else Severity.WARNING
if status == Status.UNTESTED:
return Severity.WARNING
return Severity.OK
def _storage_verdict(file_entry: dict, emulator_pack: bool) -> dict | None:
"""The result a storage tier fixes before any lookup, as the builder sees it.
A user_provided entry is never taken from the collection: a platform pack
writes its instructions in the slot and counts it filled, an emulator pack
lists it to provide. An external one is fetched from its URL when the pack
is built, never read from bios/. Resolving either by name credited a
same-named file the pack does not carry.
"""
storage = file_entry.get("storage", "embedded")
base = {"name": file_entry.get("name", ""), "required": file_entry.get("required", True)}
if storage == "user_provided":
if emulator_pack:
stated = file_entry.get("unsourceable")
why = (
stated if isinstance(stated, str) and stated
else file_entry.get("instructions") or "the user provides it"
)
return {**base, "status": Status.MISSING, "unsourceable": why}
return {**base, "status": Status.OK, "user_provided": True}
if storage == "external":
return {**base, "status": Status.MISSING, "reason": "fetched from its URL when the pack is built"}
return None
+30 -26
View File
@@ -78,11 +78,11 @@ from core.artifacts import (
)
from core.github import github_token
from model.registry import load_data_dir_registry
from refresh_data_dirs import hold_data_dirs
from packpaths import MEDIA_MARKER
from packs.datadirs import hold_data_dirs
from packs.paths import MEDIA_MARKER
if TYPE_CHECKING:
from generate_pack import PackRecord
from packs.archive import PackRecord
class StepResults(dict):
@@ -455,20 +455,20 @@ def _tree_members(
platform: str, platforms_dir: str, emulators_dir: str = "emulators",
) -> dict[str, int]:
"""Archive path -> size of every file the platform's data trees can add."""
import generate_pack
from packs import datatrees
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from packpaths import _flat
from packs.paths import _flat
config = load_platform_config(platform, platforms_dir)
base_dest = config.get("base_destination", "")
registry = load_data_dir_registry(platforms_dir)
core_trees = generate_pack.core_data_trees(
core_trees = datatrees.core_data_trees(
config, load_emulator_profiles(emulators_dir), platform, registry,
)
members: dict[str, int] = {}
with contextlib.redirect_stdout(io.StringIO()):
for src, full in generate_pack._data_directory_members(
for src, full in datatrees._data_directory_members(
config.get("systems", {}), registry,
platform, base_dest, False, set(), set(), set(),
core_trees=core_trees,
@@ -578,9 +578,10 @@ def check_emulator_packs(
required-only rules are written twice, once per side, and only this
comparison holds them together. No archive is written and no file read.
"""
import generate_pack
import packresolve
import verify
from packs import archive
from packs import emulatorpack
from resolve import packfiles as packresolve
from packs import emulatorcheck
from model.profiles import (
ProfileSelectionError,
load_emulator_profiles,
@@ -597,7 +598,7 @@ def check_emulator_packs(
profiles = load_emulator_profiles(emulators_dir, skip_aliases=False)
def compare(names: list[str], standalone: bool, label: str, **narrowing: object) -> bool:
record = generate_pack.PackRecord()
record = archive.PackRecord()
was_offline = packresolve._OFFLINE
# The pack is built offline: verify counts a release asset the cache
# lacks the same way, missing, as the narrowed-pack step does.
@@ -605,12 +606,12 @@ def check_emulator_packs(
try:
with contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()):
generate_pack.generate_emulator_pack(
emulatorpack.generate_emulator_pack(
names, emulators_dir, db, "bios", "", standalone,
zip_contents=zip_contents, offline=True, platforms_dir=platforms_dir,
record=record, **narrowing,
)
report = verify.verify_emulator(
report = emulatorcheck.verify_emulator(
names, emulators_dir, db, standalone, platforms_dir=platforms_dir,
**narrowing,
)
@@ -750,9 +751,10 @@ def check_narrowed_packs(
compares every value. NARROWINGS_NOT_COMPARED says why --source and
--one-per-slot are not compared.
"""
import generate_pack
import packresolve
import verify
from packs import archive
from packs import platformpack
from resolve import packfiles as packresolve
from packs import coverage
from core.ziptools import build_zip_contents_index
from resolve.grouping import group_identical_platforms
from model.registry import list_registered_platforms
@@ -784,17 +786,17 @@ def check_narrowed_packs(
target_cores = (
load_target_config(platform, target, platforms_dir) if target else None
)
record = generate_pack.PackRecord()
record = archive.PackRecord()
with contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()):
built = generate_pack.generate_pack(
built = platformpack.generate_pack(
platform, platforms_dir, db, "bios", "",
emulators_dir=emulators_dir, zip_contents=zip_contents,
data_registry=registry, emu_profiles=profiles,
target_cores=target_cores, offline=True, record=record,
**narrowing,
)
report = verify.verify_platform(
report = coverage.verify_platform(
load_platform_config(platform, platforms_dir), db,
emulators_dir, profiles, target_cores=target_cores,
data_dir_registry=registry,
@@ -860,8 +862,10 @@ def check_split_packs(
RetroBat's 21 openmsx/ twins of openMSX/ files. Offline, as every
comparison of this step.
"""
import generate_pack
import packresolve
from packs import archive
from packs import bysystem
from packs import platformpack
from resolve import packfiles as packresolve
from core.ziptools import build_zip_contents_index
from resolve.grouping import group_identical_platforms
from model.registry import list_registered_platforms, load_data_dir_registry
@@ -886,17 +890,17 @@ def check_split_packs(
emulators_dir=emulators_dir, zip_contents=zip_contents,
data_registry=registry, emu_profiles=profiles, offline=True,
)
full = generate_pack.PackRecord()
parts: dict[str, generate_pack.PackRecord] = {}
full = archive.PackRecord()
parts: dict[str, archive.PackRecord] = {}
with contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()):
generate_pack.generate_pack(
platformpack.generate_pack(
platform, platforms_dir, db, "bios", "", record=full, **args,
)
generate_pack.generate_split_packs(
bysystem.generate_split_packs(
platform, platforms_dir, db, "bios", "", records=parts, **args,
)
lines = split_differences(full, parts, generate_pack._same_bytes)
lines = split_differences(full, parts, archive._same_bytes)
if lines:
all_ok = False
print(f" {platform} --split: {len(lines)} differences")
+1 -1
View File
@@ -289,7 +289,7 @@ def project_base() -> str:
is HEAD, and --changed --strict found nothing and passed while the PR's
CI then failed. validate_pr.py resolves the same line the same way.
"""
from validate_pr import _git_lines as git_lines, _project_main_line
from core.gitclone import _git_lines as git_lines, _project_main_line
line = _project_main_line()
if line:
+2 -634
View File
@@ -13,648 +13,16 @@ Usage:
from __future__ import annotations
import argparse
import contextlib
import json
import logging
import os
import shutil
import tarfile
import tempfile
import time
import urllib.error
import urllib.request
import zipfile
from collections.abc import Callable, Iterator
from pathlib import Path
from core.artifacts import file_lock as _file_lock, set_plain_mode
from core.cli import InputMissing, suggest_names
from core.github import github_token
from core.cli import suggest_names
from model.cliargs import platform_arg, require_platform
from model.safeparse import yaml_load
try:
import yaml
except ImportError:
yaml = None
log = logging.getLogger(__name__)
DEFAULT_REGISTRY = "platforms/_data_dirs.yml"
VERSIONS_FILE = "data/.versions.json"
USER_AGENT = "retrobios/1.0"
REQUEST_TIMEOUT = 30
DOWNLOAD_TIMEOUT = 300
# A mirror sometimes answers with a page that is not the archive: the
# buildbot's ScummVM.zip failed CI once as "File is not a zip file" and
# downloaded fine minutes later. Seconds to wait before each retry.
DOWNLOAD_RETRY_WAITS = (5, 20)
_TRANSIENT = (urllib.error.URLError, OSError, tarfile.TarError, zipfile.BadZipFile, EOFError)
def load_registry(registry_path: str = DEFAULT_REGISTRY) -> dict[str, dict]:
if yaml is None:
raise ImportError("PyYAML required: pip install pyyaml")
path = Path(registry_path)
if not path.exists():
raise InputMissing(f"Registry not found: {registry_path}")
with open(path) as f:
data = yaml_load(f) or {}
return data.get("data_directories", {})
def cache_lock(
cache_dir: str | Path, shared: bool = False
) -> contextlib.AbstractContextManager[None]:
"""The lock a refresh holds while it swaps cache_dir.
A reader takes it shared: a pack walking data/sdlpal while another run
swapped the tree shipped part of it, or nothing.
"""
cache_dir = Path(cache_dir)
return _announced_lock(cache_dir.with_name(f".{cache_dir.name}.lock"), shared, cache_dir)
def _wait_message(lock_path: Path, shared: bool, cache_dir: Path) -> str:
"""Who to wait for, and, for a refresh, how not to.
The bare "another run holds it" named neither the lock nor its holder,
and the build waited with no limit.
"""
message = (
f"waiting for {cache_dir}: another run holds {lock_path} "
f"(lsof {lock_path} names it)"
)
if not shared:
message += (
". generate_pack.py --no-refresh-data, or --offline there and in"
" pipeline.py, builds from the cache as it is without waiting"
)
return message
@contextlib.contextmanager
def _announced_lock(lock_path: Path, shared: bool, cache_dir: Path) -> Iterator[None]:
"""file_lock, saying so when it has to wait.
A pipeline holds every cache for its whole run: a refresh started beside
it waited hours with nothing on screen.
"""
try:
import fcntl
except ImportError:
with _file_lock(lock_path, shared=shared):
yield
return
lock_path.parent.mkdir(parents=True, exist_ok=True)
mode = fcntl.LOCK_SH if shared else fcntl.LOCK_EX
with open(lock_path, "a") as handle:
try:
fcntl.flock(handle, mode | fcntl.LOCK_NB)
except BlockingIOError:
log.warning(_wait_message(lock_path, shared, cache_dir))
fcntl.flock(handle, mode)
try:
yield
finally:
fcntl.flock(handle, fcntl.LOCK_UN)
def hold_data_dirs(stack: contextlib.ExitStack, registry: dict) -> None:
"""Hold every cached data directory shared for the life of *stack*.
A pack resolves names against a tree, then copies the file minutes
later. A refresh swapping the tree in between shipped bytes nobody
verified, or died on a file the new tree no longer has. A refresh waits
for the holders. Never called before a refresh in the same process:
the exclusive lock would wait on this one. A cache not yet on disk is
held too: the lock sits beside the tree, and skipped, a refresh could
install the tree after verify ran and before the packs read it.
"""
for entry in registry.values():
cache = entry.get("local_cache", "")
if cache:
stack.enter_context(cache_lock(cache, shared=True))
def _load_versions(versions_path: str = VERSIONS_FILE) -> dict[str, dict]:
path = Path(versions_path)
if not path.exists():
return {}
with open(path) as f:
return json.load(f)
def _save_versions(
versions: dict[str, dict], versions_path: str = VERSIONS_FILE
) -> None:
"""Write the version file whole or not at all.
Truncating in place let a concurrent reader load an empty file and die
on JSONDecodeError. The scratch file sits beside the target so the
rename stays on one filesystem.
"""
path = Path(versions_path)
path.parent.mkdir(parents=True, exist_ok=True)
handle, scratch = tempfile.mkstemp(
dir=path.parent, prefix=f".{path.name}.", suffix=".tmp"
)
try:
with os.fdopen(handle, "w") as f:
json.dump(versions, f, indent=2, sort_keys=True)
f.write("\n")
set_plain_mode(scratch)
os.replace(scratch, path)
except BaseException:
with contextlib.suppress(OSError):
os.unlink(scratch)
raise
def _record_version(key: str, record: dict, versions_path: str) -> None:
"""Set one key under the file lock, so two writers keep both updates."""
path = Path(versions_path)
with _file_lock(path.with_name(f".{path.name}.lock")):
versions = _load_versions(versions_path)
versions[key] = record
_save_versions(versions, versions_path)
def _staging_dir(cache_dir: Path) -> tempfile.TemporaryDirectory:
"""Scratch space beside the cache, on its filesystem.
/tmp is a 4 GB tmpfs here: staging there filled it and turned the
promotion into a copy, during which the cache held a partial tree.
"""
cache_dir.parent.mkdir(parents=True, exist_ok=True)
return tempfile.TemporaryDirectory(
dir=cache_dir.parent, prefix=f".{cache_dir.name}-"
)
def _promote(extract_dir: Path, cache_dir: Path, scratch: Path) -> None:
"""Swap the new tree in by renames alone.
The old tree steps aside into the run's own scratch directory, never a
fixed sibling name another run could be using, and comes back if the
new one cannot be moved in.
"""
previous = scratch / "previous"
if cache_dir.exists():
os.replace(cache_dir, previous)
try:
os.replace(extract_dir, cache_dir)
except BaseException:
if previous.exists() and not cache_dir.exists():
os.replace(previous, cache_dir)
raise
def _api_request(url: str) -> dict:
req = urllib.request.Request(
url,
headers={
"User-Agent": USER_AGENT,
"Accept": "application/json",
},
)
token = github_token()
if token and "github" in url:
req.add_header("Authorization", f"token {token}")
with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as resp:
return json.loads(resp.read())
def _parse_repo_from_url(source_url: str) -> tuple[str, str, str]:
"""Extract (host_type, owner, repo) from a tarball URL.
Returns host_type as 'github' or 'gitlab'.
"""
if "github.com" in source_url:
# https://github.com/owner/repo/archive/{version}.tar.gz
parts = source_url.split("github.com/")[1].split("/")
return "github", parts[0], parts[1]
if "gitlab.com" in source_url:
parts = source_url.split("gitlab.com/")[1].split("/")
return "gitlab", parts[0], parts[1]
raise ValueError(f"Unsupported host in URL: {source_url}")
def get_remote_sha(source_url: str, version: str) -> str | None:
"""Fetch the current commit SHA for a branch/tag from GitHub or GitLab."""
try:
host_type, owner, repo = _parse_repo_from_url(source_url)
except ValueError:
log.warning("cannot parse repo from URL: %s", source_url)
return None
try:
if host_type == "github":
url = f"https://api.github.com/repos/{owner}/{repo}/commits/{version}"
data = _api_request(url)
return data["sha"]
else:
encoded = f"{owner}%2F{repo}"
url = f"https://gitlab.com/api/v4/projects/{encoded}/repository/branches/{version}"
data = _api_request(url)
return data["commit"]["id"]
except (urllib.error.URLError, KeyError, OSError) as exc:
log.warning(
"failed to fetch remote SHA for %s/%s@%s: %s", owner, repo, version, exc
)
return None
class NothingExtractedError(Exception):
"""An archive that yields no file for the cache.
Promoting it replaced the cache with an empty directory, recorded the new
version and reported success, so the next run read "up to date" and the
packs left without the directory.
"""
def _is_safe_tar_member(member: tarfile.TarInfo, dest: Path) -> bool:
"""Reject path traversal, absolute paths, and symlinks in tar members."""
if member.issym() or member.islnk():
return False
if member.name.startswith("/") or ".." in member.name.split("/"):
return False
resolved = (dest / member.name).resolve()
dest_str = str(dest.resolve()) + os.sep
return str(resolved).startswith(dest_str) or str(resolved) == str(dest.resolve())
def _download_and_extract(
source_url: str,
source_path: str,
local_cache: str,
exclude: list[str] | None = None,
measured: Callable[[int], None] | None = None,
) -> int:
"""Download tarball, extract source_path subtree to local_cache.
Returns the number of files extracted. measured receives the size of
the archive downloaded.
"""
exclude = exclude or []
cache_dir = Path(local_cache)
with _staging_dir(cache_dir) as tmpdir:
tarball_path = Path(tmpdir) / "archive.tar.gz"
log.info("downloading %s", source_url)
req = urllib.request.Request(source_url, headers={"User-Agent": USER_AGENT})
with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp, open(tarball_path, "wb") as f:
while True:
chunk = resp.read(65536)
if not chunk:
break
f.write(chunk)
if measured is not None:
measured(tarball_path.stat().st_size)
log.info("extracting %s -> %s", source_path, local_cache)
prefix = source_path.rstrip("/") + "/"
file_count = 0
with tarfile.open(tarball_path, "r:gz") as tf:
extract_dir = Path(tmpdir) / "extract"
extract_dir.mkdir()
for member in tf.getmembers():
if not member.name.startswith(prefix) and member.name != source_path:
continue
rel = member.name[len(prefix) :]
if not rel:
continue
# skip excluded subdirectories
top_component = rel.split("/")[0]
if top_component in exclude:
continue
if not _is_safe_tar_member(member, extract_dir):
log.warning("skipping unsafe tar member: %s", member.name)
continue
# rewrite member name to relative path
member_copy = tarfile.TarInfo(name=rel)
member_copy.size = member.size
member_copy.mode = member.mode
member_copy.type = member.type
if member.isdir():
(extract_dir / rel).mkdir(parents=True, exist_ok=True)
elif member.isfile():
dest_file = extract_dir / rel
dest_file.parent.mkdir(parents=True, exist_ok=True)
src = tf.extractfile(member)
if src is None:
continue
with src, open(dest_file, "wb") as dst:
shutil.copyfileobj(src, dst)
file_count += 1
if not file_count:
raise NothingExtractedError(f"no file under {source_path} in the archive")
_promote(extract_dir, cache_dir, Path(tmpdir))
return file_count
def _download_and_extract_zip(
source_url: str,
local_cache: str,
exclude: list[str] | None = None,
strip_components: int = 0,
measured: Callable[[int], None] | None = None,
) -> int:
"""Download ZIP, extract to local_cache. Returns file count.
strip_components removes N leading path components from each entry
(like tar --strip-components). Useful when a ZIP has a single root
directory that should be flattened.
"""
exclude = exclude or []
cache_dir = Path(local_cache)
with _staging_dir(cache_dir) as tmpdir:
zip_path = Path(tmpdir) / "archive.zip"
log.info("downloading %s", source_url)
req = urllib.request.Request(source_url, headers={"User-Agent": USER_AGENT})
with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp, open(zip_path, "wb") as f:
while True:
chunk = resp.read(65536)
if not chunk:
break
f.write(chunk)
if measured is not None:
measured(zip_path.stat().st_size)
extract_dir = Path(tmpdir) / "extract"
extract_dir.mkdir()
file_count = 0
with zipfile.ZipFile(zip_path) as zf:
for info in zf.infolist():
if info.is_dir():
continue
name = info.filename
if ".." in name or name.startswith("/"):
continue
# strip leading path components
parts = name.split("/")
if strip_components > 0:
if len(parts) <= strip_components:
continue
parts = parts[strip_components:]
name = "/".join(parts)
# skip excludes (check against stripped path)
top = parts[0] if parts else ""
if top in exclude:
continue
dest = extract_dir / name
dest.parent.mkdir(parents=True, exist_ok=True)
with zf.open(info) as src, open(dest, "wb") as dst:
shutil.copyfileobj(src, dst)
file_count += 1
if not file_count:
raise NothingExtractedError("the archive holds no file to extract")
# The old tree is stepped aside rather than deleted: removing it
# first and then failing to move the new one in left the cache with
# nothing at all, and the next run reads that as "never fetched".
_promote(extract_dir, cache_dir, Path(tmpdir))
return file_count
def _measure_archive(source_url: str) -> int | None:
"""The size of the archive at source_url, read by streaming it: a
tarball GitHub builds on request is sent without a Content-Length."""
req = urllib.request.Request(source_url, headers={"User-Agent": USER_AGENT})
size = 0
try:
with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp:
while chunk := resp.read(65536):
size += len(chunk)
except _TRANSIENT as exc:
log.warning("could not measure %s: %s", source_url, exc)
return None
return size or None
def _record_archive_size(key: str, entry: dict, versions_path: str) -> None:
"""Record the archive size of a tree current since before it was kept.
The installer announces a tree's download as that size: a tarball
whose tree is 10 KB is a download of 21 MB. Measured, not refetched,
so the tree the packs carry stays the one recorded.
"""
path = Path(versions_path)
with _file_lock(path.with_name(f".{path.name}.lock")):
versions = _load_versions(versions_path)
record = versions.get(key)
if record is None or "archive_size" in record:
return
version = entry.get("version", "master")
size = _measure_archive(entry["source_url"].format(version=version))
if size is None:
return
with _file_lock(path.with_name(f".{path.name}.lock")):
versions = _load_versions(versions_path)
if key in versions and "archive_size" not in versions[key]:
versions[key]["archive_size"] = size
_save_versions(versions, versions_path)
log.info("[%s] archive size recorded: %d bytes", key, size)
def _get_remote_etag(source_url: str) -> str | None:
"""HEAD request to get ETag or Last-Modified for freshness check."""
try:
req = urllib.request.Request(
source_url, method="HEAD", headers={"User-Agent": USER_AGENT}
)
with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as resp:
return resp.headers.get("ETag") or resp.headers.get("Last-Modified") or ""
except (urllib.error.URLError, OSError):
return None
def _short_tag(tag: str | None) -> str:
"""A commit sha or ETag cut for a log line, quotes dropped first: a
quoted ETag cut at 12 characters kept its opening quote only."""
if not tag:
return "none"
return tag.strip().removeprefix("W/").strip('"')[:12] or "none"
def refresh_entry(
key: str,
entry: dict,
*,
force: bool = False,
dry_run: bool = False,
versions_path: str = VERSIONS_FILE,
) -> bool | None:
"""Refresh a single data directory entry.
Returns True if the entry was refreshed (or would be in dry-run mode).
The decision and the swap run under one lock per directory: a run that
waited for another session re-reads the version it recorded and finds
nothing left to do.
The exclusive lock waits for every reader, and a pipeline reads the
trees for its whole run: a second build sat on "waiting" for a tree the
remote check would have found current. The check is made first without
it, and only a tree to replace waits.
"""
if dry_run:
return _refresh_entry(key, entry, force, dry_run, versions_path)
if not force:
needs, _remote, cached_tag = _decide(key, entry, False, versions_path)
if needs is None:
return None
if not needs:
log.info("[%s] up to date (tag: %s)", key, _short_tag(cached_tag))
_record_archive_size(key, entry, versions_path)
return False
with cache_lock(entry["local_cache"]):
return _refresh_entry(key, entry, force, dry_run, versions_path)
def _decide(
key: str, entry: dict, force: bool, versions_path: str
) -> tuple[bool | None, str | None, str | None]:
"""(whether the tree needs a refresh, the remote tag read, the recorded
tag). None when the remote could not be read."""
version = entry.get("version", "master")
cached = _load_versions(versions_path).get(key, {})
cached_tag = cached.get("sha") or cached.get("etag")
if force or not Path(entry["local_cache"]).exists():
return True, None, cached_tag
if entry.get("source_type", "tarball") == "zip":
remote_tag = _get_remote_etag(entry["source_url"].format(version=version))
else:
remote_tag = get_remote_sha(entry["source_url"], version)
if remote_tag is None:
log.warning("[%s] could not check remote, skipping", key)
return None, None, cached_tag
return remote_tag != cached_tag, remote_tag, cached_tag
def _refresh_entry(
key: str, entry: dict, force: bool, dry_run: bool, versions_path: str
) -> bool | None:
source_type = entry.get("source_type", "tarball")
version = entry.get("version", "master")
source_url = entry["source_url"].format(version=version)
local_cache = entry["local_cache"]
exclude = entry.get("exclude", [])
needs_refresh, remote_tag, cached_tag = _decide(key, entry, force, versions_path)
if needs_refresh is None:
return None
if not needs_refresh:
log.info("[%s] up to date (tag: %s)", key, _short_tag(cached_tag))
return False
if dry_run:
if remote_tag is not None:
reason = f"cached: {_short_tag(cached_tag)}, remote: {_short_tag(remote_tag)}"
elif force:
reason = "forced"
else:
reason = "not cached"
log.info("[%s] would refresh (type: %s, %s)", key, source_type, reason)
return True
if remote_tag is None:
# Read before the download. A release published in between then
# leaves an older tag on newer content, which the next run refreshes.
# Read after, it left a newer tag on older content, trusted for good.
if source_type == "zip":
remote_tag = _get_remote_etag(source_url)
else:
remote_tag = get_remote_sha(entry["source_url"], version)
archive_sizes: list[int] = []
def fetch() -> int:
archive_sizes.clear()
if source_type == "zip":
return _download_and_extract_zip(
source_url, local_cache, exclude, entry.get("strip_components", 0),
measured=archive_sizes.append,
)
source_path = entry["source_path"].format(version=version)
return _download_and_extract(
source_url, source_path, local_cache, exclude, measured=archive_sizes.append
)
# An archive that reads but holds nothing under the path is the same on
# every try: only a failed or unreadable download is tried again.
for attempt, wait in enumerate((*DOWNLOAD_RETRY_WAITS, None), start=1):
try:
file_count = fetch()
break
except NothingExtractedError as exc:
log.warning("[%s] download failed: %s", key, exc)
return None
except _TRANSIENT as exc:
if wait is None:
log.warning("[%s] download failed after %d tries: %s", key, attempt, exc)
return None
log.warning("[%s] download failed (%s), trying again in %d s", key, exc, wait)
time.sleep(wait)
record = {"sha": remote_tag or "", "version": version}
if archive_sizes:
record["archive_size"] = archive_sizes[-1]
_record_version(key, record, versions_path)
log.info("[%s] refreshed: %d files extracted to %s", key, file_count, local_cache)
return True
def refresh_all(
registry: dict[str, dict],
*,
force: bool = False,
dry_run: bool = False,
versions_path: str = VERSIONS_FILE,
platform: str | None = None,
) -> dict[str, bool | None]:
"""Refresh all entries in the registry.
If platform is set, only refresh entries whose for_platforms
includes that platform (or entries with no for_platforms restriction).
Returns a dict mapping key -> True when refreshed, False when already up
to date, None when the refresh failed. A single boolean conflated the last
two, so a run that reached no remote at all exited 0 like a run with
nothing to do.
"""
results = {}
for key, entry in registry.items():
allowed = entry.get("for_platforms")
if platform and allowed and platform not in allowed:
continue
results[key] = refresh_entry(
key,
entry,
force=force,
dry_run=dry_run,
versions_path=versions_path,
)
if any(results.values()):
# A cache the resolver indexed in this process has changed under it.
from resolve.datadirs import forget_data_dir_index
forget_data_dir_index()
return results
from packs.datadirs import DEFAULT_REGISTRY, load_registry, log, refresh_all, refresh_entry
def summarize(outcomes: dict[str, bool | None], dry_run: bool) -> str:
+6 -6
View File
@@ -22,7 +22,7 @@ import sys
import zipfile
from pathlib import Path
import split_pack
from packs import parts
from core.artifacts import ArtifactLockBusy, artifact_lock, write_text_atomic
from model.registry import list_release_pack_platforms
@@ -52,11 +52,11 @@ def release_owners(platforms_dir: str = "platforms") -> dict[str, list[str]]:
the full pack and was taken for the RetroArch pack. Only the platforms
marked release_pack own a release pack.
"""
import generate_pack
from packs import naming
platforms = list_release_pack_platforms(platforms_dir)
owners: dict[str, list[str]] = {}
for platform, names in generate_pack._expected_pack_names(
for platform, names in naming._expected_pack_names(
platforms, platforms_dir, None, None
).items():
for name in names:
@@ -88,9 +88,9 @@ def build_record(
def _read_record(dist: Path, tag: str, owners: dict[str, list[str]]) -> dict:
assets: dict[str, list[Path]] = {}
for path in sorted(dist.glob("*_BIOS_Pack*.zip")):
assets.setdefault(split_pack.pack_of(path.name), []).append(path)
assets.setdefault(parts.pack_of(path.name), []).append(path)
for paths in assets.values():
whole = [p for p in paths if not split_pack.is_part(p.name)]
whole = [p for p in paths if not parts.is_part(p.name)]
if whole and len(paths) > len(whole):
raise UnfinishedSplitError(
f"{whole[0].name} lies beside its parts: the split did not finish"
@@ -110,7 +110,7 @@ def _read_record(dist: Path, tag: str, owners: dict[str, list[str]]) -> dict:
# A part's marker names its siblings and is not pack content:
# the manifest's pack_files is counted before any split.
for info in archive.infolist():
if not split_pack.is_marker(info.filename):
if not parts.is_marker(info.filename):
members[info.filename] = info.file_size
packs[name] = {
"files": len(members),
+230
View File
@@ -0,0 +1,230 @@
"""Destinations a platform declares twice and resolves to two different files."""
from __future__ import annotations
import os
import zlib
from dataclasses import dataclass, field
from core.hashing import compute_hashes, parse_md5_list
from core.ziptools import check_inside_zip
from resolve.localfile import resolve_local_file, variant_base_name
from resolve.packfiles import preferred_entries
def _normalize(destination: str, fold: bool = True) -> str:
"""Comparable form of a destination, since layers write it differently.
Case is folded only where the platform's filesystem folds it: on Linux
RetroDECK ships bios/DISK.ROM and bios/disk.rom side by side.
"""
cleaned = destination.strip().strip("/").replace("\\", "/")
return cleaned.casefold() if fold else cleaned
@dataclass
class Collision:
"""One destination a platform fills with two different files."""
destination: str
resolved: list[str]
# Each declaration with the file it resolved to, in the platform's order.
declarations: list[tuple[dict, str | None]] = field(default_factory=list)
# The system of each declaration, in the same order.
systems: list[str] = field(default_factory=list)
# The file the pack ships at the destination, as the builder decides it.
shipped: str | None = None
def find_collisions(
config: dict,
db: dict,
zip_contents: dict | None = None,
data_dir_registry: dict | None = None,
) -> list[Collision]:
"""Destinations a platform declares twice and resolves two ways.
One path holds one file, so whichever declaration the builder reaches
first decides in silence. Declaring an archive several times to name its
inner ROMs is the documented zipped_file pattern and resolves to one
archive. Two declarations landing on two files name two files for one
path. RetroDECK aims a PC-88 disk subsystem ROM and a
CoCo disk ROM at one bios/disk.rom.
"""
fold = bool(config.get("case_insensitive_fs", False))
systems = config.get("systems") or {}
# The builder lets a hash-constrained declaration that resolves by
# content take the path, else the first it reaches walking the systems
# sorted: the same choice says which file ships.
preferred = set(
preferred_entries(systems, db, "bios", "", False, zip_contents, True).values()
)
by_dest: dict[str, list[tuple[str, dict]]] = {}
for sys_id, system in systems.items():
for entry in system.get("files") or []:
if not isinstance(entry, dict):
continue
dest = entry.get("destination") or entry.get("name") or ""
if dest:
by_dest.setdefault(_normalize(dest, fold), []).append((sys_id, entry))
collisions = []
for key, claims in sorted(by_dest.items()):
if len(claims) < 2:
continue
entries = [entry for _sys_id, entry in claims]
resolved = []
declarations = []
for entry in entries:
local, _ = resolve_local_file(
entry,
db,
zip_contents,
dest_hint=entry.get("destination", ""),
data_dir_registry=data_dir_registry,
)
declarations.append((entry, local))
if local and local not in resolved:
resolved.append(local)
if len(resolved) > 1 and not _same_file_family(resolved):
# A file every declaration accepts settles the path: RetroDECK
# declares ATARIOSB.ROM twice, the second with an md5 list that
# also names the first one's file.
if any(_accepted_by_all(path, entries, db) for path in resolved):
continue
reached = sorted(
(sys_id, local)
for (sys_id, _entry), (_e, local) in zip(claims, declarations) if local
)
shipped = next(
(local for entry, local in declarations if local and id(entry) in preferred),
reached[0][1],
)
collisions.append(
Collision(
destination=key,
resolved=resolved,
declarations=declarations,
systems=[sys_id for sys_id, _entry in claims],
shipped=shipped,
)
)
return collisions
def _lists_hashes(entry: dict) -> bool:
"""Whether a declaration says anything about content at all."""
return any(
_declared_hashes(entry, field_name)
for field_name in ("md5", "sha1", "sha256", "crc32")
)
def _declared_hashes(entry: dict, field_name: str) -> set[str]:
"""Hashes an entry accepts for one field, declared as a string or a list."""
value = entry.get(field_name)
values = value if isinstance(value, list) else [value]
# Recalbox writes its md5 list comma separated, and profiles do the
# same for sha256 (mesence names four BS-X dumps in one string).
return {
part.strip().lower()
for v in values
if v
for part in str(v).split(",")
if part.strip()
}
def _record_at(path: str, db: dict) -> dict | None:
"""The database record stored at path, from an index built once per db.
A scan of db['files'] on every call was O(calls x 19 000 files) on the
path verify --all and slots.py both take.
"""
files = db.get("files", {})
cached = _PATH_INDEX.get(id(files))
if cached is None or cached[0] is not files:
cached = (files, {e.get("path"): e for e in files.values()})
_PATH_INDEX[id(files)] = cached
return cached[1].get(path)
_PATH_INDEX: dict[int, tuple[dict, dict[str, dict]]] = {}
def _content_sha1(path: str, db: dict) -> str | None:
"""The sha1 of the file at path, from the database or read from disk.
A data directory cache is not in the database, so its files are hashed.
"""
record = _record_at(path, db)
if record is not None:
return record.get("sha1")
if not os.path.isfile(path):
return None
return compute_hashes(path, frozenset({"sha1"}))["sha1"]
def _accepted_by_all(path: str, entries: list[dict], db: dict) -> bool:
"""Whether every declaration's own hashes accept the file at path."""
record = _record_at(path, db)
if record is None:
return False
for entry in entries:
if entry.get("zipped_file"):
declared = parse_md5_list(entry.get("md5"))
if declared and not any(
check_inside_zip(path, entry["zipped_file"], m) == "ok" for m in declared
):
return False
continue
for field_name in ("md5", "sha1", "sha256", "crc32"):
declared = _declared_hashes(entry, field_name)
if declared and str(record.get(field_name, "")).lower() not in declared:
if field_name == "crc32" and _headerless_crc32(path, record, entry) in declared:
continue
return False
return True
COPIER_HEADER = 512
def _headerless_crc32(path: str, record: dict, entry: dict) -> str | None:
"""The crc32 of a file past its 512-byte copier header, when the entry
declares both the file's size and the size without the header.
Geargrafx drops the header when the file is 512 bytes over the expected
size and computes the crc32 on the rest (src/media.cpp:754-773). The
profile lists both sizes. EmuELEC's headered syscard3.pce (crc32
64f78e3c) is the 6d9a73ef image the profile names.
"""
sizes = entry.get("size")
declared = sizes if isinstance(sizes, list) else [sizes]
size = record.get("size")
if not isinstance(size, int) or not {size, size - COPIER_HEADER} <= set(declared):
return None
try:
with open(path, "rb") as f:
f.seek(COPIER_HEADER)
return f"{zlib.crc32(f.read()):08x}"
except OSError:
return None
def _same_file_family(paths: list[str]) -> bool:
"""Whether the paths are one file and its own pinned variants.
A platform list built on an older romset pins bytes the primary no longer
carries, which the repository keeps side by side under .variants. That is
the documented multi-version case, not two machines fighting for a path.
"""
canonical = set()
for path in paths:
if "/.variants/" in path:
directory, _, name = path.rpartition("/")
directory = directory[: -len("/.variants")]
name = variant_base_name(name)
path = f"{directory}/{name}"
canonical.add(path.casefold())
return len(canonical) == 1
File renamed without changes.
+915
View File
@@ -0,0 +1,915 @@
"""Reviewing a contributed file: whether the collection knows it, accepts it, and where in bios/ it goes."""
from __future__ import annotations
import hashlib
import os
import sys
import urllib.parse
import zipfile
from collections.abc import Callable, Iterable
from dataclasses import dataclass
from typing import Any, TYPE_CHECKING, TypedDict
try:
import yaml
except ImportError:
yaml = None
from core.hashing import compute_hashes, parse_hash_list, parse_md5_list
from model.nodedup import _in_nodedup_dir
from model.platforms import load_platform_config
from model.profiles import load_emulator_profiles
from model.registry import list_registered_platforms
from resolve.nativemode import digest_algorithm
from resolve.validation import frontend_digest_matches, inner_rom_check
if TYPE_CHECKING:
from typing_extensions import Unpack
BLOCKED_EXTENSIONS = {
".exe",
".bat",
".cmd",
".sh",
".ps1",
".vbs",
".js",
".msi",
".dll",
".so",
".dylib",
".py",
".rb",
".pl",
}
MAX_FILE_SIZE = 100 * 1024 * 1024
LARGE_FILE_ISSUE_URL = (
"https://github.com/Abdess/retrobios/issues/new?template=missing-bios.yml"
)
def large_file_issue_url(result: ValidationResult) -> str:
"""The issue form with the values this run computed already filled in.
GitHub fills an issue form field from the query parameter named by its
id: filename, sha1, md5 and size in missing-bios.yml.
"""
fields = {
"title": f"[BIOS] Missing: {result.filename}",
"filename": result.filename,
"sha1": result.sha1,
"md5": result.md5,
"size": str(result.size),
}
return f"{LARGE_FILE_ISSUE_URL}&{urllib.parse.urlencode(fields)}"
class ValidationResult:
def __init__(self, filepath: str) -> None:
self.filepath = filepath
self.filename = os.path.basename(filepath)
self.checks: list[tuple[str, str]] = [] # (status, message) tuples
self.sha1 = ""
self.md5 = ""
self.crc32 = ""
self.size = 0
# "held" (a copy of a file the collection has) or "unknown" (no list
# or profile declares it): no check fails, and neither is a file
# the pull request adds to the collection.
self.outcome = ""
# Where --place copies the file: one folder and one declared name, or
# the .variants/ slot of a name the collection already holds.
self.destination = ""
def add_check(self, passed: bool, message: str) -> None:
self.checks.append(("PASS" if passed else "FAIL", message))
def add_warning(self, message: str) -> None:
self.checks.append(("WARN", message))
def add_info(self, message: str) -> None:
self.checks.append(("INFO", message))
@property
def passed(self) -> bool:
return all(s != "FAIL" for s, _ in self.checks)
@property
def status(self) -> str:
return "FAIL" if not self.passed else "REVIEW" if self.outcome else "PASS"
def to_markdown(self) -> str:
status = self.status
lines = [f"### {status} `{self.filename}`"]
lines.append("")
lines.append(f"- **Path**: `{self.filepath}`")
# A path refused before it was read has no size or digest to show:
# empty fields read as an empty file contributed.
if self.sha1:
lines.append(f"- **Size**: {self.size:,} bytes")
lines.append(f"- **SHA1**: `{self.sha1}`")
lines.append(f"- **MD5**: `{self.md5}`")
lines.append(f"- **CRC32**: `{self.crc32}`")
lines.append("")
for status_str, message in self.checks:
if status_str == "PASS":
lines.append(f"- Pass: {message}")
elif status_str == "FAIL":
lines.append(f"- Fail: {message}")
elif status_str == "WARN":
lines.append(f"- Warning: {message}")
else:
lines.append(f"- Info: {message}")
return "\n".join(lines)
def _note_sizes(sizes: dict[str, list], names: list[str], entry: dict) -> None:
"""Record the sizes an entry accepts under each of its names.
An entry that declares no size says nothing about it, so a name is
judged only by the declarations that do.
"""
size = entry.get("size")
accepted = []
if isinstance(size, list):
accepted = [(int(v), int(v)) for v in size]
elif isinstance(size, int) and size > 0:
accepted = [(size, size)]
if entry.get("min_size") or entry.get("max_size"):
accepted.append((int(entry.get("min_size") or 0),
int(entry.get("max_size") or 2 ** 63)))
for name in names if accepted else []:
sizes.setdefault(name, []).extend(accepted)
def load_platform_hashes(platforms_dir: str, db: dict | None = None) -> dict:
"""Load all known hashes from platform configs.
With the database, `folders` maps each declared hash to the
bios/<Manufacturer>/<Console>/ folders the collection files its system
under, read from the other files of that system it holds.
"""
known: dict[str, Any] = {"sha1": set(), "md5": set(), "sha256": set(), "crc32": set(),
"names": set(), "folders": {}, "sizes": {}, "entries": {}, "named": {},
"name_systems": {}, "system_dirs": {}, "system_folders": {}}
systems_of: dict[str, set[str]] = {}
folders_of: dict[str, dict[str, int]] = {}
files = (db or {}).get("files", {})
by_md5 = (db or {}).get("indexes", {}).get("by_md5", {})
if not os.path.isdir(platforms_dir) or yaml is None:
return known
# Read the way verify reads them: inheritance and shared groups resolved,
# and a Recalbox md5 field split into the revisions it lists. The raw
# file kept "a,b,c" as one value, so a PR adding the seventh accepted
# falcon.img was told its hash differs.
for name in list_registered_platforms(platforms_dir):
try:
config = load_platform_config(name, platforms_dir)
except (OSError, yaml.YAMLError) as exc:
print(f"WARNING: {name}: {exc}", file=sys.stderr)
continue
mode, rule = config.get("verification_mode"), config.get("hash_rule", "")
for system_id, system in config.get("systems", {}).items():
for file_entry in system.get("files", []):
sha1s = parse_hash_list(file_entry.get("sha1"))
md5s = parse_md5_list(file_entry.get("md5"))
sha256s = parse_hash_list(file_entry.get("sha256"))
known["sha1"].update(sha1s)
known["md5"].update(md5s)
known["sha256"].update(sha256s)
if not (sha1s or md5s or sha256s) and isinstance(file_entry.get("size"), int):
# The resolver's reading: a crc32 counts where no stronger
# hash is declared, bounded by the declared size.
known["crc32"].update(
(crc.zfill(8), file_entry["size"])
for crc in parse_hash_list(file_entry.get("crc32"))
)
if "name" in file_entry:
known["names"].add(file_entry["name"])
_note_sizes(known["sizes"], [file_entry["name"]], file_entry)
# A frontend that hashes a ZIP's member or its members
# together, or that takes any hash at the declared size,
# answers by its own rule, read per entry.
known["entries"].setdefault(file_entry["name"].lower(), []).append(
(file_entry, mode, rule, name)
)
known["name_systems"].setdefault(file_entry["name"].lower(), set()).add(system_id)
for value in (*sha1s, *md5s):
systems_of.setdefault(value, set()).add(system_id)
for value in (*sha1s, *md5s, *sha256s):
if "name" in file_entry:
known["named"].setdefault(value, set()).add(file_entry["name"])
_note_folder(folders_of, system_id, files, by_md5, sha1s, md5s,
known["system_dirs"])
known["folders"] = _system_homes(systems_of, folders_of)
known["system_folders"] = _single_maker_folders(folders_of)
return known
def _note_folder(
folders_of: dict[str, dict[str, int]], system_id: str, files: dict,
by_md5: dict, sha1s: list[str], md5s: list[str],
dirs_of: dict[str, set[str]] | None = None,
) -> None:
"""Count the bios/<Manufacturer>/<Console>/ folder a held file sits in,
and note the directory it sits in under *dirs_of*."""
held = next((s for s in sha1s if s in files), None) or next(
(by_md5[m] for m in md5s if m in by_md5), None
)
path = str(files.get(held, {}).get("path", ""))
if dirs_of is not None and "/" in path and "/.variants/" not in path:
dirs_of.setdefault(system_id, set()).add(path.rsplit("/", 1)[0] + "/")
parts = path.split("/")
if len(parts) >= 4 and parts[0] == "bios" and not parts[2].startswith("."):
folder = "/".join(parts[:3]) + "/"
counts = folders_of.setdefault(system_id, {})
counts[folder] = counts.get(folder, 0) + 1
def _single_maker_folders(folders_of: dict[str, dict[str, int]]) -> dict[str, set[str]]:
"""System id to the folders the collection files it under, for a system
filed under one manufacturer only, the rule _system_homes applies."""
return {
system_id: set(held_in) for system_id, held_in in folders_of.items()
if len({folder.split("/")[1] for folder in held_in}) == 1
}
def _system_homes(
systems_of: dict[str, set[str]], folders_of: dict[str, dict[str, int]]
) -> dict[str, set[str]]:
"""Hash value to the folders the collection files its systems under.
A system whose files sit under several manufacturers (arcade sets,
computers sharing ROM chips) names no single home: only a system filed
under one manufacturer says where a newcomer belongs.
"""
homes: dict[str, set[str]] = {}
for value, systems in systems_of.items():
folders: set[str] = set()
for system_id in systems:
held_in = folders_of.get(system_id, {})
if len({folder.split("/")[1] for folder in held_in}) == 1:
folders.update(held_in)
if folders:
homes[value] = folders
return homes
def load_profile_hashes(
emulators_dir: str, db: dict | None = None
) -> dict[str, dict[str, set[str]]]:
"""Hash value to the emulators whose profile declares it, per algorithm.
A file only a core reads (a standalone emulator's firmware, a game
engine's data) is in no platform list: the review called every such
contribution "not referenced, needs manual review". With the database,
`folders` maps each declared hash to the folders the collection files
the entry's system under, as load_platform_hashes does: a contributor
holding a file only a profile declares was told to pick a
bios/Manufacturer/Console/ folder alone.
"""
known: dict[str, dict] = {
"sha1": {}, "sha256": {}, "md5": {}, "crc32": {}, "sizes": {}, "folders": {},
"named": {}, "name_systems": {}, "system_dirs": {}, "system_folders": {},
}
systems_of: dict[str, set[str]] = {}
folders_of: dict[str, dict[str, int]] = {}
files = (db or {}).get("files", {})
indexes = (db or {}).get("indexes", {})
by_md5, by_sha256 = indexes.get("by_md5", {}), indexes.get("by_sha256", {})
for emulator, profile in load_emulator_profiles(emulators_dir).items():
declared_systems = profile.get("systems") or []
for entry in profile.get("files") or []:
if not isinstance(entry, dict):
continue
names = [entry.get("name"), *(entry.get("aliases") or [])]
_note_sizes(known["sizes"], [n for n in names if isinstance(n, str)], entry)
# The resolver's reading: comma lists split (mesence's four
# sha256), and a crc32 counts only where no stronger hash is
# declared, bounded by the declared size (626 entries name a
# file by crc32 alone, clk's Electron os.rom among them).
hashes = {
algo: parse_hash_list(entry.get(algo)) for algo in ("sha1", "sha256", "md5")
}
for algo, values in hashes.items():
for value in values:
known[algo].setdefault(value, set()).add(emulator)
if isinstance(entry.get("name"), str):
known["named"].setdefault(value, set()).add(entry["name"])
# The entry's own system, or the profile's when it emulates one.
system = entry.get("system") or (
declared_systems[0] if len(declared_systems) == 1 else None
)
if isinstance(system, str):
for value in (v for values in hashes.values() for v in values):
systems_of.setdefault(value, set()).add(system)
for n in names:
if isinstance(n, str):
known["name_systems"].setdefault(n.lower(), set()).add(system)
sha1s = [*hashes["sha1"], *(
by_sha256[v] for v in hashes["sha256"] if v in by_sha256
)]
_note_folder(folders_of, system, files, by_md5, sha1s, hashes["md5"],
known["system_dirs"])
if not any(entry.get(algo) for algo in ("sha1", "sha256", "md5")):
size = entry.get("size")
sizes = [int(v) for v in size] if isinstance(size, list) else (
[int(size)] if size else [None]
)
for value in parse_hash_list(entry.get("crc32")):
for accepted in sizes:
key = (value.zfill(8), accepted)
known["crc32"].setdefault(key, set()).add(emulator)
known["folders"] = _system_homes(systems_of, folders_of)
known["system_folders"] = _single_maker_folders(folders_of)
return known
def _archive_members(
filepath: str, db: dict | None, platform_hashes: dict, profile_hashes: dict
) -> list[str] | None:
"""What each file of a ZIP is, None when filepath is not a ZIP.
Read only for an archive no list declares as a whole: MAME and FBNeo
sets are ZIP BIOS files in their own right.
"""
if not zipfile.is_zipfile(filepath):
return None
held = (db or {}).get("files", {})
described = []
try:
with zipfile.ZipFile(filepath) as archive:
for info in archive.infolist():
if info.is_dir():
continue
if info.file_size > MAX_FILE_SIZE:
described.append(f"`{info.filename}` too large to read here")
continue
sha1, md5 = hashlib.sha1(), hashlib.md5()
with archive.open(info) as handle:
for chunk in iter(lambda: handle.read(1 << 20), b""):
sha1.update(chunk)
md5.update(chunk)
sha1_hex, md5_hex = sha1.hexdigest(), md5.hexdigest()
crc = f"{info.CRC:08x}"
if sha1_hex in held:
state = f"already held at `{held[sha1_hex]['path']}`"
elif (
sha1_hex in platform_hashes.get("sha1", set())
or md5_hex in platform_hashes.get("md5", set())
or (crc, info.file_size) in platform_hashes.get("crc32", set())
or profile_hashes.get("sha1", {}).get(sha1_hex)
or profile_hashes.get("md5", {}).get(md5_hex)
or profile_hashes.get("crc32", {}).get((crc, info.file_size))
):
state = "declared and not held"
else:
state = "not recognised"
described.append(f"`{info.filename}` {state}")
except (zipfile.BadZipFile, RuntimeError, OSError) as exc:
# An encrypted member raises RuntimeError.
described.append(f"unreadable ({exc})")
return described
@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):
return "Symlinks are not allowed"
if not os.path.exists(filepath):
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):
return "Folder with no file in it"
if not os.path.isfile(filepath):
return "Not a regular file: a device, a pipe or a socket"
return ""
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
# carry it. Only a maintainer can add an asset to the release.
result.add_check(
False,
f"File too large for git ({result.size:,} > {MAX_FILE_SIZE:,} bytes). "
"Leave it out of the pull request and open an issue, its hashes "
f"filled in ({large_file_issue_url(result)}), saying where the file "
"can be obtained: a maintainer adds it to the `large-files` release.",
)
elif result.size == 0:
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.
if os.path.isabs(filepath):
candidate = os.path.relpath(filepath, os.getcwd())
if not candidate.startswith(".."):
return candidate
return filepath
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 = (
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(review.filepath, result.filename, platform_hashes)
)
by_profile = (
profile_hashes.get("sha1", {}).get(result.sha1)
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()))
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,
f"Executable whose bytes an emulator profile pins by sha1: {', '.join(sorted(pinned))}",
)
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 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(
review.filepath, review.db, review.platform_hashes, review.profile_hashes
)
_report_unknown(result, members, too_large)
return members
return None
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:
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"
)
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, []),
]
size_fits = not declared or any(lo <= result.size <= hi for lo, hi in declared)
if not size_fits:
expected = sorted({lo if lo == hi else f"{lo:,} to {hi:,}" for lo, hi in declared},
key=str)
shown = ", ".join(f"{v:,}" if isinstance(v, int) else v for v in expected)
result.add_warning(
f"Every declaration of {result.filename} expects {shown} bytes, "
f"this file has {result.size:,}: truncated or another file"
)
return size_fits
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
def _platforms_accepting(filepath: str, filename: str, platform_hashes: dict) -> set[str]:
"""Platforms whose declaration of this name accepts the file by their
own check, as verify and the pack builder read it.
Batocera pins a ROM inside the ZIP (zipped_file), Recalbox hashes a
ZIP's members together, RomM takes any hash at the declared size: the
container's sha1 or md5 is in none of those lists, and adam_fdc.zip,
which Batocera accepts, was called an unknown variant.
"""
accepted: set[str] = set()
for entry, mode, rule, platform in platform_hashes.get("entries", {}).get(
filename.lower(), []
):
if platform in accepted:
continue
if entry.get("zipped_file"):
ok = inner_rom_check(entry, filepath) == "ok"
else:
algorithm = digest_algorithm(mode)
ok = bool(algorithm or rule) and frontend_digest_matches(
entry, filepath, algorithm or "", rule
)
if ok:
accepted.add(platform)
return accepted
def expected_folders(
values: Iterable[str], platform_hashes: dict, profile_hashes: dict | None
) -> list[str]:
"""The bios/<Manufacturer>/<Console>/ folders the files of a hash's
system are in, read from the first of *values* a table knows.
A platform's declaration first, then a profile's: most files the gaps
page lists are declared by a profile alone.
"""
for table in (platform_hashes, profile_hashes or {}):
for value in values:
if value and value in table.get("folders", {}):
return sorted(table["folders"][value])
return []
@dataclass(frozen=True)
class Placement:
"""Where a file not under bios/ yet goes.
``folders`` are those of its system, ``home`` the folder the collection
keeps its name in when its system names none. ``name`` is the name it
is copied under, empty when the declarations do not settle one.
``variant`` says a file of that name is already in the folder: a copy
goes beside it in .variants/, never over it.
"""
folders: tuple[str, ...] = ()
home: str = ""
name: str = ""
variant: bool = False
@property
def folder(self) -> str:
return self.folders[0] if self.folders else self.home
def destination(self, sha1: str) -> str:
if not self.name:
return ""
if self.variant:
return f"{self.folder}.variants/{self.name}.{sha1[:8]}"
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,
**options: Unpack[PlacementOptions],
) -> Placement:
"""Where a file goes, by its hashes and its name.
The review and the site's wanted page both read this one rule, so the
folder a contributor is sent to is the folder the review accepts.
*declared* says a list or a profile declares one of the hashes: a file
known by its name alone gets a slot only once its size fits.
Without a folder from its hashes, the folder comes from its system:
*systems*, or every system that declares the name (several of them
name no copy to sit beside). A file of that name held elsewhere is a
homonym and says nothing: AmberELEC's MSX config.ini
was sent beside msx.emu's ColecoVision config.ini. A declared
*directory* (Machines/MSX2/ for one machine's config.ini) narrows it: a
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:
names = {
name
for table in (platform_hashes, profile_hashes or {})
for value in values
for name in table.get("named", {}).get(value, ())
}
name = next(iter(names)) if len(names) == 1 else ""
if len(folders) == 1 and name and "/" not in name:
return Placement(tuple(folders), name=name, variant=exists(folders[0] + name))
return Placement(tuple(folders))
held = next((value for value in values if value in (db or {}).get("files", {})), "")
owners = set(systems) or name_systems(filename, platform_hashes, profile_hashes)
tables = (platform_hashes, profile_hashes or {})
# A name several systems declare does not say which one a file is:
# a copy held for one of them is no answer.
dirs: set[str] = set() if not systems and len(owners) > 1 else {
d for table in tables for s in owners for d in table.get("system_dirs", {}).get(s, ())
}
tail = _directory_tail(db, directory)
within: set[str] | None = dirs
if tail:
within = {d for d in dirs if d.endswith("/" + tail) or d == tail} if owners else None
home = _variant_home(db, filename, held, within if owners or tail else None)
if declared and home and filename and "/" not in filename:
# The folder holds a file of that name already.
return Placement(home=home, name=filename, variant=True)
if home:
return Placement(home=home)
if tail:
return Placement(home=next(d for d in _held_directories(db) if d.endswith("/" + tail) or d == tail))
homes = {f for table in tables for s in owners for f in table.get("system_folders", {}).get(s, ())}
return Placement(tuple(sorted(homes)))
_HELD_DIRECTORIES: dict[int, frozenset[str]] = {}
def _held_directories(db: dict | None) -> frozenset[str]:
"""Every directory a file of the database sits in, .variants/ aside."""
key = id(db)
if key not in _HELD_DIRECTORIES:
_HELD_DIRECTORIES[key] = frozenset(
path.rsplit("/", 1)[0] + "/"
for record in (db or {}).get("files", {}).values()
for path in [record.get("path"), *(record.get("paths") or [])]
if path and "/" in path and "/.variants/" not in path
)
return _HELD_DIRECTORIES[key]
def _directory_tail(db: dict | None, directory: str) -> str:
"""The longest tail of a declared directory, two segments at least,
that exactly one held directory ends with, empty when none does."""
parts = [p for p in directory.strip("/").split("/") if p]
held = _held_directories(db)
for size in range(len(parts), 1, -1):
tail = "/".join(parts[-size:]) + "/"
found = [d for d in held if d.endswith("/" + tail) or d == tail]
if len(found) == 1:
return tail
if found:
return ""
return ""
def name_systems(filename: str, platform_hashes: dict, profile_hashes: dict | None) -> set[str]:
"""The systems whose platform or profile entries declare this name."""
return {
system for table in (platform_hashes, profile_hashes or {})
for system in table.get("name_systems", {}).get(filename.lower(), ())
}
def _variant_home(db: dict | None, name: str, held: str = "",
within: set[str] | None = None) -> str:
"""The folder the collection keeps a name in, for its variants beside it.
The folder of an identical copy comes first: adam_fdc.zip, held in
bios/Coleco/Adam/, was sent to bios/Arcade/MAME/, the first folder
the name index gave. A copy found by name alone counts only in a
directory of *within*, those the file's own systems are held in, when
the systems are known.
"""
files = (db or {}).get("files", {})
by_name = (db or {}).get("indexes", {}).get("by_name", {}).get(name, [])
copies = [(held, True)] if held in files else []
for sha1, identical in copies + [(sha1, False) for sha1 in by_name]:
path = str(files.get(sha1, {}).get("path", ""))
folder = path.rsplit("/", 1)[0] + "/" if "/" in path else ""
if not folder or "/.variants" in "/" + folder:
continue
if identical or within is None or folder in within:
return folder
return ""
+2 -2
View File
@@ -24,9 +24,9 @@ from pathlib import Path
import archive_build
from resolve.layout import runs_standalone
from model.profiles import unique_emulator_profiles
from cross_reference import _first_hash
from packs.crossref import _first_hash
from core.hashing import cut_md5_owner, parse_hash_list
from validate_pr import LARGE_FILE_ISSUE_URL, Placement, placement
from resolve.review import LARGE_FILE_ISSUE_URL, Placement, placement
from resolve.validation import deliverable, filter_files_by_mode, installed_with_emulator
ALGORITHMS = ("sha1", "sha256", "md5", "crc32")
+8 -854
View File
@@ -19,620 +19,22 @@ feeds the report this module prints.
from __future__ import annotations
import os
import zlib
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
from resolve import nativemode
from core.hashing import compute_hashes, parse_md5_list
from model.cliargs import platform_arg, require_platform
from model.database import load_database
from model.platforms import load_platform_config
from resolve.archives import archive_entry, holds_required_members
from core.ziptools import build_zip_contents_index, check_inside_zip
from model.profiles import entry_system_ids, load_emulator_profiles
from core.ziptools import build_zip_contents_index
from model.profiles import load_emulator_profiles
from model.registry import list_registered_platforms, load_data_dir_registry
from model.targets import build_target_cores_cache
from resolve.localfile import resolution_is_hash_exact, resolve_local_file, variant_base_name
from resolve.cores import resolve_platform_cores
from resolve.standalone import platform_layouts, standalone_set as platform_standalone_set
from resolve.layout import system_dir_path
from packresolve import preferred_entries
from resolve.validation import (
content_alternatives,
outside_gap_scope,
read_from_save_dir,
with_archive_members,
)
from resolve.localfile import resolution_is_hash_exact
from resolve.standalone import standalone_set as platform_standalone_set
if TYPE_CHECKING:
from packextras import ExtraPlacement
# A profile entry can prove a slot without declaring a hash: Dolphin names no
# checksum for the GameCube boot ROM because its source names none, and the
# proof is then the path the repository stores the file at.
# A profile entry that names an exact size, for a file the code reads in
# full (no hash to declare), is proven by a held copy of that size: the
# platform's xmil/IPLROM.X1T pinned the 2 KiB X1 font where xmil reads a
# 32 KiB Turbo IPL, and a name-only claim could not contest it.
SIZE_EXACT = "size_exact"
PROVEN_STATUSES = frozenset({"path_exact", "members_held", SIZE_EXACT})
def _size_the_code_reads(entry: dict, local: str | None) -> bool:
"""Whether a name-resolved copy has the exact size the entry declares."""
size = entry.get("size")
if not local or not isinstance(size, int) or size <= 0:
return False
try:
return os.path.getsize(local) == size
except OSError:
return False
# A core that reads ROMs inside an archive proves the archive by its members:
# FBNeo's neocdz.zip is any copy holding neocd.bin and 000-lo.lo by crc.
MEMBERS_HELD = "members_held"
@dataclass
class Claim:
"""One layer's answer to what belongs at a destination."""
origin: str
destination: str
name: str
emulator: str = ""
entry: dict = field(default_factory=dict)
local_path: str | None = None
status: str = ""
# A core that identifies its firmware by content reads no file by this
# name: any dump it takes for the same system and region answers for it.
accepts: tuple[dict, ...] = ()
@property
def is_proven(self) -> bool:
"""Whether the claim rests on evidence rather than on a bare name."""
return resolution_is_hash_exact(self.status) or self.status in PROVEN_STATUSES
@dataclass
class Conflict:
"""Two proven claims on one destination that resolve to different files."""
destination: str
platform_claim: Claim
profile_claims: list[Claim]
@property
def emulators(self) -> list[str]:
return sorted({c.emulator for c in self.profile_claims if c.emulator})
def files_read(self) -> list[tuple[str | None, list[str], str]]:
"""Each file the profiles want here, with the emulators reading it
and the proof of the first claim on it.
One file stood for every claim: Recalbox's neocdz.zip line gave
geolith the archive fbneo reads, not the one geolith pins.
"""
files: dict[str | None, tuple[list[str], str]] = {}
for claim in self.profile_claims:
emulators, status = files.setdefault(claim.local_path, ([], claim.status))
if claim.emulator and claim.emulator not in emulators:
emulators.append(claim.emulator)
return [(path, sorted(emus), status) for path, (emus, status) in files.items()]
def _normalize(destination: str, fold: bool = True) -> str:
"""Comparable form of a destination, since layers write it differently.
Case is folded only where the platform's filesystem folds it: on Linux
RetroDECK ships bios/DISK.ROM and bios/disk.rom side by side.
"""
cleaned = destination.strip().strip("/").replace("\\", "/")
return cleaned.casefold() if fold else cleaned
def platform_claims(
config: dict,
db: dict,
base_dest: str = "",
zip_contents: dict | None = None,
data_dir_registry: dict | None = None,
) -> list[Claim]:
"""What the platform YAML says belongs at each of its destinations."""
claims: list[Claim] = []
for system in (config.get("systems") or {}).values():
for entry in system.get("files") or []:
if not isinstance(entry, dict):
continue
dest = entry.get("destination") or entry.get("name") or ""
if not dest:
continue
full = f"{base_dest}/{dest}" if base_dest else dest
local, status = resolve_local_file(
entry,
db,
zip_contents,
dest_hint=dest,
data_dir_registry=data_dir_registry,
)
claims.append(
Claim(
origin="platform",
destination=full,
name=entry.get("name", ""),
entry=entry,
local_path=local,
status=status,
)
)
return claims
def profile_claims(
profiles: dict,
db: dict,
base_dest: str = "",
standalone_cores: set[str] | None = None,
zip_contents: dict | None = None,
data_dir_registry: dict | None = None,
config: dict | None = None,
) -> list[Claim]:
"""What each emulator profile says belongs at each destination it names.
With the platform's config, a claim sits where the pack puts the core's
file (ExtraPlacement): under RetroDECK's bios/, under RomM's system
folder. A file the platform cannot place claims nothing.
A file can exist in one build of an emulator and not the other, and the
two builds read from different directories. The mode is decided per
emulator, not per pack: a platform runs some of its emulators as libretro
cores and others standalone, naming the latter in ``standalone_cores``.
An entry the standalone build alone loads does not address a platform
running that emulator as a core, and where it does, the destination is
``standalone_path``. This is the gate verify already applies.
"""
standalone_cores = standalone_cores or set()
placement = None
if config is not None:
from packextras import ExtraPlacement
placement = ExtraPlacement(config, base_dest, profiles)
claims: list[Claim] = []
for emu_name, profile in sorted(profiles.items()):
if profile.get("type") in ("launcher", "alias"):
continue
# The gap report skips a filename-agnostic profile whole: the builder
# carries its scan candidates, never its named entries.
if profile.get("bios_mode") == "agnostic":
continue
for layout, is_standalone in platform_layouts(emu_name, profile, standalone_cores):
claims.extend(
_archive_claims(
emu_name, layout, is_standalone, db, base_dest, placement,
zip_contents, data_dir_registry,
)
)
for entry in layout.get("files") or []:
if not isinstance(entry, dict):
continue
# The same rule as the gap report and the builder: an entry the
# pack never carries (a placeholder, a filename-agnostic scan)
# arbitrates nothing. One read below the save directory sits
# outside the BIOS tree, where no platform declares a file.
if outside_gap_scope(entry, is_standalone) or read_from_save_dir(
entry, is_standalone
) or entry.get("unplaced"):
continue
# A member of a romset is not a file at the BIOS root: the archive
# holding it occupies the destination (_archive_claims). Claiming
# the member put FBNeo's msx.zip contents loose at the root.
if entry.get("archive"):
continue
dest = (
(entry.get("standalone_path") or entry.get("path"))
if is_standalone
else system_dir_path(entry, entry.get("path") or entry.get("name") or "")
) or entry.get("name") or ""
if not dest:
continue
if placement is None:
full = f"{base_dest}/{dest}" if base_dest else dest
else:
placed = placement.place(
{
"profile": emu_name,
"system": entry.get("system"),
"systems": entry_system_ids(entry, layout),
},
dest,
)
if placed is None:
continue
full = placed[1]
# The owner's own copy is the one the builder ships.
local, status = resolve_local_file(
{
**with_archive_members(entry, layout.get("files") or []),
"source_profile": emu_name,
},
db,
zip_contents,
dest_hint=dest,
data_dir_registry=data_dir_registry,
)
if status == "name_exact" and _size_the_code_reads(entry, local):
status = SIZE_EXACT
accepts = tuple(content_alternatives(entry, layout))
claims.append(
Claim(
origin="profile",
destination=full,
name=entry.get("name", ""),
emulator=emu_name,
entry=entry,
local_path=local,
status=status,
accepts=accepts,
)
)
return claims
def _archive_claims(
emu_name: str,
profile: dict,
is_standalone: bool,
db: dict,
base_dest: str,
placement: ExtraPlacement | None,
zip_contents: dict | None,
data_dir_registry: dict | None,
) -> list[Claim]:
"""The archives a core reads its ROMs from, where the builder places them.
The archive sits at the root and, for a core that reads a directory of
its own (archive_prefix), under it as well. The claim is proven when the
copy holds every member the core requires.
"""
files = [
entry for entry in profile.get("files") or []
if isinstance(entry, dict)
and not outside_gap_scope(entry, is_standalone)
and not read_from_save_dir(entry, is_standalone)
and not entry.get("unplaced")
]
prefix = profile.get("archive_prefix", "")
claims: list[Claim] = []
for archive in sorted({entry["archive"] for entry in files if entry.get("archive")}):
entry = archive_entry(archive, files)
members = entry.get("members")
if not members:
continue
member = next(f for f in files if f.get("archive") == archive)
system = member.get("system")
if member.get("system_dir"):
entry = {**entry, "system_dir": member["system_dir"]}
root = system_dir_path(entry, archive)
for dest in (root, f"{prefix}/{archive}") if prefix else (root,):
if placement is None:
full = f"{base_dest}/{dest}" if base_dest else dest
else:
placed = placement.place({"profile": emu_name, "system": system}, dest)
if placed is None:
continue
full = placed[1]
local, status = resolve_local_file(
{**entry, "source_profile": emu_name},
db,
zip_contents,
dest_hint=dest,
data_dir_registry=data_dir_registry,
)
if (
local
and not resolution_is_hash_exact(status)
and holds_required_members(local, members)
):
status = MEMBERS_HELD
claims.append(
Claim(
origin="profile",
destination=full,
name=archive,
emulator=emu_name,
entry=entry,
local_path=local,
status=status,
)
)
return claims
def checked_by_path(mode: str, entry: dict, rule: str = "") -> bool:
"""Whether the frontend checks this declaration by its path alone.
Whether a frontend reads the bytes is a property of the platform, but
what it compares them with is the entry's: Batocera skips an empty md5
(batocera-systems:1088), and EmuDeck declares neocdz.zip with no hash at
all. Such an entry is a path, in an md5 platform as in an existence one.
A member pinned inside an archive is content.
"""
if not nativemode.reads_file_contents(mode):
return True
if entry.get("zipped_file"):
return False
if rule == nativemode.SIZE_AND_ANY_HASH:
fields: tuple[str, ...] = ("md5", "sha1", "crc32")
else:
fields = (nativemode.digest_algorithm(mode) or "",)
return not any(
parse_md5_list(entry.get(name)) if name == "md5" else entry.get(name)
for name in fields
)
def _claim_rank(claim: Claim) -> int:
"""How strongly a platform claim speaks for what the pack ships."""
if resolution_is_hash_exact(claim.status):
return 2
return 1 if claim.is_proven else 0
def _slot_claims(
config: dict,
profiles: dict,
db: dict,
base_dest: str,
standalone_cores: set[str] | None,
zip_contents: dict | None,
data_dir_registry: dict | None,
) -> tuple[dict[str, Claim], dict[str, list[Claim]]]:
"""The platform claim and the proven profile claims at each destination."""
fold = bool(config.get("case_insensitive_fs", False))
# The builder's own choice among declarations sharing a destination,
# read from the same function: the most accepting archive for zipped_file
# members, then md5_exact. A rule of its own here compared profiles with
# a file the pack does not ship (Batocera adam_fdc.zip).
shipped = set(
preferred_entries(
config.get("systems") or {}, db, "bios", base_dest, False,
zip_contents, True,
).values()
)
by_dest: dict[str, Claim] = {}
for claim in platform_claims(
config, db, base_dest, zip_contents, data_dir_registry
):
key = _normalize(claim.destination, fold)
held = by_dest.get(key)
if held is not None and id(held.entry) in shipped:
continue
# A bare sibling met first must not stand for the destination: it
# would hide the contradiction with the file actually shipped.
if (
held is None
or id(claim.entry) in shipped
or _claim_rank(claim) > _claim_rank(held)
):
by_dest[key] = claim
# Grouped before judging: a profile may declare several revisions that are
# all acceptable at one destination, and the platform choosing one of them
# is agreement, not contradiction. Only a destination where no profile
# claim at all matches what ships is a disagreement.
# A platform claim resting on a bare name, or on a pin no local file
# matches, asserts nothing about content. Where the frontend never reads
# the bytes, a proven profile claim then decides: RetroArch's neocdz.zip
# pins an md5 nobody holds, and the primary shipped without the 000-lo.lo
# geolith and FBNeo read inside it. Decided per entry: EmuDeck, an md5
# platform, declares the same archive with no hash.
mode = config.get("verification_mode", "existence")
rule = config.get("hash_rule", "")
by_slot: dict[str, list[Claim]] = {}
for claim in profile_claims(
profiles, db, base_dest, standalone_cores, zip_contents, data_dir_registry,
config=config,
):
key = _normalize(claim.destination, fold)
platform = by_dest.get(key)
if platform is None or not claim.is_proven:
continue
if claim.status == SIZE_EXACT and (
not platform.local_path
or _size_the_code_reads(claim.entry, platform.local_path)
):
# A size proves a claim only against a file of another size.
continue
if not platform.is_proven and not (
platform.local_path and checked_by_path(mode, platform.entry, rule)
):
continue
by_slot.setdefault(key, []).append(claim)
return by_dest, by_slot
def find_conflicts(
config: dict,
profiles: dict,
db: dict,
base_dest: str = "",
standalone_cores: set[str] | None = None,
zip_contents: dict | None = None,
data_dir_registry: dict | None = None,
) -> list[Conflict]:
"""Destinations where a proven profile claim contradicts what ships.
Only proven claims are compared. A claim resolved by filename alone
asserts nothing about content and cannot contradict anything.
"""
by_dest, by_slot = _slot_claims(
config, profiles, db, base_dest, standalone_cores, zip_contents,
data_dir_registry,
)
# A declaration that lists several accepted hashes is satisfied by any of
# them: Recalbox names both scph1001.bin revisions, and mesence names
# four BS-X dumps among which System.dat pins one. The resolver stops on
# the first it finds, so the paths differ while both layers agree.
disputed = {
key: claims
for key, claims in by_slot.items()
if not any(_satisfies(c, by_dest[key], db) for c in claims)
}
return [
Conflict(
destination=by_dest[key].destination,
platform_claim=by_dest[key],
profile_claims=claims,
)
for key, claims in sorted(disputed.items())
]
# Why a decision went the way it did. Not the mode's own name: the mode is
# spelt in one place only, and nativemode answers whether it reads content.
SERVES_BOTH = "path_only_check"
ADDRESSEE = "addressee"
FRONTEND_CHECKS_CONTENT = "frontend_checks_content"
@dataclass
class Decision:
"""Which claim a pack should honour at a contested destination, and why."""
conflict: Conflict
winner: Claim
reason: str
@property
def serves_both(self) -> bool:
"""Whether honouring the winner still satisfies the other layer."""
return self.reason == SERVES_BOTH
def pack_overrides(
config: dict,
profiles: dict,
db: dict,
zip_contents: dict | None = None,
data_dir_registry: dict | None = None,
target_cores: set[str] | None = None,
source: str = "full",
choices: dict[str, list[tuple[str, str | None]]] | None = None,
) -> dict[str, str]:
"""Full pack destination -> the file a platform pack serves there instead.
Where a source-verified profile contradicts the scraped baseline on one
destination, the pack answers to the platform it is built for. In
existence mode the frontend never reads the bytes, so serving the
emulator's file satisfies both. The ZIP builder, the install manifest and
verify all read this: two of them deciding alone gave the one-line
installer different bytes than the ZIP. ``choices`` is slot_choices
for the same arguments when the caller already holds it.
"""
# A baseline-only pack serves what the platform declares, and a target's
# pack answers to the cores that hardware builds: DuckStation does not
# exist on any RetroArch target and still replaced its scph5000.bin.
if not profiles or source == "platform":
return {}
cores = set(resolve_platform_cores(config, profiles, target_cores=target_cores))
overrides: dict[str, str] = {}
if choices is None:
choices = slot_choices(config, profiles, db, zip_contents, data_dir_registry)
for destination, ordered in choices.items():
path = next((path for emulator, path in ordered if emulator in cores), None)
if path:
overrides[destination] = path
return overrides
def slot_choices(
config: dict,
profiles: dict,
db: dict,
zip_contents: dict | None = None,
data_dir_registry: dict | None = None,
) -> dict[str, list[tuple[str, str | None]]]:
"""Destination -> (core, the file it has served there) in decision order.
A pack built for a set of cores serves the first choice whose core is in
it, None standing for the platform's own answer. No core in it leaves
the platform's answer too. The order is arbitrate's: a core agreeing with
the platform settles the slot whatever else is present, then the
strongest proof decides. Read for one core set by pack_overrides and
recorded whole in the install manifest, so a target narrowed from the
full manifest gets the bytes the target's own pack carries.
"""
mode = config.get("verification_mode", "existence")
rule = config.get("hash_rule", "")
platform_profiles = {
name: profiles[name] for name in resolve_platform_cores(config, profiles)
}
by_dest, by_slot = _slot_claims(
config,
platform_profiles,
db,
config.get("base_destination", ""),
platform_standalone_set(config),
zip_contents,
data_dir_registry,
)
choices: dict[str, list[tuple[str, str | None]]] = {}
for key, claims in sorted(by_slot.items()):
platform = by_dest[key]
# Where the frontend compares a hash, the platform's file stays.
if not checked_by_path(mode, platform.entry, rule):
continue
agree = [_satisfies(c, platform, db) for c in claims]
agreeing = [c for c, ok in zip(claims, agree) if ok]
others = sorted(
(c for c, ok in zip(claims, agree) if not ok),
key=lambda claim: (-_claim_rank(claim), claims.index(claim)),
)
if not others:
continue
choices[platform.destination] = [
*((c.emulator, None) for c in agreeing),
*((c.emulator, c.local_path) for c in others),
]
return choices
def _strongest(claims: list[Claim]) -> Claim:
"""The profile claim with the strongest proof, the first emulator breaking ties.
yaps2 pins its GameIndex.yaml by sha1 while armsx2 and lrps2 only match a
path: alphabetical order served armsx2's copy to all three.
"""
return max(claims, key=lambda claim: (_claim_rank(claim), -claims.index(claim)))
def arbitrate(
conflict: Conflict, mode: str, addressee: str = "platform", rule: str = "",
) -> Decision:
"""Decide a contested destination for the pack being built.
A pack answers to whoever asked for it. A platform pack must leave the
frontend's own check green, because a user reading red concludes the pack
is broken. A pack built for one emulator answers to that emulator. The
other layer is served as well whenever the destination allows it.
In ``existence`` mode the frontend only looks for a path, so the emulator's
file satisfies both sides at once and there is nothing to trade away. In a
content-checking mode the two answers cannot share one path, and the pack's
addressee decides. The loss is reported rather than absorbed: only the
platform's own list can change what its frontend accepts there.
"""
profile = _strongest(conflict.profile_claims)
if addressee == "emulator":
return Decision(conflict, profile, ADDRESSEE)
if checked_by_path(mode, conflict.platform_claim.entry, rule):
return Decision(conflict, profile, SERVES_BOTH)
return Decision(conflict, conflict.platform_claim, FRONTEND_CHECKS_CONTENT)
pass
from packs.slots import ADDRESSEE, Claim, Conflict, Decision, arbitrate, find_conflicts
from resolve.collisions import Collision, find_collisions
def _pinned_elsewhere(claims: list[Claim], winner: str | None) -> set[str]:
@@ -679,20 +81,6 @@ def format_decision(decision: Decision) -> str:
)
@dataclass
class Collision:
"""One destination a platform fills with two different files."""
destination: str
resolved: list[str]
# Each declaration with the file it resolved to, in the platform's order.
declarations: list[tuple[dict, str | None]] = field(default_factory=list)
# The system of each declaration, in the same order.
systems: list[str] = field(default_factory=list)
# The file the pack ships at the destination, as the builder decides it.
shipped: str | None = None
def _collision_json(collision: Collision) -> dict:
return {
"destination": collision.destination,
@@ -705,240 +93,6 @@ def _collision_json(collision: Collision) -> dict:
}
def find_collisions(
config: dict,
db: dict,
zip_contents: dict | None = None,
data_dir_registry: dict | None = None,
) -> list[Collision]:
"""Destinations a platform declares twice and resolves two ways.
One path holds one file, so whichever declaration the builder reaches
first decides in silence. Declaring an archive several times to name its
inner ROMs is the documented zipped_file pattern and resolves to one
archive. Two declarations landing on two files name two files for one
path. RetroDECK aims a PC-88 disk subsystem ROM and a
CoCo disk ROM at one bios/disk.rom.
"""
fold = bool(config.get("case_insensitive_fs", False))
systems = config.get("systems") or {}
# The builder lets a hash-constrained declaration that resolves by
# content take the path, else the first it reaches walking the systems
# sorted: the same choice says which file ships.
preferred = set(
preferred_entries(systems, db, "bios", "", False, zip_contents, True).values()
)
by_dest: dict[str, list[tuple[str, dict]]] = {}
for sys_id, system in systems.items():
for entry in system.get("files") or []:
if not isinstance(entry, dict):
continue
dest = entry.get("destination") or entry.get("name") or ""
if dest:
by_dest.setdefault(_normalize(dest, fold), []).append((sys_id, entry))
collisions = []
for key, claims in sorted(by_dest.items()):
if len(claims) < 2:
continue
entries = [entry for _sys_id, entry in claims]
resolved = []
declarations = []
for entry in entries:
local, _ = resolve_local_file(
entry,
db,
zip_contents,
dest_hint=entry.get("destination", ""),
data_dir_registry=data_dir_registry,
)
declarations.append((entry, local))
if local and local not in resolved:
resolved.append(local)
if len(resolved) > 1 and not _same_file_family(resolved):
# A file every declaration accepts settles the path: RetroDECK
# declares ATARIOSB.ROM twice, the second with an md5 list that
# also names the first one's file.
if any(_accepted_by_all(path, entries, db) for path in resolved):
continue
reached = sorted(
(sys_id, local)
for (sys_id, _entry), (_e, local) in zip(claims, declarations) if local
)
shipped = next(
(local for entry, local in declarations if local and id(entry) in preferred),
reached[0][1],
)
collisions.append(
Collision(
destination=key,
resolved=resolved,
declarations=declarations,
systems=[sys_id for sys_id, _entry in claims],
shipped=shipped,
)
)
return collisions
def _satisfies(profile: Claim, platform: Claim, db: dict) -> bool:
"""Whether the two layers agree on what ships at this destination.
They agree when they resolve to the same bytes, when the platform's own
hash list accepts the profile's file, or when the profile's accepts the
platform's. A contradiction needs both lists to reject the other side.
A core found by content (found_by: content) reads no file by the
destination's name, so any dump it takes for the same system and region
settles the slot: DuckStation takes Batocera's scph1001.bin v2.0, which its profile
labels scph1001_v20.bin.
"""
if profile.local_path == platform.local_path:
return True
# Two paths can hold one content: AmberELEC's bluemsx declarations
# resolve into the data/bluemsx cache, the profile's into bios/.
if profile.local_path and platform.local_path:
shipped = _content_sha1(platform.local_path, db)
if shipped is not None and shipped == _content_sha1(profile.local_path, db):
return True
members = profile.entry.get("members")
if members and platform.local_path:
return holds_required_members(platform.local_path, members)
if (
profile.local_path
and _lists_hashes(platform.entry)
and _accepted_by_all(profile.local_path, [platform.entry], db)
):
return True
if platform.local_path and any(
_lists_hashes(label) and _accepted_by_all(platform.local_path, [label], db)
for label in profile.accepts
):
return True
return bool(
platform.local_path
and _lists_hashes(profile.entry)
and _accepted_by_all(platform.local_path, [profile.entry], db)
)
def _lists_hashes(entry: dict) -> bool:
"""Whether a declaration says anything about content at all."""
return any(
_declared_hashes(entry, field_name)
for field_name in ("md5", "sha1", "sha256", "crc32")
)
def _declared_hashes(entry: dict, field_name: str) -> set[str]:
"""Hashes an entry accepts for one field, declared as a string or a list."""
value = entry.get(field_name)
values = value if isinstance(value, list) else [value]
# Recalbox writes its md5 list comma separated, and profiles do the
# same for sha256 (mesence names four BS-X dumps in one string).
return {
part.strip().lower()
for v in values
if v
for part in str(v).split(",")
if part.strip()
}
def _record_at(path: str, db: dict) -> dict | None:
"""The database record stored at path, from an index built once per db.
A scan of db['files'] on every call was O(calls x 19 000 files) on the
path verify --all and slots.py both take.
"""
files = db.get("files", {})
cached = _PATH_INDEX.get(id(files))
if cached is None or cached[0] is not files:
cached = (files, {e.get("path"): e for e in files.values()})
_PATH_INDEX[id(files)] = cached
return cached[1].get(path)
_PATH_INDEX: dict[int, tuple[dict, dict[str, dict]]] = {}
def _content_sha1(path: str, db: dict) -> str | None:
"""The sha1 of the file at path, from the database or read from disk.
A data directory cache is not in the database, so its files are hashed.
"""
record = _record_at(path, db)
if record is not None:
return record.get("sha1")
if not os.path.isfile(path):
return None
return compute_hashes(path, frozenset({"sha1"}))["sha1"]
def _accepted_by_all(path: str, entries: list[dict], db: dict) -> bool:
"""Whether every declaration's own hashes accept the file at path."""
record = _record_at(path, db)
if record is None:
return False
for entry in entries:
if entry.get("zipped_file"):
declared = parse_md5_list(entry.get("md5"))
if declared and not any(
check_inside_zip(path, entry["zipped_file"], m) == "ok" for m in declared
):
return False
continue
for field_name in ("md5", "sha1", "sha256", "crc32"):
declared = _declared_hashes(entry, field_name)
if declared and str(record.get(field_name, "")).lower() not in declared:
if field_name == "crc32" and _headerless_crc32(path, record, entry) in declared:
continue
return False
return True
COPIER_HEADER = 512
def _headerless_crc32(path: str, record: dict, entry: dict) -> str | None:
"""The crc32 of a file past its 512-byte copier header, when the entry
declares both the file's size and the size without the header.
Geargrafx drops the header when the file is 512 bytes over the expected
size and computes the crc32 on the rest (src/media.cpp:754-773). The
profile lists both sizes. EmuELEC's headered syscard3.pce (crc32
64f78e3c) is the 6d9a73ef image the profile names.
"""
sizes = entry.get("size")
declared = sizes if isinstance(sizes, list) else [sizes]
size = record.get("size")
if not isinstance(size, int) or not {size, size - COPIER_HEADER} <= set(declared):
return None
try:
with open(path, "rb") as f:
f.seek(COPIER_HEADER)
return f"{zlib.crc32(f.read()):08x}"
except OSError:
return None
def _same_file_family(paths: list[str]) -> bool:
"""Whether the paths are one file and its own pinned variants.
A platform list built on an older romset pins bytes the primary no longer
carries, which the repository keeps side by side under .variants. That is
the documented multi-version case, not two machines fighting for a path.
"""
canonical = set()
for path in paths:
if "/.variants/" in path:
directory, _, name = path.rpartition("/")
directory = directory[: -len("/.variants")]
name = variant_base_name(name)
path = f"{directory}/{name}"
canonical.add(path.casefold())
return len(canonical) == 1
def format_collision(collision: Collision) -> str:
"""One line naming the destination, which system declares which file,
and the one the pack ships there."""
@@ -1033,7 +187,7 @@ def main() -> int:
import contextlib
from model.registry import load_data_dir_registry
from refresh_data_dirs import hold_data_dirs
from packs.datadirs import hold_data_dirs
# Claims resolve against data/: the trees stay put until the process
# ends, which releases the hold.
+1 -289
View File
@@ -20,301 +20,13 @@ Usage:
from __future__ import annotations
import argparse
import io
import re
import struct
import sys
import zipfile
import zlib
from pathlib import Path
from core.artifacts import ArtifactLockBusy, artifact_lock
# "Each file included in a release must be under 2 GiB."
ASSET_LIMIT = 2 * 1024**3
PACK_SUFFIX = "_BIOS_Pack.zip"
_PART_NAME = re.compile(r"^(?P<stem>.+_BIOS_Pack)\.part(?P<index>\d+)of(?P<count>\d+)\.zip$")
_MARKER_NAME = re.compile(r"^(?P<stem>.+_BIOS_Pack)\.part(?P<index>\d+)of(?P<count>\d+)\.txt$")
# Sizes are written at a fixed width, so a marker's length, and with it the
# size of its own part, does not depend on the sizes it records.
_SIZE_WIDTH = 13
_LOCAL = struct.Struct("<4s2B4HL2L2H")
_CENTRAL = struct.Struct("<4s4B4HL2L5H2L")
_END = struct.Struct("<4s4H2LH")
_LOCAL_SIG = b"PK\x03\x04"
_CENTRAL_SIG = b"PK\x01\x02"
_END_SIG = b"PK\x05\x06"
_DATA_DESCRIPTOR = 0x08
_UTF8_NAME = 0x800
_CHUNK = 1024 * 1024
_MAX_ENTRIES = 0xFFFF
_MAX_FIELD = 0xFFFFFFFF
def is_part(name: str) -> bool:
"""Whether a file name is one part of a split pack."""
return _PART_NAME.match(name) is not None
def pack_of(name: str) -> str:
"""The pack a published file belongs to, a part folded into its archive."""
part = _PART_NAME.match(name)
return f"{part['stem']}.zip" if part else name
def part_name(pack_name: str, index: int, count: int) -> str:
return f"{pack_name[: -len('.zip')]}.part{index}of{count}.zip"
def marker_name(pack_name: str, index: int, count: int) -> str:
return f"{pack_name[: -len('.zip')]}.part{index}of{count}.txt"
def is_marker(name: str) -> bool:
"""Whether an archive member is the marker a split writes in each part."""
return _MARKER_NAME.match(name) is not None
def marker_text(pack_name: str, index: int, sizes: list[int]) -> bytes:
"""The marker of part *index* of a pack published in ``len(sizes)`` parts.
Plain text a person can read, in a form install.py parses back: the
lines that matter are `pack:`, `part:` and one `file:` per part.
"""
count = len(sizes)
lines = [
"RetroBIOS split pack",
f"This folder holds part {index} of {count} of {pack_name}.",
"Every part is needed: extract them all into this same folder.",
"The installer's --check names a part missing from the folder.",
"",
f"pack: {pack_name}",
f"part: {index} of {count}",
]
lines += [
f"file: {size:>{_SIZE_WIDTH}} {part_name(pack_name, number, count)}"
for number, size in enumerate(sizes, 1)
]
return ("\n".join(lines) + "\n").encode("utf-8")
def _marker_weight(pack_name: str, index: int, count: int) -> int:
name = len(marker_name(pack_name, index, count).encode("utf-8"))
body = len(marker_text(pack_name, index, [0] * count))
return _LOCAL.size + name + body + _CENTRAL.size + name
def _name_bytes(info: zipfile.ZipInfo) -> bytes:
encoding = "utf-8" if info.flag_bits & _UTF8_NAME else "cp437"
return info.orig_filename.encode(encoding)
def _weight(info: zipfile.ZipInfo) -> int:
"""Bytes a member adds to a part: both headers and its stored data."""
name = len(_name_bytes(info))
return _LOCAL.size + name + info.compress_size + _CENTRAL.size + name
def plan_parts(
members: list[zipfile.ZipInfo], limit: int, reserve: int = 0
) -> list[list[zipfile.ZipInfo]]:
"""Fill each part in archive order, up to the limit less *reserve*."""
parts: list[list[zipfile.ZipInfo]] = [[]]
floor = _END.size + reserve
size = floor
for info in members:
weight = _weight(info)
if floor + weight >= limit:
raise ValueError(
f"{info.filename} needs {weight:,} bytes, more than a part of "
f"{limit:,} can hold"
)
if info.compress_size > _MAX_FIELD or info.file_size > _MAX_FIELD:
raise ValueError(f"{info.filename} needs ZIP64, which a part does not use")
if size + weight >= limit or len(parts[-1]) >= _MAX_ENTRIES - 1:
parts.append([])
size = floor
parts[-1].append(info)
size += weight
return parts
def _dos_stamp(info: zipfile.ZipInfo) -> tuple[int, int]:
year, month, day, hour, minute, second = info.date_time
return (
(hour << 11) | (minute << 5) | (second // 2),
((year - 1980) << 9) | (month << 5) | day,
)
def _data_offset(source: io.BufferedReader, info: zipfile.ZipInfo) -> int:
"""Where a member's stored bytes begin, read from its own local header."""
source.seek(info.header_offset)
header = _LOCAL.unpack(source.read(_LOCAL.size))
if header[0] != _LOCAL_SIG:
raise ValueError(f"{info.filename}: no local header at its offset")
return info.header_offset + _LOCAL.size + header[10] + header[11]
def _marker_info(name: str, body: bytes) -> zipfile.ZipInfo:
info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0))
info.compress_type = zipfile.ZIP_STORED
info.CRC = zlib.crc32(body)
info.compress_size = info.file_size = len(body)
info.create_system = 3
info.external_attr = (0o100000 | 0o644) << 16
return info
def _write_part(
source: io.BufferedReader, members: list[zipfile.ZipInfo], dest: Path,
marker: tuple[str, bytes],
) -> None:
directory = []
marker_info = _marker_info(*marker)
with open(dest, "wb") as out:
for info in [marker_info, *members]:
name = _name_bytes(info)
flags = info.flag_bits & ~_DATA_DESCRIPTOR
dos_time, dos_date = _dos_stamp(info)
offset = out.tell()
out.write(
_LOCAL.pack(
_LOCAL_SIG, info.extract_version, info.reserved, flags,
info.compress_type, dos_time, dos_date, info.CRC,
info.compress_size, info.file_size, len(name), 0,
)
)
out.write(name)
if info is marker_info:
out.write(marker[1])
remaining = 0
else:
source.seek(_data_offset(source, info))
remaining = info.compress_size
while remaining:
chunk = source.read(min(_CHUNK, remaining))
if not chunk:
raise ValueError(f"{info.filename}: the pack ends inside it")
out.write(chunk)
remaining -= len(chunk)
directory.append(
_CENTRAL.pack(
_CENTRAL_SIG, info.create_version, info.create_system,
info.extract_version, info.reserved, flags,
info.compress_type, dos_time, dos_date, info.CRC,
info.compress_size, info.file_size, len(name), 0, 0, 0,
info.internal_attr, info.external_attr, offset,
)
+ name
)
start = out.tell()
for record in directory:
out.write(record)
out.write(
_END.pack(
_END_SIG, 0, 0, len(directory), len(directory),
out.tell() - start, start, 0,
)
)
def _identity(archive: zipfile.ZipFile) -> list[tuple[str, int, int]]:
return [
(info.filename, info.CRC, info.file_size)
for info in archive.infolist()
if not is_marker(info.filename)
]
def marker_weight(pack_name: str, count: int) -> int:
"""Bytes the largest marker of a pack in *count* parts adds to its part."""
return max(_marker_weight(pack_name, index, count) for index in (1, count))
def _plan_with_markers(
pack_name: str, members: list[zipfile.ZipInfo], limit: int
) -> list[list[zipfile.ZipInfo]]:
"""Plan the parts with room for the marker each one carries.
The marker lists every part, so its length grows with their count: the
plan is made again until the count it assumed is the count it gives.
"""
count = 1
while True:
reserve = marker_weight(pack_name, count)
plan = plan_parts(members, limit, reserve)
if len(plan) <= count:
return plan
count = len(plan)
def split_pack(zip_path: Path, limit: int = ASSET_LIMIT) -> list[Path]:
"""Replace a pack at or over the limit by parts that each fit under it.
Returns the files to publish. The pack is removed only once every part
has been read back in full and the parts together list exactly its
members, so a failure leaves the pack as it was and no part behind.
"""
zip_path = Path(zip_path)
if zip_path.stat().st_size < limit:
return [zip_path]
with zipfile.ZipFile(zip_path) as archive:
members = archive.infolist()
expected = _identity(archive)
taken = [info.filename for info in members if is_marker(info.filename)]
if taken:
raise ValueError(f"{zip_path.name} already holds {taken[0]}, a part marker name")
plan = _plan_with_markers(zip_path.name, members, limit)
count = len(plan)
parts = [
zip_path.with_name(part_name(zip_path.name, index, count))
for index in range(1, count + 1)
]
sizes = [
_END.size + _marker_weight(zip_path.name, index, count)
+ sum(_weight(info) for info in chosen)
for index, chosen in enumerate(plan, 1)
]
try:
with open(zip_path, "rb") as source:
for index, (dest, chosen) in enumerate(zip(parts, plan), 1):
marker = (marker_name(zip_path.name, index, count),
marker_text(zip_path.name, index, sizes))
_write_part(source, chosen, dest, marker)
if dest.stat().st_size != sizes[index - 1]:
raise ValueError(
f"{dest.name} is {dest.stat().st_size:,} bytes, its marker "
f"says {sizes[index - 1]:,}"
)
found: list[tuple[str, int, int]] = []
for dest in parts:
with zipfile.ZipFile(dest) as archive:
damaged = archive.testzip()
if damaged:
raise ValueError(f"{dest.name}: {damaged} does not read back")
found.extend(_identity(archive))
if dest.stat().st_size >= limit:
raise ValueError(f"{dest.name} reached the limit of {limit:,} bytes")
if found != expected:
raise ValueError(f"the parts of {zip_path.name} do not add up to it")
except (OSError, ValueError, zipfile.BadZipFile):
for dest in parts:
dest.unlink(missing_ok=True)
raise
zip_path.unlink()
return parts
def split_directory(directory: Path, limit: int = ASSET_LIMIT) -> list[Path]:
"""Split every pack of a directory that needs it. Returns what to publish."""
published: list[Path] = []
for path in sorted(Path(directory).glob(f"*{PACK_SUFFIX}")):
published.extend(split_pack(path, limit))
return published
from packs.parts import ASSET_LIMIT, split_directory, split_pack
def _size(text: str) -> int:
+9 -957
View File
@@ -18,984 +18,36 @@ Outputs a structured report suitable for PR comments.
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import urllib.parse
import zipfile
from collections.abc import Callable, Iterable
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any, TypedDict
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing_extensions import Unpack
pass
sys.path.insert(0, os.path.dirname(__file__))
from core.hashing import compute_hashes, parse_md5_list
from model.registry import list_registered_platforms
from model.database import load_database
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from core.cli import require_directory
from core.hashing import parse_hash_list
from resolve.nativemode import digest_algorithm
from dedup import _in_nodedup_dir
from resolve.validation import frontend_digest_matches, inner_rom_check
try:
import yaml
except ImportError:
yaml = None
from core.gitclone import _git_lines, _project_main_line
from resolve.review import (
ValidationResult,
load_platform_hashes,
load_profile_hashes,
validate_file,
)
DEFAULT_DB = "database.json"
DEFAULT_PLATFORMS_DIR = "platforms"
DEFAULT_EMULATORS_DIR = "emulators"
BLOCKED_EXTENSIONS = {
".exe",
".bat",
".cmd",
".sh",
".ps1",
".vbs",
".js",
".msi",
".dll",
".so",
".dylib",
".py",
".rb",
".pl",
}
MAX_FILE_SIZE = 100 * 1024 * 1024
LARGE_FILE_ISSUE_URL = (
"https://github.com/Abdess/retrobios/issues/new?template=missing-bios.yml"
)
def large_file_issue_url(result: ValidationResult) -> str:
"""The issue form with the values this run computed already filled in.
GitHub fills an issue form field from the query parameter named by its
id: filename, sha1, md5 and size in missing-bios.yml.
"""
fields = {
"title": f"[BIOS] Missing: {result.filename}",
"filename": result.filename,
"sha1": result.sha1,
"md5": result.md5,
"size": str(result.size),
}
return f"{LARGE_FILE_ISSUE_URL}&{urllib.parse.urlencode(fields)}"
class ValidationResult:
def __init__(self, filepath: str) -> None:
self.filepath = filepath
self.filename = os.path.basename(filepath)
self.checks: list[tuple[str, str]] = [] # (status, message) tuples
self.sha1 = ""
self.md5 = ""
self.crc32 = ""
self.size = 0
# "held" (a copy of a file the collection has) or "unknown" (no list
# or profile declares it): no check fails, and neither is a file
# the pull request adds to the collection.
self.outcome = ""
# Where --place copies the file: one folder and one declared name, or
# the .variants/ slot of a name the collection already holds.
self.destination = ""
def add_check(self, passed: bool, message: str) -> None:
self.checks.append(("PASS" if passed else "FAIL", message))
def add_warning(self, message: str) -> None:
self.checks.append(("WARN", message))
def add_info(self, message: str) -> None:
self.checks.append(("INFO", message))
@property
def passed(self) -> bool:
return all(s != "FAIL" for s, _ in self.checks)
@property
def status(self) -> str:
return "FAIL" if not self.passed else "REVIEW" if self.outcome else "PASS"
def to_markdown(self) -> str:
status = self.status
lines = [f"### {status} `{self.filename}`"]
lines.append("")
lines.append(f"- **Path**: `{self.filepath}`")
# A path refused before it was read has no size or digest to show:
# empty fields read as an empty file contributed.
if self.sha1:
lines.append(f"- **Size**: {self.size:,} bytes")
lines.append(f"- **SHA1**: `{self.sha1}`")
lines.append(f"- **MD5**: `{self.md5}`")
lines.append(f"- **CRC32**: `{self.crc32}`")
lines.append("")
for status_str, message in self.checks:
if status_str == "PASS":
lines.append(f"- Pass: {message}")
elif status_str == "FAIL":
lines.append(f"- Fail: {message}")
elif status_str == "WARN":
lines.append(f"- Warning: {message}")
else:
lines.append(f"- Info: {message}")
return "\n".join(lines)
def _note_sizes(sizes: dict[str, list], names: list[str], entry: dict) -> None:
"""Record the sizes an entry accepts under each of its names.
An entry that declares no size says nothing about it, so a name is
judged only by the declarations that do.
"""
size = entry.get("size")
accepted = []
if isinstance(size, list):
accepted = [(int(v), int(v)) for v in size]
elif isinstance(size, int) and size > 0:
accepted = [(size, size)]
if entry.get("min_size") or entry.get("max_size"):
accepted.append((int(entry.get("min_size") or 0),
int(entry.get("max_size") or 2 ** 63)))
for name in names if accepted else []:
sizes.setdefault(name, []).extend(accepted)
def load_platform_hashes(platforms_dir: str, db: dict | None = None) -> dict:
"""Load all known hashes from platform configs.
With the database, `folders` maps each declared hash to the
bios/<Manufacturer>/<Console>/ folders the collection files its system
under, read from the other files of that system it holds.
"""
known: dict[str, Any] = {"sha1": set(), "md5": set(), "sha256": set(), "crc32": set(),
"names": set(), "folders": {}, "sizes": {}, "entries": {}, "named": {},
"name_systems": {}, "system_dirs": {}, "system_folders": {}}
systems_of: dict[str, set[str]] = {}
folders_of: dict[str, dict[str, int]] = {}
files = (db or {}).get("files", {})
by_md5 = (db or {}).get("indexes", {}).get("by_md5", {})
if not os.path.isdir(platforms_dir) or yaml is None:
return known
# Read the way verify reads them: inheritance and shared groups resolved,
# and a Recalbox md5 field split into the revisions it lists. The raw
# file kept "a,b,c" as one value, so a PR adding the seventh accepted
# falcon.img was told its hash differs.
for name in list_registered_platforms(platforms_dir):
try:
config = load_platform_config(name, platforms_dir)
except (OSError, yaml.YAMLError) as exc:
print(f"WARNING: {name}: {exc}", file=sys.stderr)
continue
mode, rule = config.get("verification_mode"), config.get("hash_rule", "")
for system_id, system in config.get("systems", {}).items():
for file_entry in system.get("files", []):
sha1s = parse_hash_list(file_entry.get("sha1"))
md5s = parse_md5_list(file_entry.get("md5"))
sha256s = parse_hash_list(file_entry.get("sha256"))
known["sha1"].update(sha1s)
known["md5"].update(md5s)
known["sha256"].update(sha256s)
if not (sha1s or md5s or sha256s) and isinstance(file_entry.get("size"), int):
# The resolver's reading: a crc32 counts where no stronger
# hash is declared, bounded by the declared size.
known["crc32"].update(
(crc.zfill(8), file_entry["size"])
for crc in parse_hash_list(file_entry.get("crc32"))
)
if "name" in file_entry:
known["names"].add(file_entry["name"])
_note_sizes(known["sizes"], [file_entry["name"]], file_entry)
# A frontend that hashes a ZIP's member or its members
# together, or that takes any hash at the declared size,
# answers by its own rule, read per entry.
known["entries"].setdefault(file_entry["name"].lower(), []).append(
(file_entry, mode, rule, name)
)
known["name_systems"].setdefault(file_entry["name"].lower(), set()).add(system_id)
for value in (*sha1s, *md5s):
systems_of.setdefault(value, set()).add(system_id)
for value in (*sha1s, *md5s, *sha256s):
if "name" in file_entry:
known["named"].setdefault(value, set()).add(file_entry["name"])
_note_folder(folders_of, system_id, files, by_md5, sha1s, md5s,
known["system_dirs"])
known["folders"] = _system_homes(systems_of, folders_of)
known["system_folders"] = _single_maker_folders(folders_of)
return known
def _note_folder(
folders_of: dict[str, dict[str, int]], system_id: str, files: dict,
by_md5: dict, sha1s: list[str], md5s: list[str],
dirs_of: dict[str, set[str]] | None = None,
) -> None:
"""Count the bios/<Manufacturer>/<Console>/ folder a held file sits in,
and note the directory it sits in under *dirs_of*."""
held = next((s for s in sha1s if s in files), None) or next(
(by_md5[m] for m in md5s if m in by_md5), None
)
path = str(files.get(held, {}).get("path", ""))
if dirs_of is not None and "/" in path and "/.variants/" not in path:
dirs_of.setdefault(system_id, set()).add(path.rsplit("/", 1)[0] + "/")
parts = path.split("/")
if len(parts) >= 4 and parts[0] == "bios" and not parts[2].startswith("."):
folder = "/".join(parts[:3]) + "/"
counts = folders_of.setdefault(system_id, {})
counts[folder] = counts.get(folder, 0) + 1
def _single_maker_folders(folders_of: dict[str, dict[str, int]]) -> dict[str, set[str]]:
"""System id to the folders the collection files it under, for a system
filed under one manufacturer only, the rule _system_homes applies."""
return {
system_id: set(held_in) for system_id, held_in in folders_of.items()
if len({folder.split("/")[1] for folder in held_in}) == 1
}
def _system_homes(
systems_of: dict[str, set[str]], folders_of: dict[str, dict[str, int]]
) -> dict[str, set[str]]:
"""Hash value to the folders the collection files its systems under.
A system whose files sit under several manufacturers (arcade sets,
computers sharing ROM chips) names no single home: only a system filed
under one manufacturer says where a newcomer belongs.
"""
homes: dict[str, set[str]] = {}
for value, systems in systems_of.items():
folders: set[str] = set()
for system_id in systems:
held_in = folders_of.get(system_id, {})
if len({folder.split("/")[1] for folder in held_in}) == 1:
folders.update(held_in)
if folders:
homes[value] = folders
return homes
def load_profile_hashes(
emulators_dir: str, db: dict | None = None
) -> dict[str, dict[str, set[str]]]:
"""Hash value to the emulators whose profile declares it, per algorithm.
A file only a core reads (a standalone emulator's firmware, a game
engine's data) is in no platform list: the review called every such
contribution "not referenced, needs manual review". With the database,
`folders` maps each declared hash to the folders the collection files
the entry's system under, as load_platform_hashes does: a contributor
holding a file only a profile declares was told to pick a
bios/Manufacturer/Console/ folder alone.
"""
known: dict[str, dict] = {
"sha1": {}, "sha256": {}, "md5": {}, "crc32": {}, "sizes": {}, "folders": {},
"named": {}, "name_systems": {}, "system_dirs": {}, "system_folders": {},
}
systems_of: dict[str, set[str]] = {}
folders_of: dict[str, dict[str, int]] = {}
files = (db or {}).get("files", {})
indexes = (db or {}).get("indexes", {})
by_md5, by_sha256 = indexes.get("by_md5", {}), indexes.get("by_sha256", {})
for emulator, profile in load_emulator_profiles(emulators_dir).items():
declared_systems = profile.get("systems") or []
for entry in profile.get("files") or []:
if not isinstance(entry, dict):
continue
names = [entry.get("name"), *(entry.get("aliases") or [])]
_note_sizes(known["sizes"], [n for n in names if isinstance(n, str)], entry)
# The resolver's reading: comma lists split (mesence's four
# sha256), and a crc32 counts only where no stronger hash is
# declared, bounded by the declared size (626 entries name a
# file by crc32 alone, clk's Electron os.rom among them).
hashes = {
algo: parse_hash_list(entry.get(algo)) for algo in ("sha1", "sha256", "md5")
}
for algo, values in hashes.items():
for value in values:
known[algo].setdefault(value, set()).add(emulator)
if isinstance(entry.get("name"), str):
known["named"].setdefault(value, set()).add(entry["name"])
# The entry's own system, or the profile's when it emulates one.
system = entry.get("system") or (
declared_systems[0] if len(declared_systems) == 1 else None
)
if isinstance(system, str):
for value in (v for values in hashes.values() for v in values):
systems_of.setdefault(value, set()).add(system)
for n in names:
if isinstance(n, str):
known["name_systems"].setdefault(n.lower(), set()).add(system)
sha1s = [*hashes["sha1"], *(
by_sha256[v] for v in hashes["sha256"] if v in by_sha256
)]
_note_folder(folders_of, system, files, by_md5, sha1s, hashes["md5"],
known["system_dirs"])
if not any(entry.get(algo) for algo in ("sha1", "sha256", "md5")):
size = entry.get("size")
sizes = [int(v) for v in size] if isinstance(size, list) else (
[int(size)] if size else [None]
)
for value in parse_hash_list(entry.get("crc32")):
for accepted in sizes:
key = (value.zfill(8), accepted)
known["crc32"].setdefault(key, set()).add(emulator)
known["folders"] = _system_homes(systems_of, folders_of)
known["system_folders"] = _single_maker_folders(folders_of)
return known
def _archive_members(
filepath: str, db: dict | None, platform_hashes: dict, profile_hashes: dict
) -> list[str] | None:
"""What each file of a ZIP is, None when filepath is not a ZIP.
Read only for an archive no list declares as a whole: MAME and FBNeo
sets are ZIP BIOS files in their own right.
"""
if not zipfile.is_zipfile(filepath):
return None
held = (db or {}).get("files", {})
described = []
try:
with zipfile.ZipFile(filepath) as archive:
for info in archive.infolist():
if info.is_dir():
continue
if info.file_size > MAX_FILE_SIZE:
described.append(f"`{info.filename}` too large to read here")
continue
sha1, md5 = hashlib.sha1(), hashlib.md5()
with archive.open(info) as handle:
for chunk in iter(lambda: handle.read(1 << 20), b""):
sha1.update(chunk)
md5.update(chunk)
sha1_hex, md5_hex = sha1.hexdigest(), md5.hexdigest()
crc = f"{info.CRC:08x}"
if sha1_hex in held:
state = f"already held at `{held[sha1_hex]['path']}`"
elif (
sha1_hex in platform_hashes.get("sha1", set())
or md5_hex in platform_hashes.get("md5", set())
or (crc, info.file_size) in platform_hashes.get("crc32", set())
or profile_hashes.get("sha1", {}).get(sha1_hex)
or profile_hashes.get("md5", {}).get(md5_hex)
or profile_hashes.get("crc32", {}).get((crc, info.file_size))
):
state = "declared and not held"
else:
state = "not recognised"
described.append(f"`{info.filename}` {state}")
except (zipfile.BadZipFile, RuntimeError, OSError) as exc:
# An encrypted member raises RuntimeError.
described.append(f"unreadable ({exc})")
return described
@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):
return "Symlinks are not allowed"
if not os.path.exists(filepath):
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):
return "Folder with no file in it"
if not os.path.isfile(filepath):
return "Not a regular file: a device, a pipe or a socket"
return ""
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
# carry it. Only a maintainer can add an asset to the release.
result.add_check(
False,
f"File too large for git ({result.size:,} > {MAX_FILE_SIZE:,} bytes). "
"Leave it out of the pull request and open an issue, its hashes "
f"filled in ({large_file_issue_url(result)}), saying where the file "
"can be obtained: a maintainer adds it to the `large-files` release.",
)
elif result.size == 0:
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.
if os.path.isabs(filepath):
candidate = os.path.relpath(filepath, os.getcwd())
if not candidate.startswith(".."):
return candidate
return filepath
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 = (
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(review.filepath, result.filename, platform_hashes)
)
by_profile = (
profile_hashes.get("sha1", {}).get(result.sha1)
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()))
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,
f"Executable whose bytes an emulator profile pins by sha1: {', '.join(sorted(pinned))}",
)
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 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(
review.filepath, review.db, review.platform_hashes, review.profile_hashes
)
_report_unknown(result, members, too_large)
return members
return None
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:
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"
)
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, []),
]
size_fits = not declared or any(lo <= result.size <= hi for lo, hi in declared)
if not size_fits:
expected = sorted({lo if lo == hi else f"{lo:,} to {hi:,}" for lo, hi in declared},
key=str)
shown = ", ".join(f"{v:,}" if isinstance(v, int) else v for v in expected)
result.add_warning(
f"Every declaration of {result.filename} expects {shown} bytes, "
f"this file has {result.size:,}: truncated or another file"
)
return size_fits
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
def _platforms_accepting(filepath: str, filename: str, platform_hashes: dict) -> set[str]:
"""Platforms whose declaration of this name accepts the file by their
own check, as verify and the pack builder read it.
Batocera pins a ROM inside the ZIP (zipped_file), Recalbox hashes a
ZIP's members together, RomM takes any hash at the declared size: the
container's sha1 or md5 is in none of those lists, and adam_fdc.zip,
which Batocera accepts, was called an unknown variant.
"""
accepted: set[str] = set()
for entry, mode, rule, platform in platform_hashes.get("entries", {}).get(
filename.lower(), []
):
if platform in accepted:
continue
if entry.get("zipped_file"):
ok = inner_rom_check(entry, filepath) == "ok"
else:
algorithm = digest_algorithm(mode)
ok = bool(algorithm or rule) and frontend_digest_matches(
entry, filepath, algorithm or "", rule
)
if ok:
accepted.add(platform)
return accepted
def expected_folders(
values: Iterable[str], platform_hashes: dict, profile_hashes: dict | None
) -> list[str]:
"""The bios/<Manufacturer>/<Console>/ folders the files of a hash's
system are in, read from the first of *values* a table knows.
A platform's declaration first, then a profile's: most files the gaps
page lists are declared by a profile alone.
"""
for table in (platform_hashes, profile_hashes or {}):
for value in values:
if value and value in table.get("folders", {}):
return sorted(table["folders"][value])
return []
@dataclass(frozen=True)
class Placement:
"""Where a file not under bios/ yet goes.
``folders`` are those of its system, ``home`` the folder the collection
keeps its name in when its system names none. ``name`` is the name it
is copied under, empty when the declarations do not settle one.
``variant`` says a file of that name is already in the folder: a copy
goes beside it in .variants/, never over it.
"""
folders: tuple[str, ...] = ()
home: str = ""
name: str = ""
variant: bool = False
@property
def folder(self) -> str:
return self.folders[0] if self.folders else self.home
def destination(self, sha1: str) -> str:
if not self.name:
return ""
if self.variant:
return f"{self.folder}.variants/{self.name}.{sha1[:8]}"
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,
**options: Unpack[PlacementOptions],
) -> Placement:
"""Where a file goes, by its hashes and its name.
The review and the site's wanted page both read this one rule, so the
folder a contributor is sent to is the folder the review accepts.
*declared* says a list or a profile declares one of the hashes: a file
known by its name alone gets a slot only once its size fits.
Without a folder from its hashes, the folder comes from its system:
*systems*, or every system that declares the name (several of them
name no copy to sit beside). A file of that name held elsewhere is a
homonym and says nothing: AmberELEC's MSX config.ini
was sent beside msx.emu's ColecoVision config.ini. A declared
*directory* (Machines/MSX2/ for one machine's config.ini) narrows it: a
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:
names = {
name
for table in (platform_hashes, profile_hashes or {})
for value in values
for name in table.get("named", {}).get(value, ())
}
name = next(iter(names)) if len(names) == 1 else ""
if len(folders) == 1 and name and "/" not in name:
return Placement(tuple(folders), name=name, variant=exists(folders[0] + name))
return Placement(tuple(folders))
held = next((value for value in values if value in (db or {}).get("files", {})), "")
owners = set(systems) or name_systems(filename, platform_hashes, profile_hashes)
tables = (platform_hashes, profile_hashes or {})
# A name several systems declare does not say which one a file is:
# a copy held for one of them is no answer.
dirs: set[str] = set() if not systems and len(owners) > 1 else {
d for table in tables for s in owners for d in table.get("system_dirs", {}).get(s, ())
}
tail = _directory_tail(db, directory)
within: set[str] | None = dirs
if tail:
within = {d for d in dirs if d.endswith("/" + tail) or d == tail} if owners else None
home = _variant_home(db, filename, held, within if owners or tail else None)
if declared and home and filename and "/" not in filename:
# The folder holds a file of that name already.
return Placement(home=home, name=filename, variant=True)
if home:
return Placement(home=home)
if tail:
return Placement(home=next(d for d in _held_directories(db) if d.endswith("/" + tail) or d == tail))
homes = {f for table in tables for s in owners for f in table.get("system_folders", {}).get(s, ())}
return Placement(tuple(sorted(homes)))
_HELD_DIRECTORIES: dict[int, frozenset[str]] = {}
def _held_directories(db: dict | None) -> frozenset[str]:
"""Every directory a file of the database sits in, .variants/ aside."""
key = id(db)
if key not in _HELD_DIRECTORIES:
_HELD_DIRECTORIES[key] = frozenset(
path.rsplit("/", 1)[0] + "/"
for record in (db or {}).get("files", {}).values()
for path in [record.get("path"), *(record.get("paths") or [])]
if path and "/" in path and "/.variants/" not in path
)
return _HELD_DIRECTORIES[key]
def _directory_tail(db: dict | None, directory: str) -> str:
"""The longest tail of a declared directory, two segments at least,
that exactly one held directory ends with, empty when none does."""
parts = [p for p in directory.strip("/").split("/") if p]
held = _held_directories(db)
for size in range(len(parts), 1, -1):
tail = "/".join(parts[-size:]) + "/"
found = [d for d in held if d.endswith("/" + tail) or d == tail]
if len(found) == 1:
return tail
if found:
return ""
return ""
def name_systems(filename: str, platform_hashes: dict, profile_hashes: dict | None) -> set[str]:
"""The systems whose platform or profile entries declare this name."""
return {
system for table in (platform_hashes, profile_hashes or {})
for system in table.get("name_systems", {}).get(filename.lower(), ())
}
def _variant_home(db: dict | None, name: str, held: str = "",
within: set[str] | None = None) -> str:
"""The folder the collection keeps a name in, for its variants beside it.
The folder of an identical copy comes first: adam_fdc.zip, held in
bios/Coleco/Adam/, was sent to bios/Arcade/MAME/, the first folder
the name index gave. A copy found by name alone counts only in a
directory of *within*, those the file's own systems are held in, when
the systems are known.
"""
files = (db or {}).get("files", {})
by_name = (db or {}).get("indexes", {}).get("by_name", {}).get(name, [])
copies = [(held, True)] if held in files else []
for sha1, identical in copies + [(sha1, False) for sha1 in by_name]:
path = str(files.get(sha1, {}).get("path", ""))
folder = path.rsplit("/", 1)[0] + "/" if "/" in path else ""
if not folder or "/.variants" in "/" + folder:
continue
if identical or within is None or folder in within:
return folder
return ""
def _git_lines(*args: str) -> list[str] | None:
"""Output lines of a git command, or None when git refuses it."""
result = subprocess.run(["git", *args], capture_output=True, text=True, check=False)
if result.returncode != 0:
return None
return [line for line in result.stdout.splitlines() if line]
PROJECT_URLS = (
"https://github.com/Abdess/retrobios",
"https://github.com/Abdess/retroarch_system",
)
def _repo_key(url: str) -> str:
"""owner/name of a clone URL, whatever its scheme."""
path = url.strip().rstrip("/").removesuffix(".git")
return "/".join(re.split(r"[/:]", path)[-2:]).casefold()
def _project_main_line() -> str | None:
"""The project's main line, fetched when this clone does not hold it.
A fork's clone has origin alone. Once the commit is pushed to the fork's
main, origin/main is HEAD and the diff against it was empty, so --changed
found nothing and exited 0. A remote added as CONTRIBUTING says and never
fetched did the same: upstream/main did not exist and origin/main won.
None leaves the upstream/ and origin/ lines in charge when the clone has
no remote at all and only its uncommitted files can be read.
"""
remotes = _git_lines("remote") or []
if not remotes:
return None
project = {_repo_key(url) for url in PROJECT_URLS}
source = PROJECT_URLS[0]
for remote in remotes:
urls = _git_lines("remote", "get-url", "--all", remote) or []
if any(_repo_key(url) in project for url in urls):
if _git_lines("rev-parse", "--verify", "--quiet", f"{remote}/main"):
return f"{remote}/main"
source = remote
break
fetched = subprocess.run(
["git", "fetch", "--quiet", "--no-tags", source, "main"],
capture_output=True, text=True, check=False,
)
if fetched.returncode != 0:
raise RuntimeError(
f"this clone does not hold the main of {PROJECT_URLS[0]}, and "
f"fetching its main from {source} failed: {fetched.stderr.strip()}"
)
return "FETCH_HEAD"
def get_changed_files() -> list[str]:
"""BIOS files this checkout changes against the project's main line.
+16 -3264
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -22,7 +22,7 @@ from pathlib import Path
from model.profiles import load_emulator_profiles, _emulator_profiles_cache
from resolve.localfile import resolve_local_file
import generate_pack as builder
import packextras
from packs import extras as packextras
SIZE = 1024
+1 -1
View File
@@ -27,7 +27,7 @@ class ScanFollowsTheBuild(unittest.TestCase):
from model.database import load_database
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from packextras import _collect_emulator_extras
from packs.extras import _collect_emulator_extras
profiles = load_emulator_profiles("emulators")
entry = next(
+3 -3
View File
@@ -22,7 +22,7 @@ REPO_ROOT = Path(__file__).resolve().parents[1]
class AgnosticScan(unittest.TestCase):
def test_only_the_bios_directory_seeds_and_finds_keep_its_folder(self):
from packextras import _agnostic_scan_extras
from packs.extras import _agnostic_scan_extras
with tempfile.TemporaryDirectory() as tmp:
previous = os.getcwd()
@@ -61,7 +61,7 @@ class AgnosticScan(unittest.TestCase):
folder where another profile of the system resolves a hashed dump of
that shape is the evidence, that folder only.
"""
from packextras import _agnostic_scan_extras
from packs.extras import _agnostic_scan_extras
with tempfile.TemporaryDirectory() as tmp:
previous = os.getcwd()
@@ -125,7 +125,7 @@ class OneContentTwoPaths(unittest.TestCase):
"files": [{"name": "ps2_scph50006.bin", "standalone_path": "bios/ps2_scph50006.bin"}]}
def _copies(self, entries):
from generate_pack import _profile_copies
from packs.standalone import _profile_copies
return _profile_copies({"duckstation": self.DUCK}, list(entries), [], entries)
+5 -5
View File
@@ -86,7 +86,7 @@ class IntegrityChecksEveryMember(unittest.TestCase):
def test_a_missing_member_is_an_error_when_the_repository_holds_it(self):
import yaml
import packverify
from packs import integrity as packverify
roms = {f"r{i}.bin": bytes([i]) * 32 for i in range(3)}
with tempfile.TemporaryDirectory() as tmp:
@@ -173,7 +173,7 @@ class TheArchiveHoldingTheCoreMembers(unittest.TestCase):
self.assertTrue(path.endswith("bios/neocdz.zip"))
def test_the_extras_carry_the_members(self):
from packextras import _report_extra
from packs.extras import _report_extra
members = [{"crc32": "5a86cff2", "required": True}]
extra = _report_extra(
@@ -444,7 +444,7 @@ class AnArchiveRankedByWhatItHolds(unittest.TestCase):
"bios/MAME/hod2bios.zip")
def test_every_claim_path_carries_the_layout(self):
from packextras import _report_extra
from packs.extras import _report_extra
contents = [{"name": "epr-21329.ic27", "size": 16}]
extra = _report_extra({"name": "hod2bios.zip", "contents": contents},
@@ -470,8 +470,8 @@ class ALooseEntryNamingItsArchive(unittest.TestCase):
import yaml
from model.profiles import _emulator_profiles_cache
from generate_pack import generate_emulator_pack
from verify import verify_emulator
from packs.emulatorpack import generate_emulator_pack
from packs.emulatorcheck import verify_emulator
_emulator_profiles_cache.clear()
(REPO_ROOT / "tmp").mkdir(exist_ok=True)
+1 -1
View File
@@ -143,7 +143,7 @@ class PackLockCliTest(unittest.TestCase):
"""The refresh waits for every run holding a data tree, and a
pipeline holds them all for its whole run: probed after the refresh,
a second build sat silent for hours instead of being refused."""
from refresh_data_dirs import cache_lock
from packs.datadirs import cache_lock
platforms = Path(self.dir) / "platforms"
platforms.mkdir()
+4 -3
View File
@@ -216,14 +216,15 @@ class ScratchFilesGetThePlainMode(unittest.TestCase):
def test_packs_and_their_manifest(self):
import zipfile
import generate_pack
from packs import archive
from packs import finalize
pack = self.dir / "Pack.zip"
with generate_pack._writing_pack(str(pack)) as zf:
with archive._writing_pack(str(pack)) as zf:
zf.writestr("a.bin", b"x")
self.assertEqual(self._mode(pack), 0o644)
os.chmod(pack, 0o600)
generate_pack.inject_manifest(str(pack), {"files": []})
finalize.inject_manifest(str(pack), {"files": []})
self.assertEqual(self._mode(pack), 0o644)
with zipfile.ZipFile(pack) as zf:
self.assertIn("manifest.json", zf.namelist())
+107 -108
View File
@@ -28,15 +28,13 @@ try:
except ImportError:
jsonschema = None
import install
from packs import verdicts
from scripts import pipeline
from scripts.resolve import regionaudit, regions
from scripts.resolve.localfile import resolve_local_file
from scripts.core.ziptools import safe_extract_zip
from scripts.generate_pack import (
_emulator_region_group,
generate_target_manifests,
verify_pack_against_platform,
)
from scripts.generate_pack import _emulator_region_group, verify_pack_against_platform
from scripts.packs.targets import generate_target_manifests
HAS_JSONSCHEMA = jsonschema is not None
ROOT = Path(__file__).resolve().parent.parent
@@ -625,7 +623,7 @@ class APackIsSwappedInWhole(unittest.TestCase):
def test_a_failed_build_keeps_the_previous_pack(self):
import zipfile
from generate_pack import _writing_pack
from packs.archive import _writing_pack
directory = self._dir()
pack = directory / "Pack.zip"
@@ -641,7 +639,7 @@ class APackIsSwappedInWhole(unittest.TestCase):
def test_a_finished_build_replaces_it(self):
import zipfile
from generate_pack import _writing_pack
from packs.archive import _writing_pack
directory = self._dir()
pack = directory / "Pack.zip"
@@ -705,7 +703,7 @@ class StandaloneCopiesNameTheirSource(unittest.TestCase):
switch/prod.keys)."""
def _placed(self, copies, dests):
from generate_pack import _placed_copies
from packs.standalone import _placed_copies
return _placed_copies(copies, dests)
@@ -758,7 +756,7 @@ class StandaloneCopiesComeFromTheProfiles(unittest.TestCase):
}
def _copies(self, profiles, dests, declared=()):
from generate_pack import _profile_copies
from packs.standalone import _profile_copies
return _profile_copies(profiles, dests, list(declared))
@@ -823,7 +821,7 @@ class ADamagedArchiveIsNotPacked(unittest.TestCase):
def test_the_rebuild_refusal_reaches_the_run(self):
import zipfile
from generate_pack import DamagedArchiveError, _add_zip_to_pack
from packs.archive import DamagedArchiveError, _add_zip_to_pack
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory:
source = Path(directory) / "set.zip"
@@ -849,7 +847,7 @@ class APackedArchiveKeepsItsBytes(unittest.TestCase):
import hashlib
import zipfile
from generate_pack import _add_zip_to_pack
from packs.archive import _add_zip_to_pack
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory:
source = Path(directory) / "set.zip"
@@ -870,7 +868,7 @@ class PackReadmesSayWhatTheInstallerDoes(unittest.TestCase):
RetroArch README offered only `| sh`, which Windows cannot run."""
def _guide(self, platform: str) -> str:
from packreadme import _build_readme
from packs.readme import _build_readme
registry = yaml.safe_load((ROOT / "platforms" / "_registry.yml").read_text())
install = registry["platforms"][platform].get("install") or {}
@@ -1447,7 +1445,7 @@ class OneBaselineVerdict(unittest.TestCase):
without d32.rom is one the builder left out on purpose."""
import hashlib
from scripts.packverify import _intentional_hash_exclusion
from scripts.packs.integrity import _intentional_hash_exclusion
entry = {"name": "dragon32.zip", "zipped_file": "d32.rom", "md5": ""}
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory:
@@ -1518,7 +1516,7 @@ class OneBaselineVerdict(unittest.TestCase):
self.assertTrue(digest_verdict(plain, 0, lambda: {"md5": raw}, "md5"))
def test_a_release_asset_keeps_its_answer(self):
from scripts.packresolve import apply_override
from scripts.resolve.packfiles import apply_override
self.assertEqual(
apply_override("bios/x.bin", "/cache/big.bin", "release_asset"),
@@ -1563,8 +1561,8 @@ class OneBaselineVerdict(unittest.TestCase):
def test_verify_finds_the_cached_release_asset(self):
# verify imports the scripts directory's modules by their bare names.
import packresolve
from scripts.verify import _resolve_for_platform
from resolve import packfiles as packresolve
from scripts.packs.coverage import _resolve_for_platform
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory:
cached = Path(directory) / "BIG.PUP"
@@ -1856,7 +1854,7 @@ class RegionRegressions(unittest.TestCase):
under none of its four systems: emulator mode grouped them and
dropped pac-n1.bin for --region us, platform mode isolated each and
kept it."""
from packextras import extra_region_groups
from packs.extras import extra_region_groups
profile = {"systems": ["nec-pc-engine", "nec-pc-engine-cd", "nec-supergrafx",
"pioneer-laseractive"]}
@@ -2012,26 +2010,21 @@ class NoMd5IsNotNothingChecked(unittest.TestCase):
sha256 and no md5.
"""
def setUp(self):
import verify
self.verify = verify
def _entry(self):
return {"name": "dsifirmware.bin", "sha256": "b" * 64}
def test_a_contradicted_sha256_is_not_reported_ok(self):
result = self.verify.verify_entry_md5(
result = verdicts.verify_entry_md5(
self._entry(), "bios/whatever.bin", "hash_mismatch"
)
self.assertNotEqual(result["status"], self.verify.Status.OK)
self.assertNotEqual(result["status"], verdicts.Status.OK)
self.assertIn("contradicted", result.get("reason", ""))
def test_a_clean_resolution_is_still_ok(self):
result = self.verify.verify_entry_md5(
result = verdicts.verify_entry_md5(
self._entry(), "bios/whatever.bin", "sha256_exact"
)
self.assertEqual(result["status"], self.verify.Status.OK)
self.assertEqual(result["status"], verdicts.Status.OK)
class InstallerBoundaryRegressions(unittest.TestCase):
@@ -2147,7 +2140,7 @@ class InstallerBoundaryRegressions(unittest.TestCase):
in the pack's manifest.json, which install.py reads with the pack
alone. The pack schema refused both keys, and each is checked under
its own contract."""
import generate_pack
from packs import scope
import validate_schemas
install_list = json.loads((ROOT / "install" / "romm.json").read_text(encoding="utf-8"))
@@ -2159,8 +2152,8 @@ class InstallerBoundaryRegressions(unittest.TestCase):
"summary": {"total_files": 0, "verified": 0, "untracked": 0, "errors": 0},
"errors": [],
}
generate_pack.annotate_pack_systems(
document, generate_pack.pack_systems(install_list, targets))
scope.annotate_pack_systems(
document, scope.pack_systems(install_list, targets))
self.assertIn("install_list", document)
self.assertIn("targets", document)
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory:
@@ -2641,7 +2634,7 @@ class ReleaseAssetCriterion(unittest.TestCase):
return directory
def test_a_large_committed_file_is_served_by_the_repository(self):
from scripts import generate_pack
from scripts.packs import manifestentry
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory:
root = self._repo(directory, "bios/elsewhere.bin")
@@ -2649,44 +2642,44 @@ class ReleaseAssetCriterion(unittest.TestCase):
big.parent.mkdir()
with big.open("wb") as handle:
handle.truncate(60_000_000)
generate_pack._registered.cache_clear()
manifestentry._registered.cache_clear()
try:
self.assertFalse(generate_pack._is_release_asset(str(big), root))
self.assertFalse(manifestentry._is_release_asset(str(big), root))
finally:
generate_pack._registered.cache_clear()
manifestentry._registered.cache_clear()
def test_the_manifest_names_the_asset_as_github_serves_it(self):
# GitHub publishes a space as a dot. The site linked the dotted
# name while the manifest gave install.py the spaced one, a 404.
from scripts import generate_pack
from scripts.packs import manifestentry
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory:
root = self._repo(directory, "bios/MAME/MAME 0.174 Arcade XML.dat")
target = Path(root, "bios", "MAME", "MAME 0.174 Arcade XML.dat")
target.parent.mkdir(parents=True)
target.write_bytes(b"x")
generate_pack._registered.cache_clear()
manifestentry._registered.cache_clear()
try:
self.assertEqual(
generate_pack._release_asset_name(str(target), root),
manifestentry._release_asset_name(str(target), root),
"MAME.0.174.Arcade.XML.dat",
)
finally:
generate_pack._registered.cache_clear()
manifestentry._registered.cache_clear()
def test_a_gitignored_file_is_served_by_the_release_whatever_its_size(self):
from scripts import generate_pack
from scripts.packs import manifestentry
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory:
root = self._repo(directory, "bios/small.zip")
small = Path(root, "bios", "small.zip")
small.parent.mkdir()
small.write_bytes(b"PK")
generate_pack._registered.cache_clear()
manifestentry._registered.cache_clear()
try:
self.assertTrue(generate_pack._is_release_asset(str(small), root))
self.assertTrue(manifestentry._is_release_asset(str(small), root))
finally:
generate_pack._registered.cache_clear()
manifestentry._registered.cache_clear()
class ReleaseAssetsMatchTheCollection(unittest.TestCase):
@@ -3355,7 +3348,7 @@ class APackNameFitsAFileName(unittest.TestCase):
before writing anything, while verify --system snes reported."""
def test_a_long_selection_is_bounded_and_told_apart(self):
from scripts.generate_pack import MAX_PACK_NAME_BYTES, _bounded_pack_name
from scripts.packs.naming import MAX_PACK_NAME_BYTES, _bounded_pack_name
names = [f"Emulator_Number_{i}" for i in range(23)]
long_name = _bounded_pack_name(names, names, "_BIOS_Pack.zip")
@@ -3367,7 +3360,7 @@ class APackNameFitsAFileName(unittest.TestCase):
def test_a_long_system_list_is_bounded(self):
"""Thirty systems joined made a 261-byte platform pack name."""
from scripts.generate_pack import MAX_SYSTEM_TAG_BYTES, _system_tag
from scripts.packs.naming import MAX_SYSTEM_TAG_BYTES, _system_tag
systems = [f"vendor-console-number-{i}" for i in range(30)]
tag = _system_tag(systems)
@@ -3378,7 +3371,7 @@ class APackNameFitsAFileName(unittest.TestCase):
def test_two_systems_never_name_one_system(self):
"""sega-dreamcast,arcade and sega-dreamcast-arcade both wrote
RetroArch_..._Dreamcast_Arcade.zip, and the second replaced the first."""
from scripts.generate_pack import _system_tag
from scripts.packs.naming import _system_tag
pairs = [
(["sega-dreamcast", "arcade"], ["sega-dreamcast-arcade"]),
@@ -3420,7 +3413,7 @@ class ARegionDroppedExtraBlocksNothing(unittest.TestCase):
def test_the_report_skips_what_the_region_pass_drops(self):
from unittest import mock
from scripts import packextras
from scripts.packs import extras as packextras
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory:
other = Path(directory) / "FOO.ROM"
@@ -3503,7 +3496,7 @@ class AnotherEmulatorsTreeProvesNothing(unittest.TestCase):
self.assertTrue(patches.endswith("PlayStation 2/patches.zip"))
def test_no_desktop_retroarch_pack_serves_armsx2s_tree(self):
from scripts import slots
from scripts.packs import slots
from scripts.model.registry import load_data_dir_registry
from scripts.model.database import load_database
from scripts.model.profiles import load_emulator_profiles
@@ -3531,7 +3524,7 @@ class APinnedCoreFileTakesTheSlotFirst(unittest.TestCase):
def test_the_content_naming_claim_is_placed_first(self):
from unittest import mock
from scripts import packextras
from scripts.packs import extras as packextras
undeclared = [
{"profile": "hypseus", "emulator": "hypseus", "name": "db.txt",
@@ -3540,7 +3533,7 @@ class APinnedCoreFileTakesTheSlotFirst(unittest.TestCase):
"path": "db.txt", "in_repo": True, "systems": ["b"], "sha1": "a" * 40},
]
config = {"systems": {}, "base_destination": "bios"}
with mock.patch("verify.find_undeclared_files", return_value=undeclared), \
with mock.patch("packs.gaps.find_undeclared_files", return_value=undeclared), \
mock.patch.object(packextras, "resolve_platform_cores",
return_value=set()) as cores:
extras = packextras._collect_emulator_extras(
@@ -3673,7 +3666,7 @@ class APackNoteBesideItsSlotIsANote(unittest.TestCase):
a pack holding games/keen6/INSTRUCTIONS_egagraph.ck6.txt."""
def test_a_nested_note_is_not_hashed_against_the_collection(self):
from scripts.packverify import verify_pack
from scripts.packs.integrity import verify_pack
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory:
path = Path(directory) / "Pack.zip"
@@ -4037,7 +4030,7 @@ class AnAcceptedVersionIsNoCoreDiscrepancy(unittest.TestCase):
"source_path": "NWINTER.GRP", "source_profile": "eduke32"}
def test_a_sibling_version_matches(self):
from scripts.generate_pack import _matches_an_alternative
from scripts.packs.platformpack import _matches_an_alternative
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp:
held = Path(tmp) / "NWINTER.GRP"
@@ -4048,7 +4041,7 @@ class AnAcceptedVersionIsNoCoreDiscrepancy(unittest.TestCase):
self._extra(), str(held), {"eduke32": profile}))
def test_a_copy_no_entry_declares_still_disagrees(self):
from scripts.generate_pack import _matches_an_alternative
from scripts.packs.platformpack import _matches_an_alternative
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp:
held = Path(tmp) / "NWINTER.GRP"
@@ -4310,7 +4303,7 @@ class ASameNamedMemberIsNotTheFile(unittest.TestCase):
while verify --emulator said missing."""
def test_a_declared_hash_decides_a_member_or_data_hit(self):
from scripts import cross_reference as xr
from scripts.packs import crossref
tmp = Path(tempfile.mkdtemp(dir=TMP_ROOT))
self.addCleanup(lambda: __import__("shutil").rmtree(tmp, True))
@@ -4319,16 +4312,16 @@ class ASameNamedMemberIsNotTheFile(unittest.TestCase):
(tmp / "bios").mkdir()
with zipfile.ZipFile(tmp / "bios" / "extras.zip", "w") as zf:
zf.writestr("files/other.ttf", b"MEMBER FONT")
names = xr._build_supplemental_index(str(tmp / "data"), str(tmp / "bios"))
locations = xr._supplemental_locations(str(tmp / "data"), str(tmp / "bios"))
with mock.patch.object(xr, "_supplemental_locations", lambda: locations):
names = crossref._build_supplemental_index(str(tmp / "data"), str(tmp / "bios"))
locations = crossref._supplemental_locations(str(tmp / "data"), str(tmp / "bios"))
with mock.patch.object(crossref, "_supplemental_locations", lambda: locations):
for fname, data in (("font.ttf", b"DATA FONT"), ("other.ttf", b"MEMBER FONT")):
with self.subTest(name=fname):
held = {"name": fname, "sha1": hashlib.sha1(data).hexdigest()}
other = {"name": fname, "sha1": "0" * 40}
self.assertTrue(xr._data_hit(fname, None, held, names))
self.assertFalse(xr._data_hit(fname, None, other, names))
self.assertTrue(xr._data_hit(fname, None, {"name": fname}, names))
self.assertTrue(crossref._data_hit(fname, None, held, names))
self.assertFalse(crossref._data_hit(fname, None, other, names))
self.assertTrue(crossref._data_hit(fname, None, {"name": fname}, names))
class AnEmptyTargetIsNotEveryCore(unittest.TestCase):
@@ -4337,7 +4330,7 @@ class AnEmptyTargetIsNotEveryCore(unittest.TestCase):
def test_the_published_list_is_the_builder_reading(self):
from scripts.model.targets import load_target_config
from scripts.generate_pack import generate_target_manifests
from scripts.packs.targets import generate_target_manifests
tmp = Path(tempfile.mkdtemp(dir=TMP_ROOT))
self.addCleanup(lambda: __import__("shutil").rmtree(tmp, True))
@@ -4386,7 +4379,7 @@ class ADataDirectoryIsHeldWhileRead(unittest.TestCase):
def test_a_holder_makes_the_refresh_lock_wait(self):
import fcntl
from scripts import refresh_data_dirs
from scripts.packs import datadirs
cache = self.tmp / "bluemsx"
cache.mkdir()
@@ -4402,7 +4395,7 @@ class ADataDirectoryIsHeldWhileRead(unittest.TestCase):
return True
with contextlib.ExitStack() as held:
refresh_data_dirs.hold_data_dirs(held, {"bluemsx": {"local_cache": str(cache)}})
datadirs.hold_data_dirs(held, {"bluemsx": {"local_cache": str(cache)}})
self.assertFalse(exclusive_free())
self.assertTrue(exclusive_free())
@@ -4411,12 +4404,12 @@ class ADataDirectoryIsHeldWhileRead(unittest.TestCase):
missing for verify and present for the packs of the same run."""
import fcntl
from scripts import refresh_data_dirs
from scripts.packs import datadirs
cache = self.tmp / "absent"
lock = cache.with_name(f".{cache.name}.lock")
with contextlib.ExitStack() as held:
refresh_data_dirs.hold_data_dirs(held, {"absent": {"local_cache": str(cache)}})
datadirs.hold_data_dirs(held, {"absent": {"local_cache": str(cache)}})
self.assertFalse(cache.exists())
with open(lock, "a") as handle, self.assertRaises(BlockingIOError):
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
@@ -4442,15 +4435,15 @@ class EachRootReadsItsOwnRegistry(unittest.TestCase):
was asked: a second tree got the first tree's .gitignore."""
def test_two_roots_in_one_process(self):
from scripts import generate_pack
from scripts.packs import manifestentry
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as a, \
tempfile.TemporaryDirectory(dir=TMP_ROOT) as b:
Path(a, ".gitignore").write_text("bios/one.bin\n")
Path(b, ".gitignore").write_text("bios/two.bin\n")
self.assertTrue(generate_pack._is_release_asset(str(Path(a, "bios/one.bin")), a))
self.assertFalse(generate_pack._is_release_asset(str(Path(b, "bios/one.bin")), b))
self.assertTrue(generate_pack._is_release_asset(str(Path(b, "bios/two.bin")), b))
self.assertTrue(manifestentry._is_release_asset(str(Path(a, "bios/one.bin")), a))
self.assertFalse(manifestentry._is_release_asset(str(Path(b, "bios/one.bin")), b))
self.assertTrue(manifestentry._is_release_asset(str(Path(b, "bios/two.bin")), b))
def test_one_parser_reads_the_registry(self):
for module in ("generate_pack.py", "generate_db.py"):
@@ -4485,7 +4478,7 @@ class EveryReadmeNamesItsFolder(unittest.TestCase):
/storage/system, the folder the registry and the installer use."""
def test_the_registry_folder_is_in_the_guide(self):
from scripts.packreadme import _build_readme
from scripts.packs.readme import _build_readme
registry = yaml.safe_load((ROOT / "platforms" / "_registry.yml").read_text())
for name, entry in registry["platforms"].items():
@@ -4650,7 +4643,8 @@ class AutoFetchAsksVerifyWhatIsMissing(unittest.TestCase):
def test_the_targets_are_verify_verdicts(self):
from scripts import auto_fetch
import verify as verify_mod
from packs import coverage as packs_coverage
from packs import verdicts
config = {"verification_mode": "md5", "systems": {"s": {"files": [
{"name": "ok.bin", "md5": "1" * 32},
@@ -4659,9 +4653,9 @@ class AutoFetchAsksVerifyWhatIsMissing(unittest.TestCase):
]}}}
result = {
"details": [
{"system": "s", "name": "ok.bin", "status": verify_mod.Status.OK},
{"system": "s", "name": "gone.bin", "status": verify_mod.Status.MISSING},
{"system": "s", "name": "bad.bin", "status": verify_mod.Status.UNTESTED},
{"system": "s", "name": "ok.bin", "status": verdicts.Status.OK},
{"system": "s", "name": "gone.bin", "status": verdicts.Status.MISSING},
{"system": "s", "name": "bad.bin", "status": verdicts.Status.UNTESTED},
],
"undeclared_files": [
{"name": "diabdat.mpq", "in_repo": False, "required": True,
@@ -4674,7 +4668,7 @@ class AutoFetchAsksVerifyWhatIsMissing(unittest.TestCase):
"bundled": True, "emulator": "ZEsarUX"},
],
}
with mock.patch.object(verify_mod, "verify_platform", lambda c, d: result):
with mock.patch.object(packs_coverage, "verify_platform", lambda c, d: result):
names = [m["name"] for m in auto_fetch.find_missing(config, {})]
self.assertEqual(names, ["gone.bin", "bad.bin", "diabdat.mpq"])
@@ -4733,14 +4727,14 @@ class TheToolsPageSaysWhatDedupDoes(unittest.TestCase):
named 2 of the 11 directories dedup leaves alone."""
def test_every_protected_tree_is_named(self):
from scripts import dedup
from scripts.model import nodedup
line = next(
row for row in (ROOT / "wiki" / "tools.md").read_text().splitlines()
if row.startswith("| `dedup.py`")
)
self.assertNotIn(".variants", line)
for name in dedup.NODEDUP_DIRS:
for name in nodedup.NODEDUP_DIRS:
self.assertIn(name, line)
@@ -4842,7 +4836,7 @@ class AFileToSourceIsAFileNotAName(unittest.TestCase):
def test_rows_are_keyed_by_name_and_hash(self):
source = (ROOT / "scripts" / "generate_site.py").read_text()
self.assertIn('key = (g["name"], g.get("identity") or f"emulator:{emu_name}")', source)
from scripts.cross_reference import _first_hash
from scripts.packs.crossref import _first_hash
self.assertEqual(_first_hash({"md5": ["AB", "cd"]}), "md5:ab")
self.assertEqual(_first_hash({"crc32": "1", "sha1": "F" * 40}), "sha1:" + "f" * 40)
@@ -4946,6 +4940,7 @@ class AManifestHashesAFileOnce(unittest.TestCase):
def test_verified_hashes_are_reused(self):
from scripts import generate_pack
from scripts.packs import manifestentry
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp:
path = Path(tmp, "a.bin")
@@ -4960,8 +4955,8 @@ class AManifestHashesAFileOnce(unittest.TestCase):
return real(file_path, algorithms)
with mock.patch.object(generate_pack, "compute_hashes", counting):
first = generate_pack._stable_hashes(str(path), db)
second = generate_pack._stable_hashes(str(path), db)
first = manifestentry._stable_hashes(str(path), db)
second = manifestentry._stable_hashes(str(path), db)
self.assertEqual(first, second)
self.assertEqual(len(calls), 1)
self.assertEqual(calls[0], frozenset({"sha1", "sha256"}))
@@ -4999,7 +4994,7 @@ class CompanionsComeFromADirectoryIndex(unittest.TestCase):
"""_companions walked the whole database per scanned image."""
def test_same_answer_one_walk(self):
from scripts import packextras
from scripts.packs import extras as packextras
files_db = {
"a": {"path": "bios/Sony/PS2/ps2.bin", "name": "ps2.bin"},
@@ -5090,7 +5085,7 @@ class ATreeNobodyHoldsIsMissingNotAnAsset(unittest.TestCase):
def test_directory_entries_never_reach_the_asset_store(self):
from scripts.model import largefiles
from scripts import packresolve
from scripts.resolve import packfiles as packresolve
db = {"files": {}, "indexes": {"by_name": {}, "by_md5": {}, "by_crc32": {},
"by_path_suffix": {}}}
@@ -5302,9 +5297,10 @@ class VerifyAllSummaryNamesWhatIsWrong(unittest.TestCase):
def test_counts_carry_platforms_and_core_misses(self):
import verify
from packs import verdicts
clean = {"severity_counts": {}, "undeclared_files": []}
warned = {"severity_counts": {verify.Severity.WARNING: 1}, "undeclared_files": []}
warned = {"severity_counts": {verdicts.Severity.WARNING: 1}, "undeclared_files": []}
core_miss = {
"severity_counts": {},
"undeclared_files": [{
@@ -5372,10 +5368,11 @@ class BundledFilesAreNotToSource(unittest.TestCase):
def test_verify_does_not_count_it_missing(self):
import verify
from packs import report as packs_report
entry = {"name": "n64.psh", "required": True, "in_repo": False,
"category": "bios", "in_pack": True, "bundled": True}
self.assertEqual(verify._core_required_missing([entry]), [])
self.assertEqual(packs_report._core_required_missing([entry]), [])
summary = verify._overall_summary(
[({"severity_counts": {}, "undeclared_files": [entry]}, ["ROCKNIX"])]
)
@@ -5394,12 +5391,12 @@ class BundledFilesAreNotToSource(unittest.TestCase):
def test_a_held_bundled_file_is_not_packed(self):
"""A file installed with the emulator is already on the user's
machine, so the pack leaves it out even when the collection holds it."""
import verify
from packs import coverage as packs_coverage
entry = {"name": "n64.psh", "required": True, "in_repo": True,
"emulator": "daedalusx64", "category": "bios", "bundled": True}
with mock.patch("packextras.unplaceable_extras", return_value={}):
verify._mark_unplaced({}, [entry], {})
with mock.patch("packs.extras.unplaceable_extras", return_value={}):
packs_coverage._mark_unplaced({}, [entry], {})
self.assertFalse(entry["in_pack"])
self.assertIn("installed with its emulator", entry["omitted"])
@@ -5540,10 +5537,11 @@ class GapsPageCountsOneWay(unittest.TestCase):
self.assertEqual(_declared_destination(config, detail), "bios/quasi88/N88_KNJ1.ROM")
def test_verify_marks_the_settled_entry(self):
import verify
from packs import coverage as packs_coverage
from packs import verdicts
result = {"name": "cdibios.zip", "status": verify.Status.UNTESTED}
self.assertTrue(verify._twin_unmet(result, "arcade"))
result = {"name": "cdibios.zip", "status": verdicts.Status.UNTESTED}
self.assertTrue(packs_coverage._twin_unmet(result, "arcade"))
self.assertEqual(result["settled_by"], "arcade")
@@ -5914,7 +5912,7 @@ class ZippedFileMd5IsParsedOnce(unittest.TestCase):
import zipfile as zf_mod
from scripts.resolve.validation import inner_rom_check
from scripts.verify import verify_entry_md5
from scripts.packs.verdicts import verify_entry_md5
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory:
archive = Path(directory, "x.zip")
@@ -5942,7 +5940,7 @@ class AHashListIsReadOneWay(unittest.TestCase):
profile_sync looked the whole string up and called it missing."""
def test_every_reader_splits_the_list(self):
from scripts.cross_reference import _declared_content
from scripts.packs.crossref import _declared_content
from scripts.core.hashing import parse_hash_list
from scripts.profiling.citations import entry_hashes
@@ -6015,7 +6013,7 @@ class RommNeoGeoFoldersGetTheirBios(unittest.TestCase):
# into neogeoaes/, and FBNeo's CPS3 sets already sat in colecovision/:
# a system the platform lacks has no folder, and a mirror-only
# folder attracts no system-less file.
from scripts.packextras import _slug_for
from scripts.packs.extras import _slug_for
config_systems = {"arcade", "snk-neogeo-aes", "nintendo-ds"}
sys_to_slug = {"arcade": "arcade", "snk-neogeo-aes": "neogeoaes",
@@ -6226,7 +6224,8 @@ class TheGroundTruthFooterSaysWhatItCounts(unittest.TestCase):
import io as _io
from contextlib import redirect_stdout
from scripts.verify import Severity, print_platform_result
from scripts.packs.verdicts import Severity
from scripts.packs.report import print_platform_result
out = _io.StringIO()
counts = {Severity.OK: 1, Severity.INFO: 0, Severity.WARNING: 0, Severity.CRITICAL: 0}
@@ -6275,7 +6274,7 @@ class StrictFailsOnMissingOnly(unittest.TestCase):
def test_the_contract(self):
from scripts import verify as verify_mod
from scripts.verify import Severity
from scripts.packs.verdicts import Severity
verify_mod._exit_if_strict(True, [{"severity_counts": {Severity.WARNING: 2}}])
with self.assertRaises(SystemExit), contextlib.redirect_stderr(io.StringIO()):
@@ -6615,7 +6614,7 @@ class ThePackCheckAppliesTheFrontendRule(unittest.TestCase):
import hashlib
import zipfile
from scripts.packverify import _check_member_hash
from scripts.packs.integrity import _check_member_hash
payload = b"revision B"
entry = {
@@ -6846,7 +6845,7 @@ class DocsDescribeTheRegistriesTheyName(unittest.TestCase):
self.assertEqual(offenders, [])
def test_the_dedup_list_is_named_whole_or_by_its_constant(self):
from dedup import NODEDUP_DIRS
from model.nodedup import NODEDUP_DIRS
tools = (ROOT / "wiki" / "tools.md").read_text(encoding="utf-8")
line = next(entry for entry in tools.splitlines() if "NODEDUP_DIRS" in entry)
# Compared as list items: `mame` was missing while the substring
@@ -7100,7 +7099,7 @@ class RequiredOnlyReachesDataDirectories(unittest.TestCase):
keypad when absent (FreeIntv src/libretro.c:294-296, 350-369)."""
def _members(self, required_only: bool) -> list[str]:
from scripts import generate_pack as gp
from scripts.packs import datatrees
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp:
for key in ("needed", "optional"):
@@ -7120,7 +7119,7 @@ class RequiredOnlyReachesDataDirectories(unittest.TestCase):
}
return [
dest
for _src, dest in gp._data_directory_members(
for _src, dest in datatrees._data_directory_members(
systems, registry, "retroarch", "", False, set(), set(), set(),
required_only=required_only,
)
@@ -7213,12 +7212,12 @@ class PlatformSystemTypoGetsTheClosestNames(unittest.TestCase):
systems of the alphabet, 3do to coleco-colecovision."""
def test_the_hint_names_the_close_systems(self):
from scripts import generate_pack as gp
from scripts.packs import platformpack
out = io.StringIO()
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp, \
contextlib.redirect_stdout(out):
result = gp.generate_pack(
result = platformpack.generate_pack(
"retroarch", str(ROOT / "platforms"), {"files": {}, "indexes": {}},
str(ROOT / "bios"), tmp, emulators_dir=str(ROOT / "emulators"),
system_filter=["sony-playstaton"], offline=True,
@@ -7236,7 +7235,7 @@ class HashInputNamesWhatItAccepts(unittest.TestCase):
found in input"."""
def test_digests_are_read_by_length(self):
from scripts.packresolve import parse_hash_input
from scripts.resolve.packfiles import parse_hash_input
sha256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
self.assertEqual(parse_hash_input(f"0x1A2B3C4D,{sha256}"), [
@@ -7245,7 +7244,7 @@ class HashInputNamesWhatItAccepts(unittest.TestCase):
self.assertEqual(parse_hash_input("a" * 29), [("md5", "a" * 29)])
def test_anything_else_is_refused_with_the_formats(self):
from scripts.packresolve import parse_hash_file, parse_hash_input
from scripts.resolve.packfiles import parse_hash_file, parse_hash_input
for raw in ("1234567890ab", "zz", "490f666e1afb15b7362b406ed1cea246,zz"):
with self.subTest(raw=raw), self.assertRaises(ValueError) as ctx:
@@ -7259,7 +7258,7 @@ class HashInputNamesWhatItAccepts(unittest.TestCase):
self.assertIn("line 3 (b.bin)", str(ctx.exception))
def test_a_sha256_finds_its_file(self):
from scripts.packresolve import sha1_for_hash
from scripts.resolve.packfiles import sha1_for_hash
db = json.loads((ROOT / "database.json").read_text(encoding="utf-8"))
sha1, entry = next(
@@ -7463,7 +7462,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
return response
def test_offline_never_reaches_the_network(self):
import packresolve
from resolve import packfiles as packresolve
with tempfile.TemporaryDirectory() as tmp, \
mock.patch.object(packresolve.urllib.request, "urlopen") as urlopen, \
@@ -7473,7 +7472,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
urlopen.assert_not_called()
def test_the_run_switch_is_inherited(self):
import packresolve
from resolve import packfiles as packresolve
saved = packresolve._OFFLINE
packresolve.set_offline(True)
@@ -7487,7 +7486,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
packresolve.set_offline(saved)
def test_a_verified_body_lands_and_a_wrong_one_is_removed(self):
import packresolve
from resolve import packfiles as packresolve
with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / "x"
@@ -7868,7 +7867,7 @@ class EveryReaderOfACoreFileIsNamed(unittest.TestCase):
claims with it."""
def test_a_host_its_emulator_installs_leaves_the_others_in_the_pack(self):
from verify import _split_bundled_claims
from packs.gaps import _split_bundled_claims
dsperate = {"profile": "dsperate", "name": "usrcheat.dat", "in_repo": True}
drastic = {"profile": "drastic", "name": "usrcheat.dat", "bundled": True,
@@ -7883,14 +7882,14 @@ class EveryReaderOfACoreFileIsNamed(unittest.TestCase):
def test_a_held_file_out_of_reach_names_every_core_reading_it(self):
"""harm1.wad is a release asset: a checkout without it omits the file,
and the omission named gzdoom alone where lzdoom reads it too."""
from generate_pack import _claim_cores
from packs.manifestentry import _claim_cores
extra = {"source_profile": "gzdoom", "other_claims": [
{"source_profile": "uzdoom"}, {"source_profile": "lzdoom"}]}
self.assertEqual(_claim_cores(extra), ["gzdoom", "lzdoom", "uzdoom"])
def test_a_missing_file_names_every_core_reading_it(self):
from generate_pack import _record_absent
from packs.manifestentry import _record_absent
omitted: dict[str, dict] = {}
+1 -1
View File
@@ -31,7 +31,7 @@ from scraper.batocera_scraper import (
requirements_from_systems,
)
from siteexports import describe_change
from verify import Status, verify_entry_md5
from packs.verdicts import Status, verify_entry_md5
REPO_ROOT = Path(__file__).resolve().parents[1]
+3 -3
View File
@@ -15,7 +15,7 @@ import unittest
from pathlib import Path
import yaml
from packextras import _companion_extensions, _companions
from packs.extras import _companion_extensions, _companions
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -66,7 +66,7 @@ class Companions(unittest.TestCase):
import os
import tempfile
from packextras import _agnostic_scan_extras
from packs.extras import _agnostic_scan_extras
profile = {
"emulator": "PCSX2", "bios_mode": "agnostic", "files": [
@@ -117,7 +117,7 @@ class Companions(unittest.TestCase):
import os
import tempfile
from packextras import _agnostic_scan_extras
from packs.extras import _agnostic_scan_extras
def profile(name: str, ext: str) -> dict:
return {"emulator": name, "bios_mode": "agnostic", "files": [
+1 -1
View File
@@ -25,7 +25,7 @@ class DeclaredFilesResolveWithoutDataCaches(unittest.TestCase):
from model.registry import list_registered_platforms, load_data_dir_registry
from model.database import load_database
from model.platforms import load_platform_config
from packresolve import resolve_declaration
from resolve.packfiles import resolve_declaration
platforms_dir = REPO_ROOT / "platforms"
registry = load_data_dir_registry(str(platforms_dir))
+6 -7
View File
@@ -18,6 +18,8 @@ import unittest
from pathlib import Path
import yaml
from packs import archive
from packs import platformpack
from model.platforms import load_platform_config
@@ -45,9 +47,6 @@ class ThePackReadmeNamesTheSpellingsItLeavesOut(unittest.TestCase):
from model.platforms import _platform_config_cache
from model.profiles import _emulator_profiles_cache
import generate_db
import generate_pack
self.gp = generate_pack
tmp = tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp")
self.addCleanup(tmp.cleanup)
previous = os.getcwd()
@@ -88,18 +87,18 @@ class ThePackReadmeNamesTheSpellingsItLeavesOut(unittest.TestCase):
}}}))
_platform_config_cache.clear()
texts: dict[str, str] = {}
real = self.gp._write_generated_member
real = archive._write_generated_member
def capture(zf, arcname, text):
texts[arcname] = text
return real(zf, arcname, text)
self.gp._write_generated_member = capture
archive._write_generated_member = capture
self.addCleanup(setattr, self.gp, "_write_generated_member", real)
with contextlib.redirect_stdout(io.StringIO()):
self.gp.generate_pack(
platformpack.generate_pack(
"p", "platforms", self.db, "bios", "", emulators_dir="emulators",
offline=True, record=self.gp.PackRecord(),
offline=True, record=archive.PackRecord(),
)
return texts["README.txt"]
+1 -1
View File
@@ -23,7 +23,7 @@ from model.profiles import _emulator_profiles_cache, load_emulator_profiles
from resolve.content import content_fits, size_fits, _masked_sha1_verdict
from resolve.localfile import resolve_local_file
import generate_pack as builder
import packextras
from packs import extras as packextras
from core.romdir import romdir_accepts, walk
from resolve.validation import _build_validation_index, check_file_validation
+5 -5
View File
@@ -100,13 +100,13 @@ class BeforeOpeningAPullRequest(unittest.TestCase):
def test_a_file_too_large_for_git_has_a_route(self):
"""The guide sent any file over 25 MB through a clone, which GitHub
refuses past 100 MB, and only a maintainer can write to the release."""
import validate_pr
from resolve import review
text = generate_readme.generate_contributing()
section = text.split("## What happens next", 1)[1].split("\n## ", 1)[0]
self.assertEqual(validate_pr.MAX_FILE_SIZE, 100 * 1024 * 1024)
self.assertEqual(review.MAX_FILE_SIZE, 100 * 1024 * 1024)
self.assertIn("100 MB", section)
self.assertIn(f"]({validate_pr.LARGE_FILE_ISSUE_URL})", section)
self.assertIn(f"]({review.LARGE_FILE_ISSUE_URL})", section)
def test_it_installs_what_the_checks_need_and_no_site_package(self):
"""The site is built by Node from website/package-lock.json: a pip
@@ -177,7 +177,7 @@ class OneFileThroughTheBrowser(unittest.TestCase):
import os
import tempfile
import validate_pr
from resolve import review
scratch = REPO_ROOT / "tmp" / "tests"
scratch.mkdir(parents=True, exist_ok=True)
@@ -191,7 +191,7 @@ class OneFileThroughTheBrowser(unittest.TestCase):
cwd = os.getcwd()
os.chdir(directory)
try:
result = validate_pr.validate_file("bios/boot.rom", None, hashes)
result = review.validate_file("bios/boot.rom", None, hashes)
finally:
os.chdir(cwd)
self.assertTrue(result.passed)
+14 -12
View File
@@ -22,7 +22,9 @@ from model.profiles import load_emulator_profiles, installed_data_refs
from model.registry import load_data_dir_registry, list_registered_platforms
from resolve.cores import resolve_platform_cores
from resolve.standalone import platform_layouts, standalone_set
import generate_pack as builder
from packs import archive
from packs import datatrees
from packs import platformpack
from resolve.validation import deliverable, read_from_system_dir
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -67,7 +69,7 @@ CONFIG = {
class CoreDataTreesTest(unittest.TestCase):
def trees(self, platform: str = "plat", registry: dict | None = None) -> list[dict]:
return builder.core_data_trees(
return datatrees.core_data_trees(
CONFIG, PROFILES, platform, REGISTRY if registry is None else registry
)
@@ -96,17 +98,17 @@ class CoreDataTreesTest(unittest.TestCase):
twin = {**PROFILES["demo"], "emulator": "Twin", "cores": ["twin"]}
profiles = {**PROFILES, "twin": twin}
config = {**CONFIG, "cores": ["demo", "solo", "twin"]}
trees = builder.core_data_trees(config, profiles, "plat", REGISTRY)
trees = datatrees.core_data_trees(config, profiles, "plat", REGISTRY)
shared = [t for t in trees if t["ref"] == "shared"]
self.assertEqual(len(shared), 1)
self.assertEqual(shared[0]["readers"], ["demo", "twin"])
self.assertEqual(builder.tree_readers({}, trees)["shared"], ["demo", "twin"])
self.assertEqual(datatrees.tree_readers({}, trees)["shared"], ["demo", "twin"])
def test_a_tree_a_system_declares_names_no_core(self) -> None:
trees = self.trees()
declared = {"demo-system": {"data_directories": [{"ref": "shared"}]}}
self.assertNotIn("shared", builder.tree_readers(declared, trees))
self.assertIn("shared", builder.tree_readers({}, trees))
self.assertNotIn("shared", datatrees.tree_readers(declared, trees))
self.assertIn("shared", datatrees.tree_readers({}, trees))
def test_tree_below_the_declared_bios_folder(self) -> None:
config = {
@@ -114,13 +116,13 @@ class CoreDataTreesTest(unittest.TestCase):
"base_destination": "",
"systems": {"demo-system": {"files": [{"name": "a.bin", "destination": "bios/a.bin"}]}},
}
trees = builder.core_data_trees(config, PROFILES, "plat", REGISTRY)
trees = datatrees.core_data_trees(config, PROFILES, "plat", REGISTRY)
self.assertEqual(
[t["destination"] for t in trees if t["ref"] == "shared"], ["bios/Demo/Sys"]
)
def test_no_registry_no_tree(self) -> None:
self.assertEqual(builder.core_data_trees(CONFIG, PROFILES, "plat", None), [])
self.assertEqual(datatrees.core_data_trees(CONFIG, PROFILES, "plat", None), [])
class EveryReaderHasTheTreeOrAReason(unittest.TestCase):
@@ -170,10 +172,10 @@ class AmberelecCarriesTheMachines(unittest.TestCase):
config = load_platform_config("amberelec", platforms_dir)
registry = load_data_dir_registry(platforms_dir)
profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"))
trees = builder.core_data_trees(config, profiles, "amberelec", registry)
trees = datatrees.core_data_trees(config, profiles, "amberelec", registry)
refs: dict = {}
members = dict(
(full, src) for src, full in builder._data_directory_members(
(full, src) for src, full in datatrees._data_directory_members(
config.get("systems", {}), registry, "amberelec",
config.get("base_destination", ""), False, set(), set(), set(),
refs_out=refs, core_trees=trees,
@@ -200,10 +202,10 @@ class TheCountLineKeepsTreesOutOfTheBaseline(unittest.TestCase):
os.chdir(REPO_ROOT)
self.addCleanup(os.chdir, previous)
db = load_database("database.json")
record = builder.PackRecord()
record = archive.PackRecord()
out = io.StringIO()
with contextlib.redirect_stdout(out):
builder.generate_pack(
platformpack.generate_pack(
"myminui", "platforms", db, "bios", "tmp", offline=True, record=record,
data_registry=load_data_dir_registry("platforms"),
)
+12 -10
View File
@@ -25,8 +25,8 @@ import yaml
from model.profiles import _emulator_profiles_cache
from model.platforms import load_platform_config
from generate_pack import generate_pack
from verify import verify_platform
from packs.platformpack import generate_pack
from packs.coverage import verify_platform
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -151,6 +151,8 @@ class AMissingDataDirectoryFailsTheRun(unittest.TestCase):
def test_the_pack_records_it_and_main_exits_non_zero(self):
import generate_pack as gp
from packs import datatrees
from packs import platformpack
root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp"))
self.addCleanup(shutil.rmtree, root, True)
@@ -166,18 +168,18 @@ class AMissingDataDirectoryFailsTheRun(unittest.TestCase):
}))
db = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}, "by_crc32": {},
"by_path_suffix": {}}}
gp._MISSING_DATA_DIRS.clear()
self.addCleanup(gp._MISSING_DATA_DIRS.clear)
datatrees._MISSING_DATA_DIRS.clear()
self.addCleanup(datatrees._MISSING_DATA_DIRS.clear)
with redirect_stdout(io.StringIO()):
gp.generate_pack(
platformpack.generate_pack(
"fakeplat", str(root / "platforms"), db, str(root / "bios"),
str(root / "out"), emulators_dir=str(root / "emulators"),
data_registry={"assets": {"local_cache": str(root / "absent")}},
offline=True,
)
self.assertEqual(gp._MISSING_DATA_DIRS, {"assets"})
self.assertEqual(datatrees._MISSING_DATA_DIRS, {"assets"})
# main() starts each run with no notices, so the run itself records it.
with mock.patch.object(gp, "_main", lambda held: gp._MISSING_DATA_DIRS.add("assets")), \
with mock.patch.object(gp, "_main", lambda held: datatrees._MISSING_DATA_DIRS.add("assets")), \
contextlib.redirect_stderr(io.StringIO()), \
self.assertRaises(SystemExit) as stop:
gp.main()
@@ -191,7 +193,7 @@ class AFileNobodyHoldsIsAnOmission(unittest.TestCase):
showed no notice and said everything was verified."""
def test_the_manifest_names_it(self):
from generate_pack import generate_manifest
from packs.manifest import generate_manifest
_emulator_profiles_cache.clear()
root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp"))
@@ -232,7 +234,7 @@ class AMemberNameIsNotALooseFile(unittest.TestCase):
no archive member names, shipped nothing."""
def test_verify_reads_undeclared_files_as_the_builder_does(self):
import cross_reference
from packs import crossref
_emulator_profiles_cache.clear()
root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp"))
@@ -252,7 +254,7 @@ class AMemberNameIsNotALooseFile(unittest.TestCase):
db = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}, "by_crc32": {},
"by_path_suffix": {}}}
config = load_platform_config("fakeplat", str(root / "platforms"))
with mock.patch.object(cross_reference, "_build_supplemental_index",
with mock.patch.object(crossref, "_build_supplemental_index",
lambda *a, **k: {"315-6146.bin"}):
result = verify_platform(config, db, str(root / "emulators"))
self.assertEqual(
+6 -4
View File
@@ -24,9 +24,11 @@ import yaml
from model.platforms import _platform_config_cache
from model.profiles import load_emulator_profiles, _emulator_profiles_cache
import generate_db
import generate_pack as builder
from packs import manifest as packs_manifest
from packs import platformpack
from resolve.validation import core_size_refusal
from verify import find_undeclared_files, verify_platform
from packs.gaps import find_undeclared_files
from packs.coverage import verify_platform
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -104,7 +106,7 @@ class _Collection(unittest.TestCase):
return next(u for u in undeclared if u["profile"] == profile)
def _pack_members(self) -> set[str]:
zip_path = builder.generate_pack(
zip_path = platformpack.generate_pack(
"exist", "platforms", self.db, "bios", "out",
emulators_dir="emulators", emu_profiles=self.profiles, offline=True,
)
@@ -112,7 +114,7 @@ class _Collection(unittest.TestCase):
return set(zf.namelist())
def _manifest(self) -> dict:
return builder.generate_manifest(
return packs_manifest.generate_manifest(
"exist", "platforms", self.db, "bios", "platforms/_registry.yml",
emulators_dir="emulators", emu_profiles=self.profiles, offline=True,
)
+2 -6
View File
@@ -15,12 +15,8 @@ import tempfile
import unittest
from pathlib import Path
from cross_reference import (
_build_supplemental_index,
cross_reference,
entry_source,
print_report,
)
from packs.crossref import _build_supplemental_index, cross_reference, entry_source
from cross_reference import print_report
REPO_ROOT = Path(__file__).resolve().parent.parent
+1 -5
View File
@@ -13,11 +13,7 @@ import tests
import unittest
from pathlib import Path
from cross_reference import (
cross_reference,
declared_names,
load_platform_files,
)
from packs.crossref import cross_reference, declared_names, load_platform_files
REPO_ROOT = Path(__file__).resolve().parent.parent
+5 -4
View File
@@ -19,6 +19,7 @@ import unittest
from pathlib import Path
import dedup
from model import nodedup
class _Bios(unittest.TestCase):
@@ -286,9 +287,9 @@ class PathPriority(unittest.TestCase):
self.assertLess(primary, variant)
def test_protected_directories_are_recognised(self):
self.assertTrue(dedup._in_nodedup_dir("bios/RPG Maker/x/font.png"))
self.assertTrue(dedup._in_nodedup_dir("bios/ScummVM/x/monkey.tbl"))
self.assertFalse(dedup._in_nodedup_dir("bios/Sony/PlayStation/scph.bin"))
self.assertTrue(nodedup._in_nodedup_dir("bios/RPG Maker/x/font.png"))
self.assertTrue(nodedup._in_nodedup_dir("bios/ScummVM/x/monkey.tbl"))
self.assertFalse(nodedup._in_nodedup_dir("bios/Sony/PlayStation/scph.bin"))
class TheNoDedupListIsPinned(unittest.TestCase):
@@ -298,7 +299,7 @@ class TheNoDedupListIsPinned(unittest.TestCase):
three machines again, with the suite green."""
def test_every_tree_read_by_path_stays_undeduplicated(self):
from scripts.dedup import NODEDUP_DIRS
from scripts.model.nodedup import NODEDUP_DIRS
expected = {
"RPG Maker", "ScummVM", "tzdata", "c64-emu", "PinMAME", "BBK",
+9 -7
View File
@@ -227,7 +227,7 @@ class TestPackDeterminism(unittest.TestCase):
self._tmp.cleanup()
def _build(self, out_name: str) -> Path:
from scripts.generate_pack import generate_pack
from scripts.packs.platformpack import generate_pack
out = self.tmp / out_name
out.mkdir()
@@ -294,7 +294,7 @@ class TestPackDeterminism(unittest.TestCase):
self.assertEqual(info.date_time, _FIXED_DATE_TIME)
def _build_emulator(self, out_name: str) -> Path:
from scripts.generate_pack import generate_emulator_pack
from scripts.packs.emulatorpack import generate_emulator_pack
out = self.tmp / out_name
out.mkdir()
@@ -383,7 +383,8 @@ class TestPackDeterminism(unittest.TestCase):
)
def test_injected_manifest_is_pinned_to_the_database(self):
from scripts.generate_pack import inject_manifest, verify_pack
from scripts.packs.finalize import inject_manifest
from scripts.generate_pack import verify_pack
pack = self._build("out1")
ok, manifest = verify_pack(str(pack), self.db)
@@ -406,7 +407,8 @@ class ManifestInjectionIsAtomic(unittest.TestCase):
import tempfile
from unittest import mock
from scripts import generate_pack as gp
from scripts.packs import archive as packs_archive
from scripts.packs import finalize
with tempfile.TemporaryDirectory(dir=Path(__file__).resolve().parents[1] / "tmp") as d:
pack = Path(d) / "Pack.zip"
@@ -420,9 +422,9 @@ class ManifestInjectionIsAtomic(unittest.TestCase):
zf.fp.flush()
raise KeyboardInterrupt
with mock.patch.object(gp, "_write_generated_member", die), \
with mock.patch.object(packs_archive, "_write_generated_member", die), \
self.assertRaises(KeyboardInterrupt):
gp.inject_manifest(str(pack), {"files": ["x"] * 2000})
finalize.inject_manifest(str(pack), {"files": ["x"] * 2000})
self.assertEqual(pack.read_bytes(), before)
self.assertEqual(
[p.name for p in Path(d).iterdir()], ["Pack.zip"],
@@ -436,7 +438,7 @@ class PackMemberCompression(unittest.TestCase):
the packs' size."""
def _pack(self, tmp: Path, name: str) -> Path:
from scripts.generate_pack import _add_pack_member
from scripts.packs.archive import _add_pack_member
source = tmp / "member"
source.write_bytes(b"\x00" * 4096)
+19 -15
View File
@@ -28,8 +28,12 @@ except ImportError:
from model.profiles import load_emulator_profiles, _emulator_profiles_cache
from resolve.directories import directory_members
import generate_db
import generate_pack as builder
import verify
from packs import emulatorpack
from packs import manifest as packs_manifest
from packs import platformpack
from packs import emulatorcheck
from packs import gaps as packs_gaps
from packs import verdicts
HAS_JSONSCHEMA = jsonschema is not None
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -158,7 +162,7 @@ class DirectoryMembers(DirectoryFixture):
class CrossReferenceReadsADirectory(DirectoryFixture):
def _report(self, body: str = PROFILE) -> list[dict]:
profiles = self._profiles(body)
return verify.find_undeclared_files(
return packs_gaps.find_undeclared_files(
PLATFORM, str(self.emulators), self._db(), profiles
)
@@ -199,7 +203,7 @@ class GapReportReadsADirectory(DirectoryFixture):
listed as a file to source."""
def test_a_held_hidden_directory_is_held(self):
from cross_reference import entry_source
from packs.crossref import entry_source
self._add("Engine/cdogs/data/.wolf3d/N3D.cdogscpn/campaign.json", b"campaign")
db = self._db()
@@ -223,7 +227,7 @@ class PackCarriesADirectory(DirectoryFixture):
profiles = self._profiles()
out = self.root / "dist"
out.mkdir()
zip_path = builder.generate_pack(
zip_path = platformpack.generate_pack(
"demo", str(self.platforms), self._db(), str(self.bios), str(out),
emulators_dir=str(self.emulators),
emu_profiles=profiles, offline=True,
@@ -238,7 +242,7 @@ class PackCarriesADirectory(DirectoryFixture):
def test_the_install_manifest_lists_the_tree(self):
profiles = self._profiles()
manifest = builder.generate_manifest(
manifest = packs_manifest.generate_manifest(
"demo", str(self.platforms), self._db(), str(self.bios),
str(self.platforms / "_registry.yml"),
emulators_dir=str(self.emulators), emu_profiles=profiles,
@@ -251,9 +255,9 @@ class PackCarriesADirectory(DirectoryFixture):
def test_the_gap_report_is_computed_once_per_build(self):
"""The region grouping and phase 2 each ran find_undeclared_files with
the same arguments: 30 reports for 15 manifests."""
import verify
from packs import gaps as packs_gaps
real = verify.find_undeclared_files
real = packs_gaps.find_undeclared_files
calls: list[int] = []
def counted(*a, **kw):
@@ -263,15 +267,15 @@ class PackCarriesADirectory(DirectoryFixture):
profiles = self._profiles()
out = self.root / "counted"
out.mkdir()
with mock.patch.object(verify, "find_undeclared_files", counted):
builder.generate_manifest(
with mock.patch.object(packs_gaps, "find_undeclared_files", counted):
packs_manifest.generate_manifest(
"demo", str(self.platforms), self._db(), str(self.bios),
str(self.platforms / "_registry.yml"),
emulators_dir=str(self.emulators), emu_profiles=profiles,
offline=True,
)
self.assertEqual(len(calls), 1)
builder.generate_pack(
platformpack.generate_pack(
"demo", str(self.platforms), self._db(), str(self.bios), str(out),
emulators_dir=str(self.emulators), emu_profiles=profiles,
offline=True, regions=["north-america"],
@@ -282,7 +286,7 @@ class PackCarriesADirectory(DirectoryFixture):
self._profiles()
out = self.root / "emu"
out.mkdir()
zip_path = builder.generate_emulator_pack(
zip_path = emulatorpack.generate_emulator_pack(
["demo"], str(self.emulators), self._db(), str(self.bios), str(out),
offline=True,
)
@@ -292,17 +296,17 @@ class PackCarriesADirectory(DirectoryFixture):
def test_verify_counts_what_the_emulator_pack_ships(self):
self._profiles()
result = verify.verify_emulator(["demo"], str(self.emulators), self._db())
result = emulatorcheck.verify_emulator(["demo"], str(self.emulators), self._db())
held = {
detail["name"]
for detail in result["details"]
if detail["status"] == verify.Status.OK
if detail["status"] == verdicts.Status.OK
}
self.assertEqual(held, self.EXPECTED)
missing = [
detail["name"]
for detail in result["details"]
if detail["status"] == verify.Status.MISSING
if detail["status"] == verdicts.Status.MISSING
]
self.assertEqual(missing, ["Fonts"])
+6 -6
View File
@@ -59,7 +59,7 @@ class TestSkeletonReadsTheResultShape(unittest.TestCase):
copied from it stopped on KeyError: 0 before any assertion."""
def test_every_key_it_reads_is_one_verify_platform_returns(self):
from verify import verify_platform
from packs.coverage import verify_platform
result = verify_platform(
{"platform": "x", "verification_mode": "existence", "systems": {}},
@@ -425,7 +425,7 @@ class RecalboxSeverity(unittest.TestCase):
code never reads, and called a missing optional file GREEN."""
def test_the_verify_column_is_what_compute_severity_returns(self):
from verify import Status, compute_severity
from packs.verdicts import Status, compute_severity
section = _section(_page("verification-modes.md"), "Mandatory levels (Recalbox)")
rows = _table_rows(section)
@@ -475,9 +475,9 @@ class ValidationIndexScope(unittest.TestCase):
pass it only the profiles the platform resolves."""
def test_page_names_the_scope_the_code_uses(self):
import verify
from packs import coverage
source = inspect.getsource(verify.verify_platform)
source = inspect.getsource(coverage.verify_platform)
self.assertRegex(source, r"plat_cores = resolve_platform_cores\(config, profiles\)")
self.assertIn("_build_validation_index(platform_profiles)", source)
section = _section(_page("verification-modes.md"), "Validation index")
@@ -1751,7 +1751,7 @@ class ArchitectureStatesTheArbitration(unittest.TestCase):
checks the content: RetroBat's ATARIOSB.ROM."""
def test_the_page_says_what_arbitrate_decides(self):
import slots
from packs import slots
page = (WIKI / "architecture.md").read_text(encoding="utf-8")
self.assertNotIn("the profile takes precedence for pack generation", page)
@@ -1840,7 +1840,7 @@ class ClaimRuleNamesTheSizeProof(unittest.TestCase):
platform file of another size since 2b535525e."""
def test_the_page_states_what_slots_counts(self):
import slots
from packs import slots
self.assertIn(slots.SIZE_EXACT, slots.PROVEN_STATUSES)
page = " ".join((ROOT / "wiki" / "architecture.md").read_text(encoding="utf-8").split())
+3 -3
View File
@@ -30,7 +30,7 @@ import unittest
import zipfile
from pathlib import Path
import split_pack
from packs import parts as packs_parts
REPO_ROOT = Path(__file__).resolve().parent.parent
_spec = importlib.util.spec_from_file_location(
@@ -322,7 +322,7 @@ class ReleaseServer:
self.names: list[str] = []
if zip_parts:
# One byte under the whole archive: the last member no longer fits.
parts = split_pack.split_pack(archive, limit=len(raw) - 1)
parts = packs_parts.split_pack(archive, limit=len(raw) - 1)
self.names = [part.name for part in parts]
sums = "".join(
f"{hashlib.sha256(part.read_bytes()).hexdigest()} {part.name}\n"
@@ -455,7 +455,7 @@ class DownloaderCase(unittest.TestCase):
leftovers = sorted(
p.name for p in searched
if ("_BIOS_Pack" in p.name or p.name.startswith("."))
and not split_pack.is_marker(p.name)
and not packs_parts.is_marker(p.name)
)
self.assertEqual(leftovers, [], "download staging left behind")
+18 -22
View File
@@ -43,14 +43,10 @@ from resolve.localfile import resolve_local_file
from resolve.cores import resolve_platform_cores
from resolve.truth import diff_platform_truth, generate_platform_truth
from resolve.validation import _build_validation_index, check_file_validation, filter_files_by_mode
from verify import (
Severity,
Status,
find_exclusion_notes,
find_undeclared_files,
verify_emulator,
verify_platform,
)
from packs.verdicts import Severity, Status
from packs.gaps import find_exclusion_notes, find_undeclared_files
from packs.emulatorcheck import verify_emulator
from packs.coverage import verify_platform
try:
import jsonschema
@@ -1047,7 +1043,7 @@ class TestE2E(unittest.TestCase):
def test_45_hle_fallback_downgrades_severity(self):
"""Missing file with hle_fallback=true ->INFO severity, not CRITICAL."""
from verify import Severity, compute_severity
from packs.verdicts import Severity, compute_severity
# required + missing + NO HLE = CRITICAL
sev = compute_severity("missing", True, "md5", hle_fallback=False)
@@ -2172,7 +2168,7 @@ class TestE2E(unittest.TestCase):
def test_120_format_ground_truth_aggregate(self):
"""Aggregate format: one line with all cores."""
from verify import _format_ground_truth_aggregate
from packs.report import _format_ground_truth_aggregate
gt = [
{
@@ -2196,7 +2192,7 @@ class TestE2E(unittest.TestCase):
def test_121_format_ground_truth_verbose(self):
"""Verbose format: one line per core with expected values and source ref."""
from verify import _format_ground_truth_verbose
from packs.report import _format_ground_truth_verbose
gt = [
{
@@ -2215,7 +2211,7 @@ class TestE2E(unittest.TestCase):
def test_122_format_ground_truth_verbose_no_source_ref(self):
"""Verbose format omits bracket when source_ref is None."""
from verify import _format_ground_truth_verbose
from packs.report import _format_ground_truth_verbose
gt = [
{
@@ -5011,7 +5007,7 @@ struct BurnDriver BurnDrvneogeo = {
def test_200_find_undeclared_include_all(self):
"""include_all=True returns ALL core files, including declared ones."""
from verify import find_undeclared_files
from packs.gaps import find_undeclared_files
config = self._load_config("test_existence")
profiles = load_emulator_profiles(self.emulators_dir)
@@ -5768,7 +5764,7 @@ struct BurnDriver BurnDrvneogeo = {
def test_226_cross_reference_platform_filter(self):
"""--platform restricts declarations to that platform alone."""
from cross_reference import load_platform_files
from packs.crossref import load_platform_files
with tempfile.TemporaryDirectory() as tmpdir:
plat_dir = os.path.join(tmpdir, "platforms")
@@ -6072,7 +6068,7 @@ struct BurnDriver BurnDrvneogeo = {
def test_verify_platform_region_matches_the_pack(self):
from model.platforms import load_platform_config
from verify import verify_platform
from packs.coverage import verify_platform
self._create_region_fixtures()
profiles = self._region_profiles()
@@ -6097,7 +6093,7 @@ struct BurnDriver BurnDrvneogeo = {
def test_verify_emulator_region_matches_the_pack(self):
from generate_pack import generate_emulator_pack
from verify import verify_emulator
from packs.emulatorcheck import verify_emulator
self._create_region_fixtures()
with open(
@@ -6320,7 +6316,7 @@ struct BurnDriver BurnDrvneogeo = {
"""
import inspect
import packverify
from packs import integrity as packverify
from generate_pack import _narrows_contents, _narrowings
source = inspect.getsource(packverify.verify_pack_against_platform)
@@ -6500,7 +6496,7 @@ struct BurnDriver BurnDrvneogeo = {
--region compared nothing."""
import hashlib
from packextras import platform_region_groups
from packs.extras import platform_region_groups
files, by_name = {}, {}
for name in ("core_us.bin", "core_jp.bin"):
@@ -6538,7 +6534,7 @@ struct BurnDriver BurnDrvneogeo = {
--region us pack kept the declared Japanese BIOS."""
import hashlib
from packextras import platform_region_groups
from packs.extras import platform_region_groups
files, by_name = {}, {}
for name in ("bios_U.sms", "bios_J.sms"):
@@ -6722,7 +6718,7 @@ struct BurnDriver BurnDrvneogeo = {
}
def _gap_source(self, entry: dict, db: dict) -> str:
from cross_reference import cross_reference
from packs.crossref import cross_reference
report = cross_reference(
{"gapemu": {"emulator": "GapEmu", "systems": ["s"], "files": [entry]}},
@@ -6934,7 +6930,7 @@ class OneOfASearchList(unittest.TestCase):
)
def test_gap_report_counts_the_set_once(self):
import cross_reference
from packs import crossref
index = {
"by_name": self.db["indexes"]["by_name"],
@@ -6943,7 +6939,7 @@ class OneOfASearchList(unittest.TestCase):
"data_names": set(), "all_declared": set(), "db_files": self.db["files"],
}
report: dict = {}
cross_reference._cross_reference_profile("seq", self.profile, {}, report, index)
crossref._cross_reference_profile("seq", self.profile, {}, report, index)
gaps = {g["name"]: g for g in report["seq"]["gap_details"]}
self.assertEqual(sorted(gaps), ["none_a.bin", "plain.bin", "second.bin", "third.bin"])
self.assertEqual(gaps["none_a.bin"]["alternatives"], ["none_b.bin"])
+2 -2
View File
@@ -81,8 +81,8 @@ class APlaceholderIsAnsweredByEvidence(unittest.TestCase):
import yaml
from model.profiles import _emulator_profiles_cache
from generate_pack import generate_emulator_pack
from verify import verify_emulator
from packs.emulatorpack import generate_emulator_pack
from packs.emulatorcheck import verify_emulator
_emulator_profiles_cache.clear()
(REPO_ROOT / "tmp").mkdir(exist_ok=True)
+10 -8
View File
@@ -10,7 +10,9 @@ import tests
import unittest
import verify
from packs import coverage
from packs import report
from packs import verdicts
from resolve.categories import BIOS, GAME_DATA, UNREAD, EntryCategories, ProofIndex, ReadEvidence
PROFILES = {
@@ -108,7 +110,7 @@ class Evidence(unittest.TestCase):
"emulator": "devilutionx", "proof": "name", "runs_system": True,
"entries": [{"name": "diabdat.mpq", "source_ref": "Source/init.cpp:120",
"by": "name"}]}])
self.assertEqual(verify.category_evidence_text(found),
self.assertEqual(report.category_evidence_text(found),
"read by devilutionx (diabdat.mpq at Source/init.cpp:120)")
def test_unread_names_the_cores_examined(self):
@@ -123,7 +125,7 @@ class Evidence(unittest.TestCase):
cats = EntryCategories(_config(["bluemsx", "devilutionx", "other"], []), profiles)
found = cats.explain({"name": "diabdat.mpq"}, "ports/diablo/diabdat.mpq", "diablo")
self.assertEqual([r["emulator"] for r in found["read_by"]], ["devilutionx", "other"])
self.assertEqual(verify.category_evidence_text(found),
self.assertEqual(report.category_evidence_text(found),
"read by devilutionx (diabdat.mpq at Source/init.cpp:120), "
"also named by other (diabdat.mpq)")
@@ -134,7 +136,7 @@ class Evidence(unittest.TestCase):
{"name": "hardwareconfig.xml"}, "bios/Machines/MSX/hardwareconfig.xml",
"microsoft-msx")
self.assertEqual(found, {"category": UNREAD, "cores_examined": ["bluemsx"]})
self.assertEqual(verify.category_evidence_text(found),
self.assertEqual(report.category_evidence_text(found),
"no reader found (cores examined: bluemsx)")
def test_an_unsettled_entry_says_why(self):
@@ -143,7 +145,7 @@ class Evidence(unittest.TestCase):
"bios/Machines/MSX/hardwareconfig.xml", "microsoft-msx")
self.assertEqual(found["category"], BIOS)
self.assertIn("mystery", found["unsettled"])
self.assertIn("not settled", verify.category_evidence_text(found))
self.assertIn("not settled", report.category_evidence_text(found))
class StrictCountsFirmwareOnly(unittest.TestCase):
@@ -156,13 +158,13 @@ class StrictCountsFirmwareOnly(unittest.TestCase):
], system="microsoft-msx")
db = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}, "by_crc32": {},
"by_path_suffix": {}}}
result = verify.verify_platform(config, db, emu_profiles=PROFILES)
self.assertEqual(result["severity_counts"][verify.Severity.CRITICAL], 1)
result = coverage.verify_platform(config, db, emu_profiles=PROFILES)
self.assertEqual(result["severity_counts"][verdicts.Severity.CRITICAL], 1)
self.assertEqual(result["missing_not_firmware"], {
"game_data": ["ports/diablo/diabdat.mpq"],
"unread": ["bios/Machines/MSX/hardwareconfig.xml"],
})
self.assertEqual(result["status_counts"][verify.Status.MISSING], 3)
self.assertEqual(result["status_counts"][verdicts.Status.MISSING], 3)
evidence = {d["name"]: d.get("category_evidence") for d in result["details"]}
self.assertEqual(evidence["hardwareconfig.xml"]["cores_examined"], ["bluemsx"])
self.assertEqual(evidence["diabdat.mpq"]["read_by"][0]["emulator"], "devilutionx")
+2 -2
View File
@@ -14,8 +14,8 @@ import unittest
from pathlib import Path
from model.profiles import PROFILE_IDENTITY_FIELDS
from packextras import _collect_emulator_extras
from verify import find_undeclared_files
from packs.extras import _collect_emulator_extras
from packs.gaps import find_undeclared_files
REPO_ROOT = Path(__file__).resolve().parents[1]
+2 -2
View File
@@ -15,7 +15,7 @@ import tempfile
import unittest
from pathlib import Path
from cross_reference import FileConsumers, entry_target
from packs.crossref import FileConsumers, entry_target
from generate_site import generate_system_page
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -90,7 +90,7 @@ class PlatformReadersResolveAsThePack(unittest.TestCase):
the one its manifest installs."""
def test_the_declared_file_is_the_one_the_pack_ships(self):
from packresolve import resolve_declaration
from resolve.packfiles import resolve_declaration
first, first_entry = _collected("bios/Arcade/MAME/hash/apfm1000.xml", b"one")
other, other_entry = _collected("bios/Other/mame/hash/apfm1000.xml", b"two")
+1 -1
View File
@@ -16,7 +16,7 @@ import unittest
import zipfile
from pathlib import Path
from generate_pack import verify_and_finalize_packs
from packs.finalize import verify_and_finalize_packs
REPO_ROOT = Path(__file__).resolve().parents[1]
+2 -2
View File
@@ -199,7 +199,7 @@ class TheGapReportAsksAsTheEmulator(unittest.TestCase):
self.entry = {"name": "et4000.bin", "required": True}
def _source(self, owner: str) -> str | None:
from cross_reference import entry_source
from packs.crossref import entry_source
by_name = self.db["indexes"]["by_name"]
index = {
@@ -218,7 +218,7 @@ class TheGapReportAsksAsTheEmulator(unittest.TestCase):
self.assertEqual(self._source("pcem"), "bios")
def test_core_files_follow_the_resolver(self):
from verify import find_undeclared_files
from packs.gaps import find_undeclared_files
profiles = {"dosbox-x": {
"emulator": "DOSBox-X", "type": "libretro", "systems": ["dos"],
+3 -2
View File
@@ -20,8 +20,9 @@ from pathlib import Path
import yaml
from model.platforms import load_platform_config
from generate_pack import generate_manifest, generate_pack
from verify import verify_platform
from packs.manifest import generate_manifest
from packs.platformpack import generate_pack
from packs.coverage import verify_platform
REPO_ROOT = Path(__file__).resolve().parents[1]
+3 -3
View File
@@ -224,7 +224,7 @@ class SecondPassKeepsIdentity(unittest.TestCase):
"""
def test_flag_and_hashes_reach_the_alternative_destination(self):
from packextras import _collect_emulator_extras
from packs.extras import _collect_emulator_extras
sha = "a" * 40
md5 = "b" * 32
@@ -266,7 +266,7 @@ class ReleaseAssetIsNotANameMatch(unittest.TestCase):
def test_an_unsourceable_entry_without_hash_never_reaches_the_asset_store(self):
from unittest import mock
import packresolve
from resolve import packfiles as packresolve
entry = {"name": "pak0.pk3", "unsourceable": "retail"}
db = {"files": {}, "indexes": {"by_name": {}, "by_md5": {}, "by_path_suffix": {}}}
@@ -287,7 +287,7 @@ class ReleaseAssetAnswersEveryDeclaredHash(unittest.TestCase):
import tempfile
from unittest import mock
import packresolve
from resolve import packfiles as packresolve
db = {"files": {}, "indexes": {"by_name": {}, "by_md5": {}, "by_path_suffix": {}}}
with tempfile.TemporaryDirectory() as tmp:
+1 -1
View File
@@ -12,7 +12,7 @@ import tests
import unittest
from pathlib import Path
from cross_reference import cross_reference
from packs.crossref import cross_reference
from resolve.validation import case_folded_slots, declaration_settles
REPO_ROOT = Path(__file__).resolve().parents[1]
+7 -6
View File
@@ -15,7 +15,7 @@ import os
import unittest
from pathlib import Path
from packpaths import placement_block
from packs.paths import placement_block
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -88,7 +88,7 @@ class TheReportSaysSo(unittest.TestCase):
try:
from model.database import load_database
from model.profiles import load_emulator_profiles
from verify import verify_platform
from packs.coverage import verify_platform
from model.platforms import load_platform_config
db = load_database("database.json")
@@ -152,7 +152,8 @@ class TheGapReportIsComputedOnce(unittest.TestCase):
previous = os.getcwd()
os.chdir(REPO_ROOT)
try:
import verify
from packs import coverage
from packs import gaps
from model.database import load_database
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
@@ -161,9 +162,9 @@ class TheGapReportIsComputedOnce(unittest.TestCase):
profiles = load_emulator_profiles("emulators")
config = load_platform_config("emudeck", "platforms")
with mock.patch.object(
verify, "find_undeclared_files", wraps=verify.find_undeclared_files
gaps, "find_undeclared_files", wraps=gaps.find_undeclared_files
) as counted:
verify.verify_platform(config, db, "emulators", profiles)
coverage.verify_platform(config, db, "emulators", profiles)
finally:
os.chdir(previous)
self.assertEqual(counted.call_count, 1)
@@ -177,7 +178,7 @@ class TheReplayResolvesAsTheBuilder(unittest.TestCase):
def test_an_unresolved_extra_blocks_nothing(self):
from unittest import mock
import packextras
from packs import extras as packextras
extras = [
{"destination": "box.bin/inner.rom", "name": "inner.rom",
+5 -4
View File
@@ -4471,9 +4471,10 @@ class DataDirectoriesAreInstalled(unittest.TestCase):
manifest = json.loads((REPO_ROOT / "install" / "retroarch.json").read_text())
dirs = manifest.get("data_directories") or []
files = sum(len(d["files"]) for d in dirs)
import generate_pack
from packs import archive as packs_archive
from packs import datatrees
written = generate_pack.PACK_DOCUMENTS + generate_pack.pack_markers(
written = packs_archive.PACK_DOCUMENTS + datatrees.pack_markers(
"retroarch", None, str(REPO_ROOT / "platforms"))
self.assertEqual(written, ("README.txt", "manifest.json", ".nomedia"))
self.assertEqual(
@@ -7728,13 +7729,13 @@ class TheListVersionIsComparedWithTheSystems(unittest.TestCase):
"""A handheld without network installs from the pack: its manifest.json
records the list's version, which generate_pack takes from the
install list built with the same choices."""
import generate_pack
from packs import scope
data = b"bios"
install_list = {"version": "43.1", "files": [
{"dest": "a.bin", "sha1": hashlib.sha1(data).hexdigest(), "size": 4}]}
pack_list = {"files": [{"path": "a.bin", "sha1": hashlib.sha1(data).hexdigest(),
"size": 4}]}
generate_pack.annotate_pack_systems(pack_list, generate_pack.pack_systems(install_list))
scope.annotate_pack_systems(pack_list, scope.pack_systems(install_list))
self.assertEqual(pack_list["list_version"], "43.1")
pack = Path(_tempdir(self)) / "Batocera_43.1_BIOS_Pack.zip"
with zipfile.ZipFile(pack, "w") as archive:
+7 -7
View File
@@ -265,14 +265,14 @@ class TheBuildersOrder(unittest.TestCase):
db_path = REPO_ROOT / "database.json"
if not db_path.exists():
self.skipTest("database.json is not built")
import generate_pack as gp
from packs import manifest as packs_manifest
from model.profiles import load_emulator_profiles
db = json.loads(db_path.read_text(encoding="utf-8"))
profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"))
def manifest(cores):
return gp.generate_manifest(
return packs_manifest.generate_manifest(
"retropie", str(REPO_ROOT / "platforms"), db, str(REPO_ROOT / "bios"),
str(REPO_ROOT / "platforms" / "_registry.yml"),
emulators_dir=str(REPO_ROOT / "emulators"), emu_profiles=profiles,
@@ -366,14 +366,14 @@ class APlatformOmissionKeepsItsClaim(unittest.TestCase):
self.assertEqual(omitted, [])
def test_the_generator_files_the_core_behind_the_platform(self):
import generate_pack as gp
from packs import manifestentry
held = {"cores": None}
self.assertTrue(gp._claim_platform_omission(held, "melonds"))
self.assertTrue(gp._claim_platform_omission(held, "melonds"))
self.assertTrue(manifestentry._claim_platform_omission(held, "melonds"))
self.assertTrue(manifestentry._claim_platform_omission(held, "melonds"))
self.assertEqual(held["alternatives"], [{"cores": ["melonds"]}])
self.assertFalse(gp._claim_platform_omission({"cores": ["x"]}, "melonds"))
self.assertFalse(gp._claim_platform_omission(None, "melonds"))
self.assertFalse(manifestentry._claim_platform_omission({"cores": ["x"]}, "melonds"))
self.assertFalse(manifestentry._claim_platform_omission(None, "melonds"))
def test_the_boundary_takes_only_core_names(self):
manifest = {"manifest_version": 2, "platform": "retroarch", "files": [],
+8 -8
View File
@@ -197,7 +197,7 @@ class ProgramsAreMarked(unittest.TestCase):
the git mode cannot, hundreds of MAME archives carrying an execute bit."""
def test_header_decides(self):
import generate_pack
from packs import manifestentry
with tempfile.TemporaryDirectory() as tmp:
for data, expected in ((b"\x7fELF\x02", True), (b"#!/bin/sh\n", True),
@@ -205,7 +205,7 @@ class ProgramsAreMarked(unittest.TestCase):
path = Path(tmp) / "f"
path.write_bytes(data)
with self.subTest(head=data):
self.assertEqual(generate_pack._is_program(str(path)), expected)
self.assertEqual(manifestentry._is_program(str(path)), expected)
def test_retrodeck_launchers_are_executable(self):
manifest = json.loads((REPO_ROOT / "install" / "retrodeck.json").read_text())
@@ -224,24 +224,24 @@ class ManifestHashesMatchTheScan(unittest.TestCase):
file holds, the same wrong value in two runs."""
def test_a_contradicted_hash_is_refused(self):
import generate_pack
from packs import manifestentry
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "nand.bin"
path.write_bytes(b"real")
real = hashlib.sha1(b"real").hexdigest()
good = {"files": {real: {"path": str(path)}}}
self.assertEqual(generate_pack._stable_hashes(str(path), good)["sha1"], real)
self.assertEqual(manifestentry._stable_hashes(str(path), good)["sha1"], real)
bad = {"files": {"0" * 40: {"path": str(path)}}}
with self.assertRaises(RuntimeError):
generate_pack._stable_hashes(str(path), bad)
self.assertEqual(generate_pack._stable_hashes(str(path), {"files": {}})["sha1"], real)
manifestentry._stable_hashes(str(path), bad)
self.assertEqual(manifestentry._stable_hashes(str(path), {"files": {}})["sha1"], real)
def test_a_wrong_first_reading_is_read_again_from_disk(self):
"""The retries went through the hash cache and got the first, wrong
value back: one read of the file, then a refusal a second read would
have avoided."""
import generate_pack
from packs import manifestentry
from core import hashing
real_compute = hashing._compute_hashes
@@ -260,7 +260,7 @@ class ManifestHashesMatchTheScan(unittest.TestCase):
real = hashlib.sha1(b"flaky").hexdigest()
db = {"files": {real: {"path": str(path)}}}
with mock.patch.object(hashing, "_compute_hashes", flaky):
self.assertEqual(generate_pack._stable_hashes(str(path), db)["sha1"], real)
self.assertEqual(manifestentry._stable_hashes(str(path), db)["sha1"], real)
self.assertEqual(len(reads), 2)
def test_the_cache_is_keyed_by_what_was_checked(self):
+11 -10
View File
@@ -22,6 +22,10 @@ import subprocess
import sys
import tempfile
import unittest
from packs import archive
from packs import emulatorpack
from packs import manifest as packs_manifest
from packs import platformpack
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -48,13 +52,10 @@ class RealListParity(unittest.TestCase):
if sys.version_info < BUILDER_FLOOR:
# The builder's floor: install.py alone keeps 3.8.
raise unittest.SkipTest("generate_pack.py needs Python 3.9 or newer")
import generate_pack as gp
from core.ziptools import build_zip_contents_index
from model.registry import list_registered_platforms
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
cls.gp = gp
cls.config = staticmethod(
lambda plat: load_platform_config(plat, str(REPO_ROOT / "platforms")))
cls.db = json.loads(db_path.read_text(encoding="utf-8"))
@@ -72,7 +73,7 @@ class RealListParity(unittest.TestCase):
if plat not in self.manifests:
self.layouts[plat] = {}
with contextlib.redirect_stdout(io.StringIO()):
self.manifests[plat] = self.gp.generate_install_list(
self.manifests[plat] = packs_manifest.generate_install_list(
plat, str(REPO_ROOT / "platforms"), self.db, str(REPO_ROOT / "bios"),
str(REPO_ROOT / "platforms" / "_registry.yml"),
emulators_dir=str(REPO_ROOT / "emulators"),
@@ -86,10 +87,10 @@ class RealListParity(unittest.TestCase):
trees apart (data_directories), and a cache copy at a destination
the list serves from the collection is no choice of either option."""
base = self.config(plat).get("base_destination", "")
record = self.gp.PackRecord()
record = archive.PackRecord()
with contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()):
self.gp.generate_pack(
platformpack.generate_pack(
plat, str(REPO_ROOT / "platforms"), self.db, str(REPO_ROOT / "bios"),
str(REPO_ROOT / "tmp"), emulators_dir=str(REPO_ROOT / "emulators"),
zip_contents=self.zip_contents, emu_profiles=self.profiles,
@@ -185,10 +186,10 @@ class RealListParity(unittest.TestCase):
self.assertEqual(sorted(layouts), full.get("standalone_builds", []))
for profile in sorted(layouts):
with self.subTest(platform=plat, emulator=profile):
record = self.gp.PackRecord()
record = archive.PackRecord()
with contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()):
self.gp.generate_emulator_pack(
emulatorpack.generate_emulator_pack(
[profile], str(REPO_ROOT / "emulators"), self.db,
str(REPO_ROOT / "bios"), str(REPO_ROOT / "tmp"),
standalone=True, zip_contents=self.zip_contents,
@@ -268,7 +269,7 @@ class TheSlotRuleIsTheBuilders(unittest.TestCase):
def test_random_slots_against_the_builder(self):
import random
import manifestselect
from packs import manifestselect
from resolve import slot as slot_mod
rng = random.Random(7)
@@ -303,7 +304,7 @@ class TheSlotRuleIsTheBuilders(unittest.TestCase):
does (slot.lookup_slot per member), whatever cores the board runs."""
import random
import manifestselect
from packs import manifestselect
from resolve import slot as slot_mod
rng = random.Random(11)
+7 -6
View File
@@ -28,7 +28,7 @@ import zipfile
from pathlib import Path
import install
import split_pack
from packs import parts as packs_parts
from tests.test_install_selection import FakeRepository
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -342,7 +342,7 @@ class SplitParts(Scratch):
downloads = self.root / "downloads"
downloads.mkdir()
pack = _pack(downloads, "RetroArch_v1_BIOS_Pack.zip", BIG)
parts = split_pack.split_pack(pack, limit=pack.stat().st_size // 3)
parts = packs_parts.split_pack(pack, limit=pack.stat().st_size // 3)
self.assertGreater(len(parts), 2)
return parts
@@ -432,16 +432,17 @@ class ABoardWithoutTheNetwork(Scratch):
if p.is_file()}
def test_the_builder_writes_both_into_the_pack_list(self):
import generate_pack
from packs import scope
from packs import targets
install_list = manifest()
board_file = REPO_ROOT / "platforms" / "targets" / "batocera.yml"
boards = generate_pack.target_list(board_file)
boards = targets.target_list(board_file)
self.assertEqual(boards, json.loads(
(REPO_ROOT / "install" / "targets" / "batocera.json").read_text()))
pack_list = {"files": []}
generate_pack.annotate_pack_systems(
pack_list, generate_pack.pack_systems(install_list, boards))
scope.annotate_pack_systems(
pack_list, scope.pack_systems(install_list, boards))
self.assertEqual(pack_list["install_list"], install_list)
self.assertEqual(pack_list["targets"], boards)
+21 -36
View File
@@ -27,6 +27,10 @@ import sys
import tempfile
import threading
import unittest
from packs import archive
from packs import manifest as packs_manifest
from packs import platformpack
from packs import coverage
from unittest import mock
from pathlib import Path
@@ -813,17 +817,14 @@ class InstallMatchesThePack(unittest.TestCase):
db_path = REPO_ROOT / "database.json"
if not db_path.exists():
raise unittest.SkipTest("database.json is not built")
import generate_pack as gp
from model.profiles import load_emulator_profiles
cls.gp = gp
cls.db = json.loads(db_path.read_text(encoding="utf-8"))
cls.profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"))
cls.full = cls._manifest(None)
@classmethod
def _manifest(cls, regions):
return cls.gp.generate_manifest(
return packs_manifest.generate_manifest(
cls.PLATFORM, str(REPO_ROOT / "platforms"), cls.db,
str(REPO_ROOT / "bios"), str(REPO_ROOT / "platforms" / "_registry.yml"),
emulators_dir=str(REPO_ROOT / "emulators"), emu_profiles=cls.profiles,
@@ -866,17 +867,15 @@ class InstallMatchesASystemPack(unittest.TestCase):
db_path = REPO_ROOT / "database.json"
if not db_path.exists():
raise unittest.SkipTest("database.json is not built")
import generate_pack as gp
from packs import manifest as packs_manifest
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
cls.gp = gp
cls.db = json.loads(db_path.read_text(encoding="utf-8"))
cls.profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"))
cls.base = load_platform_config(
cls.PLATFORM, str(REPO_ROOT / "platforms")
).get("base_destination", "")
cls.full = gp.generate_manifest(
cls.full = packs_manifest.generate_manifest(
cls.PLATFORM, str(REPO_ROOT / "platforms"), cls.db,
str(REPO_ROOT / "bios"), str(REPO_ROOT / "platforms" / "_registry.yml"),
emulators_dir=str(REPO_ROOT / "emulators"), emu_profiles=cls.profiles,
@@ -887,7 +886,7 @@ class InstallMatchesASystemPack(unittest.TestCase):
import zipfile
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as out:
zip_path = self.gp.generate_pack(
zip_path = platformpack.generate_pack(
self.PLATFORM, str(REPO_ROOT / "platforms"), self.db,
str(REPO_ROOT / "bios"), out,
emulators_dir=str(REPO_ROOT / "emulators"),
@@ -927,7 +926,7 @@ class DataTreesFollowTheSystemsTheyServe(InstallMatchesASystemPack):
# The trees come from the registry the manifest reads by itself.
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as out:
zip_path = self.gp.generate_pack(
zip_path = platformpack.generate_pack(
self.PLATFORM, str(REPO_ROOT / "platforms"), self.db,
str(REPO_ROOT / "bios"), out,
emulators_dir=str(REPO_ROOT / "emulators"),
@@ -998,17 +997,14 @@ class InstallMatchesATargetManifest(unittest.TestCase):
db_path = REPO_ROOT / "database.json"
if not db_path.exists():
raise unittest.SkipTest("database.json is not built")
import generate_pack as gp
from model.profiles import load_emulator_profiles
from model.targets import load_target_config
cls.gp = gp
cls.load_target_config = staticmethod(load_target_config)
cls.db = json.loads(db_path.read_text(encoding="utf-8"))
cls.profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"))
def _manifest(self, platform, target_cores=None, target=None):
return self.gp.generate_manifest(
return packs_manifest.generate_manifest(
platform, str(REPO_ROOT / "platforms"), self.db,
str(REPO_ROOT / "bios"), str(REPO_ROOT / "platforms" / "_registry.yml"),
emulators_dir=str(REPO_ROOT / "emulators"), emu_profiles=self.profiles,
@@ -1056,9 +1052,6 @@ class AHeldFileTheInstallerCannotFetch(unittest.TestCase):
from model.platforms import _platform_config_cache
from model.profiles import _emulator_profiles_cache
import generate_db
import generate_pack
self.gp = generate_pack
tmp = tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp")
self.addCleanup(tmp.cleanup)
previous = os.getcwd()
@@ -1106,7 +1099,7 @@ class AHeldFileTheInstallerCannotFetch(unittest.TestCase):
self.profiles = profiles.load_emulator_profiles("emulators")
def _manifest(self, regions):
return self.gp.generate_manifest(
return packs_manifest.generate_manifest(
"p", "platforms", self.db, "bios", "platforms/_registry.yml",
emulators_dir="emulators", emu_profiles=self.profiles,
regions=regions, offline=True,
@@ -1140,9 +1133,6 @@ class AStandaloneLayoutBelowTheBiosFolder(unittest.TestCase):
from model.platforms import _platform_config_cache
from model.profiles import _emulator_profiles_cache
import generate_db
import generate_pack
self.gp = generate_pack
tmp = tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp")
self.addCleanup(tmp.cleanup)
previous = os.getcwd()
@@ -1192,7 +1182,7 @@ class AStandaloneLayoutBelowTheBiosFolder(unittest.TestCase):
self.profiles = profiles.load_emulator_profiles("emulators")
def _manifest(self, regions):
return self.gp.generate_manifest(
return packs_manifest.generate_manifest(
"p", "platforms", self.db, "bios", "platforms/_registry.yml",
emulators_dir="emulators", emu_profiles=self.profiles,
regions=regions, offline=True,
@@ -1226,9 +1216,6 @@ class AnExtraBesideItsDeclarationBelowTheBiosFolder(unittest.TestCase):
from model.platforms import _platform_config_cache
from model.profiles import _emulator_profiles_cache
import generate_db
import generate_pack
self.gp = generate_pack
tmp = tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp")
self.addCleanup(tmp.cleanup)
previous = os.getcwd()
@@ -1284,15 +1271,15 @@ class AnExtraBesideItsDeclarationBelowTheBiosFolder(unittest.TestCase):
self.profiles = profiles.load_emulator_profiles("emulators")
def _manifest(self, regions):
return self.gp.generate_manifest(
return packs_manifest.generate_manifest(
"p", "platforms", self.db, "bios", "platforms/_registry.yml",
emulators_dir="emulators", emu_profiles=self.profiles,
regions=regions, offline=True,
)
def _pack(self, regions):
record = self.gp.PackRecord()
self.gp.generate_pack(
record = archive.PackRecord()
platformpack.generate_pack(
"p", "platforms", self.db, "bios", "", emulators_dir="emulators",
emu_profiles=self.profiles, regions=regions, offline=True, record=record,
)
@@ -1301,7 +1288,7 @@ class AnExtraBesideItsDeclarationBelowTheBiosFolder(unittest.TestCase):
def test_the_slot_choices_are_computed_once(self):
"""pack_overrides recomputed the choices the manifest had just
computed with the same arguments: 8% of a manifest run."""
import slots
from packs import slots
real = slots.slot_choices
with mock.patch.object(slots, "slot_choices", side_effect=real) as counted:
@@ -1383,7 +1370,7 @@ class ThePlatformsOwnSystemNamesAreAccepted(unittest.TestCase):
source)
def test_every_listed_system_gets_the_title_the_site_prints(self):
from generate_pack import system_titles
from packs.scope import system_titles
files = [{"dest": "a.bin", "systems": ["sony-playstation", "nintendo-gba"]}]
omitted = [{"dest": "b.bin", "systems": ["3do"]}]
@@ -1431,12 +1418,10 @@ class ANativeNameSelectsOneSetEverywhere(unittest.TestCase):
db_path = REPO_ROOT / "database.json"
if not db_path.exists():
raise unittest.SkipTest("database.json is not built")
import generate_pack as gp
import pipeline
import verify
from model.profiles import load_emulator_profiles
cls.gp, cls.pipeline, cls.verify = gp, pipeline, verify
cls.pipeline = pipeline
cls.db = json.loads(db_path.read_text(encoding="utf-8"))
cls.profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"))
@@ -1447,7 +1432,7 @@ class ANativeNameSelectsOneSetEverywhere(unittest.TestCase):
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as out, \
contextlib.redirect_stdout(io.StringIO()):
zip_path = self.gp.generate_pack(
zip_path = platformpack.generate_pack(
platform, str(REPO_ROOT / "platforms"), self.db,
str(REPO_ROOT / "bios"), out,
emulators_dir=str(REPO_ROOT / "emulators"),
@@ -1469,7 +1454,7 @@ class ANativeNameSelectsOneSetEverywhere(unittest.TestCase):
self.assertEqual(chosen, resolve_system_arg(system_id, systems, config))
self.assertEqual(chosen, [system_id])
report = self.verify.verify_platform(
report = coverage.verify_platform(
config, self.db, str(REPO_ROOT / "emulators"), self.profiles,
system_filter=chosen,
)
@@ -1485,7 +1470,7 @@ class ANativeNameSelectsOneSetEverywhere(unittest.TestCase):
self.assertTrue(written)
self.assertEqual(credited, written)
manifest = self.gp.generate_manifest(
manifest = packs_manifest.generate_manifest(
platform, str(REPO_ROOT / "platforms"), self.db,
str(REPO_ROOT / "bios"),
str(REPO_ROOT / "platforms" / "_registry.yml"),
+8 -9
View File
@@ -41,6 +41,8 @@ from pathlib import Path, PurePosixPath, PureWindowsPath
from unittest import mock
import install
from packs import archive as packs_archive
from packs import emulatorpack
from tests.test_install_app import make_card
from tests.test_install_selection import FakeRepository, _QuietHandler
from tests.netguard import module_guard
@@ -7617,11 +7619,11 @@ class _CardFixtures:
if sys.version_info < BUILDER_FLOOR:
# generate_pack.py's context managers need Python 3.9.
return listing, None, {}
import generate_pack
from packs import scope
pack_list = {"files": [{"path": dest, "sha1": entry["sha1"], "size": entry["size"]}
for dest, entry in zip(payloads, files)]}
generate_pack.annotate_pack_systems(pack_list, generate_pack.pack_systems(install_list))
scope.annotate_pack_systems(pack_list, scope.pack_systems(install_list))
name = {"minui": "MinUI", "misterfpga": "MiSTer_FPGA"}[plat]
pack = self.root / f"{name}_v1_BIOS_Pack.zip"
with zipfile.ZipFile(pack, "w") as archive:
@@ -9246,14 +9248,14 @@ class PacksWordingAndDocs(unittest.TestCase):
@unittest.skipIf(sys.version_info < BUILDER_FLOOR,
"generate_pack.py's context managers need Python 3.9")
def test_a_pack_records_the_systems_of_its_files(self):
import generate_pack
from packs import scope
install_list = {"files": [{"dest": "a.bin", "systems": ["3do"]},
{"dest": "b/c.bin", "systems": []}],
"system_titles": {"3do": "3DO Interactive Multiplayer"},
"system_names": {"3do": ["3do"]}}
manifest = {"files": [{"path": "a.bin"}, {"path": "b/c.bin"}, {"path": "README.md"}]}
generate_pack.annotate_pack_systems(manifest, generate_pack.pack_systems(install_list))
scope.annotate_pack_systems(manifest, scope.pack_systems(install_list))
self.assertEqual([entry.get("systems") for entry in manifest["files"]],
[["3do"], [], None])
self.assertEqual(manifest["system_titles"], {"3do": "3DO Interactive Multiplayer"})
@@ -16164,18 +16166,15 @@ class EmulatorChoiceMatchesTheEmulatorPack(unittest.TestCase):
if sys.version_info < BUILDER_FLOOR:
# The builder's floor: install.py alone keeps 3.8.
raise unittest.SkipTest("generate_pack.py needs Python 3.9 or newer")
import generate_pack as gp
from core.ziptools import build_zip_contents_index
cls.gp = gp
cls.db = json.loads(db_path.read_text(encoding="utf-8"))
cls.zip_contents = build_zip_contents_index(cls.db)
cls.by_path = {entry["path"]: sha1 for sha1, entry in cls.db["files"].items()}
def pack(self, emulator: str) -> dict[str, str]:
record = self.gp.PackRecord()
record = packs_archive.PackRecord()
with contextlib.redirect_stdout(io.StringIO()):
self.gp.generate_emulator_pack(
emulatorpack.generate_emulator_pack(
[emulator], str(REPO_ROOT / "emulators"), self.db, str(REPO_ROOT / "bios"),
str(REPO_ROOT / "tmp"), zip_contents=self.zip_contents, offline=True,
record=record)
+4 -4
View File
@@ -553,21 +553,21 @@ class ReleaseAssetNames(unittest.TestCase):
self.assertEqual(name, os.path.basename(registered_path))
def test_manifest_checker_and_fetcher_agree_on_a_path(self):
import generate_pack
from packs import manifestentry
expected = largefiles.asset_names(self.REGISTERED)
gitignore = "\n".join(["tmp/", *self.REGISTERED]) + "\n"
with tempfile.TemporaryDirectory() as root:
Path(root, ".gitignore").write_text(gitignore, encoding="utf-8")
generate_pack._registered.cache_clear()
manifestentry._registered.cache_clear()
try:
manifest = {
p: generate_pack._release_asset_name(os.path.join(root, p), root)
p: manifestentry._release_asset_name(os.path.join(root, p), root)
for p in self.REGISTERED
}
finally:
generate_pack._registered.cache_clear()
manifestentry._registered.cache_clear()
self.assertEqual(manifest, expected)
sizes = {self.ET: 228138631, self.RTCW: 122757192, self.PUP: 10}
+8 -11
View File
@@ -28,15 +28,12 @@ from unittest import mock
import yaml
import verify
from packs import coverage
from packs import report as packs_report
from model.profiles import _emulator_profiles_cache, load_emulator_profiles
from model.platforms import load_platform_config
from cross_reference import (
LAUNCHER_READS_KEY,
LAUNCHER_UNPROVEN_KEY,
launcher_file_names,
launcher_reads_not_held,
print_launcher_reads,
)
from cross_reference import LAUNCHER_READS_KEY, LAUNCHER_UNPROVEN_KEY, print_launcher_reads
from packs.crossref import launcher_file_names, launcher_reads_not_held
ROOT = Path(__file__).resolve().parent.parent
@@ -287,11 +284,11 @@ class LauncherGapTest(unittest.TestCase):
def test_verify_counts_and_exit_code_are_unchanged(self) -> None:
"""A launcher name is reported, not judged: nothing else moves."""
with_rows = verify.verify_platform(
with_rows = coverage.verify_platform(
self.config, self.db, self.emulators_dir, self.profiles, data_dir_registry={}
)
with mock.patch.object(verify, "launcher_reads_not_held", return_value=[]):
without = verify.verify_platform(
without = coverage.verify_platform(
self.config, self.db, self.emulators_dir, self.profiles,
data_dir_registry={},
)
@@ -313,13 +310,13 @@ class LauncherGapTest(unittest.TestCase):
exit_code(without))
def test_verify_prints_a_count_and_lists_on_verbose(self) -> None:
result = verify.verify_platform(
result = coverage.verify_platform(
self.config, self.db, self.emulators_dir, self.profiles, data_dir_registry={}
)
for verbose, expected in ((False, "(--verbose lists them)"), (True, "absent.bin")):
out = io.StringIO()
with contextlib.redirect_stdout(out):
verify.print_platform_result(result, ["GapTest"], verbose=verbose)
packs_report.print_platform_result(result, ["GapTest"], verbose=verbose)
self.assertIn("Launcher reads, not held: 3", out.getvalue())
self.assertIn(expected, out.getvalue())
+2 -2
View File
@@ -428,7 +428,7 @@ class LauncherLayerTest(unittest.TestCase):
"""cross_reference --platform batocera listed duckstation's
scph1002a.bin as packed while the PAL slot was filled by the
launcher's scph5502.bin, which verify and the builder both knew."""
from cross_reference import cross_reference, declared_names, load_platform_files
from packs.crossref import cross_reference, declared_names, load_platform_files
from resolve.launchers import declared_destinations
selected = ["launchertest"]
@@ -453,7 +453,7 @@ class LauncherLayerTest(unittest.TestCase):
def test_one_decision_for_verify_and_pack(self) -> None:
"""The layer is applied once, in the report both sides read."""
import generate_pack
import packextras
from packs import extras as packextras
import verify
self.assertIn("LauncherLayer(", inspect.getsource(verify.find_undeclared_files))
+3 -2
View File
@@ -26,8 +26,9 @@ import yaml
from model.profiles import _emulator_profiles_cache, load_emulator_profiles
from model.platforms import load_platform_config
from resolve.standalone import platform_layouts, standalone_set
from generate_pack import generate_manifest, generate_pack
from verify import verify_platform
from packs.manifest import generate_manifest
from packs.platformpack import generate_pack
from packs.coverage import verify_platform
REPO_ROOT = Path(__file__).resolve().parents[1]
+12 -12
View File
@@ -19,35 +19,35 @@ from pathlib import Path
SCRIPTS = Path(__file__).resolve().parent.parent / "scripts"
PACKAGE_LAYERS = {"core": 0, "model": 1, "resolve": 2, "scraper": 3, "exporter": 3, "profiling": 3}
PACKAGE_LAYERS = {"core": 0, "model": 1, "resolve": 2, "packs": 3, "scraper": 3, "exporter": 3, "profiling": 3}
LIBRARY_LAYER = 3
COMMAND_LAYER = 4
# The other domain packages a domain package may import. A package listed
# here imports no sibling outside its set.
SIBLING_IMPORTS: dict[str, frozenset[str]] = {
"packs": frozenset(),
"profiling": frozenset(),
}
# Top-level modules other modules of scripts/ import: library code that a
# later wave moves into a package.
NOT_YET_PACKAGED = frozenset({
"archive_build", "autorun", "build_port", "campaign", "campaign_profiles",
"campaign_rules", "check_buildbot_system", "check_release_assets", "commit_rules", "core_probe",
"cross_reference", "dedup", "derivations", "generate_event_schema",
"generate_pack", "generate_readme", "generate_site", "manifestselect", "measurement_records",
"packextras", "packpaths", "packreadme", "packresolve", "packverify", "pin_installer",
"pr_checks", "provenance_report", "refresh_data_dirs",
"release_record", "romfolders", "romset_recipes", "siteagents", "sitebootstrap",
"sitecollection", "sitediagrams", "siteentries", "siteexports", "siteguides", "sitehandheld",
"siteinputs", "sitemarkup", "sitemeasurements", "siterender", "sitesources", "sitestarlight",
"sitesteps", "sitewanted", "sitewrite", "slots", "split_pack", "validate_pr", "verify",
"archive_build", "autorun", "build_port", "campaign", "campaign_profiles", "campaign_rules",
"check_buildbot_system", "check_release_assets", "commit_rules", "core_probe", "derivations",
"generate_event_schema", "generate_readme", "generate_site", "measurement_records",
"pin_installer", "pr_checks", "provenance_report", "release_record", "romfolders",
"romset_recipes", "siteagents", "sitebootstrap", "sitecollection", "sitediagrams",
"siteentries", "siteexports", "siteguides", "sitehandheld", "siteinputs", "sitemarkup",
"sitemeasurements", "siterender", "sitesources", "sitestarlight", "sitesteps", "sitewanted",
"sitewrite",
})
# Imports from a package module to a top-level module, left for the wave that
# packages the top-level side.
PENDING_TOP_LEVEL_IMPORTS = frozenset({
("exporter.doubled", "slots"),
("packs.readme", "siteguides"),
("packs.scope", "siterender"),
})
Loaded 100 of 167 files, more files were not shown because too many files have changed in this diff. Show more