refactor: read hashes and the registry one way

Hash fields go through core.hashing.parse_hash_list, which also splits comma-joined list items: the truth model compared a comma-joined sha256 list as one value. _registry.yml goes through load_platform_registry (required= where an absent file must stop the run), database.json through load_database, file and member digests through file_digest and stream_hashes. download.py and check_release read SHA256SUMS.txt with one parser: a sha256sum -b line matched nothing in download.py and the pack went unchecked.
This commit is contained in:
Abdessamad Derraz committed 2026-11-20 18:28:40 +01:00
1 parent 7cd499531d
commit 348d5b51c3
32 files changed
+130 -217

No files matched your search

+2 -2
View File
@@ -32,10 +32,10 @@ Usage:
from __future__ import annotations
import argparse
import hashlib
import sys
from pathlib import Path
from core.hashing import file_digest
from core.artifacts import ArtifactLockBusy, artifact_lock
from core.paths import REPO_ROOT
from installer_build.port import ARCHIVES, build_archive
@@ -55,7 +55,7 @@ def main() -> int:
print(f"Error: {exc}", file=sys.stderr)
return 1
for path in paths:
digest = hashlib.sha256(path.read_bytes()).hexdigest()
digest = file_digest(path, "sha256")
print(f"{path} ({path.stat().st_size} bytes, sha256 {digest})")
return 0
+4 -13
View File
@@ -62,7 +62,7 @@ from exporter.originals import (
from installer_build import pins as installer_build_pins
from packs import datadirs
from core import upstream
from core.cli import InputMissing, require_directory, suggest_names
from core.cli import InputMissing, add_repo_inputs, require_directory, suggest_names
from model.targets import apply_target_overrides
from model.registry import list_registered_platforms, load_platform_registry
from model.profiles import load_emulator_profiles, upstream_profile_index
@@ -315,8 +315,7 @@ def _scrapable_platforms(platforms_dir: Path) -> list[tuple[str, str, Path]]:
A platform that only inherits another and declares no source of its own
(Lakka) has nothing to scrape: its scraper writes the parent's file.
"""
with (platforms_dir / "_registry.yml").open(encoding="utf-8") as fh:
registry = (yaml_load(fh) or {}).get("platforms") or {}
registry = load_platform_registry(platforms_dir, required=True)
rows = []
for name in list_registered_platforms(str(platforms_dir)):
path = platforms_dir / f"{name}.yml"
@@ -337,8 +336,7 @@ def rescrape_args(platforms_dir: Path, name: str) -> tuple[str, ...]:
A scraper that rereads the revision its platform file pins by default
(RetroBat) names the ref to move to in the registry's rescrape_args.
"""
with (platforms_dir / "_registry.yml").open(encoding="utf-8") as fh:
registry = (yaml_load(fh) or {}).get("platforms") or {}
registry = load_platform_registry(platforms_dir, required=True)
return tuple(str(a) for a in (registry.get(name) or {}).get("rescrape_args") or ())
@@ -1867,14 +1865,7 @@ def main() -> int:
help="directory of the truth models generate_truth writes (default: "
"%(default)s)",
)
parser.add_argument(
"--platforms-dir", default="platforms",
help="platform YAML directory (default: %(default)s)",
)
parser.add_argument(
"--emulators-dir", default="emulators",
help="emulator profile directory (default: %(default)s)",
)
add_repo_inputs(parser, "platforms", "emulators")
parser.add_argument(
"--record-coreinfo", nargs="*", metavar="CORE",
help="record the current .info of CORE (every core when none is named) "
+2 -2
View File
@@ -37,8 +37,8 @@ from release.check import (
compare_release,
fetch_assets,
fetch_sums,
parse_sums,
)
from core.hashing import parse_sha256sums
def main() -> int:
@@ -88,7 +88,7 @@ def main() -> int:
print(f"ERROR: {exc}", file=sys.stderr)
return 2
try:
sums = parse_sums(sums_text)
sums = parse_sha256sums(sums_text)
except ValueError as exc:
print(f"ERROR: {SUMS}: {exc}", file=sys.stderr)
return 2
+18 -2
View File
@@ -168,10 +168,11 @@ def parse_hash_list(raw: str | list | int | None) -> list[str]:
"""
if raw is None or raw == "":
return []
items = raw if isinstance(raw, list) else str(raw).split(",")
# A list item can itself be comma-joined (a list of Recalbox md5 fields).
items = [part for item in (raw if isinstance(raw, list) else [raw]) for part in str(item).split(",")]
out: list[str] = []
for item in items:
value = str(item).strip().lower().removeprefix("0x")
value = item.strip().lower().removeprefix("0x")
if value and value not in out:
out.append(value)
return out
@@ -184,3 +185,18 @@ def parse_md5_list(raw: str | list | None) -> list[str]:
emulator profiles carry a YAML list. Both reach here.
"""
return parse_hash_list(raw)
def parse_sha256sums(text: str) -> dict[str, str]:
"""`sha256sum` output by file name: digest, a space, then the mode
character (space for text, `*` for binary) before the name."""
sums: dict[str, str] = {}
for line in text.splitlines():
line = line.strip()
if not line:
continue
digest, _, name = line.partition(" ")
if len(digest) != 64 or not name:
raise ValueError(f"not a sha256sum line: {line!r}")
sums[name.lstrip(" *")] = digest.lower()
return sums
+8 -7
View File
@@ -31,7 +31,7 @@ from dataclasses import dataclass
from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
from core.hashing import compute_hashes
from core.hashing import compute_hashes, parse_sha256sums
from core.ziptools import safe_extract_zip
DEFAULT_API = "https://api.github.com"
@@ -185,12 +185,13 @@ def fetch_checksums(release: dict) -> dict[str, str]:
)
with urllib.request.urlopen(req, timeout=60) as resp:
body = resp.read(MAX_CHECKSUMS_BYTES).decode("utf-8", "replace")
sums = {}
for line in body.splitlines():
digest, _, name = line.strip().partition(" ")
if digest and name:
sums[name] = digest.lower()
return sums
# A file that is not sha256sum output refuses the download: read
# leniently, a `*name` line matched nothing and the pack went
# unchecked.
try:
return parse_sha256sums(body)
except ValueError as exc:
raise SystemExit(f"ERROR: {CHECKSUMS_ASSET}: {exc}") from exc
return {}
+2 -6
View File
@@ -20,7 +20,7 @@ from .originals import collect_originals, unpinned, wanted_sources
from model.database import load_database
from model.platforms import load_platform_config, native_layer
from model.profiles import load_emulator_profiles
from model.registry import load_data_dir_registry
from model.registry import load_data_dir_registry, load_platform_registry
from model.safeparse import yaml_load
from resolve.categories import removal_candidates
from resolve.reconcile import Report, build_native_model
@@ -56,11 +56,7 @@ class StaleTruth(ValueError):
@functools.cache
def _truth_sources(platforms_dir: str) -> tuple[dict, dict, dict | None]:
"""Registry, profiles and database, as generate_truth reads them."""
registry_path = Path(platforms_dir) / "_registry.yml"
registry: dict = {}
if registry_path.exists():
with open(registry_path) as handle:
registry = (yaml_load(handle) or {}).get("platforms", {})
registry = load_platform_registry(platforms_dir)
profiles = load_emulator_profiles("emulators")
db = load_database(TRUTH_DB) if Path(TRUTH_DB).exists() else None
return registry, profiles, db
+3 -4
View File
@@ -34,8 +34,8 @@ import urllib.parse
import urllib.request
from pathlib import Path
import yaml
from core.paths import REPO_ROOT
from model.registry import load_platform_registry
from core.paths import PLATFORMS_DIR, REPO_ROOT
sys.path.insert(0, str(REPO_ROOT / "scripts"))
@@ -151,8 +151,7 @@ def write_manifest(directory: Path, note: str, entries: list[dict]) -> None:
def fetch_logos() -> None:
from model.guides import GROUP_TILES, GUIDES
with open(REPO_ROOT / "platforms" / "_registry.yml", encoding="utf-8") as handle:
platforms = yaml.safe_load(handle)["platforms"]
platforms = load_platform_registry(REPO_ROOT / PLATFORMS_DIR, required=True)
LOGO_DIR.mkdir(parents=True, exist_ok=True)
entries = []
# The tiles of a kind of device (Android handhelds) beside the setups
+2 -2
View File
@@ -2,10 +2,10 @@
from __future__ import annotations
import hashlib
import re
from pathlib import Path
from core.hashing import file_digest
from core.paths import REPO_ROOT
@@ -24,7 +24,7 @@ COMMAND = "python scripts/pin_installer.py"
def installer_sha256(root: Path = REPO_ROOT) -> str:
return hashlib.sha256((root / INSTALLER).read_bytes()).hexdigest()
return file_digest(root / INSTALLER, "sha256")
def stale_pins(root: Path = REPO_ROOT) -> list[str]:
+2 -2
View File
@@ -7,6 +7,7 @@ import textwrap
from dataclasses import dataclass, fields
from pathlib import Path
from model.registry import load_platform_registry
from core.paths import REPO_ROOT
from model.safeparse import require_yaml
@@ -344,8 +345,7 @@ def load_guides(path: Path = GUIDES_FILE, registry: dict | None = None) -> dict:
"""
yaml = require_yaml()
if registry is None:
with open(PLATFORMS_DIR / "_registry.yml", encoding="utf-8") as handle:
registry = (yaml.safe_load(handle) or {}).get("platforms", {})
registry = load_platform_registry(PLATFORMS_DIR, required=True)
with open(path, encoding="utf-8") as handle:
data = yaml.safe_load(handle) or {}
if not isinstance(data, dict):
+2 -3
View File
@@ -21,7 +21,7 @@ from collections.abc import Iterable
from pathlib import Path
from core.artifacts import set_plain_mode
from core.hashing import compute_hashes
from core.hashing import compute_hashes, parse_hash_list
from core.paths import REPO_ROOT
@@ -436,6 +436,5 @@ def _matches(hashes: dict, expected_sha1: str, expected_md5: str) -> bool:
if expected_sha1 and hashes["sha1"].lower() != expected_sha1.lower():
return False
if expected_md5:
md5_list = [m.strip().lower() for m in expected_md5.split(",") if m.strip()]
return hashes["md5"].lower() in md5_list
return hashes["md5"].lower() in parse_hash_list(expected_md5)
return True
+14 -7
View File
@@ -6,11 +6,12 @@ import json
import os
from pathlib import Path
from core.paths import PLATFORMS_DIR
from core.cli import InputMissing
from model.sources import source_yaml
def load_data_dir_registry(platforms_dir: str = "platforms") -> dict:
def load_data_dir_registry(platforms_dir: str = PLATFORMS_DIR) -> dict:
"""Load the data directory registry from _data_dirs.yml."""
registry_path = os.path.join(platforms_dir, "_data_dirs.yml")
if not os.path.exists(registry_path):
@@ -20,16 +21,22 @@ def load_data_dir_registry(platforms_dir: str = "platforms") -> dict:
return data.get("data_directories", {})
def load_platform_registry(platforms_dir: str = "platforms") -> dict:
"""Return the `platforms:` mapping from _registry.yml, empty if absent."""
def load_platform_registry(platforms_dir: str | Path = PLATFORMS_DIR, required: bool = False) -> dict:
"""Return the `platforms:` mapping from _registry.yml.
An absent file is an empty registry, or with ``required`` an input the
command cannot run without.
"""
registry_path = os.path.join(platforms_dir, "_registry.yml")
if not os.path.exists(registry_path):
if required:
raise InputMissing(f"{registry_path} not found")
return {}
with open(registry_path) as f:
return (source_yaml(f) or {}).get("platforms", {})
with open(registry_path, encoding="utf-8") as f:
return (source_yaml(f) or {}).get("platforms") or {}
def list_registered_platforms(platforms_dir: str = "platforms") -> list[str]:
def list_registered_platforms(platforms_dir: str = PLATFORMS_DIR) -> list[str]:
"""List platforms registered in _registry.yml.
Only registered platforms generate packs and appear in CI.
@@ -55,7 +62,7 @@ def list_registered_platforms(platforms_dir: str = "platforms") -> list[str]:
return platforms
def list_release_pack_platforms(platforms_dir: str = "platforms") -> list[str]:
def list_release_pack_platforms(platforms_dir: str = PLATFORMS_DIR) -> list[str]:
"""Registered platforms a release publishes a ZIP pack for.
`release_pack: true` in _registry.yml is the whole list: the build of
+3 -5
View File
@@ -97,14 +97,12 @@ def ensure_console_sections() -> None:
them, so a page rendered on its own names systems as the site does."""
if _sections_installed[0]:
return
import json
from model.profiles import load_emulator_profiles
from model.collection import group_by_manufacturer
from model.database import load_database
from model.profiles import load_emulator_profiles
inputs = siteinputs.current()
with open(inputs.db, encoding="utf-8") as handle:
db = json.load(handle)
db = load_database(str(inputs.db))
profiles = load_emulator_profiles(str(inputs.emulators), skip_aliases=False)
set_console_sections(group_by_manufacturer(db), program_names(profiles))
+8 -17
View File
@@ -2,19 +2,18 @@
from __future__ import annotations
import io
import dataclasses
import hashlib
import json
import sys
import zipfile
import zlib
from collections import Counter
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, TypedDict
from core.hashing import parse_hash_list, parse_md5_list
from core.paths import REPO_ROOT
from core.hashing import parse_hash_list, parse_md5_list, stream_hashes
from core.paths import BIOS_DIR, PLATFORMS_DIR, REPO_ROOT
from model.alternatives import set_keys, set_requirements, settle_sets
from model.database import get_mame_clone_map
from model.declarations import OUTER_ROOTS
@@ -56,9 +55,6 @@ if TYPE_CHECKING:
from typing_extensions import Unpack
DEFAULT_PLATFORMS_DIR = "platforms"
def load_platform_files(
platforms_dir: str,
platforms: list[str] | None = None,
@@ -131,7 +127,7 @@ def folded_declared_slots(
def build_supplemental_index(
data_root: str = "data", bios_root: str = "bios"
data_root: str = "data", bios_root: str = BIOS_DIR
) -> set[str]:
"""Build a set of filenames and directory names in data/ and inside bios/ ZIPs.
@@ -326,7 +322,7 @@ _locations_cache: dict[tuple[str, str], dict[str, list[tuple[str, str]]]] = {}
def _supplemental_locations(
data_root: str = "data", bios_root: str = "bios"
data_root: str = "data", bios_root: str = BIOS_DIR
) -> dict[str, list[tuple[str, str]]]:
"""Where each name of the supplemental index sits: a data/ file, or a
member of a ZIP under bios/, keyed by lowercased basename."""
@@ -368,12 +364,7 @@ def _content_matches(location: tuple[str, str], declared: dict[str, set[str]]) -
except (zipfile.BadZipFile, KeyError, OSError) as exc:
print(f" WARNING: cannot read {path} {member}: {exc}", file=sys.stderr)
return False
actual = {
"sha1": hashlib.sha1(data).hexdigest(),
"md5": hashlib.md5(data).hexdigest(),
"sha256": hashlib.sha256(data).hexdigest(),
"crc32": f"{zlib.crc32(data) & 0xFFFFFFFF:08x}",
}
actual = stream_hashes(io.BytesIO(data), frozenset({"sha1", "md5", "sha256", "crc32"}))
return any(actual[field] in values for field, values in declared.items())
@@ -395,7 +386,7 @@ def _trees(data_root: str, bios_root: str) -> list[str]:
def held_copy(
entry: dict, data_root: str = "data", bios_root: str = "bios"
entry: dict, data_root: str = "data", bios_root: str = BIOS_DIR
) -> tuple[str, str] | None:
"""The data/ file, directory or bios/ ZIP member holding an entry.
@@ -444,7 +435,7 @@ class FileConsumers:
self._data_dir_registry = (
data_dir_registry if data_dir_registry is not None
else load_data_dir_registry(
str(REPO_ROOT / DEFAULT_PLATFORMS_DIR)
str(REPO_ROOT / PLATFORMS_DIR)
)
)
self._sha1_by_path = {
+8 -15
View File
@@ -10,7 +10,6 @@ from collections import Counter
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, TypedDict
from packs.verdicts import DEFAULT_BIOS_DIR
from core.artifacts import build_timestamp
from packs.paths import MEDIA_MARKER, has_path_conflict
from core.ziptools import build_zip_contents_index
@@ -36,7 +35,7 @@ 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
from core.paths import declared_destination
from core.paths import BIOS_DIR, EMULATORS_DIR, declared_destination
import zipfile
from collections.abc import Callable
from pathlib import Path
@@ -153,14 +152,8 @@ def _is_pack_note(name: str) -> bool:
def _member_digests(zf: zipfile.ZipFile, info: zipfile.ZipInfo) -> tuple[str, str, int]:
"""(sha1, md5, size) of a pack member."""
with zf.open(info) as f:
sha1_h = hashlib.sha1()
md5_h = hashlib.md5()
size = 0
for chunk in iter(lambda: f.read(65536), b""):
sha1_h.update(chunk)
md5_h.update(chunk)
size += len(chunk)
return sha1_h.hexdigest(), md5_h.hexdigest(), size
digests = stream_hashes(f, frozenset({"sha1", "md5"}))
return digests["sha1"], digests["md5"], info.file_size
def _rebuilt_from(zf: zipfile.ZipFile, name: str, by_name: dict, files_db: dict) -> str | None:
@@ -479,7 +472,7 @@ def _held_nowhere(
resolve_file(
entry,
db,
DEFAULT_BIOS_DIR,
BIOS_DIR,
zip_contents,
data_dir_registry=data_dir_registry,
offline=True,
@@ -491,7 +484,7 @@ def _held_nowhere(
def _intentional_hash_exclusion(
entries: list[dict],
db: dict,
bios_dir: str = DEFAULT_BIOS_DIR,
bios_dir: str = BIOS_DIR,
zip_contents: dict | None = None,
data_dir_registry: dict | None = None,
verification_mode: str = "md5",
@@ -571,7 +564,7 @@ def _shipped_copy(
The verdict verify applies before it lets a declaration hold its path.
"""
local, status = resolve_declaration(
entry, db, DEFAULT_BIOS_DIR, None, data_registry, None, offline=True,
entry, db, BIOS_DIR, None, data_registry, None, offline=True,
)
if local and baseline_verdict(entry, local, status, mode, hash_rule)[1] is None:
return local
@@ -631,7 +624,7 @@ def _builder_extras(
config, expect.opts.emulators_dir, db, emu_profiles, shipped, expect.target_cores,
expect.region_drops or None,
resolver=ExtraResolver(
db, DEFAULT_BIOS_DIR, build_zip_contents_index(db), data_registry,
db, BIOS_DIR, build_zip_contents_index(db), data_registry,
build_validation_index(platform_profiles),
destination_owners(platform_profiles), True, profiles=emu_profiles,
),
@@ -667,7 +660,7 @@ class PlatformCheckOptions(TypedDict, total=False):
class _PlatformCheckSettings:
"""PlatformCheckOptions with their defaults."""
emulators_dir: str = "emulators"
emulators_dir: str = EMULATORS_DIR
emu_profiles: dict | None = None
regions: list[str] | None = None
data_registry: dict | None = None
+2 -3
View File
@@ -8,6 +8,7 @@ import sys
from dataclasses import dataclass
from typing import TYPE_CHECKING, TypedDict
from core.hashing import parse_hash_list
from core.options import reject_unknown
from model.platforms import load_platform_config
from model.profiles import ProfileSelectionError, load_emulator_profiles, select_emulator_profiles
@@ -28,9 +29,7 @@ def _entry_for_file(candidates: list[dict], held: dict) -> dict:
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()}
return set(parse_hash_list(fe.get(key)))
for fe in candidates:
if any(
+3 -9
View File
@@ -61,6 +61,7 @@ from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
from model.registry import load_platform_registry
from core.paths import REPO_ROOT
LOG_DIR = REPO_ROOT / "tmp" / "refresh_stale"
@@ -99,15 +100,8 @@ class JobResult:
def _load_platform_registry() -> dict[str, dict]:
"""Return the platforms map from _registry.yml.
pyyaml is already a project dependency, and the registry is small so we read
it once at startup rather than parsing each dispatch.
"""
import yaml
with PLATFORMS_REGISTRY.open(encoding="utf-8") as fh:
return (yaml.safe_load(fh) or {}).get("platforms") or {}
"""Return the platforms map from _registry.yml, read once at startup."""
return load_platform_registry(PLATFORMS_REGISTRY.parent, required=True)
def _platform_parents(registry: dict[str, dict]) -> dict[str, str]:
-14
View File
@@ -25,20 +25,6 @@ class Finding:
detail: str
def parse_sums(text: str) -> dict[str, str]:
"""`sha256sum` output: digest, then a space and a mode character."""
sums: dict[str, str] = {}
for line in text.splitlines():
line = line.strip()
if not line:
continue
digest, _, name = line.partition(" ")
if len(digest) != 64 or not name:
raise ValueError(f"not a sha256sum line: {line!r}")
sums[name.lstrip(" *")] = digest.lower()
return sums
def _registry_findings(packs: dict, released: set[str]) -> list[Finding]:
"""Each platform marked release_pack has a pack, and each pack serves one."""
served = {p for pack in packs.values() for p in pack.get("platforms", ())}
+2 -4
View File
@@ -8,6 +8,7 @@ import sys
import tempfile
from pathlib import Path
from model.largefiles import registered_paths
from core.artifacts import copy_file_atomic, set_plain_mode
from core.hashing import file_digest
from model.database import load_database
@@ -19,10 +20,7 @@ def gitignored_paths(gitignore: str) -> set[str]:
A missing file raises: read as empty, it left nothing to restore and
nothing unsatisfied, and the run exited 0 with every asset absent.
"""
with open(gitignore) as f:
return {
line.strip() for line in f if line.strip().startswith("bios/")
}
return set(registered_paths(Path(gitignore).read_text(encoding="utf-8")))
def index_cache(cache_dir: str) -> dict[str, str]:
+2 -12
View File
@@ -6,7 +6,7 @@ import os
import zlib
from dataclasses import dataclass, field
from core.hashing import compute_hashes, parse_md5_list
from core.hashing import compute_hashes, parse_hash_list, parse_md5_list
from core.ziptools import check_inside_zip
from resolve.localfile import resolve_local_file, variant_base_name
from resolve.packfiles import records_by_path, preferred_entries
@@ -123,17 +123,7 @@ def lists_hashes(entry: dict) -> bool:
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()
}
return set(parse_hash_list(entry.get(field_name)))
def _record_at(path: str, db: dict) -> dict | None:
+2 -2
View File
@@ -20,6 +20,7 @@ import re
from collections.abc import Callable, Iterable, Mapping
from dataclasses import dataclass
from core.hashing import parse_hash_list
from model.declarations import CONFIGS_ROOT, ROMS_ROOT, declared_root, outer_layout
from resolve.content import name_match_size_ok
from resolve.localfile import resolve_local_file
@@ -1267,8 +1268,7 @@ def _hashes(entry: dict) -> dict[str, set[str]]:
value = entry.get(field) or (entry.get("expected") or {}).get(field)
if not value:
continue
values = value if isinstance(value, list) else str(value).split(",")
found[field] = {str(v).strip().lower() for v in values if str(v).strip()}
found[field] = set(parse_hash_list(value))
return found
+2 -13
View File
@@ -15,7 +15,7 @@ import zipfile
from pathlib import Path
from model.largefiles import fetch_large_file
from core.hashing import cut_md5_owner
from core.hashing import cut_md5_owner, parse_hash_list
from resolve.content import declared_hash_verdict
from resolve.localfile import resolution_is_hash_exact, resolve_local_file
from core.paths import REPO_ROOT, declared_destination
@@ -84,20 +84,9 @@ def download_external(
return False
return True
def _values(raw: object) -> list[str]:
"""A hash field's values: one, a list, or a comma-separated string."""
items = raw if isinstance(raw, list) else [raw] if raw else []
return [
value.strip().lower().removeprefix("0x")
for item in items
for value in str(item).split(",")
if value.strip()
]
def _declared_hashes(file_entry: dict) -> dict[str, list[str]]:
return {
field: _values(file_entry.get(field))
field: parse_hash_list(file_entry.get(field))
for field in ("sha1", "md5", "sha256", "crc32")
}
+2 -6
View File
@@ -17,6 +17,7 @@ from collections.abc import Callable
from dataclasses import dataclass, field
from core.hashing import parse_hash_list
from model.systems import norm_system_id
from core.paths import REPO_ROOT
@@ -25,12 +26,7 @@ HASH_FIELDS = ("sha1", "md5", "sha256", "crc32")
def hash_values(entry: dict, field_name: str) -> list[str]:
"""Return a hash field as a list, whatever shape it was written in."""
raw = entry.get(field_name)
if not raw:
return []
if isinstance(raw, list):
return [str(v).strip().lower() for v in raw if str(v).strip()]
return [v.strip().lower() for v in str(raw).split(",") if v.strip()]
return parse_hash_list(entry.get(field_name))
def checked_hashes(entry: dict | None) -> dict | None:
+8 -10
View File
@@ -17,7 +17,7 @@ from model.registry import load_data_dir_registry
from resolve.standalone import platform_layouts, standalone_set as platform_standalone_set
from resolve.cores import resolve_platform_cores
from model.alternatives import groups_of
from core.hashing import compute_hashes
from core.hashing import compute_hashes, parse_hash_list
from resolve.validation import (
filter_files_by_mode,
installed_with_emulator,
@@ -249,10 +249,8 @@ def _shares_hash(a: dict, b: dict) -> bool:
def _declared(entry: dict, field: str) -> set[str]:
"""The values an entry declares for a hash field, one or a list."""
value = entry.get(field)
values = value if isinstance(value, list) else [value]
return {str(v).lower() for v in values if v}
"""The values an entry declares for a hash field, one, a list or comma-joined."""
return set(parse_hash_list(entry.get(field)))
def _contents_disagree(a: dict, b: dict) -> bool:
@@ -350,15 +348,15 @@ def _merge_hashes(
existing[h] = theirs
existing.setdefault("_hash_by", {})[h] = emu_name
continue
t_list = theirs if isinstance(theirs, list) else [theirs]
o_list = ours if isinstance(ours, list) else [ours]
# A field holds one value, a list or a comma-joined string (mesence
# names twelve BS-X dumps in one sha256): compared value by value.
t_list, o_list = parse_hash_list(theirs), parse_hash_list(ours)
if revision:
known = {str(v).lower() for v in o_list}
added = [v for v in t_list if str(v).lower() not in known]
added = [v for v in t_list if v not in o_list]
if added:
existing[h] = [*o_list, *added]
continue
if not {str(v).lower() for v in t_list} & {str(v).lower() for v in o_list}:
if not set(t_list) & set(o_list):
# The value kept is one revision among those the cores accept:
# it pairs an entry, it never overrules one (checked_hashes).
existing["hash_conflict"] = sorted({*existing.get("hash_conflict", ()), h})
+8 -24
View File
@@ -22,9 +22,9 @@ from resolve.content import (
)
from resolve.archives import archive_members
from model.profiles import CONTENT_CHECKS, entry_system_ids
from core.hashing import compute_hashes
from core.paths import sanitize_pack_path
from core.hashing import md5_composite, parse_hash_list, parse_md5_list
from core.hashing import compute_hashes, parse_hash_list
from core.paths import BIOS_DIR, sanitize_pack_path
from core.hashing import md5_composite, parse_md5_list
from resolve.nativemode import SIZE_AND_ANY_HASH, digest_algorithm, hash_mismatch_excludes_file
from core.ziptools import check_inside_zip
@@ -281,35 +281,19 @@ def _merge_sizes(item: dict, f: dict) -> None:
)
def _hex_values(value: object) -> list[str]:
"""Hash values without their 0x prefix, lowercased."""
values = value if isinstance(value, list) else [value] if value else []
out = []
for item in values:
norm = str(item).lower()
if norm.startswith("0x"):
norm = norm[2:]
out.append(norm)
return out
def _merge_hashes(item: dict, f: dict, checks: list[str]) -> None:
# Hash checks: collect all accepted hashes as sets (multiple valid
# versions of the same file, e.g. MT-32 ROM versions)
if "crc32" in checks and f.get("crc32"):
item["crc32"].update(_hex_values(f["crc32"]))
item["crc32"].update(parse_hash_list(f["crc32"]))
# A hash field may carry several accepted values, as a list or as
# the comma-separated string the schema spells out
for hash_type in ("md5", "sha1", "sha256"):
if hash_type in checks and f.get(hash_type):
val = f[hash_type]
values = val if isinstance(val, list) else str(val).split(",")
item[hash_type].update(
str(h).strip().lower() for h in values if str(h).strip()
)
item[hash_type].update(parse_hash_list(f[hash_type]))
# Adler32: stored as known_hash_adler32 field (not in validation: list
# for Dolphin, but support it in both forms for future profiles)
item["adler32"].update(_hex_values(f.get("known_hash_adler32") or f.get("adler32")))
item["adler32"].update(parse_hash_list(f.get("known_hash_adler32") or f.get("adler32")))
if f.get("adler32_byteswap"):
item["adler32_byteswap"] = True
@@ -487,7 +471,7 @@ def check_file_validation(
local_path: str,
filename: str,
validation_index: dict[str, dict],
bios_dir: str = "bios",
bios_dir: str = BIOS_DIR,
emulators: set[str] | None = None,
strict: bool = False,
) -> tuple[str, list[str]] | None:
@@ -894,7 +878,7 @@ def find_validated_variant(
db: dict,
current_path: str,
validation_index: dict,
bios_dir: str = "bios",
bios_dir: str = BIOS_DIR,
platform_digest: str | None = None,
emulators: set[str] | None = None,
strict: bool = False,
+2 -3
View File
@@ -15,7 +15,6 @@ Invoke-RestMethod reads any type that is neither JSON nor XML as text.
from __future__ import annotations
import hashlib
import os
import re
import subprocess
@@ -23,7 +22,7 @@ from pathlib import Path
from core.artifacts import write_if_changed
from model.guides import PS1_NAME, SH_NAME
from installer_build.pins import PIN
from installer_build.pins import PIN, installer_sha256
REPO_RAW = "https://raw.githubusercontent.com/Abdess/retrobios"
@@ -75,7 +74,7 @@ def served_text(name: str, root: Path, commit: str) -> str:
pinned = PIN[source].findall(text)
if len(pinned) != 1:
raise ValueError(f"{source}: {len(pinned)} installer pins, expected one")
actual = hashlib.sha256((root / "install.py").read_bytes()).hexdigest()
actual = installer_sha256(root)
if pinned[0] != actual:
raise ValueError(f"{source} pins {pinned[0][:12]}, install.py is {actual[:12]}: "
"re-pin the bootstrap before the site serves it")
+2 -8
View File
@@ -20,8 +20,7 @@ from model.database import load_database
from model.dumpcatalog import load_provenance_snapshots
from model.guides import HANDHELD_GUIDE
from model.profiles import load_emulator_profiles
from model.registry import list_registered_platforms
from model.safeparse import yaml_load
from model.registry import list_registered_platforms, load_platform_registry
from model.systemnames import program_names, set_console_sections, system_name
from packs.crossref import FileConsumers
from acquire.provenance import build_report, profile_needs
@@ -165,12 +164,7 @@ def _write_public_assets(docs: Path, public: Path) -> None:
def _load_registry(platforms_dir: str) -> dict:
"""The platforms of _registry.yml, by name."""
registry_path = Path(platforms_dir) / "_registry.yml"
registry = {}
if registry_path.exists():
with open(registry_path) as f:
registry = (yaml_load(f) or {}).get("platforms", {})
return registry
return load_platform_registry(platforms_dir)
@dataclass
+4 -4
View File
@@ -11,6 +11,7 @@ import urllib.parse
import zipfile
from collections.abc import Callable
from core.hashing import parse_hash_list
from model.collection import profiles_on_disk
from packs.crossref import FileConsumers
from sitegen import markup, wanted as sitewanted
@@ -789,10 +790,9 @@ def emulator_display(emulator: str) -> str:
def _first_hash_value(entry: dict) -> str:
"""The first declared hash of an entry, lowercase, for a stable anchor."""
for field in ("sha1", "md5", "crc32", "sha256"):
value = entry.get(field)
value = value[0] if isinstance(value, list) and value else value
if value:
return str(value).lower().split(",")[0].strip().removeprefix("0x")
values = parse_hash_list(entry.get(field))
if values:
return values[0]
return ""
+2 -4
View File
@@ -13,6 +13,7 @@ from functools import cache
from pathlib import Path
from xml.sax.saxutils import escape
from model.registry import load_platform_registry
from core.paths import REPO_ROOT
from model import siteinputs
from sitegen import markup
@@ -390,10 +391,7 @@ def registry() -> dict:
@cache
def _registry_in(platforms_dir: str) -> dict:
import yaml
with open(Path(platforms_dir) / "_registry.yml", encoding="utf-8") as handle:
return yaml.safe_load(handle).get("platforms", {})
return load_platform_registry(platforms_dir, required=True)
def setups() -> tuple[str, ...]:
+4 -4
View File
@@ -8,6 +8,7 @@ import urllib.parse
from collections.abc import Callable, Sequence
from dataclasses import dataclass
from core.hashing import parse_hash_list
from model.systemnames import system_name
from packs.crossref import FileConsumers
from sitegen import entries as siteentries, markup, measurements as sitemeasurements
@@ -454,10 +455,9 @@ def _hash_short(f: dict) -> str:
"""The shortest way to tell two dumps apart in a table: the first 12
characters of an md5, crc32 or sha1, the whole value in its title."""
for field in ("md5", "crc32", "sha1"):
value = f.get(field)
value = value[0] if isinstance(value, list) and value else value
if value:
full = html.escape(str(value).lower().split(",")[0].strip().removeprefix("0x"))
values = parse_hash_list(f.get(field))
if values:
full = html.escape(values[0])
# Kept on one line: the label above the value doubled each row.
return f'{field.upper()}\u00a0<code title="{full}">{full[:12]}</code>'
return ""
+2 -3
View File
@@ -6,6 +6,7 @@ import re
import urllib.parse
from collections.abc import Callable
from model.database import load_database
from model import siteinputs
from sitegen import markup
from core.paths import REPO_ROOT
@@ -418,7 +419,6 @@ def _build_boards() -> None:
def _read_arcade_source() -> tuple[dict, dict] | None:
"""The profiles and database of the repository, None without a database."""
import json
from model.profiles import load_emulator_profiles
@@ -426,8 +426,7 @@ def _read_arcade_source() -> tuple[dict, dict] | None:
database = inputs.db
if not database.exists():
return None
with open(database, encoding="utf-8") as handle:
db = json.load(handle)
db = load_database(str(database))
profiles = load_emulator_profiles(str(inputs.emulators), skip_aliases=False)
return profiles, db
+3 -6
View File
@@ -13,9 +13,10 @@ from pathlib import Path, PurePosixPath
import yaml
from model.registry import load_platform_registry
from model.profiles import source_yaml_paths
from model.safeparse import yaml_load
from core.paths import REPO_ROOT
from core.paths import PLATFORMS_DIR, REPO_ROOT
try:
from jsonschema import Draft202012Validator, FormatChecker
@@ -629,11 +630,7 @@ def _save_directory_blocks() -> list[str]:
folder per launched system) needs the platform file's libretro_systems,
and ``by_core_for`` names the cores a launcher sorts by core.
"""
registry_path = REPO_ROOT / "platforms" / "_registry.yml"
if not registry_path.is_file():
return []
with registry_path.open(encoding="utf-8") as handle:
platforms = (yaml_load(handle) or {}).get("platforms") or {}
platforms = load_platform_registry(REPO_ROOT / PLATFORMS_DIR)
out: list[str] = []
for name, entry in sorted(platforms.items()):
if not isinstance(entry, dict) or "save_directory" not in entry:
+2 -1
View File
@@ -12,7 +12,8 @@ import tests
import unittest
from installer_build import port
from release.check import SIGNATURE, SUMS, Asset, compare_release, parse_sums
from core.hashing import parse_sha256sums as parse_sums
from release.check import SIGNATURE, SUMS, Asset, compare_release
A = "a" * 64
B = "b" * 64