chore: merge the wanted files page

This commit is contained in:
Abdessamad Derraz committed 2026-11-13 12:26:49 +01:00
commit c4f746e2d5
18 files changed
+1409 -170

No files matched your search

+3
View File
@@ -4,6 +4,9 @@
Have a file the collection lacks? Add it from the browser. It is checked on arrival.
Not sure? Drop it on [the wanted page](https://abdess.github.io/retrobios/wanted/). It reads the file on
your device, says if it is wanted, and opens the upload in the right folder.
[Upload it into `bios/`](https://github.com/Abdess/retrobios/upload/main/bios), 25 MB at most per file. GitHub
writes it to a fork and opens the pull request.
-12
View File
@@ -378,7 +378,6 @@ scripts/generate_site.py:0: error: Argument 5 to "_card_index" has incompatible
scripts/generate_site.py:0: error: Expected iterable as variadic argument [misc]
scripts/generate_site.py:0: error: Generator has incompatible item type "int"; expected "bool" [misc]
scripts/generate_site.py:0: error: Incompatible types in assignment (expression has type "Any | None", target has type "str") [assignment]
scripts/generate_site.py:0: error: Incompatible types in assignment (expression has type "dict[Any, Any]", variable has type "int") [assignment]
scripts/generate_site.py:0: error: Incompatible types in assignment (expression has type "dict[str, set[str]]", variable has type "set[str]") [assignment]
scripts/generate_site.py:0: error: Incompatible types in assignment (expression has type "dict[str, str]", variable has type "dict[str, tuple[str, dict[str, list[Any]]]]") [assignment]
scripts/generate_site.py:0: error: Incompatible types in assignment (expression has type "list[dict[str, Sequence[str]]]", target has type "str") [assignment]
@@ -408,15 +407,6 @@ scripts/generate_site.py:0: error: No overload variant of "__getitem__" of "list
scripts/generate_site.py:0: error: No overload variant of "get" of "dict" matches argument type "str" [call-overload]
scripts/generate_site.py:0: error: Unpacking a string is disallowed [str-unpack]
scripts/generate_site.py:0: error: Value of type "Match[str] | None" is not indexable [index]
scripts/generate_site.py:0: error: Value of type "int" is not indexable [index]
scripts/generate_site.py:0: error: Value of type "int" is not indexable [index]
scripts/generate_site.py:0: error: Value of type "int" is not indexable [index]
scripts/generate_site.py:0: error: Value of type "int" is not indexable [index]
scripts/generate_site.py:0: error: Value of type "int" is not indexable [index]
scripts/generate_site.py:0: error: Value of type "int" is not indexable [index]
scripts/generate_site.py:0: error: Value of type "int" is not indexable [index]
scripts/generate_site.py:0: error: Value of type "int" is not indexable [index]
scripts/generate_site.py:0: error: Value of type "int" is not indexable [index]
scripts/generate_site.py:0: error: Value of type "object" is not indexable [index]
scripts/hashing.py:0: error: No overload variant of "open" matches argument types "object", "str" [call-overload]
scripts/launchers.py:0: error: Argument 1 to "len" has incompatible type "list[str] | None"; expected "Sized" [arg-type]
@@ -879,9 +869,7 @@ scripts/validate_pr.py:0: error: "_MutuallyExclusiveGroup" has no attribute "app
scripts/validate_pr.py:0: error: "add" of "set" does not return a value (it only ever returns None) [func-returns-value]
scripts/validate_pr.py:0: error: Argument 1 to "_note_sizes" has incompatible type "Collection[Any]"; expected "dict[str, list[Any]]" [arg-type]
scripts/validate_pr.py:0: error: Incompatible types in assignment (expression has type "list[Never]", variable has type "_MutuallyExclusiveGroup") [assignment]
scripts/validate_pr.py:0: error: Incompatible types in assignment (expression has type "set[Any]", variable has type "list[Any]") [assignment]
scripts/validate_pr.py:0: error: Need type annotation for "checks" (hint: "checks: list[<type>] = ...") [var-annotated]
scripts/validate_pr.py:0: error: Need type annotation for "expected" [var-annotated]
scripts/validate_pr.py:0: error: Need type annotation for "known" [var-annotated]
scripts/validate_schemas.py:0: error: "object" has no attribute "get" [attr-defined]
scripts/validate_schemas.py:0: error: "object" has no attribute "get" [attr-defined]
+3
View File
@@ -856,6 +856,9 @@ def contributing_text(
Have a file the collection lacks? Add it from the browser. It is checked on arrival.
Not sure? Drop it on [the wanted page]({link("wanted")}). It reads the file on
your device, says if it is wanted, and opens the upload in the right folder.
[Upload it into `bios/`]({UPLOAD_URL}), 25 MB at most per file. GitHub
writes it to a fork and opens the pull request.
+41 -24
View File
@@ -130,6 +130,8 @@ import release_record
import sitebootstrap
import sitehandheld
import sitemeasurements
import sitewanted
from validate_pr import load_platform_hashes, load_profile_hashes
# The Starlight project, and where its pages go inside it.
STARLIGHT_DIR = "website"
@@ -2536,6 +2538,7 @@ def _page_description(markdown: str, relative: Path, title: str) -> str:
"explore.md": "Systems, emulators and installer options to explore, with the figures of the BIOS collection.",
"which-pack.md": "Pick a device or setup and get its BIOS files: the folder they go in, one command that installs and checks them, or a ZIP pack to extract.",
"contributing.md": "Add a BIOS file the collection lacks from the browser, checked on arrival, or add a platform or an emulator profile.",
"wanted.md": "Drop files on the page to learn if the collection wants them, then upload a wanted one to its folder on GitHub. Files are read on your device.",
}
if key in specific:
return specific[key]
@@ -3237,7 +3240,7 @@ def page_level(relative: Path) -> str:
return "explore"
if path in _REFERENCE_PAGES:
return "reference"
if path == "contributing.md":
if path in ("contributing.md", "wanted.md"):
return "contribute"
return ""
@@ -4884,6 +4887,8 @@ def generate_files_page() -> str:
"`scph5501.bin`, the PlayStation BIOS v3.0. "
"To look a file up by its name, use the search at the top of the page.",
"",
"Have a file the collection lacks? [See if it is wanted](../wanted.md).",
"",
"## Permanent links",
"",
"A file's card lives on its manufacturer's page, and a file refiled "
@@ -10924,24 +10929,12 @@ def _ratio_cell(done: int, total: int, alarm: int = 0) -> str:
# GitHub's upload page for a folder of bios/: a browser upload by someone
# without write access lands on a fork and opens a pull request.
UPLOAD_URL = f"{REPO_URL}/upload/main/bios"
UPLOAD_URL = f"{sitewanted.UPLOAD_ROOT}bios"
# Rows of Files to source on one page: 601 on one page made a phone page
# 274,509 px long.
FILES_TO_SOURCE_PART = 100
def _upload_folder(profile: dict) -> str:
"""The bios/ folder a file the emulator loads is uploaded into: the
console folder of its first system that has one, else none."""
from siterender import _own_section
for sys_id in profile.get("systems") or []:
own = _own_section(str(sys_id))
if own is not None:
return "/".join(own)
return ""
def reading_platforms(emu_name: str, profile: dict, name: str,
configs: dict[str, dict]) -> set[str]:
"""Of the platforms running an emulator (name -> config), those whose
@@ -10967,9 +10960,13 @@ def generate_gap_analysis(
gap_report: dict | None = None,
moved: dict[str, str] | None = None,
catalogued: dict | None = None,
placer: sitewanted.Placer | None = None,
) -> str:
"""Generate a unified gap analysis page.
``placer`` gives each file to source the folder its upload goes to,
the one validate_pr asks for. Without it the link opens bios/.
``catalogued`` is a provenance report built with the profiles' needs:
a file the collection does not hold yet names the catalog or romset
that lists it.
@@ -11044,7 +11041,8 @@ def generate_gap_analysis(
"",
"Each file here is a request: for a file under \"Files to source\", "
"[adding it](contributing.md) fills the gap for "
"every platform at once.",
"every platform at once. Have some of these? [Drop them on the wanted "
"page](wanted.md): it says which ones are wanted and where each goes.",
"",
" ".join([
markup.button("Download gaps CSV", "downloads/gaps.csv"),
@@ -11265,10 +11263,10 @@ def generate_gap_analysis(
for emu_name, data in sorted(emulator_gaps, key=lambda x: -x[1]["gaps"]):
display = data["emulator"]
sources = _gap_sources(data)
m = sources["missing"]
to_source = sources["missing"]
missing_str = (
f'<span class="rb-badge rb-badge-danger">{m}</span>'
if m > 0
f'<span class="rb-badge rb-badge-danger">{to_source}</span>'
if to_source > 0
else '<span class="rb-badge rb-badge-success">0</span>'
)
lines.append(
@@ -11374,14 +11372,17 @@ def generate_gap_analysis(
f"[{_escape_tags(display)}](emulators/{key}.md)"
for display, key in zip(m["emulators"], m["emu_keys"])
)
folder = _upload_folder(profiles[m["emu_keys"][0]])
upload = f"{UPLOAD_URL}/{urllib.parse.quote(folder)}" if folder else UPLOAD_URL
owner = profiles[m["emu_keys"][0]]
declared = sitewanted.gap_entries(owner, m["name"], m["identity"], False)
folder = placer.folder(declared[0]) if placer and declared else ""
upload = sitewanted.upload_href(sitewanted.UPLOAD_ROOT, folder)
rows.append(
f"| `{m['name']}` [Have it? Upload]({upload}) | {destination} | {expected} "
f"| {emulators} | {req} | {plat_badges} | "
f"{_source_ref_markdown(profiles[m['emu_keys'][0]], m['source_ref'])} |"
f"{_source_ref_markdown(owner, m['source_ref'])} |"
)
lines.extend(["### Files to source", "", counted, ""])
lines.extend(["### Files to source", "", counted,
"[The wanted page](wanted.md) recognises the ones with a known hash.", ""])
if moved is None:
lines.extend([*head, *rows, ""])
else:
@@ -12427,7 +12428,7 @@ def generate_nav(
(68, {"Updated platform files": "exports.md"}, "Data"),
(69, {"Measurements": sitemeasurements.EXPLORER_PAGE}, "Data"),
],
"contribute": [(0, "contributing.md")],
"contribute": [(0, "contributing.md"), (5, {"Wanted": "wanted.md"})],
}
wiki = wiki_nav(wiki_dir)
nav = []
@@ -12814,18 +12815,34 @@ def _generate(args: argparse.Namespace) -> None:
provenance_report = build_report(
db, load_provenance_snapshots(), needs=profile_needs(profiles, db))
# Where an upload goes, by validate_pr's own rule: the gaps page and the
# wanted page send a file to the folder the review asks for.
placer = sitewanted.Placer(
db, load_platform_hashes(args.platforms_dir, db),
load_profile_hashes(args.emulators_dir, db),
)
print("Generating gap analysis page...")
gap_pages: dict[str, str] = {}
write_if_changed(
str(docs / "gaps.md"),
tables_out_of_search(generate_gap_analysis(
profiles, coverages, db, suppl_names, registry, gap_report, gap_pages,
catalogued=provenance_report,
catalogued=provenance_report, placer=placer,
)) + reference_next(),
)
for stem, page in gap_pages.items():
write_if_changed(str(docs / f"{stem}.md"), tables_out_of_search(page))
print("Generating the wanted page...")
wanted = sitewanted.build_wanted(
profiles, coverages, gap_report, db, placer, system_name,
sitewanted.load_ledger(archive_build.ARCHIVES_FILE),
)
(public / "data").mkdir(parents=True, exist_ok=True)
write_if_changed(str(public / sitewanted.DATA_FILE),
json.dumps(wanted, ensure_ascii=False, separators=(",", ":")) + "\n")
write_if_changed(str(docs / "wanted.md"), sitewanted.page(len(wanted["entries"])))
print("Generating updated platform files page...")
write_if_changed(
str(docs / "exports.md"),
+1
View File
@@ -28,6 +28,7 @@ COMPONENTS = {
"Tabs": "@astrojs/starlight/components",
"TabItem": "@astrojs/starlight/components",
"FilePicker": "components/FilePicker.astro",
"WantedFiles": "components/WantedFiles.astro",
"MeasurementsExplorer": "components/MeasurementsExplorer.astro",
"InstallDemo": "components/InstallDemo.astro",
}
+344
View File
@@ -0,0 +1,344 @@
"""The files the collection lacks, as the wanted page reads them.
A visitor drops files on wanted/, each is hashed in the browser and
compared with this list. The list is the gaps page's: a file a platform
lists that its own check finds missing or under another hash, a file an
emulator loads that no platform lists and the collection does not hold,
and a file not collected yet. A declaration that names no hash cannot be
recognised by its bytes and is left out.
Each entry keeps the hashes its declaration writes, read as the resolver
reads them (comma lists split, a crc32 counted only where no stronger hash
is declared), and the folder validate_pr.placement() gives those hashes:
the review of the pull request asks for that same folder.
"""
from __future__ import annotations
import urllib.parse
from collections.abc import Callable, Iterable
from pathlib import Path
import archive_build
from common import unique_emulator_profiles
from cross_reference import _first_hash
from hashing import cut_md5_owner, parse_hash_list
from validate_pr import LARGE_FILE_ISSUE_URL, Placement, placement
ALGORITHMS = ("sha1", "sha256", "md5", "crc32")
# GitHub's upload page takes 25 MB per file. A larger file goes in by a
# push or, past 100 MB, through the issue form (CONTRIBUTING.md).
BROWSER_UPLOAD_LIMIT = 25 * 1024 * 1024
# The upload page of a folder is this followed by the folder.
UPLOAD_ROOT = "https://github.com/Abdess/retrobios/upload/main/"
# Under the site's public folder, read by WantedFiles.astro.
DATA_FILE = "data/wanted.json"
def _sizes(entry: dict) -> list[int]:
size = entry.get("size")
values = size if isinstance(size, list) else [size]
return sorted({int(v) for v in values if isinstance(v, int) and not isinstance(v, bool) and v > 0})
def declared_hashes(entry: dict) -> dict[str, list[str]]:
"""The hashes that identify an entry's own bytes, by algorithm.
A zipped_file md5 is the md5 of a ROM inside the archive, not of the
archive, so it says nothing about the file a visitor drops. A crc32
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}
if entry.get("zipped_file"):
hashes["md5"] = []
hashes["md5"] = [v for v in hashes["md5"] if 0 < len(v) <= 32]
hashes["sha1"] = [v for v in hashes["sha1"] if len(v) == 40]
hashes["sha256"] = [v for v in hashes["sha256"] if len(v) == 64]
hashes["crc32"] = [v.zfill(8) for v in hashes["crc32"] if len(v) <= 8]
if hashes["sha1"] or hashes["sha256"] or hashes["md5"]:
hashes["crc32"] = []
return {algo: values for algo, values in hashes.items() if values}
def _alternatives(hashes: dict[str, list[str]]) -> list[dict[str, list[str]]]:
"""One declaration per file it accepts.
A Recalbox entry lists every revision its check takes in one md5 field:
each is a file of its own, with a folder of its own. Values of two
algorithms cannot be paired, so such an entry stays whole.
"""
listed = [algo for algo, values in hashes.items() if len(values) > 1]
if len(hashes) == 1 and listed:
algo = listed[0]
return [{algo: [value]} for value in hashes[algo]]
return [hashes]
class Held:
"""What the collection holds, by every hash a file or an archive
member is known under."""
def __init__(self, db: dict, ledger: Iterable[dict] = ()) -> None:
files = db.get("files", {})
indexes = db.get("indexes", {})
self.sha1 = set(files)
self.md5 = set(indexes.get("by_md5", {}))
self.sha256 = set(indexes.get("by_sha256", {}))
self.crc32: dict[str, set[int]] = {}
for record in files.values():
crc = str(record.get("crc32") or "").lower()
if crc:
self.crc32.setdefault(crc, set()).add(int(record.get("size") or 0))
# A ROM held only inside one of the collection's archives.
for archive in ledger:
for member in archive.get("members") or []:
if member.get("sha1"):
self.sha1.add(str(member["sha1"]).lower())
crc = str(member.get("crc32") or "").lower()
if crc:
self.crc32.setdefault(crc, set()).add(int(member.get("size") or 0))
def holds(self, hashes: dict[str, list[str]], sizes: list[int]) -> bool:
if any(v in self.sha1 for v in hashes.get("sha1", [])):
return True
if any(v in self.sha256 for v in hashes.get("sha256", [])):
return True
for value in hashes.get("md5", []):
if value in self.md5 or (len(value) < 32 and cut_md5_owner(value, self.md5)):
return True
for value in hashes.get("crc32", []):
held = self.crc32.get(value, set())
if held and (not sizes or held & set(sizes)):
return True
return False
def gap_entries(profile: dict, name: str, identity: str, unsourceable: bool) -> list[dict]:
"""The profile entries behind one row of the gap report."""
named = [f for f in profile.get("files") or []
if isinstance(f, dict) and f.get("name") == name]
if unsourceable:
return [f for f in named if f.get("unsourceable")] or named
if identity:
return [f for f in named if _first_hash(f) == identity] or named
return named
def wanted_declarations(profiles: dict, coverages: dict, gap_report: dict) -> list[dict]:
"""Every declaration of a file the gaps page reports as lacking.
Each is {name, system, required, reader: (kind, key, label), entry}.
"""
found: list[dict] = []
for key, coverage in sorted(coverages.items()):
systems = coverage.get("config", {}).get("systems") or {}
for detail in coverage.get("details", []):
if detail.get("settled_by") or detail.get("status") not in ("missing", "untested"):
continue
system = detail.get("system", "")
for entry in (systems.get(system) or {}).get("files") or []:
if isinstance(entry, dict) and entry.get("name") == detail.get("name"):
found.append({
"name": str(entry["name"]), "system": system,
"required": bool(detail.get("required", True)),
"reader": ("platform", key, coverage["platform"]), "entry": entry,
})
unique = unique_emulator_profiles(profiles)
for key, data in sorted(gap_report.items()):
profile = unique.get(key)
if profile is None:
continue
systems = [str(s) for s in data.get("systems") or profile.get("systems") or []]
rows = [(gap, False) for gap in data.get("gap_details") or []
if gap.get("source") == "missing" and not gap.get("bundled")]
rows += [(row, True) for row in data.get("unsourceable") or []]
for row, unsourceable in rows:
for entry in gap_entries(profile, str(row.get("name", "")),
str(row.get("identity") or ""), unsourceable):
system = entry.get("system") or (systems[0] if len(systems) == 1 else "")
found.append({
"name": str(entry["name"]), "system": str(system),
"required": bool(row.get("required", False)),
"reader": ("emulator", key, str(data.get("emulator", key))), "entry": entry,
})
return found
def _settle_cut(records: list[dict]) -> None:
"""A cut md5 names a dump only if exactly one md5 starts with it.
Matched against the wanted md5s: one of them, and the cut is that md5;
several, and it names none; none, and the page compares by prefix.
"""
full = {v for r in records for v in r["hashes"].get("md5", []) if len(v) == 32}
for record in records:
kept = []
for value in record["hashes"].get("md5", []):
if len(value) == 32:
kept.append(value)
continue
starting = {md5 for md5 in full if md5.startswith(value)}
if len(starting) == 1:
kept.append(starting.pop())
elif not starting:
kept.append(value)
if kept:
record["hashes"]["md5"] = sorted(set(kept))
else:
record["hashes"].pop("md5", None)
class Placer:
"""validate_pr's placement for a declaration: its declared hashes,
strongest first, and its name.
The database stands in for the disk validate_pr reads: the site is
built from a checkout whose release assets are not on disk.
"""
def __init__(self, db: dict, platform_hashes: dict, profile_hashes: dict) -> None:
self.db = db
self.platform_hashes = platform_hashes
self.profile_hashes = profile_hashes
self.paths = {
path for record in db.get("files", {}).values()
for path in [record.get("path"), *(record.get("paths") or [])] if path
}
def place(self, hashes: dict[str, list[str]], name: str) -> Placement:
values = [value for algo in ("sha1", "md5", "sha256") for value in hashes.get(algo, [])
if len(value) == FULL_LENGTH[algo]]
return placement(values, name, self.db, self.platform_hashes, self.profile_hashes,
declared=True, exists=self.paths.__contains__)
def folder(self, entry: dict) -> str:
"""The folder an upload of a profile or platform entry goes to."""
return self.place(declared_hashes(entry), str(entry.get("name", ""))).folder
FULL_LENGTH = {"sha1": 40, "md5": 32, "sha256": 64}
def upload_href(root: str, folder: str) -> str:
"""GitHub's upload page for a folder of the repository, bios/ when the
placement names none."""
return root + urllib.parse.quote((folder or "bios/").rstrip("/"))
def build_wanted(
profiles: dict,
coverages: dict,
gap_report: dict,
db: dict,
placer: Placer,
system_name: Callable[[str], str],
ledger: Iterable[dict] = (),
) -> dict:
"""The wanted list, compact, as public/data/wanted.json carries it.
Readers, systems and folders are written once and named by position.
An entry: n name, h hashes, w readers, s systems, r required, z sizes,
f folder, t the name it is uploaded under, v that name goes to the
folder's .variants/ with the first 8 characters of its sha1.
"""
held = Held(db, ledger)
records: dict[tuple, dict] = {}
for declaration in wanted_declarations(profiles, coverages, gap_report):
entry = declaration["entry"]
sizes = _sizes(entry)
for hashes in _alternatives(declared_hashes(entry)):
if held.holds(hashes, sizes):
continue
key = (declaration["name"], tuple(sorted((a, tuple(v)) for a, v in hashes.items())),
tuple(sizes))
record = records.setdefault(key, {
"name": declaration["name"], "hashes": {a: list(v) for a, v in hashes.items()},
"sizes": sizes, "systems": set(), "required": False, "readers": set(),
})
if declaration["system"]:
record["systems"].add(declaration["system"])
record["required"] = record["required"] or declaration["required"]
record["readers"].add(declaration["reader"])
ordered = sorted(records.values(), key=lambda r: (r["name"].casefold(), sorted(r["readers"])))
_settle_cut(ordered)
ordered = [r for r in ordered if r["hashes"]]
readers = sorted({reader for r in ordered for reader in r["readers"]},
key=lambda reader: (reader[0], reader[2].casefold(), reader[1]))
reader_at = {reader: i for i, reader in enumerate(readers)}
folders: list[str] = []
folder_at: dict[str, int] = {}
titles: dict[str, str] = {}
entries = []
for record in ordered:
spot = placer.place(record["hashes"], record["name"])
if spot.folder and spot.folder not in folder_at:
folder_at[spot.folder] = len(folders)
folders.append(spot.folder)
systems = sorted({titles.setdefault(s, system_name(s)) for s in record["systems"]})
item: dict = {
"n": record["name"],
"h": {algo: record["hashes"][algo] for algo in ALGORITHMS if algo in record["hashes"]},
"w": sorted(reader_at[reader] for reader in record["readers"]),
}
if systems:
item["s"] = ", ".join(systems)
if record["required"]:
item["r"] = 1
if record["sizes"]:
item["z"] = record["sizes"]
if spot.folder:
item["f"] = folder_at[spot.folder]
if spot.name:
item["t"] = spot.name
if spot.variant:
item["v"] = 1
entries.append(item)
return {
"upload": UPLOAD_ROOT,
"issue": LARGE_FILE_ISSUE_URL,
"limit": BROWSER_UPLOAD_LIMIT,
"readers": [[kind[0], key, label] for kind, key, label in readers],
"folders": folders,
"entries": entries,
}
def load_ledger(path: Path) -> list[dict]:
"""The archive records of recipes/archives.json, empty when absent."""
return list(archive_build.load_ledger(path).values())
def page(known: int) -> str:
"""The wanted page: the drop box, then what happens after an upload.
Held to the Start here budgets (tests/test_site_copy.py): anyone with a
file in hand reads it.
"""
return "\n".join([
"---",
"terms: wanted list, donate, give a file, upload to github, help the collection",
"---",
"",
"# Wanted",
"",
"Have a file the collection lacks? Drop it below. The page says if we want it.",
"",
"<WantedFiles />",
"",
"Your files are read on this device. Nothing is sent until you upload one to GitHub.",
"",
"## After the upload",
"",
"1. The button opens GitHub's upload page in the right folder. Sign in and drop the file there.",
"2. GitHub puts it in your own copy of the project and opens a pull request.",
"3. A check reads the file and says if it fits. Then we add it.",
"",
(f"The page knows {known:,} wanted files by their hash, a fingerprint of the contents. "
"The rest are listed on [the gaps page](gaps.md)."),
"",
("To look up any file, use [Find or check a file](files/index.md). "
"More ways to help are on [Contributing](contributing.md)."),
"",
])
+106 -40
View File
@@ -27,6 +27,8 @@ import subprocess
import sys
import urllib.parse
import zipfile
from collections.abc import Callable, Iterable
from dataclasses import dataclass
from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
@@ -554,18 +556,8 @@ def validate_file(
)
normalized = os.path.normpath(relative)
# A platform's declaration first, then a profile's: most files the gaps
# page lists are declared by a profile alone.
expected = next(
(
table["folders"][value]
for table in (platform_hashes, profile_hashes)
for value in (result.sha1, result.md5, hashes.get("sha256", ""))
if value in table.get("folders", {})
),
set(),
)
expected_folders = sorted(expected)
values = (result.sha1, result.md5, hashes.get("sha256", ""))
expected = expected_folders(values, platform_hashes, profile_hashes)
if too_large:
# The file stays out of the pull request, so no folder of bios/ is
# the contributor's to choose: the release asset is placed by hand.
@@ -578,7 +570,7 @@ def validate_file(
# Depth alone passed a PS1 BIOS filed under bios/Nintendo/Game Boy/.
result.add_warning(
"Placed under " + (here or "the bios/ root") + ", while the other files of "
"its system are in " + " or ".join(f"`{f}`" for f in sorted(expected))
"its system are in " + " or ".join(f"`{f}`" for f in expected)
)
elif len(parts) >= 4:
result.add_check(True, f"Correct placement: bios/{parts[1]}/{parts[2]}/")
@@ -587,35 +579,28 @@ def validate_file(
elif result.outcome == "held" or members is not None:
# Nothing to place: a copy, or an archive whose files go in unzipped.
pass
elif expected_folders:
# The contributor asks before forking: say where it goes.
names = {
name
for table in (platform_hashes, profile_hashes)
for value in (result.sha1, result.md5, hashes.get("sha256", ""))
for name in table.get("named", {}).get(value, ())
}
name = next(iter(names)) if len(names) == 1 else ""
if len(expected_folders) == 1 and name and "/" not in name:
folder = expected_folders[0]
result.destination = (
f"{folder}.variants/{name}.{result.sha1[:8]}"
if os.path.exists(folder + name) else folder + name
)
result.add_warning(
"File is not under bios/ yet. Its system's files are in "
+ " or ".join(f"`{f}`" for f in expected_folders)
+ (f". --place copies it to `{result.destination}`" if result.destination else "")
)
elif _variant_home(db, result.filename, result.sha1):
result.add_warning(
"File is not under bios/ yet. The collection keeps this name in "
f"`{_variant_home(db, result.filename, result.sha1)}`"
)
else:
result.add_warning(
"File is not under bios/ yet. Place it in bios/Manufacturer/Console/"
# The contributor asks before forking: say where it goes.
spot = placement(
values, result.filename, db, platform_hashes, profile_hashes,
declared=bool(sha1_known or md5_known or other_known or accepted_by or by_profile),
)
result.destination = spot.destination(result.sha1)
copies = f". --place copies it to `{result.destination}`" if result.destination else ""
if spot.folders:
result.add_warning(
"File is not under bios/ yet. Its system's files are in "
+ " or ".join(f"`{f}`" for f in spot.folders) + copies
)
elif spot.home:
result.add_warning(
f"File is not under bios/ yet. The collection keeps this name in `{spot.home}`"
+ copies
)
else:
result.add_warning(
"File is not under bios/ yet. Place it in bios/Manufacturer/Console/"
)
declared = [
*platform_hashes.get("sizes", {}).get(result.filename, []),
@@ -671,6 +656,87 @@ def _platforms_accepting(filepath: str, filename: str, platform_hashes: dict) ->
return accepted
def expected_folders(
values: Iterable[str], platform_hashes: dict, profile_hashes: dict | None
) -> list[str]:
"""The bios/<Manufacturer>/<Console>/ folders the files of a hash's
system are in, read from the first of *values* a table knows.
A platform's declaration first, then a profile's: most files the gaps
page lists are declared by a profile alone.
"""
for table in (platform_hashes, profile_hashes or {}):
for value in values:
if value and value in table.get("folders", {}):
return sorted(table["folders"][value])
return []
@dataclass(frozen=True)
class Placement:
"""Where a file not under bios/ yet goes.
``folders`` are those of its system, ``home`` the folder the collection
keeps its name in when its system names none. ``name`` is the name it
is copied under, empty when the declarations do not settle one.
``variant`` says a file of that name is already in the folder: a copy
goes beside it in .variants/, never over it.
"""
folders: tuple[str, ...] = ()
home: str = ""
name: str = ""
variant: bool = False
@property
def folder(self) -> str:
return self.folders[0] if self.folders else self.home
def destination(self, sha1: str) -> str:
if not self.name:
return ""
if self.variant:
return f"{self.folder}.variants/{self.name}.{sha1[:8]}"
return self.folder + self.name
def placement(
values: Iterable[str],
filename: str,
db: dict | None,
platform_hashes: dict,
profile_hashes: dict | None,
declared: bool,
exists: Callable[[str], bool] = os.path.exists,
) -> Placement:
"""Where a file goes, by its hashes and its name.
The review and the site's wanted page both read this one rule, so the
folder a contributor is sent to is the folder the review accepts.
*declared* says a list or a profile declares one of the hashes: a file
known by its name alone gets a slot only once its size fits.
"""
values = [value for value in values if value]
folders = expected_folders(values, platform_hashes, profile_hashes)
if folders:
names = {
name
for table in (platform_hashes, profile_hashes or {})
for value in values
for name in table.get("named", {}).get(value, ())
}
name = next(iter(names)) if len(names) == 1 else ""
if len(folders) == 1 and name and "/" not in name:
return Placement(tuple(folders), name=name, variant=exists(folders[0] + name))
return Placement(tuple(folders))
held = next((value for value in values if value in (db or {}).get("files", {})), "")
home = _variant_home(db, filename, held)
if declared and home and filename and "/" not in filename:
# The folder holds a file of that name already.
return Placement(home=home, name=filename, variant=True)
return Placement(home=home)
def _variant_home(db: dict | None, name: str, held: str = "") -> str:
"""The folder the collection keeps a name in, for its variants beside it.
+96 -13
View File
@@ -43,6 +43,7 @@ WEBSITE = REPO_ROOT / "website"
DIST = WEBSITE / "dist"
COMPONENTS = WEBSITE / "src" / "components"
SITE_TS = WEBSITE / "src" / "scripts" / "site.ts"
HASHES_TS = WEBSITE / "src" / "scripts" / "hashes.ts"
CONFIG = WEBSITE / "astro.config.mjs"
PLUGIN = WEBSITE / "src" / "plugins" / "rehype-stack-tables.mjs"
@@ -188,6 +189,38 @@ class SectionTabsInTheHeader(unittest.TestCase):
self.assertRegex(nav.group(1), r'aria-current="true"[^>]*>\s*Start here')
class TheWantedPageIsInTheBar(unittest.TestCase):
"""The wanted page is the site's call to contribute: in the bar on every
page, beside the search and menu buttons on a phone, where the section
tabs fold into the menu."""
LINK = re.compile(r'<a class="rb-wanted-link[^"]*" href="/retrobios/wanted/"([^>]*)>Wanted files</a>')
def test_the_bar_holds_it_outside_the_tabs(self):
header = _read(COMPONENTS / "Header.astro")
bar = header[header.index('<div class="rb-header-bar">'):header.index("</div>")]
self.assertIn('class="rb-wanted-link print:hidden"', bar)
self.assertIn("aria-current={onWanted ? 'page' : undefined}", bar)
# Theme colours only, the same in both themes' variables.
style = header[header.index(".rb-wanted-link {"):header.index("@media")]
self.assertNotRegex(style, r"#[0-9a-fA-F]{3,6}\b")
# At 360 px the name was cut to "Retr": the logo stays, the name is
# kept for screen readers only.
narrow = header[header.index("@media (max-width: 26.99rem)"):]
self.assertIn(".site-title span {", narrow[:200])
self.assertIn("clip-path: inset(50%);", narrow[:400])
def test_built_on_every_page_current_on_its_own(self):
for page in ("which-pack", "files", "systems"):
with self.subTest(page=page):
found = self.LINK.search(_built(page))
self.assertIsNotNone(found)
self.assertNotIn("aria-current", found.group(1))
own = self.LINK.search(_built("wanted"))
self.assertIsNotNone(own)
self.assertIn('aria-current="page"', own.group(1))
def _title_block(html: str) -> str:
"""What PageTitle draws: from the main column to the h1."""
end = html.index('id="_top"')
@@ -497,26 +530,76 @@ class HashAFileHere(unittest.TestCase):
source = _read(SITE_TS)
self.assertIn("input.type = 'file';", source)
self.assertIn("It is hashed on this device. Nothing is uploaded.", source)
self.assertIn("crypto.subtle.digest(name, buffer)", source)
self.assertIn("['SHA-1', 'SHA-256']", source)
self.assertIn("import { type FileHashes, hashFile } from './hashes.ts';", source)
self.assertIn("lookUp(status, result, [found.sha1, found.md5, found.crc32, found.sha256])", source)
hashing = _read(HASHES_TS)
self.assertIn("crypto.subtle.digest(name, buffer)", hashing)
self.assertIn("['SHA-1', 'SHA-256']", hashing)
def test_md5_and_crc32_match_python(self):
source = _read(SITE_TS)
block = source[source.index("// Hashing a file on this device"):source.index("type FileHashes")]
sizes = [0, 1, 55, 56, 63, 64, 65, 119, 120, 128, 1000, 70_001]
out = _node_module(block + (
f"console.log(JSON.stringify({json.dumps(sizes)}.map((n) => {{"
"const bytes = new Uint8Array(n);"
"for (let i = 0; i < n; i += 1) bytes[i] = (i * 31 + 7) & 0xff;"
"return [md5(bytes), crc32(bytes)]; })));"
class FileHashesMatchPython(unittest.TestCase):
"""MD5 and CRC32 are written here, Web Crypto having neither: each is
checked against hashlib and zlib, whole and fed in uneven slices, and
hashFile's four values against a file read in 4 MiB slices."""
SIZES = [0, 1, 55, 56, 63, 64, 65, 119, 120, 128, 1000, 70_001]
@staticmethod
def _bytes(size: int) -> bytes:
return bytes((i * 31 + 7) & 0xFF for i in range(size))
def _run(self, body: str) -> list:
return json.loads(_node_module(
f"import {{ Crc32, Md5, crc32, hashFile, md5 }} from {json.dumps(HASHES_TS.as_uri())};"
"const fill = (n) => { const b = new Uint8Array(n);"
" for (let i = 0; i < n; i += 1) b[i] = (i * 31 + 7) & 0xff; return b; };" + body
))
for size, (md5, crc) in zip(sizes, json.loads(out)):
data = bytes((i * 31 + 7) & 0xFF for i in range(size))
def test_md5_and_crc32_whole(self):
out = self._run(
f"console.log(JSON.stringify({json.dumps(self.SIZES)}.map((n) => "
"{ const bytes = fill(n); return [md5(bytes), crc32(bytes)]; })));"
)
for size, (md5, crc) in zip(self.SIZES, out):
data = self._bytes(size)
with self.subTest(size=size):
self.assertEqual(md5, hashlib.md5(data).hexdigest())
self.assertEqual(crc, f"{zlib.crc32(data):08x}")
def test_md5_and_crc32_in_slices(self):
"""A slice ending inside a 64-byte block carries it to the next."""
size, steps = 200_003, [1, 63, 64, 65, 3, 1000, 7, 100_000]
out = self._run(
f"const bytes = fill({size}); const steps = {json.dumps(steps)};"
"const m = new Md5(); const c = new Crc32();"
"for (let at = 0, k = 0; at < bytes.length; k += 1) {"
" const piece = bytes.subarray(at, at + steps[k % steps.length]);"
" m.update(piece); c.update(piece); at += piece.length; }"
"console.log(JSON.stringify([m.digest(), c.digest()]));"
)
data = self._bytes(size)
self.assertEqual(out, [hashlib.md5(data).hexdigest(), f"{zlib.crc32(data):08x}"])
def test_hash_file_reads_slices_and_reports_progress(self):
size = 9 * 1024 * 1024 + 17
out = self._run(
f"const shares = []; const found = await hashFile(new Blob([fill({size})]),"
" (share) => shares.push(share));"
"console.log(JSON.stringify([found, shares.length, shares.at(-1),"
" shares.every((v, i) => i === 0 || v >= shares[i - 1])]));"
)
data = self._bytes(size)
found, steps, last, rising = out
self.assertEqual(found, {
"sha1": hashlib.sha1(data).hexdigest(),
"md5": hashlib.md5(data).hexdigest(),
"crc32": f"{zlib.crc32(data):08x}",
"sha256": hashlib.sha256(data).hexdigest(),
})
self.assertGreaterEqual(steps, 3)
self.assertEqual(last, 1)
self.assertTrue(rising)
class SearchFoldsPagesUnderAHash(unittest.TestCase):
"""Under "Look up this hash" came 14 unrelated pages: Magnavox for
+3 -1
View File
@@ -42,6 +42,7 @@ START_PAGES = {
START_LEVEL_PAGES = {
"wiki/measurements.md": 300,
"wiki/archive-recipes.md": 160,
"wanted.md": 160,
}
# Level 1: the guide part of each setup page, above its Reference heading.
SETUP_CEILING = 220
@@ -230,7 +231,8 @@ def parse(markdown: str) -> Page:
flush()
tab = 0
continue
if "rb-button" in stripped or "rb-tile" in stripped or stripped.startswith("<FilePicker"):
if "rb-button" in stripped or "rb-tile" in stripped or stripped.startswith(
("<FilePicker", "<WantedFiles")):
act()
continue
if re.match(r"</?(?!abbr\b|a\b|code\b|strong\b|em\b)[A-Za-z]", stripped):
+13 -4
View File
@@ -55,6 +55,7 @@ REPO_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO_ROOT / "scripts"))
import generate_site # noqa: E402
import sitewanted # noqa: E402
import siterender # noqa: E402
from common import ( # noqa: E402
list_registered_platforms,
@@ -1256,10 +1257,18 @@ class FilesToSourceOnAPhone(unittest.TestCase):
for row in rows:
self.assertIn(f"[Have it? Upload]({generate_site.UPLOAD_URL}", row)
def test_the_upload_lands_in_the_console_folder(self):
with mock.patch("siterender._own_section", return_value=("Sony", "PlayStation")):
self.assertEqual(generate_site._upload_folder({"systems": ["sony-playstation"]}),
"Sony/PlayStation")
def test_the_upload_lands_in_the_folder_the_review_asks_for(self):
"""The link read the profile's first system: Raze's Duke Nukem 3D
files were sent to bios/Monolith/Blood/. It reads validate_pr's
placement now (tests/test_site_wanted.py)."""
held = "a" * 40
db = {"files": {held: {"path": "bios/Sony/PlayStation/scph1001.bin"}},
"indexes": {"by_md5": {}, "by_sha256": {}, "by_name": {}}}
profile_hashes = {"folders": {"b" * 40: {"bios/Sony/PlayStation/"}}, "named": {}}
placer = sitewanted.Placer(db, {}, profile_hashes)
self.assertEqual(placer.folder({"name": "scph5501.bin", "sha1": "b" * 40}),
"bios/Sony/PlayStation/")
self.assertEqual(placer.folder({"name": "x.bin"}), "")
GENERATED = REPO_ROOT / "website" / "src" / "generated"
+344
View File
@@ -0,0 +1,344 @@
"""The wanted page's list: what the collection lacks, by hash, and where
each file goes.
A visitor drops a file on wanted/ and the page says whether the collection
wants it. The list is built from the gaps page's own report, so a file the
collection holds must never be on it, and its folder must be the one the
review of the pull request asks for (validate_pr.placement): a page that
sent a file elsewhere would have its upload flagged by the same project.
"""
from __future__ import annotations
import tests # noqa: F401 offline, scratch under tmp/, the suite's own cache
import hashlib
import json
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
import zlib
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(REPO_ROOT / "scripts"))
import generate_site # noqa: E402
import sitewanted # noqa: E402
import validate_pr # noqa: E402
from common import load_database # noqa: E402
WEBSITE = REPO_ROOT / "website"
WANTED_TS = WEBSITE / "src" / "scripts" / "wanted.ts"
PUBLISHED = WEBSITE / "public" / sitewanted.DATA_FILE
HELD = b"held rom"
WANTED = b"wanted rom"
VARIANT = b"another revision"
MEMBER = b"rom inside an archive"
CRC_ONLY = b"crc only rom"
CUT = b"cut md5 rom"
RECALBOX = [b"revision one", b"revision two"]
def sha1(data: bytes) -> str:
return hashlib.sha1(data).hexdigest()
def md5(data: bytes) -> str:
return hashlib.md5(data).hexdigest()
def crc(data: bytes) -> str:
return f"{zlib.crc32(data):08x}"
class _World(unittest.TestCase):
"""One held file of system x in bios/Maker/Console/, a profile and a
platform that ask for files around it."""
def setUp(self) -> None:
self._tmp = tempfile.TemporaryDirectory()
self.tmp = Path(self._tmp.name)
self._cwd = os.getcwd()
os.chdir(self.tmp)
self.addCleanup(os.chdir, self._cwd)
self.addCleanup(self._tmp.cleanup)
self.db = {
"files": {sha1(HELD): {"path": "bios/Maker/Console/a.bin", "name": "a.bin",
"size": len(HELD), "sha1": sha1(HELD), "md5": md5(HELD),
"crc32": crc(HELD)},
sha1(b"named"): {"path": "bios/Maker/Console/v.bin", "name": "v.bin",
"size": 5, "sha1": sha1(b"named"), "md5": md5(b"named"),
"crc32": crc(b"named")}},
"indexes": {"by_md5": {md5(HELD): sha1(HELD), md5(b"named"): sha1(b"named")},
"by_sha256": {}, "by_name": {"v.bin": [sha1(b"named")],
"a.bin": [sha1(HELD)]}},
}
(self.tmp / "bios" / "Maker" / "Console").mkdir(parents=True)
(self.tmp / "bios" / "Maker" / "Console" / "a.bin").write_bytes(HELD)
(self.tmp / "bios" / "Maker" / "Console" / "v.bin").write_bytes(b"named")
emulators = self.tmp / "emulators"
emulators.mkdir()
(emulators / "engine.yml").write_text(
"emulator: Engine\ntype: standalone\nsystems: [x]\nfiles:\n"
f" - name: a.bin\n system: x\n sha1: \"{sha1(HELD)}\"\n"
f" - name: b.bin\n system: x\n sha1: \"{sha1(WANTED)}\"\n required: true\n"
f" - name: m.bin\n system: x\n sha1: \"{sha1(MEMBER)}\"\n"
f" - name: c.bin\n system: x\n crc32: \"{crc(CRC_ONLY)}\"\n size: {len(CRC_ONLY)}\n"
" - name: nohash.bin\n system: x\n"
" - name: later.bin\n system: x\n unsourceable: not dumped yet\n"
f" md5: \"{md5(b'later')}\"\n"
)
self.profiles = {"engine": {
"emulator": "Engine", "type": "standalone", "systems": ["x"],
"files": [
{"name": "a.bin", "system": "x", "sha1": sha1(HELD)},
{"name": "b.bin", "system": "x", "sha1": sha1(WANTED), "required": True},
{"name": "m.bin", "system": "x", "sha1": sha1(MEMBER)},
{"name": "c.bin", "system": "x", "crc32": crc(CRC_ONLY), "size": len(CRC_ONLY)},
{"name": "nohash.bin", "system": "x"},
{"name": "later.bin", "system": "x", "unsourceable": "not dumped yet",
"md5": md5(b"later")},
],
}}
self.gap_report = {"engine": {
"emulator": "Engine", "systems": ["x"],
"gap_details": [
{"name": name, "source": "missing", "identity": "", "required": name == "b.bin"}
for name in ("a.bin", "b.bin", "m.bin", "c.bin", "nohash.bin")
] + [{"name": "pkg.bin", "source": "missing", "bundled": True, "identity": ""}],
"unsourceable": [{"name": "later.bin", "required": False, "reason": "not dumped yet"}],
}}
platform = {
"x": {"files": [
{"name": "v.bin", "md5": md5(VARIANT)},
{"name": "cut.bin", "md5": md5(CUT)[:29]},
{"name": "z.zip", "md5": md5(b"inner rom"), "zipped_file": "inner.rom"},
{"name": "r.bin", "md5": ",".join(md5(r) for r in RECALBOX)},
]},
}
self.coverages = {"plat": {
"platform": "Plat", "config": {"systems": platform},
"details": [
{"name": "v.bin", "status": "untested", "system": "x", "required": True},
{"name": "cut.bin", "status": "missing", "system": "x", "required": False},
{"name": "z.zip", "status": "missing", "system": "x", "required": True},
{"name": "r.bin", "status": "missing", "system": "x", "required": True},
{"name": "a.bin", "status": "ok", "system": "x"},
],
}}
self.ledger = [{"path": "bios/Maker/Console/set.zip", "members": [
{"name": "m.bin", "size": len(MEMBER), "crc32": crc(MEMBER), "sha1": sha1(MEMBER)},
]}]
self.platform_hashes = {"sha1": set(), "md5": set(), "names": set(), "folders": {},
"named": {}}
self.profile_hashes = validate_pr.load_profile_hashes(str(emulators), self.db)
self.placer = sitewanted.Placer(self.db, self.platform_hashes, self.profile_hashes)
self.data = sitewanted.build_wanted(
self.profiles, self.coverages, self.gap_report, self.db, self.placer,
lambda system: f"System {system.upper()}", self.ledger,
)
def entry(self, name: str) -> dict:
found = [e for e in self.data["entries"] if e["n"] == name]
self.assertEqual(len(found), 1, name)
return found[0]
class TheListHoldsWhatTheGapsReportLacks(_World):
def test_names(self):
names = sorted(e["n"] for e in self.data["entries"])
# a.bin is held, m.bin is held inside set.zip, nohash.bin and z.zip
# (a zipped_file md5 names a ROM inside the archive) declare nothing
# a dropped file can be compared with, pkg.bin comes with its
# emulator: none is wanted. r.bin is one entry per revision.
self.assertEqual(names, ["b.bin", "c.bin", "cut.bin", "later.bin", "r.bin", "r.bin", "v.bin"])
def test_an_entry_carries_its_readers_system_and_need(self):
entry = self.entry("b.bin")
self.assertEqual(entry["h"], {"sha1": [sha1(WANTED)]})
self.assertEqual(entry["s"], "System X")
self.assertEqual(entry["r"], 1)
self.assertEqual([self.data["readers"][i] for i in entry["w"]], [["e", "engine", "Engine"]])
self.assertEqual([self.data["readers"][i] for i in self.entry("v.bin")["w"]],
[["p", "plat", "Plat"]])
def test_hashes_as_the_resolver_reads_them(self):
self.assertEqual(self.entry("c.bin")["h"], {"crc32": [crc(CRC_ONLY)]})
self.assertEqual(self.entry("c.bin")["z"], [len(CRC_ONLY)])
self.assertEqual(self.entry("cut.bin")["h"], {"md5": [md5(CUT)[:29]]})
revisions = sorted(e["h"]["md5"][0] for e in self.data["entries"] if e["n"] == "r.bin")
self.assertEqual(revisions, sorted(md5(r) for r in RECALBOX))
def test_a_cut_md5_another_wanted_md5_starts_is_that_md5(self):
records = [{"hashes": {"md5": [md5(CUT)[:29]]}}, {"hashes": {"md5": [md5(CUT)]}}]
sitewanted._settle_cut(records)
self.assertEqual(records[0]["hashes"], {"md5": [md5(CUT)]})
both = [{"hashes": {"md5": ["ab" * 14 + "a"]}},
{"hashes": {"md5": ["ab" * 14 + "a" + "000"]}},
{"hashes": {"md5": ["ab" * 14 + "a" + "111"]}}]
sitewanted._settle_cut(both)
self.assertEqual(both[0]["hashes"], {})
def test_a_cut_md5_a_held_md5_starts_is_held(self):
held = sitewanted.Held(self.db)
self.assertTrue(held.holds({"md5": [md5(HELD)[:29]]}, []))
self.assertFalse(held.holds({"md5": [md5(CUT)[:29]]}, []))
def test_a_crc32_counts_at_its_declared_size(self):
held = sitewanted.Held(self.db)
self.assertTrue(held.holds({"crc32": [crc(HELD)]}, [len(HELD)]))
self.assertTrue(held.holds({"crc32": [crc(HELD)]}, []))
self.assertFalse(held.holds({"crc32": [crc(HELD)]}, [len(HELD) + 1]))
class EveryFolderIsTheReviewsFolder(_World):
"""The folder and name of each entry, against what validate_pr says for
the same bytes dropped outside bios/: the destination --place copies to."""
def test_the_review_places_each_file_where_the_page_sends_it(self):
platform_hashes = {**self.platform_hashes, "md5": {md5(VARIANT)}, "names": {"v.bin"}}
for data, name in ((WANTED, "b.bin"), (VARIANT, "v.bin")):
with self.subTest(name=name):
path = self.tmp / "card" / name
path.parent.mkdir(exist_ok=True)
path.write_bytes(data)
result = validate_pr.validate_file(
f"card/{name}", self.db, platform_hashes, self.profile_hashes)
entry = self.entry(name)
folder = self.data["folders"][entry["f"]]
expected = (f"{folder}.variants/{entry['t']}.{sha1(data)[:8]}" if entry.get("v")
else folder + entry["t"])
self.assertEqual(result.destination, expected)
self.assertEqual(self.data["folders"][self.entry("b.bin")["f"]], "bios/Maker/Console/")
self.assertEqual(self.entry("v.bin").get("v"), 1)
def test_each_entry_is_placed_by_validate_pr(self):
for entry in self.data["entries"]:
values = [v for algo in ("sha1", "md5", "sha256") for v in entry["h"].get(algo, [])
if len(v) == sitewanted.FULL_LENGTH[algo]]
spot = validate_pr.placement(values, entry["n"], self.db, self.platform_hashes,
self.profile_hashes, declared=True,
exists=self.placer.paths.__contains__)
with self.subTest(entry=entry["n"]):
self.assertEqual(self.data["folders"][entry["f"]] if "f" in entry else "",
spot.folder)
self.assertEqual(entry.get("t", ""), spot.name)
self.assertEqual(bool(entry.get("v")), spot.variant)
def test_the_gaps_page_upload_link_reads_the_same_rule(self):
source = (REPO_ROOT / "scripts" / "generate_site.py").read_text(encoding="utf-8")
self.assertIn("folder = placer.folder(declared[0]) if placer and declared else \"\"", source)
self.assertNotIn("def _upload_folder", source)
self.assertEqual(self.placer.folder(self.profiles["engine"]["files"][1]),
"bios/Maker/Console/")
self.assertEqual(sitewanted.upload_href(sitewanted.UPLOAD_ROOT, "bios/Maker/Sub Dir/"),
"https://github.com/Abdess/retrobios/upload/main/bios/Maker/Sub%20Dir")
self.assertEqual(sitewanted.upload_href(sitewanted.UPLOAD_ROOT, ""),
generate_site.UPLOAD_URL)
def _node(script: str) -> str:
node = shutil.which("node")
if not node:
raise unittest.SkipTest("node is missing")
return subprocess.run([node, "--input-type=module-typescript", "-e", script],
capture_output=True, text=True, check=True, cwd=WEBSITE).stdout
class ThePageReadsTheListAsTheResolverDoes(_World):
"""wanted.ts against the list built above: a dropped file matches by
every hash its entry declares, and its upload goes where the review
places it."""
def _page(self, data: bytes, own_name: str) -> dict:
hashes = {"sha1": sha1(data), "md5": md5(data), "crc32": crc(data),
"sha256": hashlib.sha256(data).hexdigest()}
return json.loads(_node(
f"import {{ matches, target, uploadUrl, issueUrl }} from {json.dumps(WANTED_TS.as_uri())};"
f"const data = {json.dumps(self.data)}; const file = {json.dumps(hashes)};"
f"const found = matches(data, file, {len(data)});"
f"const place = found.length ? target(data, found[0], file, {json.dumps(own_name)}) : null;"
"console.log(JSON.stringify({names: found.map((e) => e.n), place,"
" upload: place && uploadUrl(data, place.folder),"
f" issue: found.length && issueUrl(data, found[0].n, file, {len(data)})}}));"
))
def test_matches(self):
self.assertEqual(self._page(WANTED, "x.bin")["names"], ["b.bin"])
self.assertEqual(self._page(CRC_ONLY, "x.bin")["names"], ["c.bin"])
self.assertEqual(self._page(CUT, "x.bin")["names"], ["cut.bin"])
self.assertEqual(self._page(RECALBOX[1], "x.bin")["names"], ["r.bin"])
self.assertEqual(self._page(HELD, "a.bin")["names"], [])
self.assertEqual(self._page(b"unknown", "u.bin")["names"], [])
def test_a_crc32_at_another_size_is_not_the_file(self):
entry = {"n": "c.bin", "h": {"crc32": [crc(CRC_ONLY)]}, "w": [], "z": [len(CRC_ONLY) + 1]}
out = _node(
f"import {{ satisfies }} from {json.dumps(WANTED_TS.as_uri())};"
f"console.log(JSON.stringify(satisfies({json.dumps(entry)}, "
f"{{sha1: '', md5: '', sha256: '', crc32: {json.dumps(crc(CRC_ONLY))}}}, {len(CRC_ONLY)})));"
)
self.assertFalse(json.loads(out))
def test_the_upload_goes_where_the_review_places_it(self):
page = self._page(WANTED, "dump.rom")
self.assertEqual(page["place"], {"folder": "bios/Maker/Console/", "name": "b.bin"})
self.assertEqual(page["upload"],
"https://github.com/Abdess/retrobios/upload/main/bios/Maker/Console")
variant = self._page(VARIANT, "v.bin")["place"]
self.assertEqual(variant, {"folder": "bios/Maker/Console/.variants/",
"name": f"v.bin.{sha1(VARIANT)[:8]}"})
def test_the_issue_form_is_filled_as_the_review_fills_it(self):
result = validate_pr.ValidationResult("b.bin")
result.sha1, result.md5, result.size = sha1(WANTED), md5(WANTED), len(WANTED)
self.assertEqual(self._page(WANTED, "b.bin")["issue"], validate_pr.large_file_issue_url(result))
class TheTwoPagesLinkEachOther(unittest.TestCase):
"""files/ checks any file, wanted/ the ones the collection lacks: each
sends a reader to the other in one line."""
def test_links(self):
self.assertIn("[See if it is wanted](../wanted.md)", generate_site.generate_files_page())
self.assertIn("[Find or check a file](files/index.md)", sitewanted.page(1))
class ThePublishedList(unittest.TestCase):
"""The list generate_site.py wrote, against the collection: nothing it
holds, every folder by validate_pr, and light enough for a phone."""
@classmethod
def setUpClass(cls) -> None:
if not PUBLISHED.is_file():
raise unittest.SkipTest("no generated site data")
cls.data = json.loads(PUBLISHED.read_text(encoding="utf-8"))
cls.db = load_database(str(REPO_ROOT / "database.json"))
def test_nothing_held_is_wanted(self):
held = sitewanted.Held(self.db, sitewanted.load_ledger(REPO_ROOT / "recipes" / "archives.json"))
for entry in self.data["entries"]:
with self.subTest(entry=entry["n"]):
self.assertFalse(held.holds(entry["h"], entry.get("z", [])))
def test_every_folder_is_the_reviews(self):
placer = sitewanted.Placer(
self.db, validate_pr.load_platform_hashes(str(REPO_ROOT / "platforms"), self.db),
validate_pr.load_profile_hashes(str(REPO_ROOT / "emulators"), self.db))
for entry in self.data["entries"]:
spot = placer.place(entry["h"], entry["n"])
with self.subTest(entry=entry["n"]):
self.assertEqual(self.data["folders"][entry["f"]] if "f" in entry else "", spot.folder)
self.assertEqual(entry.get("t", ""), spot.name)
def test_weight(self):
self.assertLess(PUBLISHED.stat().st_size, 200_000)
if __name__ == "__main__":
unittest.main()
+27
View File
@@ -186,6 +186,33 @@ class AFileOnlyACoreReadsIsKnown(_Fixture):
self.assertTrue(any("Placed under bios/Other/Place/" in m for _s, m in placed.checks))
class ADeclaredFileBesideItsHeldNameIsAVariant(_Fixture):
"""A file a profile declares, of a system the collection files nowhere
yet, whose name the collection holds: the review named the folder and
left the copy to land on the held file of that name."""
def test_place_copies_it_beside_the_held_name(self):
import hashlib # noqa: PLC0415
data = b"declared revision"
emulators = self.tmp / "emulators"
emulators.mkdir()
(emulators / "engine.yml").write_text(
"emulator: Engine\ntype: standalone\nsystems: [x, y]\nfiles:\n"
f" - name: \"v.bin\"\n sha1: \"{hashlib.sha1(data).hexdigest()}\"\n"
)
db = {"files": {"a" * 40: {"path": "bios/Maker/Console/v.bin"}},
"indexes": {"by_md5": {}, "by_sha256": {}, "by_name": {"v.bin": ["a" * 40]}}}
known = validate_pr.load_profile_hashes(str(emulators), db)
result = validate_pr.validate_file(
self._bios_file("card/v.bin", data), db, EMPTY_HASHES, known)
slot = f"bios/Maker/Console/.variants/v.bin.{result.sha1[:8]}"
self.assertEqual(result.destination, slot)
self.assertIn(("WARN", "File is not under bios/ yet. The collection keeps this name in "
f"`bios/Maker/Console/`. --place copies it to `{slot}`"),
result.checks)
class ASizeEveryDeclarationRulesOutIsNotAVariant(_Fixture):
"""1024 random bytes named scph5501.bin, a name every declaration sizes
at 524288, were told "File size OK" and offered a .variants slot at the
+48 -2
View File
@@ -3,12 +3,20 @@
// tabs: the funnel (Start here to Contribute) is the site's structure, so it
// sits where every docs site puts its sections. On a phone the tabs stay the
// first row of the menu, where the sidebar lists them.
// The wanted page is the one call to contribute, in the bar on every page
// and every width: on a phone it sits beside the search and menu buttons.
import Default from '@astrojs/starlight/components/Header.astro';
const topics = Astro.locals.starlightSidebarTopics?.topics ?? [];
const base = import.meta.env.BASE_URL.replace(/\/?$/, '/');
const wanted = `${base}wanted/`;
const onWanted = Astro.url.pathname.replace(/\/?$/, '/') === wanted;
---
<div class="rb-header-bar"><Default /></div>
<div class="rb-header-bar">
<Default />
<a class="rb-wanted-link print:hidden" href={wanted} aria-current={onWanted ? 'page' : undefined}>Wanted files</a>
</div>
{
topics.length > 0 && (
<nav class="rb-tabs print:hidden" aria-label="Sections">
@@ -27,7 +35,45 @@ const topics = Astro.locals.starlightSidebarTopics?.topics ?? [];
<!-- Global: the bar height and the sidebar's topic list belong to other components. -->
<style is:global>
.rb-header-bar { height: 100%; }
.rb-header-bar {
display: flex;
align-items: center;
gap: var(--sl-nav-gap);
height: 100%;
}
.rb-header-bar > .header { flex: 1; min-width: 0; }
/* A call to contribute: an outlined pill in the link colour, filled on
its own page. The colours are the theme's, in light and dark. */
.rb-wanted-link {
display: inline-flex;
flex: none;
align-items: center;
min-height: 2rem;
padding: 0 0.75rem;
border: 1px solid var(--rb-link);
border-radius: 999px;
color: var(--rb-link);
font-size: var(--sl-text-sm);
font-weight: 600;
text-decoration: none;
white-space: nowrap;
}
.rb-wanted-link:hover { background: var(--sl-color-accent-low); }
.rb-wanted-link:focus-visible { outline: 2px solid var(--rb-link); outline-offset: 2px; }
.rb-wanted-link[aria-current='page'] { background: var(--rb-link); color: var(--sl-color-black); }
/* Below 27rem the bar cannot hold the name, the search, the link and the
menu: the logo stays as the home link and the name is kept for screen
readers, rather than cut to "Retr". */
@media (max-width: 26.99rem) {
.site-title span {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
}
.rb-tabs { display: none; }
/* "Look up this hash", the first result of a hash typed in the search (site.ts). */
+180
View File
@@ -0,0 +1,180 @@
---
// The wanted page: files dropped here are hashed on this device and
// compared with public/data/wanted.json, the files the gaps page reports
// the collection lacks (scripts/sitewanted.py). A file the collection
// holds is found in the hash lookup (api/v1/lookup/, one shard per first
// two characters). Nothing is sent anywhere: a wanted file gets a link to
// GitHub's upload page for its folder, and the visitor uploads it there.
const base = import.meta.env.BASE_URL.replace(/\/?$/, '/');
---
<div class="rb-wanted" data-base={base}>
<div class="rb-wanted-drop">
<p><strong>Drop files here</strong></p>
<label class="rb-button" for="rb-wanted-input">Or choose them</label>
<input id="rb-wanted-input" type="file" multiple class="rb-wanted-input" />
</div>
<p class="rb-wanted-status" role="status" aria-live="polite"></p>
<ol class="rb-wanted-list"></ol>
</div>
<script>
import { type FileHashes, hashFile } from '../scripts/hashes.ts';
import { type Entry, type Wanted, issueUrl, matches, target, uploadUrl } from '../scripts/wanted.ts';
type Item = { layer: string; value: string; url: string; archive?: string; sha1?: string };
const size = (bytes: number) =>
bytes >= 1024 ** 3 ? `${(bytes / 1024 ** 3).toFixed(1)} GB`
: bytes >= 1024 ** 2 ? `${(bytes / 1024 ** 2).toFixed(1)} MB`
: bytes >= 1024 ? `${(bytes / 1024).toFixed(1)} KB`
: `${bytes} B`;
const element = <K extends keyof HTMLElementTagNameMap>(tag: K, ...content: (Node | string)[]) => {
const node = document.createElement(tag);
node.append(...content);
return node;
};
const code = (text: string) => element('code', text);
const listed = (nodes: Node[]) =>
nodes.flatMap((node, i) => (i === 0 ? [node] : [i === nodes.length - 1 ? ' and ' : ', ', node]));
for (const root of document.querySelectorAll<HTMLElement>('.rb-wanted')) {
const base = root.dataset.base ?? '/';
const drop = root.querySelector<HTMLElement>('.rb-wanted-drop')!;
const input = root.querySelector<HTMLInputElement>('.rb-wanted-input')!;
const status = root.querySelector<HTMLElement>('.rb-wanted-status')!;
const list = root.querySelector<HTMLOListElement>('.rb-wanted-list')!;
let wanted: Promise<Wanted> | null = null;
const shards = new Map<string, Promise<Item[]>>();
const shard = (value: string) => {
const prefix = value.slice(0, 2);
if (!shards.has(prefix)) {
shards.set(prefix, fetch(`${base}api/v1/lookup/${prefix}.json`)
.then((response) => (response.ok ? response.json() : { items: [] }))
.then((data) => data.items ?? []));
}
return shards.get(prefix)!;
};
const link = (href: string, text: string) => {
const a = element('a', text);
a.href = href;
return a;
};
const verdict = async (file: File, hashes: FileHashes): Promise<Node[]> => {
const bySha1 = (await shard(hashes.sha1)).find((item) =>
item.value === hashes.sha1 && (item.layer === 'collection' || item.layer === 'data-directory'));
if (bySha1) {
return [element('p', element('strong', 'Already held.'), ' The collection has this file. ',
link(new URL(bySha1.url, location.origin).href, 'See it'), '.')];
}
const data = await (wanted ??= fetch(`${base}data/wanted.json`).then((response) => response.json()));
const found = matches(data, hashes, file.size);
if (found.length) return wantedBlock(data, found, file, hashes);
const member = (await shard(hashes.crc32)).find((item) => item.value === hashes.crc32 && item.layer === 'archive-member');
if (member) {
return [element('p', element('strong', 'Already held.'), ' The collection has it inside ',
code(member.archive ?? ''), '. ', link(new URL(member.url, location.origin).href, 'See it'), '.')];
}
return [element('p', element('strong', 'Not wanted.'), ' No list we follow asks for this file.')];
};
const wantedBlock = (data: Wanted, found: Entry[], file: File, hashes: FileHashes): Node[] => {
const best = found[0];
const readers = [...new Set(found.flatMap((entry) => entry.w))].map((index) => {
const [kind, key, label] = data.readers[index];
return link(`${base}${kind === 'p' ? 'platforms' : 'emulators'}/${key}/`, label);
});
const systems = [...new Set(found.flatMap((entry) => (entry.s ? [entry.s] : [])))];
const required = found.some((entry) => entry.r);
const blocks: Node[] = [
element('p', element('strong', 'Wanted.'), ' This is ', code(best.n),
...(systems.length ? [`, for ${systems.join(', ')}`] : []), '. ',
required ? 'Needed by ' : 'Used by ', ...listed(readers), '.'),
];
const place = target(data, best, hashes, file.name);
if (file.size > data.limit) {
blocks.push(element('p', `GitHub's upload page takes ${size(data.limit)} at most. `,
link(issueUrl(data, best.n, hashes, file.size), 'Open an issue'),
' with its hashes filled in, and we add it.'));
return blocks;
}
if (place.name !== file.name) blocks.push(element('p', 'Rename it to ', code(place.name), ' first.'));
const button = link(uploadUrl(data, place.folder), `Upload to ${place.folder}`);
button.className = 'rb-button rb-button-primary';
button.target = '_blank';
button.rel = 'noopener';
blocks.push(element('p', button));
return blocks;
};
const run = async (files: File[]) => {
if (!files.length) return;
list.replaceChildren();
const rows = files.map((file) => {
const bar = element('progress');
bar.max = 1;
bar.value = 0;
bar.setAttribute('aria-label', `Reading ${file.name}`);
const body = element('div', bar);
list.append(element('li', element('p', code(file.name), ` ${size(file.size)}`), body));
return { file, bar, body };
});
let done = 0;
for (const { file, bar, body } of rows) {
status.textContent = `Reading ${file.name} (${done + 1} of ${files.length})...`;
try {
const hashes = await hashFile(file, (share) => { bar.value = share; });
body.replaceChildren(...(await verdict(file, hashes)));
} catch {
body.replaceChildren(element('p', 'This file could not be read here.'));
}
done += 1;
}
status.textContent = `Done: ${files.length} ${files.length === 1 ? 'file' : 'files'}.`;
};
input.addEventListener('change', () => run([...(input.files ?? [])]));
drop.addEventListener('dragover', (event) => {
event.preventDefault();
drop.classList.add('rb-wanted-over');
});
drop.addEventListener('dragleave', () => drop.classList.remove('rb-wanted-over'));
drop.addEventListener('drop', (event) => {
event.preventDefault();
drop.classList.remove('rb-wanted-over');
run([...(event.dataTransfer?.files ?? [])]);
});
}
</script>
<style is:global>
.rb-wanted-drop {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.5rem;
padding: 2rem 1rem;
border: 2px dashed var(--rb-border);
border-radius: 8px;
text-align: center;
}
.rb-wanted-drop.rb-wanted-over { border-color: var(--rb-link); background: var(--sl-color-accent-low); }
.sl-markdown-content .rb-wanted-drop > * { margin: 0; }
/* The input stays in the page for keyboards and screen readers; its
label is the button people see. */
.rb-wanted-input {
position: absolute;
width: 1px;
height: 1px;
opacity: 0;
overflow: hidden;
}
.rb-wanted-drop:focus-within label { outline: 2px solid var(--rb-link); outline-offset: 2px; }
.rb-wanted-drop label { cursor: pointer; }
.rb-wanted-list { padding-left: 1.25rem; }
.rb-wanted-list li { margin-top: 1rem; }
.rb-wanted-list progress { width: 100%; max-width: 20rem; }
.rb-wanted-status { margin-top: 1rem; font-weight: 600; }
</style>
+125
View File
@@ -0,0 +1,125 @@
// Hashing a file on this device: SHA1 and SHA256 by Web Crypto, MD5 and
// CRC32 here, since Web Crypto has neither. The bytes never leave the page.
// MD5 and CRC32 take the file piece by piece, so a large file is read in
// slices and the page keeps answering between them.
const CRC_TABLE = (() => {
const table = new Uint32Array(256);
for (let n = 0; n < 256; n += 1) {
let c = n;
for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
table[n] = c >>> 0;
}
return table;
})();
export const hexBytes = (bytes: Uint8Array) => [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('');
export class Crc32 {
crc = 0xffffffff;
update(bytes: Uint8Array): this {
let crc = this.crc;
for (let i = 0; i < bytes.length; i += 1) crc = CRC_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
this.crc = crc;
return this;
}
digest(): string {
return ((this.crc ^ 0xffffffff) >>> 0).toString(16).padStart(8, '0');
}
}
const MD5_SHIFTS = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
const MD5_TABLE = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 2 ** 32) >>> 0);
// RFC 1321. Whole 64-byte blocks are read in place from each slice; only a
// block split between two slices is copied.
export class Md5 {
state = new Int32Array([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]);
words = new Int32Array(16);
pending = new Uint8Array(64);
pendingLength = 0;
length = 0;
block(view: DataView, offset: number) {
const words = this.words;
const state = this.state;
for (let i = 0; i < 16; i += 1) words[i] = view.getInt32(offset + i * 4, true);
let [a, b, c, d] = state;
for (let i = 0; i < 64; i += 1) {
const round = i >> 4;
const f = round === 0 ? (b & c) | (~b & d) : round === 1 ? (d & b) | (~d & c) : round === 2 ? b ^ c ^ d : c ^ (b | ~d);
const g = round === 0 ? i : round === 1 ? (5 * i + 1) % 16 : round === 2 ? (3 * i + 5) % 16 : (7 * i) % 16;
const shift = MD5_SHIFTS[round * 4 + (i % 4)];
const sum = (a + f + MD5_TABLE[i] + words[g]) | 0;
a = d;
d = c;
c = b;
b = (b + ((sum << shift) | (sum >>> (32 - shift)))) | 0;
}
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
}
update(bytes: Uint8Array): this {
this.length += bytes.length;
let start = 0;
if (this.pendingLength) {
start = Math.min(64 - this.pendingLength, bytes.length);
this.pending.set(bytes.subarray(0, start), this.pendingLength);
this.pendingLength += start;
if (this.pendingLength < 64) return this;
this.block(new DataView(this.pending.buffer), 0);
this.pendingLength = 0;
}
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const whole = start + ((bytes.length - start) - ((bytes.length - start) % 64));
for (let offset = start; offset < whole; offset += 64) this.block(view, offset);
this.pending.set(bytes.subarray(whole));
this.pendingLength = bytes.length - whole;
return this;
}
digest(): string {
const tail = new Uint8Array(this.pendingLength < 56 ? 64 : 128);
tail.set(this.pending.subarray(0, this.pendingLength));
tail[this.pendingLength] = 0x80;
const view = new DataView(tail.buffer);
const bits = this.length * 8;
view.setUint32(tail.length - 8, bits >>> 0, true);
view.setUint32(tail.length - 4, Math.floor(bits / 2 ** 32), true);
for (let offset = 0; offset < tail.length; offset += 64) this.block(view, offset);
return hexBytes(new Uint8Array(this.state.buffer));
}
}
export const md5 = (bytes: Uint8Array) => new Md5().update(bytes).digest();
export const crc32 = (bytes: Uint8Array) => new Crc32().update(bytes).digest();
export type FileHashes = { sha1: string; md5: string; crc32: string; sha256: string };
const SLICE = 4 * 1024 * 1024;
// The four hashes of a file. MD5 and CRC32 read it slice by slice, each
// slice awaited so the page stays responsive; *progress* gets the share
// read so far, from 0 to 1. SHA1 and SHA256 then hash it whole in Web
// Crypto, which works off the page's own thread.
export const hashFile = async (file: Blob, progress?: (share: number) => void): Promise<FileHashes> => {
const md5State = new Md5();
const crcState = new Crc32();
for (let offset = 0; offset < file.size; offset += SLICE) {
const bytes = new Uint8Array(await file.slice(offset, offset + SLICE).arrayBuffer());
md5State.update(bytes);
crcState.update(bytes);
progress?.(Math.min(1, (offset + bytes.length) / file.size));
}
const buffer = await file.arrayBuffer();
const [sha1, sha256] = await Promise.all(
['SHA-1', 'SHA-256'].map(async (name) => hexBytes(new Uint8Array(await crypto.subtle.digest(name, buffer)))),
);
progress?.(1);
return { sha1, md5: md5State.digest(), crc32: crcState.digest(), sha256 };
};
+2 -73
View File
@@ -7,6 +7,8 @@
// Which tables stack on a phone is decided when the page is built
// (src/plugins/rehype-stack-tables.mjs), so the layout is right on first paint.
import { type FileHashes, hashFile } from './hashes.ts';
const HASH_LENGTHS: Record<number, string> = { 8: 'CRC32', 32: 'MD5', 40: 'SHA1', 64: 'SHA256' };
// One line of api/v1/lookup/. `system_name` is read when a record carries it.
// `algorithm` is the hash the value was found under, `declared` the hash
@@ -263,79 +265,6 @@ const breakPaths = () => {
});
};
// Hashing a file on this device: SHA1 and SHA256 by Web Crypto, MD5 and
// CRC32 here, since Web Crypto has neither. The bytes never leave the page.
const CRC_TABLE = (() => {
const table = new Uint32Array(256);
for (let n = 0; n < 256; n += 1) {
let c = n;
for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
table[n] = c >>> 0;
}
return table;
})();
const crc32 = (bytes: Uint8Array): string => {
let crc = 0xffffffff;
for (let i = 0; i < bytes.length; i += 1) crc = CRC_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
return ((crc ^ 0xffffffff) >>> 0).toString(16).padStart(8, '0');
};
const MD5_SHIFTS = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
const MD5_TABLE = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 2 ** 32) >>> 0);
const hexBytes = (bytes: Uint8Array) => [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('');
// RFC 1321, block by block over the file's own buffer: no padded copy of a
// 500 MB file.
const md5 = (bytes: Uint8Array): string => {
const state = new Int32Array([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]);
const words = new Int32Array(16);
const block = (view: DataView, offset: number) => {
for (let i = 0; i < 16; i += 1) words[i] = view.getInt32(offset + i * 4, true);
let [a, b, c, d] = state;
for (let i = 0; i < 64; i += 1) {
const round = i >> 4;
const f = round === 0 ? (b & c) | (~b & d) : round === 1 ? (d & b) | (~d & c) : round === 2 ? b ^ c ^ d : c ^ (b | ~d);
const g = round === 0 ? i : round === 1 ? (5 * i + 1) % 16 : round === 2 ? (3 * i + 5) % 16 : (7 * i) % 16;
const shift = MD5_SHIFTS[round * 4 + (i % 4)];
const sum = (a + f + MD5_TABLE[i] + words[g]) | 0;
a = d;
d = c;
c = b;
b = (b + ((sum << shift) | (sum >>> (32 - shift)))) | 0;
}
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
};
const whole = bytes.length - (bytes.length % 64);
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
for (let offset = 0; offset < whole; offset += 64) block(view, offset);
const tail = new Uint8Array(bytes.length - whole < 56 ? 64 : 128);
tail.set(bytes.subarray(whole));
tail[bytes.length - whole] = 0x80;
const tailView = new DataView(tail.buffer);
const bits = bytes.length * 8;
tailView.setUint32(tail.length - 8, bits >>> 0, true);
tailView.setUint32(tail.length - 4, Math.floor(bits / 2 ** 32), true);
for (let offset = 0; offset < tail.length; offset += 64) block(tailView, offset);
return hexBytes(new Uint8Array(state.buffer));
};
type FileHashes = { sha1: string; md5: string; crc32: string; sha256: string };
const hashFile = async (file: Blob): Promise<FileHashes> => {
const buffer = await file.arrayBuffer();
const bytes = new Uint8Array(buffer);
const [sha1, sha256] = await Promise.all(
['SHA-1', 'SHA-256'].map(async (name) => hexBytes(new Uint8Array(await crypto.subtle.digest(name, buffer)))),
);
return { sha1, md5: md5(bytes), crc32: crc32(bytes), sha256 };
};
// files/?hash= reads one shard of the lookup, named by the first two hex
// characters of the value. ?md5=, ?crc32= and ?sha256= are read the same way.
+72
View File
@@ -0,0 +1,72 @@
// The wanted page's reading of public/data/wanted.json (scripts/sitewanted.py):
// which entries a hashed file is, and where its upload goes.
import type { FileHashes } from './hashes.ts';
export type Entry = {
n: string;
h: { sha1?: string[]; sha256?: string[]; md5?: string[]; crc32?: string[] };
w: number[];
s?: string;
r?: number;
z?: number[];
f?: number;
t?: string;
v?: number;
};
export type Wanted = {
upload: string;
issue: string;
limit: number;
readers: [string, string, string][];
folders: string[];
entries: Entry[];
};
// A declaration is met when every hash it writes is the file's, as
// resolve_local_file reads it. An md5 cut short (Batocera writes 29
// characters) is compared as a prefix: the list keeps a cut only when no
// other wanted md5 starts with it. A crc32 is declared only where no
// stronger hash is, and a declared size bounds it.
export const satisfies = (entry: Entry, file: FileHashes, size: number): boolean => {
const { sha1, sha256, md5, crc32 } = entry.h;
if (sha1 && !sha1.includes(file.sha1)) return false;
if (sha256 && !sha256.includes(file.sha256)) return false;
if (md5 && !md5.some((value) => (value.length === 32 ? value === file.md5 : file.md5.startsWith(value)))) return false;
if (crc32 && (!crc32.includes(file.crc32) || (entry.z && !entry.z.includes(size)))) return false;
return true;
};
// The strongest hash an entry declares, the lowest first: a sha1 match
// settles the folder before an md5 or a crc32 one.
const strength = (entry: Entry) =>
entry.h.sha1 ? 0 : entry.h.sha256 ? 1 : entry.h.md5?.some((value) => value.length === 32) ? 2 : entry.h.md5 ? 3 : 4;
export const matches = (data: Wanted, file: FileHashes, size: number): Entry[] =>
data.entries.filter((entry) => satisfies(entry, file, size)).sort((a, b) => strength(a) - strength(b));
// The folder and the name an upload carries, as validate_pr.Placement
// gives them: the declared name, beside the held file of that name in
// .variants/ with the first 8 characters of the sha1, or the file's own
// name when the declarations settle none. bios/ when no folder is known.
export const target = (data: Wanted, entry: Entry, file: FileHashes, ownName: string) => {
const folder = entry.f === undefined ? 'bios/' : data.folders[entry.f];
if (!entry.t) return { folder, name: ownName };
if (entry.v) return { folder: `${folder}.variants/`, name: `${entry.t}.${file.sha1.slice(0, 8)}` };
return { folder, name: entry.t };
};
export const uploadUrl = (data: Wanted, folder: string) =>
data.upload + folder.replace(/\/$/, '').split('/').map(encodeURIComponent).join('/');
// The issue form for a file too large for the browser, filled as
// validate_pr.large_file_issue_url fills it.
export const issueUrl = (data: Wanted, name: string, file: FileHashes, size: number) =>
`${data.issue}&${new URLSearchParams({
title: `[BIOS] Missing: ${name}`,
filename: name,
sha1: file.sha1,
md5: file.md5,
size: String(size),
})}`;
+1 -1
View File
@@ -77,7 +77,7 @@ Every module in `tests/`, by the area it guards.
| Pack probe | the cores a platform runs for a system, staging grown to a fixed point, runs mapped to pack and manifest entries, the line and its schema, the probe lock per run, that no page shows its lines. One class builds a real pack narrowed to PlayStation and lays it out both ways, from the archive and with `install.py --dest`, and skips without the collection | `test_pack_probe` |
| Automation runner, disk cleanup, asset sync and bit-flip repair | fake jobs, git repositories with a bare origin and session worktrees, a committed file with one bit flipped, canned CI runs in place of `gh` | `test_autorun` |
| Truth and native export | synthetic + cached originals | `test_export_counts`, `test_export_native_layer`, `test_export_report`, `test_exporters`, `test_truth_data_dir_readers`, `test_truth_diff`, `test_truth_layout` |
| Scrapers, upstream and provenance | inline sources, synthetic | `test_auto_fetch_lookup`, `test_batocera_md5_list`, `test_find_embedded`, `test_report_excerpt`, `test_check_freshness`, `test_cited_lines`, `test_contributing_text`, `test_coverage_cache`, `test_data_dir_refs`, `test_dataclass_defaults`, `test_dedup`, `test_doc_pages`, `test_doc_surfaces`, `test_elec_scrapers`, `test_fbneo_parser`, `test_find_pinned_revision`, `test_hash_merge`, `test_launchers`, `test_launchers_amberelec`, `test_launchers_emudeck`, `test_launchers_emuelec`, `test_launchers_knulli`, `test_launchers_recalbox`, `test_launchers_retrobat`, `test_launchers_retrodeck`, `test_launchers_retropie`, `test_launchers_rocknix`, `test_mame_devices`, `test_mame_parser`, `test_mame_ref_audit`, `test_optional_dependencies`, `test_pin_build`, `test_profile_sync`, `test_prose_style`, `test_provenance`, `test_refresh_data_dirs`, `test_refresh_failures`, `test_refresh_stale`, `test_retired_files`, `test_retrodeck_scraper_errors`, `test_romset_recipes`, `test_schema_semantic_gate`, `test_scraper_contract`, `test_site_agents`, `test_site_arcade_boards`, `test_site_availability`, `test_site_bootstrap`, `test_site_built_gate`, `test_site_components`, `test_site_console_folders`, `test_site_content_data`, `test_site_copy`, `test_site_cores`, `test_site_css`, `test_site_demo`, `test_site_density_cards`, `test_site_emulator_page`, `test_site_emulators`, `test_site_entry`, `test_site_entry_tables`, `test_site_exports`, `test_site_freshness`, `test_site_funnel`, `test_site_images`, `test_site_inputs`, `test_site_insights`, `test_site_integration`, `test_site_nav`, `test_site_page_text`, `test_site_picker`, `test_site_platform_density`, `test_site_platform_hashes`, `test_site_privacy`, `test_site_pronouns`, `test_site_reference`, `test_site_render`, `test_site_search`, `test_site_steps`, `test_site_system_links`, `test_site_system_names`, `test_site_system_sections`, `test_site_systems`, `test_site_validation`, `test_site_weight`, `test_site_wiki`, `test_site_write`, `test_source_ref_targets`, `test_upstream`, `test_upstream_index`, `test_validate_pr`, `test_validate_pr_flow`, `test_validate_pr_hashes`, `test_version_basis`, `test_workflow_paths` |
| Scrapers, upstream and provenance | inline sources, synthetic | `test_auto_fetch_lookup`, `test_batocera_md5_list`, `test_find_embedded`, `test_report_excerpt`, `test_check_freshness`, `test_cited_lines`, `test_contributing_text`, `test_coverage_cache`, `test_data_dir_refs`, `test_dataclass_defaults`, `test_dedup`, `test_doc_pages`, `test_doc_surfaces`, `test_elec_scrapers`, `test_fbneo_parser`, `test_find_pinned_revision`, `test_hash_merge`, `test_launchers`, `test_launchers_amberelec`, `test_launchers_emudeck`, `test_launchers_emuelec`, `test_launchers_knulli`, `test_launchers_recalbox`, `test_launchers_retrobat`, `test_launchers_retrodeck`, `test_launchers_retropie`, `test_launchers_rocknix`, `test_mame_devices`, `test_mame_parser`, `test_mame_ref_audit`, `test_optional_dependencies`, `test_pin_build`, `test_profile_sync`, `test_prose_style`, `test_provenance`, `test_refresh_data_dirs`, `test_refresh_failures`, `test_refresh_stale`, `test_retired_files`, `test_retrodeck_scraper_errors`, `test_romset_recipes`, `test_schema_semantic_gate`, `test_scraper_contract`, `test_site_agents`, `test_site_arcade_boards`, `test_site_availability`, `test_site_bootstrap`, `test_site_built_gate`, `test_site_components`, `test_site_console_folders`, `test_site_content_data`, `test_site_copy`, `test_site_cores`, `test_site_css`, `test_site_demo`, `test_site_density_cards`, `test_site_emulator_page`, `test_site_emulators`, `test_site_entry`, `test_site_entry_tables`, `test_site_exports`, `test_site_freshness`, `test_site_funnel`, `test_site_images`, `test_site_inputs`, `test_site_insights`, `test_site_integration`, `test_site_nav`, `test_site_page_text`, `test_site_picker`, `test_site_platform_density`, `test_site_platform_hashes`, `test_site_privacy`, `test_site_pronouns`, `test_site_reference`, `test_site_render`, `test_site_search`, `test_site_steps`, `test_site_system_links`, `test_site_system_names`, `test_site_system_sections`, `test_site_systems`, `test_site_validation`, `test_site_wanted`, `test_site_weight`, `test_site_wiki`, `test_site_write`, `test_source_ref_targets`, `test_upstream`, `test_upstream_index`, `test_validate_pr`, `test_validate_pr_flow`, `test_validate_pr_hashes`, `test_version_basis`, `test_workflow_paths` |
| Games on the card | small DATs, listxml and setup sources, a fake fetcher, fixture install lists, and the committed data against its schemas | `test_arcade_parents`, `test_game_catalogs`, `test_game_headers`, `test_game_regions`, `test_games_index`, `test_romfolders_card`, `test_romfolders_es` |
## Test architecture