refactor: look up a path's sha1 with sha1_at

This commit is contained in:
Abdessamad Derraz committed 2026-11-21 05:59:51 +01:00
1 parent 82d3f595de
commit 8fdc00e07f
8 files changed
+43 -51

No files matched your search

+6 -5
View File
@@ -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
+3 -9
View File
@@ -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."""
+3 -11
View File
@@ -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
+2 -6
View File
@@ -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():
+7 -7
View File
@@ -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"],
+7 -8
View File
@@ -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":