diff --git a/scripts/model/retired.py b/scripts/model/retired.py index a6ba0a252..ec66fec39 100644 --- a/scripts/model/retired.py +++ b/scripts/model/retired.py @@ -21,6 +21,7 @@ from pathlib import Path from core.artifacts import write_if_changed from core.paths import REPO_ROOT +from model.database import sha1_at RETIRED_FILE = REPO_ROOT / "retired.json" @@ -34,14 +35,15 @@ def retired_path(database: str | Path) -> Path: return Path(database).with_name("retired.json") -def _successor(entry: dict, by_path: dict[str, str], +def _successor(entry: dict, new: dict, by_name: dict[str, list[tuple[str, str]]]) -> str | None: """The sha1 the new database holds at the entry's path, else under its name in the same folder, else the one file of that name: a2diskiing.zip was rebuilt from its recipe and filed under Apple II the same day.""" path = str(entry.get("path", "")) - if path in by_path: - return by_path[path] + held = sha1_at(new, path) + if held: + return held named = by_name.get(str(entry.get("name", "")), []) folder = path.rsplit("/", 1)[0] beside = [sha1 for sha1, other in named if other.rsplit("/", 1)[0] == folder] @@ -55,7 +57,6 @@ def retired_between(old: dict, new: dict, day: str) -> dict[str, dict]: """sha1 -> record, for each file of *old* that *new* no longer holds.""" old_files = old.get("files") or {} new_files = new.get("files") or {} - by_path = {str(e.get("path", "")): sha1 for sha1, e in new_files.items()} by_name: dict[str, list[tuple[str, str]]] = {} for sha1, e in new_files.items(): by_name.setdefault(str(e.get("name", "")), []).append((sha1, str(e.get("path", "")))) @@ -64,7 +65,7 @@ def retired_between(old: dict, new: dict, day: str) -> dict[str, dict]: entry = old_files[sha1] record = {key: entry[key] for key in KEPT_FIELDS if entry.get(key) not in (None, "")} record["left"] = day - successor = _successor(entry, by_path, by_name) + successor = _successor(entry, new, by_name) if successor: record["successor"] = successor records[sha1] = record diff --git a/scripts/packs/crossref.py b/scripts/packs/crossref.py index a5b5f4ba2..f40ad2df3 100644 --- a/scripts/packs/crossref.py +++ b/scripts/packs/crossref.py @@ -15,7 +15,7 @@ from typing import TYPE_CHECKING, TypedDict 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.database import get_mame_clone_map, sha1_at from model.profiles import lists_files from model.declarations import OUTER_ROOTS from model.platforms import load_platform_config @@ -450,12 +450,6 @@ class FileConsumers: str(REPO_ROOT / PLATFORMS_DIR) ) ) - self._sha1_by_path = { - path: sha1 - for sha1, entry in db.get("files", {}).items() - for path in {entry.get("path", ""), *entry.get("paths", [])} - if path - } self.platforms: dict[str, set[str]] = {} # Under which of its systems each platform declares a file, so a # link can land on that section rather than the page top. @@ -495,7 +489,7 @@ class FileConsumers: entry.get("zipped_file") and inner_rom_check(entry, path) == "ok" ): return None - return self._sha1_by_path.get(path) + return sha1_at(self._db, path) def add_platforms(self, configs: dict[str, dict]) -> None: for name, config in configs.items(): @@ -537,7 +531,7 @@ class FileConsumers: def sha1_at(self, path: str) -> str | None: """The file the database records at a collection path.""" - return self._sha1_by_path.get(path) + return sha1_at(self._db, path) def path_of(self, sha1: str) -> str: """The collection path the database records for a file.""" diff --git a/scripts/release/sync.py b/scripts/release/sync.py index aea9e55b3..92faec923 100644 --- a/scripts/release/sync.py +++ b/scripts/release/sync.py @@ -10,6 +10,7 @@ from dataclasses import dataclass from pathlib import Path from core.hashing import file_digest +from model.database import sha1_at from model.largefiles import LARGE_FILES_RELEASE, LARGE_FILES_REPO, asset_names, registered_paths from release.assets import compare, expected_assets, expected_digests, fetch_release @@ -27,14 +28,6 @@ class Upload: reason: str = "" -def database_sha1(db: dict) -> dict[str, str]: - return { - entry["path"]: str(entry.get("sha1") or key).lower() - for key, entry in db.get("files", {}).items() - if entry.get("path") - } - - def plan_uploads( root: Path, db: dict, @@ -45,7 +38,6 @@ def plan_uploads( """Each out-of-date asset, cleared for upload or refused with its reason.""" names = asset_names([*registered_paths(gitignore_text), *expected_assets(db, gitignore_text)]) - recorded = database_sha1(db) plans = [] for kind, path, _size, _published in findings: if kind not in OUT_OF_DATE: @@ -58,10 +50,10 @@ def plan_uploads( if first != second: plans.append(Upload(path, names[path], kind, "refused", f"two reads disagree ({first[:12]} != {second[:12]})")) - elif first != recorded.get(path): + elif first != sha1_at(db, path): plans.append(Upload(path, names[path], kind, "refused", f"sha1 {first[:12]} is not the database's " - f"{str(recorded.get(path))[:12]}")) + f"{str(sha1_at(db, path))[:12]}")) else: plans.append(Upload(path, names[path], kind, "upload")) return plans diff --git a/scripts/sitegen/apiitems.py b/scripts/sitegen/apiitems.py index 76e062f3f..ca9505ba2 100644 --- a/scripts/sitegen/apiitems.py +++ b/scripts/sitegen/apiitems.py @@ -6,16 +6,13 @@ import urllib.parse from collections.abc import Callable from model.collection import group_by_manufacturer, manufacturer_slug +from model.database import sha1_at from model.systemnames import system_name from sitegen.config import SITE_URL from sitegen.lookup import sorted_hash_values, site_path from sitegen.render import console_href -def sha1_index_by_path(db: dict | None) -> dict[str, str]: - return {str(e.get("path", "")): sha1 for sha1, e in ((db or {}).get("files") or {}).items()} - - def system_index_items(db: dict, coverages: dict, profiles: dict) -> list[dict]: """Each system id the platforms and profiles write, reachable by that id. @@ -28,14 +25,13 @@ def system_index_items(db: dict, coverages: dict, profiles: dict) -> list[dict]: """ from sitegen.render import card_page, system_ids, system_section - sha1_by_path = sha1_index_by_path(db) files = db.get("files") or {} by_md5 = (db.get("indexes") or {}).get("by_md5") or {} held: dict[str, set[str]] = {} for coverage in coverages.values(): for detail in coverage.get("details") or []: path = str(detail.get("path") or "") - sha1 = sha1_by_path.get(path) if detail.get("status") != "missing" else None + sha1 = sha1_at(db, path) if detail.get("status") != "missing" else None if sha1: held.setdefault(str(detail.get("system", "")), set()).add(sha1) for profile in profiles.values(): diff --git a/scripts/sitegen/dataexports.py b/scripts/sitegen/dataexports.py index 1dfbc31ae..4acfc9d78 100644 --- a/scripts/sitegen/dataexports.py +++ b/scripts/sitegen/dataexports.py @@ -16,10 +16,11 @@ from pathlib import Path from core.artifacts import json_text as _json_text from core.hashing import file_digest from model import retired as model_retired +from model.database import sha1_at from model.dumpcatalog import load_provenance_snapshots from packs.crossref import FileConsumers from acquire.provenance import build_report -from sitegen.apiitems import sha1_index_by_path, core_index_items, system_index_items +from sitegen.apiitems import core_index_items, system_index_items from sitegen.config import DATA_LICENSE, REPO_URL, build_commit, data_timestamp from core.paths import REPO_ROOT from sitegen.install import release_pack_platforms @@ -91,7 +92,7 @@ def _csv_document(fieldnames: list[str], rows: list[dict]) -> str: def _verify_outcomes( - coverage: dict, sha1_by_path: dict[str, str] + coverage: dict, db: dict ) -> Callable[[str, str], dict]: """For each declared entry, in declaration order: what verify found. @@ -114,7 +115,7 @@ def _verify_outcomes( "status": detail.get("status", ""), "category": detail.get("category", ""), "collection_path": path, - "resolved_sha1": sha1_by_path.get(path, "") if path else "", + "resolved_sha1": sha1_at(db, path) or "", } return outcome @@ -180,10 +181,9 @@ def _platform_export_rows( """Normalized platform summaries and one row per declared file.""" items: list[dict] = [] file_rows: list[dict] = [] - sha1_by_path = sha1_index_by_path(db) for key, coverage in sorted(coverages.items()): config = coverage["config"] - outcome = _verify_outcomes(coverage, sha1_by_path) + outcome = _verify_outcomes(coverage, db or {}) contract, registry = _split_contract(config) items.append({ "id": key, @@ -302,7 +302,7 @@ def _gap_export_rows( A `layer` column keeps the two apart instead of publishing only one. """ rows: list[dict] = [] - sha1_by_path = sha1_index_by_path(db) + db = db or {} for key, coverage in sorted(coverages.items()): for detail in coverage.get("details", []): if detail.get("status") == "ok" and not detail.get("discrepancy"): @@ -311,7 +311,7 @@ def _gap_export_rows( rows.append({ "category": detail.get("category", "bios"), "collection_path": path, - "resolved_sha1": sha1_by_path.get(path, "") if path else "", + "resolved_sha1": sha1_at(db, path) or "", "layer": "platform", "platform_id": key, "platform": coverage["platform"], diff --git a/scripts/sitegen/platformfiles.py b/scripts/sitegen/platformfiles.py index c740b662f..284e224c1 100644 --- a/scripts/sitegen/platformfiles.py +++ b/scripts/sitegen/platformfiles.py @@ -10,6 +10,7 @@ import urllib.parse from model import siteinputs from model.collection import profiles_in, profiles_on_disk +from model.database import load_database, sha1_at from model.profiles import upstream_profile_index from model.systemnames import system_name from sitegen import entries as siteentries, markup @@ -38,16 +39,14 @@ from sitegen.render import ( ) -def _collection_sha1_by_path() -> dict[str, str]: - """The sha1 of each file the collection holds, by its path.""" - return _sha1_by_path_in(str(siteinputs.current().db)) +def _collection_sha1(path: str) -> str: + """The sha1 of the file the collection holds at a path.""" + return sha1_at(_collection_db(str(siteinputs.current().db)), path) or "" @functools.cache -def _sha1_by_path_in(db_path: str) -> dict[str, str]: - with open(db_path, encoding="utf-8") as handle: - files = json.load(handle).get("files", {}) - return {str(entry.get("path", "")): sha1 for sha1, entry in files.items()} +def _collection_db(db_path: str) -> dict: + return load_database(db_path) def _system_heading_link(sys_id: str, prefix: str = "") -> str: @@ -96,7 +95,7 @@ def _served_line(f: dict, declared_sha1: str = "") -> str: if not path: # A slot the pack fills from a release asset or leaves to the user. return "" - sha1 = _collection_sha1_by_path().get(path, "") + sha1 = _collection_sha1(path) label = "Served by" if f.get("status") == "ok" else "Held, not the declared hash" parts = path.split("/") if not sha1 or len(parts) < 3 or parts[0] != "bios": diff --git a/tests/test_site_inputs.py b/tests/test_site_inputs.py index 98d2b8d1c..6b10232b2 100644 --- a/tests/test_site_inputs.py +++ b/tests/test_site_inputs.py @@ -53,7 +53,7 @@ class TheGivenDatabase(_Inputs): def test_paths_are_read_from_the_given_collection(self) -> None: self.use(db=self.db) - self.assertEqual(platformfiles._collection_sha1_by_path(), {"bios/X/only-here.bin": SHA1}) + self.assertEqual(platformfiles._collection_sha1("bios/X/only-here.bin"), SHA1) class TheGivenProfilesAndPlatforms(_Inputs): diff --git a/tests/test_site_reference.py b/tests/test_site_reference.py index 9aa09edeb..bcfef96d0 100644 --- a/tests/test_site_reference.py +++ b/tests/test_site_reference.py @@ -52,6 +52,7 @@ import zipfile import runpy import urllib.error +from model import siteinputs from sitegen import apiitems from sitegen import cards from sitegen import config as sitegen_config @@ -227,8 +228,9 @@ class EvidenceLinksItsSource(unittest.TestCase): class EachEntryNamesItsFile(unittest.TestCase): def test_served_held_and_missing(self): path, digest = next( - (p, d) for p, d in platformfiles._collection_sha1_by_path().items() - if p.startswith("bios/") and p.count("/") >= 3) + (entry["path"], d) + for d, entry in platformfiles._collection_db(str(siteinputs.current().db))["files"].items() + if entry["path"].startswith("bios/") and entry["path"].count("/") >= 3) served = platformfiles._served_line({"status": "ok", "path": path}) self.assertRegex(served, rf"\]\(\.\./systems/[^)]+\.md#sha1-{digest[:12]}\)") self.assertTrue(served.startswith("Served by: ")) @@ -386,7 +388,7 @@ class UpstreamsGrouped(unittest.TestCase): class ExportsComplete(unittest.TestCase): def test_gap_rows_once_with_their_outcome(self): - path = next(iter(platformfiles._collection_sha1_by_path())) + path = next(iter(platformfiles._collection_db(str(siteinputs.current().db))["files"].values()))["path"] detail = {"name": "x.bin", "system": "s", "status": "untested", "path": path, "category": "bios"} coverages = {"p": {"platform": "P", "details": [ @@ -397,9 +399,17 @@ class ExportsComplete(unittest.TestCase): self.assertEqual([r["name"] for r in rows], ["h.xml", "x.bin"]) held = rows[1] self.assertEqual(held["collection_path"], path) - self.assertEqual(held["resolved_sha1"], platformfiles._collection_sha1_by_path()[path]) + self.assertEqual(held["resolved_sha1"], platformfiles._collection_sha1(path)) self.assertEqual(held["category"], "bios") + def test_a_path_spelled_another_way_keeps_its_sha1(self): + """The export matched the raw string: bios/./x lost its sha1.""" + db = {"files": {"a" * 40: {"path": "bios/X/x.bin"}}} + coverages = {"p": {"platform": "P", "details": [ + {"name": "x.bin", "system": "s", "status": "untested", "path": "bios/./X/x.bin"}]}} + rows = dataexports._gap_export_rows(coverages, {}, db) + self.assertEqual(rows[0]["resolved_sha1"], "a" * 40) + def test_platform_rows_carry_status_and_file(self): db = json.loads((REPO_ROOT / "database.json").read_text(encoding="utf-8")) sha1, entry = next(iter(db["files"].items()))