refactor: read declared hashes with one helper

core.hashing.declared_hash_lists gives an entry's declared values per
field in the order written, and declared_hashes builds its sets on it.
The gap page, the doubled-destination report and the file lookup used
their own copies of that reader. The wanted page keeps its filters on
top of it. sitegen.lookup.hash_pairs replaces sorted_hash_values for
the lookup, the data exports and the structured data. The one-field
aliases parse_md5_list and reconcile.hash_values are gone, and
model.profiles reads HASH_FIELDS instead of a fourth tuple.
This commit is contained in:
Abdessamad Derraz committed 2026-11-21 10:29:37 +01:00
1 parent ea68e85c06
commit 02969dda06
30 files changed
+176 -195

No files matched your search

+2 -2
View File
@@ -12,7 +12,7 @@ import urllib.parse
from pathlib import Path
from core import upstream
from core.hashing import parse_hash_list, parse_md5_list
from core.hashing import parse_hash_list
from core.paths import EMULATORS_DIR, PLATFORMS_DIR, REPO_ROOT
from resolve.localfile import held_record_for
from resolve.review import load_platform_hashes, load_profile_hashes, placement
@@ -293,7 +293,7 @@ def place_file(
values = [
*parse_hash_list(entry.get("sha1")),
*parse_md5_list(entry.get("md5")),
*parse_hash_list(entry.get("md5")),
*parse_hash_list(entry.get("sha256")),
]
spot = placement(
+8 -11
View File
@@ -198,10 +198,16 @@ def parse_hash_list(raw: str | list | int | None) -> list[str]:
HASH_FIELDS = ("sha1", "md5", "sha256", "crc32")
def declared_hash_lists(entry: dict, fields: Iterable[str] = HASH_FIELDS) -> dict[str, list[str]]:
"""Hash field -> the values an entry declares, in the order written, for
each field it declares, the fields in the order given."""
found = {f: parse_hash_list(entry.get(f)) for f in fields}
return {f: values for f, values in found.items() if values}
def declared_hashes(entry: dict, fields: Iterable[str] = HASH_FIELDS) -> dict[str, set[str]]:
"""Hash field -> the values an entry declares, for each field it declares."""
found = {f: set(parse_hash_list(entry.get(f))) for f in fields}
return {f: values for f, values in found.items() if values}
return {f: set(values) for f, values in declared_hash_lists(entry, fields).items()}
def lists_hashes(entry: dict) -> bool:
@@ -209,15 +215,6 @@ def lists_hashes(entry: dict) -> bool:
return bool(declared_hashes(entry))
def parse_md5_list(raw: str | list | None) -> list[str]:
"""Normalize an md5 field into a lowercase list.
Platform YAMLs carry Recalbox multi-hash as one comma-separated string,
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."""
+4 -9
View File
@@ -18,8 +18,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
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 core.hashing import lists_hashes
from core.hashing import declared_hash_lists, lists_hashes
from model.profiles import lists_files
from resolve.collisions import accepted_by_all, find_collisions
from resolve.content import size_fits
from resolve.validation import opens_by_name, outside_gap_scope
@@ -58,11 +58,6 @@ def _reads(entry: dict, by_name: bool, local: str, db: dict) -> bool:
return by_name and _size_fits(entry, local)
def _hashes(entry: dict) -> dict[str, list[str]]:
found = {f: hash_values(entry, f) for f in HASH_FIELDS}
return {f: values for f, values in found.items() if values}
def doubled_destinations(
scraped: dict | None,
profiles: dict[str, dict],
@@ -86,7 +81,7 @@ def doubled_destinations(
named: dict[str, list[tuple[str, dict, dict, bool]]] = {}
for key in sorted(resolve_platform_cores(scraped, profiles)):
profile = profiles[key]
if profile.get("type") in ("launcher", "alias"):
if not lists_files(profile):
continue
for layout, is_standalone in platform_layouts(key, profile, standalone):
for entry in layout.get("files") or []:
@@ -117,7 +112,7 @@ def doubled_destinations(
"system": entry.get("native_system") or "",
"component": entry.get("component") or "",
"name": entry.get("name", ""),
"hashes": _hashes(entry),
"hashes": declared_hash_lists(entry),
"file": local,
"readers": readers,
})
+4 -3
View File
@@ -18,7 +18,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from scraper.emudeck_scraper import FUNCTION_HASH_MAP, RE_FUNC, RE_LOCAL_HASHES
from .base_exporter import BaseExporter
from resolve.reconcile import NativeFile, NativeSystem, Report, hash_values
from core.hashing import parse_hash_list
from resolve.reconcile import NativeFile, NativeSystem, Report
SOURCE_URL = (
"https://raw.githubusercontent.com/dragoonDorise/EmuDeck/main"
@@ -80,7 +81,7 @@ class Exporter(BaseExporter[str]):
adds nothing, and the truth's extra accepted revisions are not
appended: either would grow an array other consumers read too.
"""
theirs = hash_values(fe.platform or {}, "md5")
theirs = parse_hash_list((fe.platform or {}).get("md5"))
if not theirs:
return []
if "md5" in fe.corrections:
@@ -124,7 +125,7 @@ class Exporter(BaseExporter[str]):
if system.native_id == system_id
for fe in system.files
if "md5" in fe.corrections
for value in hash_values(fe.platform or {}, "md5")
for value in parse_hash_list((fe.platform or {}).get("md5"))
}
@classmethod
+5 -4
View File
@@ -6,7 +6,8 @@ from __future__ import annotations
from dataclasses import dataclass, field
from .base_exporter import BaseExporter
from resolve.reconcile import HASH_FIELDS, NativeFile, hash_values, single_size
from core.hashing import parse_hash_list
from resolve.reconcile import HASH_FIELDS, NativeFile, single_size
@dataclass
@@ -75,7 +76,7 @@ def _change(
def _platform_value(entry: NativeFile, field_name: str) -> str | list[str]:
values = hash_values(entry.platform or {}, field_name)
values = parse_hash_list((entry.platform or {}).get(field_name))
if (entry.platform or {}).get(f"{field_name}_list"):
return values
return ",".join(values)
@@ -157,7 +158,7 @@ def landed_changes(exporter: BaseExporter, systems: dict) -> LandedChanges:
listed is not None
and field_name not in entry.corrections
and field_name not in entry.filled
and listed != hash_values(entry.platform, field_name)
and listed != parse_hash_list(entry.platform.get(field_name))
and exporter.states(entry, field_name)
):
records.append(_change(
@@ -196,7 +197,7 @@ def landed_changes(exporter: BaseExporter, systems: dict) -> LandedChanges:
_change("hash_cleared", entry, field_name,
_platform_value(entry, field_name), None)
for field_name in HASH_FIELDS
if hash_values(entry.platform, field_name)
if parse_hash_list(entry.platform.get(field_name))
and not entry.hashes(field_name)
and exporter.clears(entry, field_name)
)
+3 -2
View File
@@ -21,11 +21,12 @@ from xml.sax.saxutils import quoteattr
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from model.profiles import load_emulator_profiles
from core.hashing import parse_hash_list
from model.safeparse import parse_untrusted_xml
from .base_exporter import BaseExporter
from resolve.reconcile import (
NativeFile, NativeSystem, Report, by_destination, by_name, hash_values,
NativeFile, NativeSystem, Report, by_destination, by_name,
)
SOURCE_URL = (
@@ -83,7 +84,7 @@ def _stated(text: str) -> dict[str, str]:
# Recalbox accepts any digest of the list (Bios.cpp:109-130): the
# order is not content, and neogeo.zip's 24, reordered, were
# written again.
attrs["md5"] = ",".join(sorted(hash_values(attrs, "md5")))
attrs["md5"] = ",".join(sorted(parse_hash_list(attrs.get("md5"))))
return attrs
+4 -3
View File
@@ -13,7 +13,8 @@ import json
from collections import OrderedDict
from .base_exporter import BaseExporter
from resolve.reconcile import NativeFile, NativeSystem, Report, hash_values
from core.hashing import parse_hash_list
from resolve.reconcile import NativeFile, NativeSystem, Report
COMPONENTS_REPO = "RetroDECK/components"
COMPONENTS_BRANCH = "main"
@@ -250,7 +251,7 @@ class Exporter(BaseExporter[str]):
other_revision = (
keys
and seen_keys.get(keys[0], 0) > 1
and not set(hash_values(entry, "md5")) & set(hash_values(by_key[keys[0]], "md5"))
and not set(parse_hash_list(entry.get("md5"))) & set(parse_hash_list(by_key[keys[0]].get("md5")))
)
if other_revision or not keys:
merged.append(OrderedDict(entry))
@@ -302,7 +303,7 @@ class Exporter(BaseExporter[str]):
for field in ("md5", "sha256"):
if field in cls.carries() and field not in own:
combined.pop(field, None)
if set(hash_values(entry, "md5")) == set(hash_values(combined, "md5")):
if set(parse_hash_list(entry.get("md5"))) == set(parse_hash_list(combined.get("md5"))):
# Their own spelling, and no key where they wrote none: an
# equal empty set wrote "md5": null 39 times.
if "md5" in entry:
+4 -3
View File
@@ -18,7 +18,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from scraper.romm_scraper import SLUG_MAP
from .base_exporter import BaseExporter
from resolve.reconcile import NativeFile, NativeSystem, Report, hash_values
from core.hashing import parse_hash_list
from resolve.reconcile import NativeFile, NativeSystem, Report
SOURCE_URL = (
"https://raw.githubusercontent.com/rommapp/romm/master/backend/models"
@@ -161,7 +162,7 @@ class Exporter(BaseExporter[str]):
output[key] = OrderedDict(
(field, value)
for field, name in _FIELDS
if (value := ",".join(hash_values(fe.platform, name))
if (value := ",".join(parse_hash_list(fe.platform.get(name)))
if name != "size" else str(fe.platform["size"]))
)
continue
@@ -185,7 +186,7 @@ class Exporter(BaseExporter[str]):
def _contradicted(fe: NativeFile, name: str) -> bool:
"""A hash the platform states and the truth, taking the entry over,
does not keep."""
return bool(hash_values(fe.platform or {}, name)) and not fe.hashes(name)
return bool(parse_hash_list((fe.platform or {}).get(name))) and not fe.hashes(name)
def states(self, fe: NativeFile, field_name: str) -> bool:
"""An entry left whole carries none of the truth's values."""
+2 -4
View File
@@ -7,6 +7,7 @@ import sys
from pathlib import Path
from core.cli import InputMissing, suggest_names
from core.hashing import HASH_FIELDS
from model.alternatives import derive_member_requirements
from model.profilekinds import is_emulator as is_emulator
from model.profilekinds import lists_files as lists_files
@@ -235,9 +236,6 @@ def load_emulator_profiles(
return profiles
_HASH_FIELDS = ("crc32", "md5", "sha1", "sha256")
def _normalize_hash_fields(node: object) -> None:
"""Coerce hash values to str in place.
@@ -246,7 +244,7 @@ def _normalize_hash_fields(node: object) -> None:
"""
if isinstance(node, dict):
for key, val in node.items():
if key in _HASH_FIELDS:
if key in HASH_FIELDS:
if isinstance(val, int):
node[key] = str(val)
elif isinstance(val, list):
+2 -2
View File
@@ -12,7 +12,7 @@ from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, TypedDict
from core.hashing import parse_hash_list, parse_md5_list, stream_hashes
from core.hashing import parse_hash_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, sha1_at
@@ -630,7 +630,7 @@ def entry_source(f: dict, index: dict) -> str | None:
# The declared content anywhere in bios/ comes before a data/ copy, as in
# the resolver: the hash steps run before the data directories.
held = (
any(index["by_md5"].get(v) for v in parse_md5_list(f.get("md5")))
any(index["by_md5"].get(v) for v in parse_hash_list(f.get("md5")))
or any(v in db_files for v in values("sha1"))
# rust_dos names its SC-55 ROMs by sha256 alone
or any(v in index["by_sha256"] for v in values("sha256"))
+2 -2
View File
@@ -6,7 +6,7 @@ import os
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
from core.hashing import lists_hashes, parse_md5_list
from core.hashing import lists_hashes, parse_hash_list
from model.declarations import declared_slot
from model.profiles import entry_system_ids, lists_files
from packs.gaps import gap_destination
@@ -336,7 +336,7 @@ def checked_by_path(mode: str, entry: dict, rule: str = "") -> bool:
else:
fields = (nativemode.digest_algorithm(mode) or "",)
return not any(
parse_md5_list(entry.get(name)) if name == "md5" else entry.get(name)
parse_hash_list(entry.get(name)) if name == "md5" else entry.get(name)
for name in fields
)
+2 -2
View File
@@ -2,7 +2,7 @@
from __future__ import annotations
from core.hashing import compute_hashes, md5sum, parse_md5_list
from core.hashing import compute_hashes, md5sum, parse_hash_list
from core.ziptools import check_inside_zip
from resolve.nativemode import SIZE_AND_ANY_HASH, reads_file_contents
from resolve.validation import (
@@ -142,7 +142,7 @@ def verify_entry_md5(
# 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)
md5_list = parse_hash_list(expected_md5)
if not local_path:
return {**base, "status": Status.MISSING}
+7 -7
View File
@@ -18,9 +18,9 @@ from pathlib import Path
from model.systems import norm_system_id
from resolve.cores import resolve_platform_cores, unresolved_platform_cores
from core.hashing import declared_hashes
from core.hashing import declared_hashes, parse_hash_list
from resolve.reconcile import (
HASH_FIELDS, NativeSystem, comparable, contradicts, entry_names, hash_values,
HASH_FIELDS, NativeSystem, comparable, contradicts, entry_names,
)
from resolve.launchers import record_names as launcher_names
@@ -32,10 +32,10 @@ def _tails(path: str) -> list[str]:
def _entry_hashes(entry: dict) -> set[str]:
values = {v for f in HASH_FIELDS for v in hash_values(entry, f)}
values = {v for f in HASH_FIELDS for v in parse_hash_list(entry.get(f))}
for member in entry.get("contents") or []:
if isinstance(member, dict):
values |= {v for f in HASH_FIELDS for v in hash_values(member, f)}
values |= {v for f in HASH_FIELDS for v in parse_hash_list(member.get(f))}
return values
@@ -47,7 +47,7 @@ def _declared_hashes(entry: dict) -> dict[str, set[str]]:
"""
entry = comparable(entry)
found = declared_hashes(entry)
if alt := set(hash_values(entry, "alt_md5")):
if alt := set(parse_hash_list(entry.get("alt_md5"))):
found["md5"] = found.get("md5", set()) | alt
return found
@@ -129,7 +129,7 @@ class ReadEvidence:
if names & self.names or (tails and tails[-1] in self.names):
return "name"
hashes = {
v for f in (*HASH_FIELDS, "alt_md5") for v in hash_values(entry, f)
v for f in (*HASH_FIELDS, "alt_md5") for v in parse_hash_list(entry.get(f))
}
if hashes & self.hashes:
return "hash"
@@ -183,7 +183,7 @@ class ProofIndex:
tails = _tails(destination)
last = {tails[-1]} if tails else set()
hashes = {
v for f in (*HASH_FIELDS, "alt_md5") for v in hash_values(entry, f)
v for f in (*HASH_FIELDS, "alt_md5") for v in parse_hash_list(entry.get(f))
}
# "/" + d in "/" + path: d is a run of whole segments ending in "/",
# so it is a run of the path's segments before the last one.
+2 -2
View File
@@ -6,7 +6,7 @@ import os
import zlib
from dataclasses import dataclass, field
from core.hashing import compute_hashes, declared_hashes, parse_md5_list
from core.hashing import compute_hashes, declared_hashes, parse_hash_list
from core.paths import comparable_destination
from core.ziptools import check_inside_zip
from resolve.localfile import resolve_local_file, variant_base_name
@@ -126,7 +126,7 @@ def accepted_by_all(path: str, entries: list[dict], db: dict) -> bool:
return False
for entry in entries:
if entry.get("zipped_file"):
declared = parse_md5_list(entry.get("md5"))
declared = parse_hash_list(entry.get("md5"))
if declared and not any(
check_inside_zip(path, entry["zipped_file"], m) == "ok" for m in declared
):
+3 -3
View File
@@ -10,7 +10,7 @@ from collections.abc import Iterator
from dataclasses import dataclass
from typing import Any
from core.hashing import cut_md5_owner, md5_composite, parse_md5_list
from core.hashing import cut_md5_owner, md5_composite, parse_hash_list
from core.memo import DerivedView
from core.ziptools import check_inside_zip
from model.database import get_mame_clone_map
@@ -339,7 +339,7 @@ def held_record_for(file_entry: dict, db: dict) -> str | None:
by_md5 = indexes.get("by_md5", {})
md5_list = [
(cut_md5_owner(value, by_md5) or value) if len(value) < 32 else value
for value in parse_md5_list(file_entry.get("md5"))
for value in parse_hash_list(file_entry.get("md5"))
]
q = _lookup(
file_entry, db, "", md5_list,
@@ -1026,7 +1026,7 @@ def resolve_local_file(
file_entry, db, zip_contents, dest_hint,
depth=_depth, data_dir_registry=data_dir_registry,
)
md5_list = parse_md5_list(file_entry.get("md5"))
md5_list = parse_hash_list(file_entry.get("md5"))
by_md5 = db.get("indexes", {}).get("by_md5", {})
# A value cut short stands for the one held md5 it starts, and only
# then (cut_md5_owner): the dump it names is still name-guarded below.
+11 -16
View File
@@ -23,11 +23,6 @@ from model.systems import norm_system_id
from core.paths import REPO_ROOT
def hash_values(entry: dict, field_name: str) -> list[str]:
"""Return a hash field as a list, whatever shape it was written in."""
return parse_hash_list(entry.get(field_name))
def checked_hashes(entry: dict | None) -> dict | None:
"""The truth entry with only the hashes its code checks.
@@ -57,8 +52,8 @@ def checked_hashes(entry: dict | None) -> dict | None:
kinds = {str(k) for k in raw}
else:
kinds = {str(raw)}
checked = [f for f in HASH_FIELDS if f in kinds and hash_values(entry, f)]
if checked and all(len(set(hash_values(entry, f))) == 1 for f in checked):
checked = [f for f in HASH_FIELDS if f in kinds and parse_hash_list(entry.get(f))]
if checked and all(len(set(parse_hash_list(entry.get(f)))) == 1 for f in checked):
return entry
return {k: v for k, v in entry.items() if k not in HASH_FIELDS or k in kinds}
@@ -116,7 +111,7 @@ def is_placeholder(name: str) -> bool:
def _field_sets(entry: dict | None) -> dict[str, set[str]]:
return {f: set(hash_values(entry or {}, f)) for f in HASH_FIELDS}
return {f: set(parse_hash_list((entry or {}).get(f))) for f in HASH_FIELDS}
def single_size(value: int | str | list[int | str]) -> int | None:
@@ -206,9 +201,9 @@ class NativeFile:
rejects a file will reject it whatever the platform declares.
"""
if field_name == "md5" and self.composite_md5:
return hash_values(self.platform or {}, field_name)
truth_values = hash_values(self._checked_truth, field_name)
platform_values = hash_values(self.platform or {}, field_name)
return parse_hash_list((self.platform or {}).get(field_name))
truth_values = parse_hash_list(self._checked_truth.get(field_name))
platform_values = parse_hash_list((self.platform or {}).get(field_name))
source = self._identity_source()
if source == "platform":
return platform_values
@@ -242,11 +237,11 @@ class NativeFile:
is written when it names one value, which is then that dump's.
"""
if field_name == "md5" and self.composite_md5:
values = hash_values(self.platform or {}, field_name)
values = parse_hash_list((self.platform or {}).get(field_name))
return values[0] if values else ""
source = self._identity_source()
truth_values = hash_values(self._checked_truth, field_name)
platform_values = hash_values(self.platform or {}, field_name)
truth_values = parse_hash_list(self._checked_truth.get(field_name))
platform_values = parse_hash_list((self.platform or {}).get(field_name))
if source == "truth":
return truth_values[0] if truth_values else ""
if source == "platform" or not truth_values:
@@ -531,8 +526,8 @@ def _correct_matched(matched: NativeFile, truth_entry: dict, report: Report) ->
report.hashes_corrected.append(
f"{matched.native_system}/{matched.name} {field_name}"
)
elif hash_values(checked, field_name) and not hash_values(
comparable(matched.platform), field_name
elif parse_hash_list(checked.get(field_name)) and not parse_hash_list(
comparable(matched.platform).get(field_name)
):
matched.filled.append(field_name)
t_req = truth_entry.get("required")
+2 -2
View File
@@ -15,7 +15,7 @@ try:
except ImportError:
yaml = None
from core.hashing import compute_hashes, parse_hash_list, parse_md5_list, stream_hashes
from core.hashing import compute_hashes, parse_hash_list, stream_hashes
from model.nodedup import in_nodedup_dir
from model.platforms import load_platform_config
from model.profiles import load_emulator_profiles
@@ -179,7 +179,7 @@ def load_platform_hashes(platforms_dir: str, db: dict | None = None) -> dict:
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"))
md5s = parse_hash_list(file_entry.get("md5"))
sha256s = parse_hash_list(file_entry.get("sha256"))
known["sha1"].update(sha1s)
known["md5"].update(md5s)
+4 -4
View File
@@ -26,7 +26,7 @@ from resolve.archives import archive_members
from model.profiles import CONTENT_CHECKS, entry_system_ids, lists_files
from core.hashing import compute_hashes, parse_hash_list
from core.paths import BIOS_DIR, sanitize_pack_path
from core.hashing import lists_hashes, md5_composite, parse_md5_list
from core.hashing import lists_hashes, md5_composite
from resolve.nativemode import SIZE_AND_ANY_HASH, digest_algorithm, hash_mismatch_excludes_file
from core.ziptools import check_inside_zip, check_inside_zip_data
@@ -791,7 +791,7 @@ def _platform_accepted(file_entry: dict, platform_digest: str) -> set[str]:
"""The values of the digest the frontend compares that the entry declares."""
declared = file_entry.get(platform_digest) or ""
if platform_digest == "md5":
return set(parse_md5_list(declared))
return set(parse_hash_list(declared))
if isinstance(declared, str) and declared:
return {declared.lower()}
if isinstance(declared, list):
@@ -964,7 +964,7 @@ def digest_verdict(
if file_entry.get(field)
)
if algorithm == "md5":
declared = parse_md5_list(file_entry.get("md5"))
declared = parse_hash_list(file_entry.get("md5"))
else:
value = file_entry.get(algorithm)
values = value if isinstance(value, list) else [value]
@@ -1011,7 +1011,7 @@ def inner_rom_data_check(file_entry: dict, data: bytes) -> str:
def _first_accepted_md5(file_entry: dict, check: Callable[[str], str]) -> str:
# With no md5 declared, checkInsideZip still runs and needs the member.
result = "not_in_zip"
for candidate in parse_md5_list(file_entry.get("md5")) or [""]:
for candidate in parse_hash_list(file_entry.get("md5")) or [""]:
result = check(candidate)
if result == "ok":
break
+4 -3
View File
@@ -10,7 +10,8 @@ from model.database import sha1_at
from model.systemnames import system_name
from model.profiles import is_emulator
from sitegen.config import SITE_URL
from sitegen.lookup import sorted_hash_values, site_path
from core.hashing import parse_hash_list
from sitegen.lookup import site_path
from sitegen.render import card_anchor, console_href
@@ -45,8 +46,8 @@ def system_index_items(db: dict, coverages: dict, profiles: dict) -> list[dict]:
ids = ([str(entry["system"])] if entry.get("system")
else [str(s) for s in entry.get("systems") or []] or
(own if len(own) == 1 else []))
found = {v for v in sorted_hash_values(entry.get("sha1")) if v in files}
for md5 in sorted_hash_values(entry.get("md5")):
found = {v for v in parse_hash_list(entry.get("sha1")) if v in files}
for md5 in parse_hash_list(entry.get("md5")):
match = by_md5.get(md5)
found.update([match] if isinstance(match, str) else match or [])
for sys_id in ids:
+20 -21
View File
@@ -28,7 +28,7 @@ from core.paths import REPO_ROOT
from sitegen.install import release_pack_platforms
from sitegen.lookup import (
HASH_ALGORITHMS,
sorted_hash_values,
hash_pairs,
data_directory_members,
file_location_items,
file_lookup_records,
@@ -48,23 +48,23 @@ def _accepted_hash_rows(platform_files: list[dict], emulator_items: list[dict])
"""One row per accepted hash value, for both layers, lookup-ready."""
rows: list[dict] = []
for row in platform_files:
for algorithm in HASH_ALGORITHMS:
rows.extend({
"layer": "platform", "owner": row["platform_id"],
"system": row["system"], "name": row["name"],
"path": row["destination"], "algorithm": algorithm, "value": value,
} for value in sorted_hash_values(row.get(f"{algorithm}_raw", row.get(algorithm))))
# A table row keeps the field as declared under <algorithm>_raw.
declared = {algo: row.get(f"{algo}_raw", row.get(algo)) for algo in HASH_ALGORITHMS}
rows.extend({
"layer": "platform", "owner": row["platform_id"],
"system": row["system"], "name": row["name"],
"path": row["destination"], "algorithm": algorithm, "value": value,
} for algorithm, value in hash_pairs(declared))
for item in emulator_items:
for entry in item["profile"].get("files", []) or []:
if not isinstance(entry, dict):
continue
for algorithm in HASH_ALGORITHMS:
rows.extend({
"layer": "emulator", "owner": item["id"],
"system": _json_text(entry.get("system")),
"name": entry.get("name", ""), "path": entry.get("path", "") or "",
"algorithm": algorithm, "value": value,
} for value in sorted_hash_values(entry.get(algorithm)))
rows.extend({
"layer": "emulator", "owner": item["id"],
"system": _json_text(entry.get("system")),
"name": entry.get("name", ""), "path": entry.get("path", "") or "",
"algorithm": algorithm, "value": value,
} for algorithm, value in hash_pairs(entry))
# Members of an archive: MAME and FBNeo hash the ROMs inside the
# set, never the set. Left out, a loose nmk004.bin (crc32
# 83b6f611) found no row while the site search found it.
@@ -72,13 +72,12 @@ def _accepted_hash_rows(platform_files: list[dict], emulator_items: list[dict])
for member in entry.get("contents") or []:
if not isinstance(member, dict) or not member.get("name"):
continue
for algorithm in HASH_ALGORITHMS:
rows.extend({
"layer": "emulator", "owner": item["id"],
"system": _json_text(entry.get("system")),
"name": str(member["name"]), "path": f"{archive}/{member['name']}",
"algorithm": algorithm, "value": value,
} for value in sorted_hash_values(member.get(algorithm)))
rows.extend({
"layer": "emulator", "owner": item["id"],
"system": _json_text(entry.get("system")),
"name": str(member["name"]), "path": f"{archive}/{member['name']}",
"algorithm": algorithm, "value": value,
} for algorithm, value in hash_pairs(member))
rows.sort(key=lambda r: (r["layer"], r["owner"], r["name"], r["algorithm"], r["value"]))
return rows
+5 -19
View File
@@ -7,6 +7,7 @@ import html
import re
from dataclasses import dataclass
from core.hashing import declared_hash_lists
from core.text import series
from model.platforms import native_layer
from model.profiles import is_emulator
@@ -51,24 +52,6 @@ def _held_accepted(discrepancy: str, db: dict | None) -> str:
return ""
_PROBLEM_HASHES = ("sha1", "md5", "sha256", "crc32")
def _declared_hashes(entry: dict) -> dict[str, list[str]]:
"""The hashes the platform declares for a reported file, by algorithm.
The untested table said "declared hash contradicted by the local file"
and named neither: the reader could not look for the dump RetroDECK asks
for, nor report the difference.
"""
from core.hashing import parse_hash_list
return {
algo: parse_hash_list(entry.get(algo))
for algo in _PROBLEM_HASHES if parse_hash_list(entry.get(algo))
}
def _declarations(cov: dict) -> dict[int, dict]:
"""Each verify detail of a platform, by id, with the declaration it
scores (wanted.paired_declarations): AmberELEC declares
@@ -422,7 +405,10 @@ def _problem_record(pname: str, cov: dict, d: dict, entry: dict) -> dict:
"reason": d.get("reason", ""),
"discrepancy": d.get("discrepancy", ""),
"system": d.get("system", ""),
"declared": _declared_hashes(entry),
# The untested table said "declared hash contradicted by the local
# file" and named neither: the reader could not look for the dump
# RetroDECK asks for, nor report the difference.
"declared": declared_hash_lists(entry),
"destination": str(entry.get("destination") or d.get("name", "")),
"path": d.get("path") or "",
}
+35 -39
View File
@@ -9,7 +9,7 @@ import urllib.parse
import zipfile
from pathlib import Path
from core.hashing import parse_hash_list
from core.hashing import declared_hash_lists
from model import siteinputs
from model.collection import manufacturer_slug
from model.registry import load_versions
@@ -26,13 +26,15 @@ from sitegen.write import write_if_changed
HASH_ALGORITHMS = ("sha1", "sha256", "md5", "crc32")
def sorted_hash_values(value: object) -> list[str]:
"""Every accepted value of one hash field, lowercase.
def hash_pairs(entry: dict, fields: tuple[str, ...] = HASH_ALGORITHMS) -> list[tuple[str, str]]:
"""(algorithm, value) for every value an entry declares, lowercase, the
algorithms in the order given and the values sorted within each.
A field holds one value, a list of accepted revisions, or (Recalbox) a
comma-joined string: an exact lookup missed all but the first form.
"""
return sorted(parse_hash_list(value))
return [(algo, value) for algo, values in declared_hash_lists(entry, fields).items()
for value in sorted(values)]
def site_path(markdown_target: str) -> str:
@@ -307,11 +309,10 @@ def retired_records(retired: dict[str, dict], files: dict, locations: list[dict]
else:
# The page its card was on: the reader lands among its neighbours.
url = site_path(f"systems/{card_page(str(record.get('path', '')), sha1)}.md")
for algorithm in HASH_ALGORITHMS:
value = sha1 if algorithm == "sha1" else record.get(algorithm)
records.extend({"value": one, "algorithm": algorithm, "layer": "retired",
"name": str(record.get("name", "")), "sha1": sha1,
"url": url, **extra} for one in sorted_hash_values(value))
records.extend({"value": one, "algorithm": algorithm, "layer": "retired",
"name": str(record.get("name", "")), "sha1": sha1,
"url": url, **extra}
for algorithm, one in hash_pairs({**record, "sha1": sha1}))
return records
@@ -365,12 +366,11 @@ def _collection_lookup_records(
continue
parts = str(entry.get("path", "")).split("/")
held_by = named.get((manufacturer_slug(parts[1]), parts[2])) if len(parts) > 3 else None
for algorithm in HASH_ALGORITHMS:
records.extend({
"value": value, "algorithm": algorithm, "layer": "collection",
"name": str(entry.get("name", "")), "sha1": sha1, "url": item["url"],
**({"system_name": held_by} if held_by else {}),
} for value in sorted_hash_values(entry.get(algorithm)))
records.extend({
"value": value, "algorithm": algorithm, "layer": "collection",
"name": str(entry.get("name", "")), "sha1": sha1, "url": item["url"],
**({"system_name": held_by} if held_by else {}),
} for algorithm, value in hash_pairs(entry))
records += _archive_member_records(entry, sha1, item["url"])
return records
@@ -388,13 +388,12 @@ def _platform_lookup_records(coverages: dict, consumers: FileConsumers | None) -
# no collection file by itself: the archive holding it is the one.
archive = (consumers.sha1_of(entry)
if consumers is not None and entry.get("zipped_file") else None)
for algorithm in HASH_ALGORITHMS:
records.extend({
"value": value, "algorithm": algorithm, "layer": "platform",
"owner": key, "name": str(entry.get("name", "")), "url": url,
**({"system_name": system_label} if system_label else {}),
**({"sha1": archive} if archive else {}),
} for value in sorted_hash_values(entry.get(algorithm)))
records.extend({
"value": value, "algorithm": algorithm, "layer": "platform",
"owner": key, "name": str(entry.get("name", "")), "url": url,
**({"system_name": system_label} if system_label else {}),
**({"sha1": archive} if archive else {}),
} for algorithm, value in hash_pairs(entry))
return records
@@ -416,12 +415,11 @@ def _emulator_lookup_records(profiles: dict) -> list[dict]:
if isinstance(member, dict) and member.get("name")
]
for name, holder in holders:
for algorithm in HASH_ALGORITHMS:
records.extend({
"value": value, "algorithm": algorithm, "layer": "emulator",
"owner": key, "name": name, "url": url,
**({"system_name": entry_label} if entry_label else {}),
} for value in sorted_hash_values(holder.get(algorithm)))
records.extend({
"value": value, "algorithm": algorithm, "layer": "emulator",
"owner": key, "name": name, "url": url,
**({"system_name": entry_label} if entry_label else {}),
} for algorithm, value in hash_pairs(holder))
return records
@@ -503,12 +501,11 @@ def _read_by_name(records: list[dict], files: dict, consumers: FileConsumers) ->
anchor = emulator_card_anchor(emulator, entries, index)
url = site_path(f"emulators/{emulator_card_page(emulator, anchor)}.md#{anchor}")
name = str(entries[index].get("name", ""))
for algorithm in HASH_ALGORITHMS:
added.extend({
"value": value, "algorithm": algorithm, "layer": "emulator",
"owner": emulator, "name": name, "url": url, "sha1": sha1,
"declared": "name",
} for value in sorted_hash_values(entry.get(algorithm)))
added.extend({
"value": value, "algorithm": algorithm, "layer": "emulator",
"owner": emulator, "name": name, "url": url, "sha1": sha1,
"declared": "name",
} for algorithm, value in hash_pairs(entry))
return added
@@ -539,11 +536,10 @@ def _held_under_every_hash(records: list[dict], files: dict, indexes: dict) -> l
if sha1 not in files:
continue
record["sha1"] = sha1
for algorithm in HASH_ALGORITHMS:
copies.extend({**record, "value": value, "algorithm": algorithm,
"declared": record["algorithm"]}
for value in sorted_hash_values(files[sha1].get(algorithm))
if value != record["value"])
copies.extend({**record, "value": value, "algorithm": algorithm,
"declared": record["algorithm"]}
for algorithm, value in hash_pairs(files[sha1])
if value != record["value"])
return copies
+4 -11
View File
@@ -16,7 +16,7 @@ from core.paths import REPO_ROOT
from sitegen.descriptions import EMULATOR_SNIPPETS, NOTHING_TO_FETCH, PAGE_DATA, TITLE_NOUNS, title_noun
from sitegen.emulatorcards import snippet_noun
from sitegen.install import comes_with_app
from sitegen.lookup import data_member_digests, sorted_hash_values
from sitegen.lookup import data_member_digests, hash_pairs
from sitegen.render import card_anchor, system_page_map
from sitegen.write import write_if_changed
@@ -197,8 +197,7 @@ def platform_structured_data(name: str, coverage: dict) -> dict:
}
identifiers = [
f"{field}:{value}"
for field in ("sha1", "md5", "crc32", "sha256")
for value in sorted_hash_values(entry.get(field))
for field, value in hash_pairs(entry, ("sha1", "md5", "crc32", "sha256"))
]
if identifiers:
part["identifier"] = identifiers
@@ -369,11 +368,7 @@ def emulator_structured_data(profile: dict) -> dict:
continue
# One identifier per accepted value: "sha256:a,b,c,d" matched no
# exact search (mesence's BS-X.bin).
identifiers = [
f"{field}:{value}"
for field in ("sha1", "sha256", "md5", "crc32")
for value in sorted_hash_values(f.get(field))
]
identifiers = [f"{field}:{value}" for field, value in hash_pairs(f)]
part: dict[str, object] = {
"@type": "CreativeWork",
"name": str(f.get("path") or f["name"]),
@@ -389,9 +384,7 @@ def emulator_structured_data(profile: dict) -> dict:
"@type": "CreativeWork",
"name": str(member.get("name", "")),
"identifier": [
f"{field}:{value}"
for field in ("sha1", "crc32")
for value in sorted_hash_values(member.get(field))
f"{field}:{value}" for field, value in hash_pairs(member, ("sha1", "crc32"))
],
}
for member in f.get("contents") or []
+3 -2
View File
@@ -26,7 +26,7 @@ from resolve.layout import runs_standalone
from resolve.standalone import standalone_set
from model.profiles import unique_emulator_profiles
from packs.crossref import first_hash
from core.hashing import cut_md5_owner, parse_hash_list
from core.hashing import cut_md5_owner, declared_hash_lists, parse_hash_list
from resolve.review import LARGE_FILE_ISSUE_URL, Placement, placement
from resolve.validation import deliverable, filter_files_by_mode, installed_with_emulator
from sitegen.config import UPLOAD_ROOT
@@ -53,7 +53,8 @@ def declared_hashes(entry: dict) -> dict[str, list[str]]:
counts only where no stronger hash is declared, as in
resolve_local_file.
"""
hashes = {algo: parse_hash_list(entry.get(algo)) for algo in ALGORITHMS}
declared = declared_hash_lists(entry, ALGORITHMS)
hashes = {algo: declared.get(algo, []) for algo in ALGORITHMS}
if entry.get("zipped_file"):
hashes["md5"] = []
hashes["md5"] = [v for v in hashes["md5"] if 0 < len(v) <= 32]
+1 -1
View File
@@ -6021,7 +6021,7 @@ class ZippedFileMd5IsParsedOnce(unittest.TestCase):
def test_the_three_sites_share_the_parser(self):
for module in ("resolve/validation.py", "verify.py"):
source = script_source(module)
self.assertIn("parse_md5_list(", source, module)
self.assertIn("parse_hash_list(", source, module)
self.assertIn("inner_rom_data_check(", script_source("packs/integrity.py"))
+7 -7
View File
@@ -35,7 +35,7 @@ from unittest import mock
from model import largefiles
import yaml
from core.ziptools import build_zip_contents_index, check_inside_zip, safe_extract_zip
from core.hashing import compute_hashes, md5_composite, parse_md5_list
from core.hashing import compute_hashes, md5_composite, parse_hash_list
from model.declarations import expand_platform_declared_names
from resolve.grouping import group_identical_platforms
from model.profiles import load_emulator_profiles
@@ -1726,12 +1726,12 @@ class TestE2E(unittest.TestCase):
self.assertIsNone(path)
self.assertEqual(status, "not_found")
def test_106_parse_md5_list(self):
"""parse_md5_list normalizes comma-separated MD5s."""
self.assertEqual(parse_md5_list(""), [])
self.assertEqual(parse_md5_list("ABC123"), ["abc123"])
self.assertEqual(parse_md5_list("abc, DEF , ghi"), ["abc", "def", "ghi"])
self.assertEqual(parse_md5_list(",,,"), [])
def test_106_parse_hash_list(self):
"""parse_hash_list normalizes comma-separated MD5s."""
self.assertEqual(parse_hash_list(""), [])
self.assertEqual(parse_hash_list("ABC123"), ["abc123"])
self.assertEqual(parse_hash_list("abc, DEF , ghi"), ["abc", "def", "ghi"])
self.assertEqual(parse_hash_list(",,,"), [])
def test_107filter_files_by_mode(self):
"""filter_files_by_mode filters standalone/libretro correctly."""
+2 -3
View File
@@ -1937,10 +1937,9 @@ class RecalboxPatchesAttributesNotElements(unittest.TestCase):
self.assertEqual(_stated('<bios path="a" md5="B,,a, " />')["md5"], "a,b")
def test_retrodeck_compares_md5_lists_as_sets(self):
from resolve.reconcile import hash_values
from core.hashing import parse_hash_list
self.assertEqual(set(hash_values({"md5": ["A", "b"]}, "md5")),
set(hash_values({"md5": "b, a"}, "md5")))
self.assertEqual(set(parse_hash_list(["A", "b"])), set(parse_hash_list("b, a")))
def test_one_attribute_changes_in_place(self):
from exporter.recalbox_exporter import patch_element
+17 -2
View File
@@ -93,8 +93,18 @@ class TheSiteReadsAHashFieldTheResolversWay(unittest.TestCase):
("0xDEADBEEF", ["deadbeef"]), (12345678, ["12345678"]),
):
with self.subTest(raw=raw):
self.assertEqual(lookup.sorted_hash_values(raw), expected)
self.assertEqual(lookup.sorted_hash_values(raw), sorted(hashing.parse_hash_list(raw)))
pairs = lookup.hash_pairs({"md5": raw})
self.assertEqual([value for _algo, value in pairs], expected)
self.assertEqual({algo for algo, _value in pairs}, {"md5"} if expected else set())
def test_algorithms_keep_the_order_given(self):
from sitegen import lookup
entry = {"crc32": "0xAB", "sha1": "b, a", "md5": ""}
self.assertEqual(lookup.hash_pairs(entry),
[("sha1", "a"), ("sha1", "b"), ("crc32", "ab")])
self.assertEqual(lookup.hash_pairs(entry, ("crc32", "sha1")),
[("crc32", "ab"), ("sha1", "a"), ("sha1", "b")])
@@ -106,6 +116,11 @@ class DeclaredHashes(unittest.TestCase):
self.assertFalse(hashing.lists_hashes({"sha1": " , "}))
self.assertTrue(hashing.lists_hashes({"crc32": "1234abcd"}))
def test_lists_keep_the_written_order(self):
entry = {"crc32": "0xAB", "md5": "B, a, b", "sha1": ""}
self.assertEqual(hashing.declared_hash_lists(entry), {"md5": ["b", "a"], "crc32": ["ab"]})
self.assertEqual(list(hashing.declared_hash_lists(entry, ("crc32", "md5"))), ["crc32", "md5"])
if __name__ == "__main__":
unittest.main()
+2 -1
View File
@@ -51,6 +51,7 @@ class AnUntestedRowNamesBothHashes(unittest.TestCase):
nor the one the collection holds."""
def test_declared_and_held(self):
from core.hashing import declared_hash_lists
from sitegen import gaps
path = "bios/Nintendo/Nintendo DS/dsifirmware.bin"
@@ -59,7 +60,7 @@ class AnUntestedRowNamesBothHashes(unittest.TestCase):
problem = {
"platform": "RetroDECK", "name": "dsifirmware.bin", "status": "untested",
"required": True, "reason": "declared hash contradicted by the local file",
"declared": gaps._declared_hashes(entry), "path": path,
"declared": declared_hash_lists(entry), "path": path,
}
db = {"files": {"f" * 40: {"path": path, "sha256": held}}}
table = "\n".join(gaps._render_problem_files([problem], db=db))
+5 -5
View File
@@ -74,7 +74,7 @@ from model import systemnames
from model.registry import list_registered_platforms, list_release_pack_platforms
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from resolve.reconcile import HASH_FIELDS, hash_values
from core.hashing import HASH_FIELDS, parse_hash_list
from resolve.categories import EntryCategories
from sitegen.sources import launcher_ref_markdown, list_source
import check_platform_folder
@@ -91,10 +91,10 @@ DIST = REPO_ROOT / "website" / "dist"
def _accepted(profile_entry: dict) -> set[str]:
values = {v for f in HASH_FIELDS for v in hash_values(profile_entry, f)}
values = {v for f in HASH_FIELDS for v in parse_hash_list(profile_entry.get(f))}
for member in profile_entry.get("contents") or []:
if isinstance(member, dict):
values |= {v for f in HASH_FIELDS for v in hash_values(member, f)}
values |= {v for f in HASH_FIELDS for v in parse_hash_list(member.get(f))}
return values
@@ -125,11 +125,11 @@ class ReaderMatchedByHash(unittest.TestCase):
cats = EntryCategories(config, self.profiles)
for sys_id, system in (config.get("systems") or {}).items():
for entry in system.get("files") or []:
md5s = set(hash_values(entry, "md5")) | set(hash_values(entry, "alt_md5"))
md5s = set(parse_hash_list(entry.get("md5"))) | set(parse_hash_list(entry.get("alt_md5")))
if not md5s:
continue
# The same dump, named by whichever hash both sides state.
declared = md5s | {v for f in HASH_FIELDS for v in hash_values(entry, f)}
declared = md5s | {v for f in HASH_FIELDS for v in parse_hash_list(entry.get(f))}
found = cats.explain(entry, entry.get("destination") or entry["name"], sys_id)
for reader in found.get("read_by", []):
if reader["emulator"] == "launcher":