From b18e478db041117d7e9399aabd749fde355fef83 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:45:12 +0100 Subject: [PATCH 1/4] refactor: share the placement rule of validate_pr placement() decides the folder and name of a file not under bios/ yet, so the wanted page and the gaps page send an upload where the review asks for it. A declared file whose name the collection holds now gets the .variants/ slot beside it. --- scripts/validate_pr.py | 146 +++++++++++++++++++++++++++----------- tests/test_validate_pr.py | 27 +++++++ 2 files changed, 133 insertions(+), 40 deletions(-) diff --git a/scripts/validate_pr.py b/scripts/validate_pr.py index e31edce6c..4d2b6c609 100644 --- a/scripts/validate_pr.py +++ b/scripts/validate_pr.py @@ -27,6 +27,8 @@ import subprocess import sys import urllib.parse import zipfile +from collections.abc import Callable, Iterable +from dataclasses import dataclass from pathlib import Path sys.path.insert(0, os.path.dirname(__file__)) @@ -554,18 +556,8 @@ def validate_file( ) normalized = os.path.normpath(relative) - # A platform's declaration first, then a profile's: most files the gaps - # page lists are declared by a profile alone. - expected = next( - ( - table["folders"][value] - for table in (platform_hashes, profile_hashes) - for value in (result.sha1, result.md5, hashes.get("sha256", "")) - if value in table.get("folders", {}) - ), - set(), - ) - expected_folders = sorted(expected) + values = (result.sha1, result.md5, hashes.get("sha256", "")) + expected = expected_folders(values, platform_hashes, profile_hashes) if too_large: # The file stays out of the pull request, so no folder of bios/ is # the contributor's to choose: the release asset is placed by hand. @@ -578,7 +570,7 @@ def validate_file( # Depth alone passed a PS1 BIOS filed under bios/Nintendo/Game Boy/. result.add_warning( "Placed under " + (here or "the bios/ root") + ", while the other files of " - "its system are in " + " or ".join(f"`{f}`" for f in sorted(expected)) + "its system are in " + " or ".join(f"`{f}`" for f in expected) ) elif len(parts) >= 4: result.add_check(True, f"Correct placement: bios/{parts[1]}/{parts[2]}/") @@ -587,35 +579,28 @@ def validate_file( elif result.outcome == "held" or members is not None: # Nothing to place: a copy, or an archive whose files go in unzipped. pass - elif expected_folders: - # The contributor asks before forking: say where it goes. - names = { - name - for table in (platform_hashes, profile_hashes) - for value in (result.sha1, result.md5, hashes.get("sha256", "")) - for name in table.get("named", {}).get(value, ()) - } - name = next(iter(names)) if len(names) == 1 else "" - if len(expected_folders) == 1 and name and "/" not in name: - folder = expected_folders[0] - result.destination = ( - f"{folder}.variants/{name}.{result.sha1[:8]}" - if os.path.exists(folder + name) else folder + name - ) - result.add_warning( - "File is not under bios/ yet. Its system's files are in " - + " or ".join(f"`{f}`" for f in expected_folders) - + (f". --place copies it to `{result.destination}`" if result.destination else "") - ) - elif _variant_home(db, result.filename, result.sha1): - result.add_warning( - "File is not under bios/ yet. The collection keeps this name in " - f"`{_variant_home(db, result.filename, result.sha1)}`" - ) else: - result.add_warning( - "File is not under bios/ yet. Place it in bios/Manufacturer/Console/" + # The contributor asks before forking: say where it goes. + spot = placement( + values, result.filename, db, platform_hashes, profile_hashes, + declared=bool(sha1_known or md5_known or other_known or accepted_by or by_profile), ) + result.destination = spot.destination(result.sha1) + copies = f". --place copies it to `{result.destination}`" if result.destination else "" + if spot.folders: + result.add_warning( + "File is not under bios/ yet. Its system's files are in " + + " or ".join(f"`{f}`" for f in spot.folders) + copies + ) + elif spot.home: + result.add_warning( + f"File is not under bios/ yet. The collection keeps this name in `{spot.home}`" + + copies + ) + else: + result.add_warning( + "File is not under bios/ yet. Place it in bios/Manufacturer/Console/" + ) declared = [ *platform_hashes.get("sizes", {}).get(result.filename, []), @@ -671,6 +656,87 @@ def _platforms_accepting(filepath: str, filename: str, platform_hashes: dict) -> return accepted +def expected_folders( + values: Iterable[str], platform_hashes: dict, profile_hashes: dict | None +) -> list[str]: + """The bios/// folders the files of a hash's + system are in, read from the first of *values* a table knows. + + A platform's declaration first, then a profile's: most files the gaps + page lists are declared by a profile alone. + """ + for table in (platform_hashes, profile_hashes or {}): + for value in values: + if value and value in table.get("folders", {}): + return sorted(table["folders"][value]) + return [] + + +@dataclass(frozen=True) +class Placement: + """Where a file not under bios/ yet goes. + + ``folders`` are those of its system, ``home`` the folder the collection + keeps its name in when its system names none. ``name`` is the name it + is copied under, empty when the declarations do not settle one. + ``variant`` says a file of that name is already in the folder: a copy + goes beside it in .variants/, never over it. + """ + + folders: tuple[str, ...] = () + home: str = "" + name: str = "" + variant: bool = False + + @property + def folder(self) -> str: + return self.folders[0] if self.folders else self.home + + def destination(self, sha1: str) -> str: + if not self.name: + return "" + if self.variant: + return f"{self.folder}.variants/{self.name}.{sha1[:8]}" + return self.folder + self.name + + +def placement( + values: Iterable[str], + filename: str, + db: dict | None, + platform_hashes: dict, + profile_hashes: dict | None, + declared: bool, + exists: Callable[[str], bool] = os.path.exists, +) -> Placement: + """Where a file goes, by its hashes and its name. + + The review and the site's wanted page both read this one rule, so the + folder a contributor is sent to is the folder the review accepts. + *declared* says a list or a profile declares one of the hashes: a file + known by its name alone gets a slot only once its size fits. + """ + values = [value for value in values if value] + folders = expected_folders(values, platform_hashes, profile_hashes) + if folders: + names = { + name + for table in (platform_hashes, profile_hashes or {}) + for value in values + for name in table.get("named", {}).get(value, ()) + } + name = next(iter(names)) if len(names) == 1 else "" + if len(folders) == 1 and name and "/" not in name: + return Placement(tuple(folders), name=name, variant=exists(folders[0] + name)) + return Placement(tuple(folders)) + held = next((value for value in values if value in (db or {}).get("files", {})), "") + home = _variant_home(db, filename, held) + if declared and home and filename and "/" not in filename: + # The folder holds a file of that name already. + return Placement(home=home, name=filename, variant=True) + return Placement(home=home) + + def _variant_home(db: dict | None, name: str, held: str = "") -> str: """The folder the collection keeps a name in, for its variants beside it. diff --git a/tests/test_validate_pr.py b/tests/test_validate_pr.py index 1a0fb66f4..79ddef638 100644 --- a/tests/test_validate_pr.py +++ b/tests/test_validate_pr.py @@ -186,6 +186,33 @@ class AFileOnlyACoreReadsIsKnown(_Fixture): self.assertTrue(any("Placed under bios/Other/Place/" in m for _s, m in placed.checks)) +class ADeclaredFileBesideItsHeldNameIsAVariant(_Fixture): + """A file a profile declares, of a system the collection files nowhere + yet, whose name the collection holds: the review named the folder and + left the copy to land on the held file of that name.""" + + def test_place_copies_it_beside_the_held_name(self): + import hashlib # noqa: PLC0415 + + data = b"declared revision" + emulators = self.tmp / "emulators" + emulators.mkdir() + (emulators / "engine.yml").write_text( + "emulator: Engine\ntype: standalone\nsystems: [x, y]\nfiles:\n" + f" - name: \"v.bin\"\n sha1: \"{hashlib.sha1(data).hexdigest()}\"\n" + ) + db = {"files": {"a" * 40: {"path": "bios/Maker/Console/v.bin"}}, + "indexes": {"by_md5": {}, "by_sha256": {}, "by_name": {"v.bin": ["a" * 40]}}} + known = validate_pr.load_profile_hashes(str(emulators), db) + result = validate_pr.validate_file( + self._bios_file("card/v.bin", data), db, EMPTY_HASHES, known) + slot = f"bios/Maker/Console/.variants/v.bin.{result.sha1[:8]}" + self.assertEqual(result.destination, slot) + self.assertIn(("WARN", "File is not under bios/ yet. The collection keeps this name in " + f"`bios/Maker/Console/`. --place copies it to `{slot}`"), + result.checks) + + class ASizeEveryDeclarationRulesOutIsNotAVariant(_Fixture): """1024 random bytes named scph5501.bin, a name every declaration sizes at 524288, were told "File size OK" and offered a .variants slot at the From d685451f4418405561d67c2195be6cc5f062ad3b Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:45:12 +0100 Subject: [PATCH 2/4] refactor: hash a file in slices in one module MD5 and CRC32 take the file piece by piece, so a large file keeps the page responsive. The lookup and the wanted page read the same code, checked against hashlib and zlib. --- tests/test_site_components.py | 77 +++++++++++++++++---- website/src/scripts/hashes.ts | 125 ++++++++++++++++++++++++++++++++++ website/src/scripts/site.ts | 75 +------------------- 3 files changed, 191 insertions(+), 86 deletions(-) create mode 100644 website/src/scripts/hashes.ts diff --git a/tests/test_site_components.py b/tests/test_site_components.py index e89ddceb6..a3521afde 100644 --- a/tests/test_site_components.py +++ b/tests/test_site_components.py @@ -43,6 +43,7 @@ WEBSITE = REPO_ROOT / "website" DIST = WEBSITE / "dist" COMPONENTS = WEBSITE / "src" / "components" SITE_TS = WEBSITE / "src" / "scripts" / "site.ts" +HASHES_TS = WEBSITE / "src" / "scripts" / "hashes.ts" CONFIG = WEBSITE / "astro.config.mjs" PLUGIN = WEBSITE / "src" / "plugins" / "rehype-stack-tables.mjs" @@ -497,26 +498,76 @@ class HashAFileHere(unittest.TestCase): source = _read(SITE_TS) self.assertIn("input.type = 'file';", source) self.assertIn("It is hashed on this device. Nothing is uploaded.", source) - self.assertIn("crypto.subtle.digest(name, buffer)", source) - self.assertIn("['SHA-1', 'SHA-256']", source) + self.assertIn("import { type FileHashes, hashFile } from './hashes.ts';", source) self.assertIn("lookUp(status, result, [found.sha1, found.md5, found.crc32, found.sha256])", source) + hashing = _read(HASHES_TS) + self.assertIn("crypto.subtle.digest(name, buffer)", hashing) + self.assertIn("['SHA-1', 'SHA-256']", hashing) - def test_md5_and_crc32_match_python(self): - source = _read(SITE_TS) - block = source[source.index("// Hashing a file on this device"):source.index("type FileHashes")] - sizes = [0, 1, 55, 56, 63, 64, 65, 119, 120, 128, 1000, 70_001] - out = _node_module(block + ( - f"console.log(JSON.stringify({json.dumps(sizes)}.map((n) => {{" - "const bytes = new Uint8Array(n);" - "for (let i = 0; i < n; i += 1) bytes[i] = (i * 31 + 7) & 0xff;" - "return [md5(bytes), crc32(bytes)]; })));" + +class FileHashesMatchPython(unittest.TestCase): + """MD5 and CRC32 are written here, Web Crypto having neither: each is + checked against hashlib and zlib, whole and fed in uneven slices, and + hashFile's four values against a file read in 4 MiB slices.""" + + SIZES = [0, 1, 55, 56, 63, 64, 65, 119, 120, 128, 1000, 70_001] + + @staticmethod + def _bytes(size: int) -> bytes: + return bytes((i * 31 + 7) & 0xFF for i in range(size)) + + def _run(self, body: str) -> list: + return json.loads(_node_module( + f"import {{ Crc32, Md5, crc32, hashFile, md5 }} from {json.dumps(HASHES_TS.as_uri())};" + "const fill = (n) => { const b = new Uint8Array(n);" + " for (let i = 0; i < n; i += 1) b[i] = (i * 31 + 7) & 0xff; return b; };" + body )) - for size, (md5, crc) in zip(sizes, json.loads(out)): - data = bytes((i * 31 + 7) & 0xFF for i in range(size)) + + def test_md5_and_crc32_whole(self): + out = self._run( + f"console.log(JSON.stringify({json.dumps(self.SIZES)}.map((n) => " + "{ const bytes = fill(n); return [md5(bytes), crc32(bytes)]; })));" + ) + for size, (md5, crc) in zip(self.SIZES, out): + data = self._bytes(size) with self.subTest(size=size): self.assertEqual(md5, hashlib.md5(data).hexdigest()) self.assertEqual(crc, f"{zlib.crc32(data):08x}") + def test_md5_and_crc32_in_slices(self): + """A slice ending inside a 64-byte block carries it to the next.""" + size, steps = 200_003, [1, 63, 64, 65, 3, 1000, 7, 100_000] + out = self._run( + f"const bytes = fill({size}); const steps = {json.dumps(steps)};" + "const m = new Md5(); const c = new Crc32();" + "for (let at = 0, k = 0; at < bytes.length; k += 1) {" + " const piece = bytes.subarray(at, at + steps[k % steps.length]);" + " m.update(piece); c.update(piece); at += piece.length; }" + "console.log(JSON.stringify([m.digest(), c.digest()]));" + ) + data = self._bytes(size) + self.assertEqual(out, [hashlib.md5(data).hexdigest(), f"{zlib.crc32(data):08x}"]) + + def test_hash_file_reads_slices_and_reports_progress(self): + size = 9 * 1024 * 1024 + 17 + out = self._run( + f"const shares = []; const found = await hashFile(new Blob([fill({size})])," + " (share) => shares.push(share));" + "console.log(JSON.stringify([found, shares.length, shares.at(-1)," + " shares.every((v, i) => i === 0 || v >= shares[i - 1])]));" + ) + data = self._bytes(size) + found, steps, last, rising = out + self.assertEqual(found, { + "sha1": hashlib.sha1(data).hexdigest(), + "md5": hashlib.md5(data).hexdigest(), + "crc32": f"{zlib.crc32(data):08x}", + "sha256": hashlib.sha256(data).hexdigest(), + }) + self.assertGreaterEqual(steps, 3) + self.assertEqual(last, 1) + self.assertTrue(rising) + class SearchFoldsPagesUnderAHash(unittest.TestCase): """Under "Look up this hash" came 14 unrelated pages: Magnavox for diff --git a/website/src/scripts/hashes.ts b/website/src/scripts/hashes.ts new file mode 100644 index 000000000..840d97c58 --- /dev/null +++ b/website/src/scripts/hashes.ts @@ -0,0 +1,125 @@ +// Hashing a file on this device: SHA1 and SHA256 by Web Crypto, MD5 and +// CRC32 here, since Web Crypto has neither. The bytes never leave the page. +// MD5 and CRC32 take the file piece by piece, so a large file is read in +// slices and the page keeps answering between them. + +const CRC_TABLE = (() => { + const table = new Uint32Array(256); + for (let n = 0; n < 256; n += 1) { + let c = n; + for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + table[n] = c >>> 0; + } + return table; +})(); + +export const hexBytes = (bytes: Uint8Array) => [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join(''); + +export class Crc32 { + crc = 0xffffffff; + + update(bytes: Uint8Array): this { + let crc = this.crc; + for (let i = 0; i < bytes.length; i += 1) crc = CRC_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8); + this.crc = crc; + return this; + } + + digest(): string { + return ((this.crc ^ 0xffffffff) >>> 0).toString(16).padStart(8, '0'); + } +} + +const MD5_SHIFTS = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21]; +const MD5_TABLE = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 2 ** 32) >>> 0); + +// RFC 1321. Whole 64-byte blocks are read in place from each slice; only a +// block split between two slices is copied. +export class Md5 { + state = new Int32Array([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]); + words = new Int32Array(16); + pending = new Uint8Array(64); + pendingLength = 0; + length = 0; + + block(view: DataView, offset: number) { + const words = this.words; + const state = this.state; + for (let i = 0; i < 16; i += 1) words[i] = view.getInt32(offset + i * 4, true); + let [a, b, c, d] = state; + for (let i = 0; i < 64; i += 1) { + const round = i >> 4; + const f = round === 0 ? (b & c) | (~b & d) : round === 1 ? (d & b) | (~d & c) : round === 2 ? b ^ c ^ d : c ^ (b | ~d); + const g = round === 0 ? i : round === 1 ? (5 * i + 1) % 16 : round === 2 ? (3 * i + 5) % 16 : (7 * i) % 16; + const shift = MD5_SHIFTS[round * 4 + (i % 4)]; + const sum = (a + f + MD5_TABLE[i] + words[g]) | 0; + a = d; + d = c; + c = b; + b = (b + ((sum << shift) | (sum >>> (32 - shift)))) | 0; + } + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; + } + + update(bytes: Uint8Array): this { + this.length += bytes.length; + let start = 0; + if (this.pendingLength) { + start = Math.min(64 - this.pendingLength, bytes.length); + this.pending.set(bytes.subarray(0, start), this.pendingLength); + this.pendingLength += start; + if (this.pendingLength < 64) return this; + this.block(new DataView(this.pending.buffer), 0); + this.pendingLength = 0; + } + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const whole = start + ((bytes.length - start) - ((bytes.length - start) % 64)); + for (let offset = start; offset < whole; offset += 64) this.block(view, offset); + this.pending.set(bytes.subarray(whole)); + this.pendingLength = bytes.length - whole; + return this; + } + + digest(): string { + const tail = new Uint8Array(this.pendingLength < 56 ? 64 : 128); + tail.set(this.pending.subarray(0, this.pendingLength)); + tail[this.pendingLength] = 0x80; + const view = new DataView(tail.buffer); + const bits = this.length * 8; + view.setUint32(tail.length - 8, bits >>> 0, true); + view.setUint32(tail.length - 4, Math.floor(bits / 2 ** 32), true); + for (let offset = 0; offset < tail.length; offset += 64) this.block(view, offset); + return hexBytes(new Uint8Array(this.state.buffer)); + } +} + +export const md5 = (bytes: Uint8Array) => new Md5().update(bytes).digest(); +export const crc32 = (bytes: Uint8Array) => new Crc32().update(bytes).digest(); + +export type FileHashes = { sha1: string; md5: string; crc32: string; sha256: string }; + +const SLICE = 4 * 1024 * 1024; + +// The four hashes of a file. MD5 and CRC32 read it slice by slice, each +// slice awaited so the page stays responsive; *progress* gets the share +// read so far, from 0 to 1. SHA1 and SHA256 then hash it whole in Web +// Crypto, which works off the page's own thread. +export const hashFile = async (file: Blob, progress?: (share: number) => void): Promise => { + const md5State = new Md5(); + const crcState = new Crc32(); + for (let offset = 0; offset < file.size; offset += SLICE) { + const bytes = new Uint8Array(await file.slice(offset, offset + SLICE).arrayBuffer()); + md5State.update(bytes); + crcState.update(bytes); + progress?.(Math.min(1, (offset + bytes.length) / file.size)); + } + const buffer = await file.arrayBuffer(); + const [sha1, sha256] = await Promise.all( + ['SHA-1', 'SHA-256'].map(async (name) => hexBytes(new Uint8Array(await crypto.subtle.digest(name, buffer)))), + ); + progress?.(1); + return { sha1, md5: md5State.digest(), crc32: crcState.digest(), sha256 }; +}; diff --git a/website/src/scripts/site.ts b/website/src/scripts/site.ts index 22c97bbb1..52c87f533 100644 --- a/website/src/scripts/site.ts +++ b/website/src/scripts/site.ts @@ -7,6 +7,8 @@ // Which tables stack on a phone is decided when the page is built // (src/plugins/rehype-stack-tables.mjs), so the layout is right on first paint. +import { type FileHashes, hashFile } from './hashes.ts'; + const HASH_LENGTHS: Record = { 8: 'CRC32', 32: 'MD5', 40: 'SHA1', 64: 'SHA256' }; // One line of api/v1/lookup/. `system_name` is read when a record carries it. // `algorithm` is the hash the value was found under, `declared` the hash @@ -263,79 +265,6 @@ const breakPaths = () => { }); }; -// Hashing a file on this device: SHA1 and SHA256 by Web Crypto, MD5 and -// CRC32 here, since Web Crypto has neither. The bytes never leave the page. - -const CRC_TABLE = (() => { - const table = new Uint32Array(256); - for (let n = 0; n < 256; n += 1) { - let c = n; - for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; - table[n] = c >>> 0; - } - return table; -})(); - -const crc32 = (bytes: Uint8Array): string => { - let crc = 0xffffffff; - for (let i = 0; i < bytes.length; i += 1) crc = CRC_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8); - return ((crc ^ 0xffffffff) >>> 0).toString(16).padStart(8, '0'); -}; - -const MD5_SHIFTS = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21]; -const MD5_TABLE = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 2 ** 32) >>> 0); - -const hexBytes = (bytes: Uint8Array) => [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join(''); - -// RFC 1321, block by block over the file's own buffer: no padded copy of a -// 500 MB file. -const md5 = (bytes: Uint8Array): string => { - const state = new Int32Array([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]); - const words = new Int32Array(16); - const block = (view: DataView, offset: number) => { - for (let i = 0; i < 16; i += 1) words[i] = view.getInt32(offset + i * 4, true); - let [a, b, c, d] = state; - for (let i = 0; i < 64; i += 1) { - const round = i >> 4; - const f = round === 0 ? (b & c) | (~b & d) : round === 1 ? (d & b) | (~d & c) : round === 2 ? b ^ c ^ d : c ^ (b | ~d); - const g = round === 0 ? i : round === 1 ? (5 * i + 1) % 16 : round === 2 ? (3 * i + 5) % 16 : (7 * i) % 16; - const shift = MD5_SHIFTS[round * 4 + (i % 4)]; - const sum = (a + f + MD5_TABLE[i] + words[g]) | 0; - a = d; - d = c; - c = b; - b = (b + ((sum << shift) | (sum >>> (32 - shift)))) | 0; - } - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - }; - const whole = bytes.length - (bytes.length % 64); - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); - for (let offset = 0; offset < whole; offset += 64) block(view, offset); - const tail = new Uint8Array(bytes.length - whole < 56 ? 64 : 128); - tail.set(bytes.subarray(whole)); - tail[bytes.length - whole] = 0x80; - const tailView = new DataView(tail.buffer); - const bits = bytes.length * 8; - tailView.setUint32(tail.length - 8, bits >>> 0, true); - tailView.setUint32(tail.length - 4, Math.floor(bits / 2 ** 32), true); - for (let offset = 0; offset < tail.length; offset += 64) block(tailView, offset); - return hexBytes(new Uint8Array(state.buffer)); -}; - -type FileHashes = { sha1: string; md5: string; crc32: string; sha256: string }; - -const hashFile = async (file: Blob): Promise => { - const buffer = await file.arrayBuffer(); - const bytes = new Uint8Array(buffer); - const [sha1, sha256] = await Promise.all( - ['SHA-1', 'SHA-256'].map(async (name) => hexBytes(new Uint8Array(await crypto.subtle.digest(name, buffer)))), - ); - return { sha1, md5: md5(bytes), crc32: crc32(bytes), sha256 }; -}; - // files/?hash= reads one shard of the lookup, named by the first two hex // characters of the value. ?md5=, ?crc32= and ?sha256= are read the same way. From 4a9317cb4c14180d601d50e51a3d287c950a78cc Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:45:18 +0100 Subject: [PATCH 3/4] 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. --- CONTRIBUTING.md | 3 + mypy-baseline.txt | 12 - scripts/generate_readme.py | 3 + scripts/generate_site.py | 63 +++-- scripts/sitestarlight.py | 1 + scripts/sitewanted.py | 342 +++++++++++++++++++++++ tests/test_site_copy.py | 4 +- tests/test_site_reference.py | 17 +- tests/test_site_wanted.py | 335 ++++++++++++++++++++++ website/src/components/WantedFiles.astro | 180 ++++++++++++ website/src/scripts/wanted.ts | 72 +++++ wiki/testing-guide.md | 2 +- 12 files changed, 992 insertions(+), 42 deletions(-) create mode 100644 scripts/sitewanted.py create mode 100644 tests/test_site_wanted.py create mode 100644 website/src/components/WantedFiles.astro create mode 100644 website/src/scripts/wanted.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f48f7baad..2fbb50bda 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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. diff --git a/mypy-baseline.txt b/mypy-baseline.txt index 3a6b1ca25..8f879cac1 100644 --- a/mypy-baseline.txt +++ b/mypy-baseline.txt @@ -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[] = ...") [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] diff --git a/scripts/generate_readme.py b/scripts/generate_readme.py index 8b1a88a99..704c24f5b 100644 --- a/scripts/generate_readme.py +++ b/scripts/generate_readme.py @@ -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. diff --git a/scripts/generate_site.py b/scripts/generate_site.py index 017124bf2..99f15f80a 100644 --- a/scripts/generate_site.py +++ b/scripts/generate_site.py @@ -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'{m}' - if m > 0 + f'{to_source}' + if to_source > 0 else '0' ) 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"), diff --git a/scripts/sitestarlight.py b/scripts/sitestarlight.py index 1480517e7..8f166d233 100644 --- a/scripts/sitestarlight.py +++ b/scripts/sitestarlight.py @@ -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", } diff --git a/scripts/sitewanted.py b/scripts/sitewanted.py new file mode 100644 index 000000000..206283fc6 --- /dev/null +++ b/scripts/sitewanted.py @@ -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.", + "", + "", + "", + "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)."), + "", + ]) diff --git a/tests/test_site_copy.py b/tests/test_site_copy.py index 999a4503b..4064d6662 100644 --- a/tests/test_site_copy.py +++ b/tests/test_site_copy.py @@ -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(" 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() diff --git a/website/src/components/WantedFiles.astro b/website/src/components/WantedFiles.astro new file mode 100644 index 000000000..5595a1364 --- /dev/null +++ b/website/src/components/WantedFiles.astro @@ -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(/\/?$/, '/'); +--- + +
+
+

Drop files here

+ + +
+

+
    +
    + + + + diff --git a/website/src/scripts/wanted.ts b/website/src/scripts/wanted.ts new file mode 100644 index 000000000..751752eab --- /dev/null +++ b/website/src/scripts/wanted.ts @@ -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), + })}`; diff --git a/wiki/testing-guide.md b/wiki/testing-guide.md index 4cb7454b7..4147891f5 100644 --- a/wiki/testing-guide.md +++ b/wiki/testing-guide.md @@ -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 From e6738e591b400d2d66a3ee53cb3a4c3975cf2ddb Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:26:18 +0100 Subject: [PATCH 4/4] feat: put the wanted page in the site header A Wanted files link sits in the bar on every page and every width, beside the search and menu buttons on a phone, current on its own page. Below 27rem the site name is kept for screen readers only. files/ and wanted/ link each other in one line. --- scripts/generate_site.py | 2 ++ scripts/sitewanted.py | 4 ++- tests/test_site_components.py | 32 ++++++++++++++++++ tests/test_site_wanted.py | 9 ++++++ website/src/components/Header.astro | 50 +++++++++++++++++++++++++++-- 5 files changed, 94 insertions(+), 3 deletions(-) diff --git a/scripts/generate_site.py b/scripts/generate_site.py index 99f15f80a..c222ba787 100644 --- a/scripts/generate_site.py +++ b/scripts/generate_site.py @@ -4887,6 +4887,8 @@ def generate_files_page() -> str: "`scph5501.bin`, the PlayStation BIOS v3.0. " "To look a file up by its name, use the search at the top of the page.", "", + "Have a file the collection lacks? [See if it is wanted](../wanted.md).", + "", "## Permanent links", "", "A file's card lives on its manufacturer's page, and a file refiled " diff --git a/scripts/sitewanted.py b/scripts/sitewanted.py index 206283fc6..4753cba01 100644 --- a/scripts/sitewanted.py +++ b/scripts/sitewanted.py @@ -336,7 +336,9 @@ def page(known: int) -> str: "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). " + "The rest are listed on [the gaps page](gaps.md)."), + "", + ("To look up any file, use [Find or check a file](files/index.md). " "More ways to help are on [Contributing](contributing.md)."), "", ]) diff --git a/tests/test_site_components.py b/tests/test_site_components.py index a3521afde..513974d5e 100644 --- a/tests/test_site_components.py +++ b/tests/test_site_components.py @@ -189,6 +189,38 @@ class SectionTabsInTheHeader(unittest.TestCase): self.assertRegex(nav.group(1), r'aria-current="true"[^>]*>\s*Start here') +class TheWantedPageIsInTheBar(unittest.TestCase): + """The wanted page is the site's call to contribute: in the bar on every + page, beside the search and menu buttons on a phone, where the section + tabs fold into the menu.""" + + LINK = re.compile(r']*)>Wanted files') + + def test_the_bar_holds_it_outside_the_tabs(self): + header = _read(COMPONENTS / "Header.astro") + bar = header[header.index('
    '):header.index("
    ")] + self.assertIn('class="rb-wanted-link print:hidden"', bar) + self.assertIn("aria-current={onWanted ? 'page' : undefined}", bar) + # Theme colours only, the same in both themes' variables. + style = header[header.index(".rb-wanted-link {"):header.index("@media")] + self.assertNotRegex(style, r"#[0-9a-fA-F]{3,6}\b") + # At 360 px the name was cut to "Retr": the logo stays, the name is + # kept for screen readers only. + narrow = header[header.index("@media (max-width: 26.99rem)"):] + self.assertIn(".site-title span {", narrow[:200]) + self.assertIn("clip-path: inset(50%);", narrow[:400]) + + def test_built_on_every_page_current_on_its_own(self): + for page in ("which-pack", "files", "systems"): + with self.subTest(page=page): + found = self.LINK.search(_built(page)) + self.assertIsNotNone(found) + self.assertNotIn("aria-current", found.group(1)) + own = self.LINK.search(_built("wanted")) + self.assertIsNotNone(own) + self.assertIn('aria-current="page"', own.group(1)) + + def _title_block(html: str) -> str: """What PageTitle draws: from the main column to the h1.""" end = html.index('id="_top"') diff --git a/tests/test_site_wanted.py b/tests/test_site_wanted.py index 307063c97..c41a5386a 100644 --- a/tests/test_site_wanted.py +++ b/tests/test_site_wanted.py @@ -300,6 +300,15 @@ class ThePageReadsTheListAsTheResolverDoes(_World): self.assertEqual(self._page(WANTED, "b.bin")["issue"], validate_pr.large_file_issue_url(result)) +class TheTwoPagesLinkEachOther(unittest.TestCase): + """files/ checks any file, wanted/ the ones the collection lacks: each + sends a reader to the other in one line.""" + + def test_links(self): + self.assertIn("[See if it is wanted](../wanted.md)", generate_site.generate_files_page()) + self.assertIn("[Find or check a file](files/index.md)", sitewanted.page(1)) + + class ThePublishedList(unittest.TestCase): """The list generate_site.py wrote, against the collection: nothing it holds, every folder by validate_pr, and light enough for a phone.""" diff --git a/website/src/components/Header.astro b/website/src/components/Header.astro index b8d5299b4..4dd6f1ca5 100644 --- a/website/src/components/Header.astro +++ b/website/src/components/Header.astro @@ -3,12 +3,20 @@ // tabs: the funnel (Start here to Contribute) is the site's structure, so it // sits where every docs site puts its sections. On a phone the tabs stay the // first row of the menu, where the sidebar lists them. +// The wanted page is the one call to contribute, in the bar on every page +// and every width: on a phone it sits beside the search and menu buttons. import Default from '@astrojs/starlight/components/Header.astro'; const topics = Astro.locals.starlightSidebarTopics?.topics ?? []; +const base = import.meta.env.BASE_URL.replace(/\/?$/, '/'); +const wanted = `${base}wanted/`; +const onWanted = Astro.url.pathname.replace(/\/?$/, '/') === wanted; --- -
    + { topics.length > 0 && (