feat: add the wanted page

Files dropped on wanted/ are hashed in the browser and compared with the files the gaps page reports the collection lacks. A wanted file gets a link to GitHub's upload page for the folder validate_pr asks for, and the name to give it. The gaps page upload link reads the same rule.
This commit is contained in:
Abdessamad Derraz committed 2026-11-13 10:45:18 +01:00
1 parent d685451f44
commit 4a9317cb4c
12 files changed
+992 -42

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.
+39 -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 ""
@@ -10924,24 +10927,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 +10958,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 +11039,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 +11261,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 +11370,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 +12426,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 +12813,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",
}
+342
View File
@@ -0,0 +1,342 @@
"""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). "
"More ways to help are on [Contributing](contributing.md)."),
"",
])
+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"
+335
View File
@@ -0,0 +1,335 @@
"""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 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()
+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>
+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