feat: list every wanted file with its upload

The wanted page lists every file the gaps report lacks, hashless ones included and marked, by system and most useful first, each with its own upload button to the folder validate_pr.placement() gives. Steps from a file in hand to its merge, copy without personal pronouns, list address versioned against stale caches.
This commit is contained in:
Abdessamad Derraz committed 2026-11-13 17:38:34 +01:00
1 parent aada55e656
commit 3fd61df038
9 files changed
+672 -84

No files matched your search

+9 -14
View File
@@ -2538,7 +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 the device.",
"wanted.md": "Every file the collection lacks, by system, each with its upload button to GitHub. Drop files on the page to learn if they are wanted.",
}
if key in specific:
return specific[key]
@@ -10664,17 +10664,10 @@ def _catalogued_needs(report: dict | None) -> dict[tuple[str, str], list[str]]:
"""(profile, file name casefolded) -> where a dump catalog or an
imported romset lists that file, from a provenance report built with
the profiles' needs."""
out: dict[tuple[str, str], list[str]] = {}
for source, data in sorted((report or {}).items()):
label = _PROVENANCE_LABELS.get(source, source)
for entry in data.get("missing", []):
where = [f"{label} `{_escape_tags(str(entry.get('name', '')))}`"]
where += [f"{_escape_tags(str(hit['source']))} `{_escape_tags(str(hit['archive']))}`"
for hit in entry.get("romsets", [])]
for need in entry.get("needed_by", []):
held = out.setdefault((need["emulator"], str(need["name"]).casefold()), [])
held += [w for w in where if w not in held]
return out
return {
need: [f"{_escape_tags(where)} `{_escape_tags(name)}`" for where, name in listed]
for need, listed in sitewanted.catalog_listings(report, _PROVENANCE_LABELS).items()
}
def _reason_cell(text: str) -> str:
@@ -11382,7 +11375,7 @@ def generate_gap_analysis(
f"{_source_ref_markdown(owner, m['source_ref'])} |"
)
lines.extend(["### Files to source", "", counted,
"[The wanted page](wanted.md) recognises the ones with a known hash.", ""])
"[The wanted page](wanted.md) lists them, each with its upload button.", ""])
if moved is None:
lines.extend([*head, *rows, ""])
else:
@@ -12837,11 +12830,13 @@ def _generate(args: argparse.Namespace) -> None:
wanted = sitewanted.build_wanted(
profiles, coverages, gap_report, db, placer, system_name,
sitewanted.load_ledger(archive_build.ARCHIVES_FILE),
sitewanted.catalog_listings(provenance_report, _PROVENANCE_LABELS),
)
(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"])))
write_if_changed(str(docs / "wanted.md"), sitewanted.page(
len(wanted["entries"]), sum(1 for entry in wanted["entries"] if "h" in entry)))
print("Generating updated platform files page...")
write_if_changed(
+1
View File
@@ -29,6 +29,7 @@ COMPONENTS = {
"TabItem": "@astrojs/starlight/components",
"FilePicker": "components/FilePicker.astro",
"WantedFiles": "components/WantedFiles.astro",
"WantedList": "components/WantedList.astro",
"MeasurementsExplorer": "components/MeasurementsExplorer.astro",
"InstallDemo": "components/InstallDemo.astro",
}
+157 -38
View File
@@ -1,11 +1,12 @@
"""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.
compared with this list, and the page lists every entry under the drop
box. 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 is kept and marked: it
is recognised by its name only, and the review of the upload decides.
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
@@ -15,8 +16,9 @@ the review of the pull request asks for that same folder.
from __future__ import annotations
import re
import urllib.parse
from collections.abc import Callable, Iterable
from collections.abc import Callable, Iterable, Mapping
from pathlib import Path
import archive_build
@@ -128,7 +130,8 @@ def gap_entries(profile: dict, name: str, identity: str, unsourceable: bool) ->
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}.
Each is {name, system, required, reader: (kind, key, label), entry,
reason}, the reason a file not collected yet carries, empty otherwise.
"""
found: list[dict] = []
for key, coverage in sorted(coverages.items()):
@@ -143,6 +146,7 @@ def wanted_declarations(profiles: dict, coverages: dict, gap_report: dict) -> li
"name": str(entry["name"]), "system": system,
"required": bool(detail.get("required", True)),
"reader": ("platform", key, coverage["platform"]), "entry": entry,
"reason": "",
})
unique = unique_emulator_profiles(profiles)
for key, data in sorted(gap_report.items()):
@@ -161,15 +165,54 @@ def wanted_declarations(profiles: dict, coverages: dict, gap_report: dict) -> li
"name": str(entry["name"]), "system": str(system),
"required": bool(row.get("required", False)),
"reader": ("emulator", key, str(data.get("emulator", key))), "entry": entry,
"reason": str(row.get("reason") or "") if unsourceable else "",
})
return found
def catalog_listings(report: dict | None, labels: dict[str, str]) -> dict[tuple[str, str], list[tuple[str, str]]]:
"""(profile, file name casefolded) -> (catalog or romset, the name it
lists the file under), from a provenance report built with the
profiles' needs: the "Listed in" column of the gaps page."""
out: dict[tuple[str, str], list[tuple[str, str]]] = {}
for source, data in sorted((report or {}).items()):
label = labels.get(source, source)
for entry in data.get("missing", []):
where = [(label, str(entry.get("name", "")))]
where += [(str(hit["source"]), str(hit["archive"])) for hit in entry.get("romsets", [])]
for need in entry.get("needed_by", []):
held = out.setdefault((need["emulator"], str(need["name"]).casefold()), [])
held += [w for w in where if w not in held]
return out
# A name the code builds from the content (<serial>.txt, *.ini) is a
# pattern, not a file anyone can upload.
PATTERN = re.compile(r"[<>*?]")
# What a row says the file is: the first sentence of the declaration's
# description or note, cut at a word past this many characters.
DESCRIPTION_LIMIT = 160
SENTENCE_END = re.compile(r"(?:(?<=\w\w[.!?])|(?<=[)\]][.!?]))\s+(?=[A-Z])")
def first_sentence(text: object, limit: int = DESCRIPTION_LIMIT) -> str:
"""The first sentence of a description, on one line and at most about
*limit* characters."""
flat = " ".join(str(text or "").replace("`", "").split())
end = SENTENCE_END.search(flat)
if end:
flat = flat[:end.start()]
if len(flat) > limit:
flat = flat[:limit].rsplit(" ", 1)[0].rstrip(",;:(") + "..."
return flat
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: with one match the cut is that md5.
With several it names none, and with none the page compares by prefix.
With several it names none, and an entry left with no hash is known by
its name. With none 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:
@@ -207,10 +250,12 @@ class Placer:
}
def place(self, hashes: dict[str, list[str]], name: str) -> Placement:
"""A declaration that writes no hash is known by its name alone,
as the review knows a file whose hashes nothing declares."""
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__)
declared=bool(hashes), exists=self.paths.__contains__)
def folder(self, entry: dict) -> str:
"""The folder an upload of a profile or platform entry goes to."""
@@ -226,6 +271,13 @@ def upload_href(root: str, folder: str) -> str:
return root + urllib.parse.quote((folder or "bios/").rstrip("/"))
def _order(record: dict) -> tuple:
"""Most useful first: required before optional, then by how many
setups and emulators read the file."""
return (not record["required"], -len(record["readers"]), record["name"].casefold(),
sorted(record["readers"]))
def build_wanted(
profiles: dict,
coverages: dict,
@@ -234,60 +286,81 @@ def build_wanted(
placer: Placer,
system_name: Callable[[str], str],
ledger: Iterable[dict] = (),
catalogued: Mapping[tuple[str, str], list[tuple[str, str]]] | None = None,
) -> 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.
An entry: n name, h hashes (absent when the declarations write none:
the file is known by its name only), w readers, s systems, r required,
z sizes, d what the file is, u why it is not collected yet, l the
catalogs that list it with the name they give it, 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. Entries come most useful first.
"""
held = Held(db, ledger)
records: dict[tuple, dict] = {}
for declaration in wanted_declarations(profiles, coverages, gap_report):
if PATTERN.search(declaration["name"]):
continue
entry = declaration["entry"]
sizes = _sizes(entry)
for hashes in _alternatives(declared_hashes(entry)):
if held.holds(hashes, sizes):
if hashes and held.holds(hashes, sizes):
continue
key = (declaration["name"], tuple(sorted((a, tuple(v)) for a, v in hashes.items())),
tuple(sizes))
key = ((declaration["name"], tuple(sorted((a, tuple(v)) for a, v in hashes.items())),
tuple(sizes)) if hashes
else (declaration["name"].casefold(), declaration["system"]))
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(),
"description": "", "reason": "", "listed": [],
})
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"])))
record["description"] = record["description"] or first_sentence(
entry.get("description") or entry.get("note"))
record["reason"] = record["reason"] or first_sentence(declaration["reason"])
kind, reader_key, _label = declaration["reader"]
if kind == "emulator":
for where in (catalogued or {}).get((reader_key, declaration["name"].casefold()), []):
if where not in record["listed"]:
record["listed"].append(where)
_merge_named(records)
ordered = sorted(records.values(), key=_order)
_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)}
titles = sorted({system_name(s) for r in ordered for s in r["systems"]}, key=str.casefold)
title_at = {title: i for i, title in enumerate(titles)}
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"]),
}
item: dict = {"n": record["name"]}
if record["hashes"]:
item["h"] = {algo: record["hashes"][algo] for algo in ALGORITHMS if algo in record["hashes"]}
item["w"] = sorted(reader_at[reader] for reader in record["readers"])
systems = sorted({title_at[system_name(s)] for s in record["systems"]})
if systems:
item["s"] = ", ".join(systems)
item["s"] = systems
if record["required"]:
item["r"] = 1
if record["sizes"]:
item["z"] = record["sizes"]
for field, value in (("d", record["description"]), ("u", record["reason"])):
if value:
item[field] = value
if record["listed"]:
item["l"] = [list(where) for where in record["listed"]]
if spot.folder:
item["f"] = folder_at[spot.folder]
if spot.name:
@@ -300,45 +373,91 @@ def build_wanted(
"issue": LARGE_FILE_ISSUE_URL,
"limit": BROWSER_UPLOAD_LIMIT,
"readers": [[kind[0], key, label] for kind, key, label in readers],
"systems": titles,
"folders": folders,
"entries": entries,
}
def _merge_named(records: dict[tuple, dict]) -> None:
"""A declaration that writes no hash takes any file of its name: when
a declaration of the same name and system writes one, the file that
meets it meets both, so its readers join that entry."""
hashed: dict[tuple[str, str], list[dict]] = {}
for record in records.values():
if record["hashes"]:
for system in record["systems"] or {""}:
hashed.setdefault((record["name"].casefold(), system), []).append(record)
for key in [k for k, record in records.items() if not record["hashes"]]:
targets = hashed.get(key, [])
if len(targets) != 1:
continue
record = records.pop(key)
target = targets[0]
target["readers"] |= record["readers"]
target["required"] = target["required"] or record["required"]
target["description"] = target["description"] or record["description"]
target["reason"] = target["reason"] or record["reason"]
target["listed"] += [w for w in record["listed"] if w not in target["listed"]]
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.
def page(total: int, known: int) -> str:
"""The wanted page: the drop box, the steps from a file in hand to a
file in the collection, then every wanted file (WantedList.astro).
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",
"terms: wanted list, donate, give a file, upload to github, help the collection, missing bios",
"---",
"",
"# Wanted",
"",
"Have a file the collection lacks? Drop it below. The page says if we want it.",
"Have a file the collection lacks? Drop it below to see if it is wanted.",
"Files are read on this device. Nothing leaves it before an upload to GitHub.",
"",
"<WantedFiles />",
"",
"Your files are read on this device. Nothing is sent until you upload one to GitHub.",
"Several files at once? Drop them all. Each gets its own answer and upload button.",
"",
"## After the upload",
"## Where a file comes from",
"",
"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.",
"- A console or handheld at home: its BIOS, copied with a homebrew tool.",
"- An old SD card, or the BIOS folder of an emulator used before.",
"- A firmware update package from the maker.",
"",
(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)."),
"When a catalog lists a file, its row in the list names it.",
"To check any other file, use [Find or check a file](files/index.md).",
"",
("To look up any file, use [Find or check a file](files/index.md). "
"More ways to help are on [Contributing](contributing.md)."),
"## Send it",
"",
"1. Make a free GitHub account once: [sign up](https://github.com/signup).",
"2. Press the upload button of the file. GitHub opens the right folder.",
"3. Rename the file if the page asks, then drop it there.",
"4. GitHub makes a copy of the project and opens a pull request, a request to add the file.",
"5. A check reads the file and comments on the request.",
"",
"The maintainer then merges it, and the file joins the downloads and the installer.",
"",
(f"A file over {BROWSER_UPLOAD_LIMIT // (1024 * 1024)} MB is too large for the upload page. "
"Its button opens an issue form with the details filled in."),
"",
"## The wanted list",
"",
(f"The list holds {total:,} files, most useful first. Of these, {known:,} have a "
"fingerprint (a hash), so a dropped copy is recognised."),
"",
"The others are known by name only: upload one and the check decides.",
"",
"<WantedList />",
"",
"More ways to help are on [Contributing](contributing.md).",
"",
])
+2 -1
View File
@@ -42,7 +42,8 @@ START_PAGES = {
START_LEVEL_PAGES = {
"wiki/measurements.md": 300,
"wiki/archive-recipes.md": 160,
"wanted.md": 160,
# The drop box, then the steps from a file in hand to its merge.
"wanted.md": 260,
}
# Level 1: the guide part of each setup page, above its Reference heading.
SETUP_CEILING = 220
+162 -16
View File
@@ -2,10 +2,11 @@
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.
wants it, then lists every wanted file with its own upload button. 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
@@ -20,6 +21,7 @@ import subprocess
import sys
import tempfile
import unittest
import re
import zlib
from pathlib import Path
@@ -30,9 +32,11 @@ import generate_site # noqa: E402
import sitewanted # noqa: E402
import validate_pr # noqa: E402
from common import load_database # noqa: E402
from tests.test_site_pronouns import pronouns # noqa: E402
WEBSITE = REPO_ROOT / "website"
WANTED_TS = WEBSITE / "src" / "scripts" / "wanted.ts"
COMPONENTS = WEBSITE / "src" / "components"
PUBLISHED = WEBSITE / "public" / sitewanted.DATA_FILE
HELD = b"held rom"
@@ -89,7 +93,7 @@ class _World(unittest.TestCase):
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: nohash.bin\n system: x\n description: A boot ROM. Read at start.\n"
" - name: later.bin\n system: x\n unsourceable: not dumped yet\n"
f" md5: \"{md5(b'later')}\"\n"
)
@@ -100,7 +104,7 @@ class _World(unittest.TestCase):
{"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": "nohash.bin", "system": "x", "description": "A boot ROM. Read at start."},
{"name": "later.bin", "system": "x", "unsourceable": "not dumped yet",
"md5": md5(b"later")},
],
@@ -152,16 +156,80 @@ class _World(unittest.TestCase):
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"])
# a.bin is held, m.bin is held inside set.zip, 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", "nohash.bin",
"r.bin", "r.bin", "v.bin", "z.zip"])
def test_an_entry_with_no_hash_is_kept_and_marked(self):
"""nohash.bin declares no hash and z.zip only the md5 of a ROM
inside it: a dropped file cannot be compared with either, but a
person who has it can still upload it from the list."""
for name in ("nohash.bin", "z.zip"):
with self.subTest(name=name):
self.assertNotIn("h", self.entry(name))
self.assertEqual(self.entry("nohash.bin")["d"], "A boot ROM.")
self.assertIn("h", self.entry("b.bin"))
def test_required_entries_come_first(self):
needs = [bool(e.get("r")) for e in self.data["entries"]]
self.assertEqual(needs, sorted(needs, reverse=True))
self.assertTrue(any(needs) and not all(needs))
def test_more_readers_come_first(self):
records = [{"name": "a", "required": False, "readers": {("emulator", "e", "E")}},
{"name": "b", "required": False,
"readers": {("emulator", "e", "E"), ("platform", "p", "P")}},
{"name": "c", "required": True, "readers": {("emulator", "e", "E")}}]
self.assertEqual([r["name"] for r in sorted(records, key=sitewanted._order)], ["c", "b", "a"])
def test_a_name_with_no_hash_joins_the_hashed_entry_of_its_name(self):
reader = ("emulator", "other", "Other")
records = {
("b.bin", (("sha1", ("x",)),), ()): {
"name": "b.bin", "hashes": {"sha1": ["x"]}, "systems": {"x"}, "required": False,
"readers": {("emulator", "engine", "Engine")}, "description": "",
"reason": "", "listed": []},
("b.bin", "x"): {
"name": "b.bin", "hashes": {}, "systems": {"x"}, "required": True,
"readers": {reader}, "description": "B", "reason": "", "listed": []},
}
sitewanted._merge_named(records)
self.assertEqual(len(records), 1)
merged = next(iter(records.values()))
self.assertIn(reader, merged["readers"])
self.assertTrue(merged["required"])
def test_a_pattern_is_not_a_file(self):
profiles = {"engine": {**self.profiles["engine"], "files": [
*self.profiles["engine"]["files"], {"name": "<serial>.txt", "system": "x"}]}}
report = {"engine": {**self.gap_report["engine"], "gap_details": [
*self.gap_report["engine"]["gap_details"],
{"name": "<serial>.txt", "source": "missing", "identity": ""}]}}
data = sitewanted.build_wanted(profiles, self.coverages, report, self.db, self.placer,
str, self.ledger)
self.assertNotIn("<serial>.txt", [e["n"] for e in data["entries"]])
def test_a_catalog_listing_reaches_its_entry(self):
listings = sitewanted.catalog_listings(
{"tosec": {"missing": [{"name": "Boot (1990)", "romsets": [],
"needed_by": [{"emulator": "engine", "name": "b.bin"}]}]}},
{"tosec": "TOSEC"})
data = sitewanted.build_wanted(self.profiles, self.coverages, self.gap_report, self.db,
self.placer, str, self.ledger, listings)
self.assertEqual(next(e for e in data["entries"] if e["n"] == "b.bin")["l"],
[["TOSEC", "Boot (1990)"]])
def test_first_sentence(self):
self.assertEqual(sitewanted.first_sentence("One. Two."), "One.")
self.assertEqual(sitewanted.first_sentence("Ver. 1.0 of A"), "Ver. 1.0 of A")
cut = sitewanted.first_sentence("word " * 60)
self.assertTrue(cut.endswith("...") and len(cut) <= sitewanted.DESCRIPTION_LIMIT + 3)
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([self.data["systems"][i] for i in 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"]],
@@ -219,10 +287,10 @@ class EveryFolderIsTheReviewsFolder(_World):
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, [])
values = [v for algo in ("sha1", "md5", "sha256") for v in entry.get("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,
self.profile_hashes, declared="h" in entry,
exists=self.placer.paths.__contains__)
with self.subTest(entry=entry["n"]):
self.assertEqual(self.data["folders"][entry["f"]] if "f" in entry else "",
@@ -294,6 +362,38 @@ class ThePageReadsTheListAsTheResolverDoes(_World):
self.assertEqual(variant, {"folder": "bios/Maker/Console/.variants/",
"name": f"v.bin.{sha1(VARIANT)[:8]}"})
def test_every_row_uploads_to_the_reviews_folder(self):
"""The list's own button on each row, against validate_pr.placement
for the declarations of that row."""
rows = json.loads(_node(
f"import {{ rowTarget, uploadUrl }} from {json.dumps(WANTED_TS.as_uri())};"
f"const data = {json.dumps(self.data)};"
"console.log(JSON.stringify(data.entries.map((e) => {"
" const place = rowTarget(data, e); return {...place, url: uploadUrl(data, place.folder)}; })));"
))
self.assertEqual(len(rows), len(self.data["entries"]))
for entry, place in zip(self.data["entries"], rows):
spot = self.placer.place(entry.get("h", {}), entry["n"])
folder = (spot.folder or "bios/") + (".variants/" if spot.variant else "")
with self.subTest(entry=entry["n"]):
self.assertEqual(place["folder"], folder)
self.assertEqual(place["url"], sitewanted.upload_href(sitewanted.UPLOAD_ROOT, folder))
if spot.variant:
self.assertEqual(place["name"], f"{spot.name}.{entry['h']['sha1'][0][:8]}"
if len(entry.get("h", {}).get("sha1", [])) == 1 else "")
else:
self.assertEqual(place["name"], spot.name or entry["n"])
def test_a_dropped_file_meets_a_name_only_entry_by_its_name(self):
out = json.loads(_node(
f"import {{ byName, matches }} from {json.dumps(WANTED_TS.as_uri())};"
f"const data = {json.dumps(self.data)};"
"const file = {sha1: 'x', md5: 'x', crc32: 'x', sha256: 'x'};"
"console.log(JSON.stringify([byName(data, 'NOHASH.BIN').map((e) => e.n),"
" byName(data, 'b.bin').map((e) => e.n), matches(data, file, 1).map((e) => e.n)]));"
))
self.assertEqual(out, [["nohash.bin"], [], []])
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)
@@ -306,7 +406,35 @@ class TheTwoPagesLinkEachOther(unittest.TestCase):
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))
self.assertIn("[Find or check a file](files/index.md)", sitewanted.page(2, 1))
class ThePageSpeaksWithoutPronouns(unittest.TestCase):
"""The generated page is held by test_site_pronouns. The words the
components write at run time are held here."""
STRING = re.compile(r"'((?:[^'\\\n]|\\.)*)'|`([^`]*)`")
MARKUP_TEXT = re.compile(r">([^<>{}]+)<")
def test_page(self):
self.assertEqual(pronouns(sitewanted.page(1_165, 199)), [])
def test_components(self):
for name in ("WantedFiles.astro", "WantedList.astro"):
source = (COMPONENTS / name).read_text(encoding="utf-8")
script = source[source.index("<script>"):source.index("</script>")]
texts = [a or b for a, b in self.STRING.findall(script)]
texts += self.MARKUP_TEXT.findall(source[:source.index("<script>")])
with self.subTest(component=name):
self.assertTrue(texts)
self.assertEqual([t for t in texts if pronouns(t)], [])
def test_the_page_lists_the_steps(self):
text = sitewanted.page(1_165, 199)
for step in ("<WantedFiles />", "<WantedList />", "https://github.com/signup",
"pull request", "issue form", "Drop them all", "1,165 files"):
self.assertIn(step, text)
self.assertLess(text.index("<WantedFiles />"), text.index("<WantedList />"))
class ThePublishedList(unittest.TestCase):
@@ -323,15 +451,22 @@ class ThePublishedList(unittest.TestCase):
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"]:
if "h" not in entry:
continue
with self.subTest(entry=entry["n"]):
self.assertFalse(held.holds(entry["h"], entry.get("z", [])))
def test_required_first_and_names_kept(self):
needs = [bool(e.get("r")) for e in self.data["entries"]]
self.assertEqual(needs, sorted(needs, reverse=True))
self.assertTrue(any("h" not in e for e in self.data["entries"]))
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"])
spot = placer.place(entry.get("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)
@@ -339,6 +474,17 @@ class ThePublishedList(unittest.TestCase):
def test_weight(self):
self.assertLess(PUBLISHED.stat().st_size, 200_000)
def test_the_built_page_asks_for_this_list(self):
"""The list's address carries its version: a browser that cached an
older list (another shape) fetches this one."""
built = WEBSITE / "dist" / "wanted" / "index.html"
if not built.is_file():
self.skipTest("no built site")
html = built.read_text(encoding="utf-8")
version = hashlib.sha1(PUBLISHED.read_bytes()).hexdigest()[:12]
self.assertEqual(html.count(f'data-version="{version}"'), 2)
self.assertNotIn("data/wanted.json", html)
if __name__ == "__main__":
unittest.main()
+21 -11
View File
@@ -1,14 +1,18 @@
---
// 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
// the collection lacks (scripts/sitewanted.py). A file no hash matches
// may still be an entry known by its name only. 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.
import { wantedVersion } from '../scripts/wanted-version.ts';
const base = import.meta.env.BASE_URL.replace(/\/?$/, '/');
const version = wantedVersion();
---
<div class="rb-wanted" data-base={base}>
<div class="rb-wanted" data-base={base} data-version={version}>
<div class="rb-wanted-drop">
<p><strong>Drop files here</strong></p>
<label class="rb-button" for="rb-wanted-input">Or choose them</label>
@@ -20,7 +24,7 @@ const base = import.meta.env.BASE_URL.replace(/\/?$/, '/');
<script>
import { type FileHashes, hashFile } from '../scripts/hashes.ts';
import { type Entry, type Wanted, issueUrl, matches, target, uploadUrl } from '../scripts/wanted.ts';
import { type Entry, type Wanted, byName, issueUrl, loadWanted, matches, target, uploadUrl } from '../scripts/wanted.ts';
type Item = { layer: string; value: string; url: string; archive?: string; sha1?: string };
@@ -41,11 +45,11 @@ const base = import.meta.env.BASE_URL.replace(/\/?$/, '/');
for (const root of document.querySelectorAll<HTMLElement>('.rb-wanted')) {
const base = root.dataset.base ?? '/';
const version = root.dataset.version ?? '';
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);
@@ -69,35 +73,41 @@ const base = import.meta.env.BASE_URL.replace(/\/?$/, '/');
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 data = await loadWanted(base, version);
const found = matches(data, hashes, file.size);
if (found.length) return wantedBlock(data, found, file, hashes);
if (found.length) return wantedBlock(data, found, file, hashes, 'Wanted.');
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 named = byName(data, file.name);
if (named.length) return wantedBlock(data, named, file, hashes, 'Maybe wanted.');
return [element('p', element('strong', 'Not wanted.'), ' No list the collection follows asks for this file.')];
};
const wantedBlock = (data: Wanted, found: Entry[], file: File, hashes: FileHashes): Node[] => {
const wantedBlock = (data: Wanted, found: Entry[], file: File, hashes: FileHashes, verdict: string): 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 systems = [...new Set(found.flatMap((entry) => entry.s ?? []))].map((index) => data.systems[index]);
const required = found.some((entry) => entry.r);
const blocks: Node[] = [
element('p', element('strong', 'Wanted.'), ' This is ', code(best.n),
element('p', element('strong', verdict), best.h ? ' This is ' : ' The list asks for ', code(best.n),
...(systems.length ? [`, for ${systems.join(', ')}`] : []), '. ',
required ? 'Needed by ' : 'Used by ', ...listed(readers), '.'),
];
if (!best.h) {
blocks.push(element('p', 'The list knows this file by its name only. ',
'The check after the upload compares its contents.'));
}
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.'));
' with its hashes filled in.'));
return blocks;
}
if (place.name !== file.name) blocks.push(element('p', 'Rename it to ', code(place.name), ' first.'));
+254
View File
@@ -0,0 +1,254 @@
---
// Every file of public/data/wanted.json (scripts/sitewanted.py), by system,
// most useful first. The list is fetched when the page runs, never written
// in the HTML: a group's rows are drawn when it opens or a filter reaches
// it. Each row carries its own upload button, to the folder
// validate_pr.placement() gives (wanted.ts rowTarget).
import { wantedVersion } from '../scripts/wanted-version.ts';
const base = import.meta.env.BASE_URL.replace(/\/?$/, '/');
const version = wantedVersion();
---
<div class="rb-wanted-browse" data-base={base} data-version={version}>
<div class="rb-table-filter rb-wanted-filter" hidden data-pagefind-ignore="all">
<label for="rb-wanted-filter">Filter the list</label>
<input id="rb-wanted-filter" type="search" autocomplete="off"
placeholder="Name, system, emulator, setup" aria-describedby="rb-wanted-filter-count" />
<span id="rb-wanted-filter-count" class="rb-table-filter-count" aria-live="polite"></span>
</div>
<p class="rb-wanted-state">The list loads with the page. Without JavaScript, the <a href={`${base}gaps/`}>gaps page</a> lists the same files.</p>
<div class="rb-wanted-groups"></div>
</div>
<script>
import { type Entry, type Wanted, loadWanted, rowIssueUrl, rowTarget, tooLarge, uploadUrl } from '../scripts/wanted.ts';
const LABELS: Record<string, string> = { sha1: 'SHA-1', sha256: 'SHA-256', md5: 'MD5', crc32: 'CRC32' };
const OTHER = 'Other files';
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]));
const plural = (count: number, noun: string) => `${count.toLocaleString('en')} ${noun}${count === 1 ? '' : 's'}`;
// A system's fold: its entries, those the filter keeps, and those drawn.
type Group = {
title: string; entries: Entry[]; required: number;
details: HTMLDetailsElement; list: HTMLOListElement;
found: Entry[]; drawn: Entry[] | null;
};
// A filter that keeps this many rows or fewer in a system opens it.
const OPEN_AT = 50;
for (const root of document.querySelectorAll<HTMLElement>('.rb-wanted-browse')) {
const base = root.dataset.base ?? '/';
const version = root.dataset.version ?? '';
const filter = root.querySelector<HTMLElement>('.rb-wanted-filter')!;
const input = root.querySelector<HTMLInputElement>('#rb-wanted-filter')!;
const count = root.querySelector<HTMLElement>('#rb-wanted-filter-count')!;
const state = root.querySelector<HTMLElement>('.rb-wanted-state')!;
const holder = root.querySelector<HTMLElement>('.rb-wanted-groups')!;
const link = (href: string, text: string) => {
const a = element('a', text);
a.href = href;
return a;
};
const row = (data: Wanted, entry: Entry): HTMLLIElement => {
const head = element('p', code(entry.n), ' ');
const need = element('span', entry.r ? 'Required' : 'Optional');
need.className = `rb-badge ${entry.r ? 'rb-badge-warning' : 'rb-badge-muted'}`;
head.append(need);
if (entry.z?.length) head.append(` ${entry.z.map(size).join(' or ')}`);
head.className = 'rb-wanted-row-head';
const item = element('li', head);
item.className = 'rb-wanted-row';
if (entry.d) item.append(element('p', entry.d));
const systems = (entry.s ?? []).map((index) => data.systems[index]);
const readers = entry.w.map((index) => {
const [kind, key, label] = data.readers[index];
return link(`${base}${kind === 'p' ? 'platforms' : 'emulators'}/${key}/`, label);
});
item.append(element('p', ...(systems.length ? [`For ${systems.join(', ')}. `] : []),
entry.r ? 'Needed by ' : 'Used by ', ...listed(readers), '.'));
if (entry.u) item.append(element('p', 'Not collected yet: ', entry.u.replace(/\.?$/, '.')));
for (const [where, name] of entry.l ?? []) item.append(element('p', `Listed in ${where} as `, code(name), '.'));
if (entry.h) {
const hashes = element('dl');
hashes.className = 'rb-wanted-hashes';
for (const [algo, values] of Object.entries(entry.h)) {
for (const value of values ?? []) {
const copy = element('button', 'Copy');
copy.type = 'button';
copy.className = 'rb-copy rb-wanted-copy';
copy.dataset.value = value;
copy.setAttribute('aria-label', `Copy the ${LABELS[algo]} of ${entry.n}`);
hashes.append(element('dt', LABELS[algo]), element('dd', code(value), copy));
}
}
item.append(hashes);
} else {
const note = element('p', 'No fingerprint in the list: the file is known by its name only. The check after the upload decides.');
note.className = 'rb-wanted-named';
item.append(note);
}
if (tooLarge(data, entry)) {
const issue = link(rowIssueUrl(data, entry), 'Open an issue');
issue.className = 'rb-button';
issue.target = '_blank';
issue.rel = 'noopener';
item.append(element('p', `Over ${size(data.limit)}, too large for the upload page. `, issue));
return item;
}
const place = rowTarget(data, entry);
const button = link(uploadUrl(data, place.folder), `Upload to ${place.folder}`);
button.className = 'rb-button rb-wanted-upload';
button.target = '_blank';
button.rel = 'noopener';
const naming = place.name
? ['Upload it as ', code(place.name), '.']
: ['Drop it above first: its name in that folder ends with part of its fingerprint.'];
item.append(element('p', ...naming), element('p', button));
return item;
};
const words = (text: string) => text.toLowerCase().split(/\s+/).filter(Boolean);
const draw = (data: Wanted, group: Group) => {
if (group.drawn === group.found) return;
group.list.replaceChildren(...group.found.map((entry) => row(data, entry)));
group.drawn = group.found;
};
const show = (data: Wanted, groups: Group[], haystack: Map<Entry, string>) => {
const query = words(input.value);
let rows = 0;
let visible = 0;
for (const group of groups) {
const title = group.title.toLowerCase();
group.found = query.length
? group.entries.filter((entry) => query.every((word) => haystack.get(entry)!.includes(word) || title.includes(word)))
: group.entries;
group.details.hidden = !group.found.length;
if (group.found.length) visible += 1;
rows += group.found.length;
if (query.length) group.details.open = group.found.length > 0 && group.found.length <= OPEN_AT;
if (group.details.open) draw(data, group);
}
count.textContent = query.length
? `${plural(rows, 'row')} in ${plural(visible, 'system')}`
: `${plural(data.entries.length, 'file')} in ${plural(groups.length, 'system')}`;
};
loadWanted(base, version).then((data) => {
const bySystem = new Map<string, Entry[]>();
for (const entry of data.entries) {
const titles = entry.s?.length ? entry.s.map((index) => data.systems[index]) : [OTHER];
for (const title of titles) {
if (!bySystem.has(title)) bySystem.set(title, []);
bySystem.get(title)!.push(entry);
}
}
const haystack = new Map(data.entries.map((entry) => [entry, [
entry.n, entry.d ?? '', ...(entry.s ?? []).map((index) => data.systems[index]),
...entry.w.map((index) => data.readers[index][2]),
].join(' ').toLowerCase()]));
// The list comes most useful first (sitewanted._order): a system
// comes where its first file does, and its rows keep that order.
const groups: Group[] = [...bySystem].map(([title, entries]) => {
const required = entries.filter((entry) => entry.r).length;
const summary = element('summary', element('span', title), ' ');
const counted = element('span', `${plural(entries.length, 'file')}${required ? `, ${required.toLocaleString('en')} required` : ''}`);
counted.className = 'rb-wanted-group-count';
summary.append(counted);
const list = element('ol');
list.className = 'rb-wanted-rows';
const details = element('details', summary, list);
details.className = 'rb-wanted-group';
return { title, entries, required, details, list, found: entries, drawn: null };
});
for (const group of groups) {
group.details.addEventListener('toggle', () => {
if (group.details.open) draw(data, group);
});
}
holder.replaceChildren(...groups.map((group) => group.details));
state.remove();
filter.hidden = false;
show(data, groups, haystack);
let pending = 0;
input.addEventListener('input', () => {
window.clearTimeout(pending);
pending = window.setTimeout(() => show(data, groups, haystack), 150);
});
}).catch((error) => {
console.error(error);
state.replaceChildren('The list could not load. The ', link(`${base}gaps/`, 'gaps page'), ' lists the same files.');
});
holder.addEventListener('click', async (event) => {
const button = (event.target as Element).closest?.<HTMLButtonElement>('button.rb-wanted-copy');
if (!button) return;
try {
await navigator.clipboard.writeText(button.dataset.value ?? '');
button.textContent = 'Copied';
} catch {
// No clipboard: the value is selected, for Ctrl+C.
const range = document.createRange();
range.selectNodeContents(button.previousElementSibling ?? button);
const selection = window.getSelection();
selection?.removeAllRanges();
selection?.addRange(range);
}
});
}
</script>
<style is:global>
.rb-wanted-group { border-top: 1px solid var(--rb-border); }
.rb-wanted-group:last-child { border-bottom: 1px solid var(--rb-border); }
.rb-wanted-group[hidden] { display: none; }
.rb-wanted-group > summary {
display: flex;
flex-wrap: wrap;
gap: 0.25rem 0.75rem;
align-items: baseline;
min-height: 44px;
padding: 0.6rem 0;
cursor: pointer;
font-weight: 600;
}
.rb-wanted-group-count { color: var(--rb-text-secondary); font-size: 0.85rem; font-weight: 400; }
.sl-markdown-content .rb-wanted-rows { margin: 0 0 1rem; padding: 0; list-style: none; }
.sl-markdown-content .rb-wanted-row {
margin: 0.75rem 0 0;
padding: 0.75rem;
border: 1px solid var(--rb-border);
border-radius: 6px;
overflow-wrap: anywhere;
}
.sl-markdown-content .rb-wanted-row > * { margin: 0.35rem 0 0; }
.sl-markdown-content .rb-wanted-row > :first-child { margin-top: 0; }
.rb-wanted-row-head code { font-weight: 600; }
.rb-wanted-named { color: var(--rb-text-secondary); }
.sl-markdown-content .rb-wanted-hashes {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
gap: 0.2rem 0.75rem;
font-size: 0.85rem;
}
.sl-markdown-content .rb-wanted-hashes > * { margin: 0; }
.sl-markdown-content .rb-wanted-hashes dt { color: var(--rb-text-secondary); }
.sl-markdown-content .rb-wanted-hashes code { overflow-wrap: anywhere; }
</style>
+15
View File
@@ -0,0 +1,15 @@
// Read at build time by WantedFiles.astro and WantedList.astro: the first
// characters of the sha1 of public/data/wanted.json, added to its address.
// A browser that kept an older list in its cache asks for the new one: the
// two components read the list's current shape, and an older list broke
// them.
import { createHash } from 'node:crypto';
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
// npm runs the build from website/, the project root.
const LIST = join(process.cwd(), 'public', 'data', 'wanted.json');
export const wantedVersion = (): string =>
existsSync(LIST) ? createHash('sha1').update(readFileSync(LIST)).digest('hex').slice(0, 12) : '';
+51 -4
View File
@@ -1,15 +1,20 @@
// The wanted page's reading of public/data/wanted.json (scripts/sitewanted.py):
// which entries a hashed file is, and where its upload goes.
// which entries a hashed file is, and where its upload goes. An entry
// with no h is known by its name only: a dropped file meets it by name,
// and the review of the upload decides.
import type { FileHashes } from './hashes.ts';
export type Entry = {
n: string;
h: { sha1?: string[]; sha256?: string[]; md5?: string[]; crc32?: string[] };
h?: { sha1?: string[]; sha256?: string[]; md5?: string[]; crc32?: string[] };
w: number[];
s?: string;
s?: number[];
r?: number;
z?: number[];
d?: string;
u?: string;
l?: [string, string][];
f?: number;
t?: string;
v?: number;
@@ -20,6 +25,7 @@ export type Wanted = {
issue: string;
limit: number;
readers: [string, string, string][];
systems: string[];
folders: string[];
entries: Entry[];
};
@@ -30,6 +36,7 @@ export type Wanted = {
// 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 => {
if (!entry.h) return false;
const { sha1, sha256, md5, crc32 } = entry.h;
if (sha1 && !sha1.includes(file.sha1)) return false;
if (sha256 && !sha256.includes(file.sha256)) return false;
@@ -41,11 +48,15 @@ export const satisfies = (entry: Entry, file: FileHashes, size: number): boolean
// 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;
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 entries known by their name only that a file of this name may be.
export const byName = (data: Wanted, name: string): Entry[] =>
data.entries.filter((entry) => !entry.h && entry.n.toLowerCase() === name.toLowerCase());
// 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
@@ -57,6 +68,31 @@ export const target = (data: Wanted, entry: Entry, file: FileHashes, ownName: st
return { folder, name: entry.t };
};
// Where the list sends a file before it is read: the drop target, under
// the name the declarations give. A variant's name ends with the first 8
// characters of its sha1: with no single sha1 declared, the name is known
// once the file is dropped, and name is empty.
export const rowTarget = (data: Wanted, entry: Entry) => {
const folder = entry.f === undefined ? 'bios/' : data.folders[entry.f];
if (!entry.t) return { folder, name: entry.n };
if (!entry.v) return { folder, name: entry.t };
const sha1 = entry.h?.sha1?.length === 1 ? entry.h.sha1[0] : '';
return { folder: `${folder}.variants/`, name: sha1 ? `${entry.t}.${sha1.slice(0, 8)}` : '' };
};
// Too large for GitHub's upload page: every size the declarations allow
// is over the limit.
export const tooLarge = (data: Wanted, entry: Entry) => !!entry.z?.length && entry.z.every((size) => size > data.limit);
let loaded: Promise<Wanted> | null = null;
// The list, fetched once for the drop box and the list below it. The
// version (wanted-version.ts) keeps a cached older list out.
export const loadWanted = (base: string, version = ''): Promise<Wanted> =>
(loaded ??= fetch(`${base}data/wanted.json${version ? `?v=${version}` : ''}`).then((response) => {
if (!response.ok) throw new Error(`wanted.json: ${response.status}`);
return response.json();
}));
export const uploadUrl = (data: Wanted, folder: string) =>
data.upload + folder.replace(/\/$/, '').split('/').map(encodeURIComponent).join('/');
@@ -70,3 +106,14 @@ export const issueUrl = (data: Wanted, name: string, file: FileHashes, size: num
md5: file.md5,
size: String(size),
})}`;
// The issue form for a listed file too large for the browser, with the
// hashes and the size its declarations write.
export const rowIssueUrl = (data: Wanted, entry: Entry) =>
`${data.issue}&${new URLSearchParams({
title: `[BIOS] Missing: ${entry.n}`,
filename: entry.n,
sha1: entry.h?.sha1?.[0] ?? '',
md5: entry.h?.md5?.find((value) => value.length === 32) ?? '',
size: entry.z?.length === 1 ? String(entry.z[0]) : '',
})}`;