chore: merge origin main into the lint work

This commit is contained in:
Abdessamad Derraz committed 2026-11-17 07:09:55 +01:00
commit 3e732fd57e
104 files changed
+9122 -3414

No files matched your search

+3
View File
@@ -844,6 +844,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
the 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.
+60 -35
View File
@@ -125,6 +125,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"
@@ -2531,6 +2533,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": "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]
@@ -3232,7 +3235,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 ""
@@ -4879,6 +4882,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 "
@@ -5904,6 +5909,19 @@ def _emulator_card_anchor(emulator: str, files: list, index: int) -> str:
return cached[1][index] if 0 <= index < len(cached[1]) else ""
def _wanted_link(profiles: dict) -> Callable[[str, str, dict], str]:
"""The page a row of the wanted list links: an emulator entry's card,
where its notes, hashes and source line are, else the setup's page."""
def link(kind: str, key: str, entry: dict) -> str:
files = (profiles.get(key) or {}).get("files") or [] if kind == "emulator" else []
index = next((i for i, f in enumerate(files) if f is entry), -1)
anchor = _emulator_card_anchor(key, files, index) if index >= 0 else ""
if anchor:
return f"emulators/{emulator_card_page(key, anchor)}/#{anchor}"
return sitewanted.reader_page(kind, key, entry)
return link
def _emulator_links(sha1: str, consumers: FileConsumers) -> list[str]:
"""Each emulator reading the file, linked to the entry that reads it.
@@ -10654,17 +10672,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:
@@ -10919,24 +10930,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
@@ -10962,9 +10961,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.
@@ -11039,7 +11042,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"),
@@ -11260,10 +11264,10 @@ def generate_gap_analysis(
for emu_name, data in sorted(emulator_gaps, key=lambda x: -x[1]["gaps"]):
display = data["emulator"]
sources = _gap_sources(data)
m = sources["missing"]
to_source = sources["missing"]
missing_str = (
f'<span class="rb-badge rb-badge-danger">{m}</span>'
if m > 0
f'<span class="rb-badge rb-badge-danger">{to_source}</span>'
if to_source > 0
else '<span class="rb-badge rb-badge-success">0</span>'
)
lines.append(
@@ -11369,14 +11373,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) lists them, each with its upload button.", ""])
if moved is None:
lines.extend([*head, *rows, ""])
else:
@@ -12422,7 +12429,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 = []
@@ -12809,18 +12816,36 @@ 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),
_wanted_link(profiles),
)
(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"]), sum(1 for entry in wanted["entries"] if "h" in entry)))
print("Generating updated platform files page...")
write_if_changed(
str(docs / "exports.md"),
+6 -1
View File
@@ -210,6 +210,9 @@ def _fetch_asset(
os.close(tmp_fd)
try:
downloaded = False
# Only a name no candidate answers is reported: a spaced name is
# published dotted, and logging its first 404 read as a missing asset.
failures: list[str] = []
for candidate, url in _asset_urls(name):
try:
req = urllib.request.Request(url, headers={"User-Agent": "retrobios/1.0"})
@@ -224,8 +227,10 @@ def _fetch_asset(
except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
# A stalled or cut stream is a timeout or IncompleteRead, not
# a URLError: it escaped this handler and left its scratch.
print(f" large file {candidate}: {exc}", file=sys.stderr)
failures.append(f" large file {candidate}: {exc}")
if not downloaded:
for failure in failures:
print(failure, file=sys.stderr)
return None
snapshot = _read_once(tmp_path)
if snapshot is None or not _matches(snapshot[0], expected_sha1, expected_md5):
+2
View File
@@ -28,6 +28,8 @@ COMPONENTS = {
"Tabs": "@astrojs/starlight/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",
}
+564
View File
@@ -0,0 +1,564 @@
"""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, 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
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 re
import urllib.parse
from collections.abc import Callable, Iterable
from pathlib import Path
import archive_build
from common import runs_standalone, 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
from validation import deliverable, filter_files_by_mode, installed_with_emulator
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 _directory(entry: dict) -> str:
"""The directory a declaration names for its file: a platform's
destination, a profile's path. Empty for a bare name."""
where = str(entry.get("destination") or entry.get("path") or "")
return where.rsplit("/", 1)[0] + "/" if "/" in where else ""
def _paired(files: list, details: list[dict]) -> Iterable[tuple[dict, dict]]:
"""Each verify detail of a system with the declaration it scores.
verify scores the declarations of a system in order, one detail each,
so the k-th detail of a name is the k-th declaration of that name:
AmberELEC declares config.ini once per blueMSX machine, and a match by
name alone gave each missing one every machine's folder.
"""
by_name: dict[str, list[dict]] = {}
for entry in files:
if isinstance(entry, dict):
by_name.setdefault(str(entry.get("name")), []).append(entry)
seen: dict[str, int] = {}
for detail in details:
name = str(detail.get("name"))
position = seen.get(name, 0)
seen[name] = position + 1
same = by_name.get(name, [])
if position < len(same):
yield detail, same[position]
def _brought_by_readers(detail: dict, config: dict, platform: str, profiles: dict) -> bool:
"""Whether every core that reads a platform entry installs it itself.
The readers are those verify names for the entry's category, the cores
of its system first. A reader brings the file when the entries of its
build that read it are all installed with it (validation.deliverable,
the rule the pack builder applies).
"""
readers = (detail.get("category_evidence") or {}).get("read_by") or []
own = [r for r in readers if r.get("runs_system")] or readers
standalone_cores = set(config.get("standalone_cores") or [])
verdicts = []
for reader in own:
profile = profiles.get(reader.get("emulator", ""))
if not profile:
continue
names = {str(e.get("name")) for e in reader.get("entries") or []}
read = [f for f in profile.get("files") or []
if isinstance(f, dict) and str(f.get("name")) in names]
standalone = runs_standalone(reader["emulator"], profile, standalone_cores)
if filter_files_by_mode(read, standalone):
verdicts.append(not deliverable(read, standalone, platform))
return bool(verdicts) and all(verdicts)
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,
reason, category, directory}: the reason a file not collected yet
carries, empty otherwise, and bios or unread as verify (a platform's
entry) or the profile (an emulator's) gives it. Game data is no
contributor's to send, and a file the emulator installs itself
(`bundled`, scoped by the build that reads it) is no gap: neither is
a declaration here.
"""
found: list[dict] = []
for key, coverage in sorted(coverages.items()):
systems = coverage.get("config", {}).get("systems") or {}
by_system: dict[str, list[dict]] = {}
for detail in coverage.get("details", []):
by_system.setdefault(detail.get("system", ""), []).append(detail)
for system, details in sorted(by_system.items()):
files = (systems.get(system) or {}).get("files") or []
for detail, entry in _paired(files, details):
if detail.get("settled_by") or detail.get("status") not in ("missing", "untested"):
continue
if detail.get("category") == GAME_DATA or _brought_by_readers(
detail, coverage.get("config", {}), key, profiles):
continue
found.append({
"name": str(entry["name"]), "system": system,
"required": bool(detail.get("required", True)),
"reader": ("platform", key, coverage["platform"]), "entry": entry,
"reason": "",
"category": detail.get("category") if detail.get("category") in RANK else BIOS,
"directory": _directory(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):
if entry.get("category") == GAME_DATA or installed_with_emulator(entry):
continue
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,
"reason": str(row.get("reason") or "") if unsourceable else "",
"category": BIOS,
"directory": _directory(entry),
})
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
BIOS = "bios"
GAME_DATA = "game_data"
# verify's category for a platform entry no core the platform runs reads.
UNREAD = "unread"
# Firmware first, then what a platform lists and no core reads.
RANK = {BIOS: 0, UNREAD: 1}
# A name the code builds from the content (<serial>.txt, *.ini) is a
# pattern, not a file anyone can upload.
PATTERN = re.compile(r"[<>*?]")
# A file not collected yet stays wanted, however hard it is to find ("no
# public dump located", "retail data the collection does not hold"). It
# leaves the list only when its reason (the profile's `unsourceable:`)
# says no copy can be shared, read by the rules below.
NOT_SHAREABLE = re.compile("|".join([
# Any file of the name serves: there is no one file to collect.
r"\bno canonical\b",
# The user writes, picks, records or places it (WHDLoad's key aside,
# emucorev's config.txt: "plugin list the user writes").
r"\bthe user\b|\buser[- ](?:supplied|authored|created|settings|overlay|placeholder)\b"
r"|\bother users\b",
# The emulator or the guest writes it: a save, a state, a generated key.
r"\bwritten by (?:the (?:emulator|guest|firmware editor)|bam)\b|\bgenerated by the emulator\b"
r"|\bwith the debug key\b|\bmachine state\b|\bcreat\w* (?:this directory )?empty\b",
# It belongs to one person, one account or one copy (puae's WHDLoad.key).
r"\bper[- ]user\b|\btied to the (?:account|tag)\b|\bnever distributed generically\b"
r"|\bissued for one copy\b",
# Nothing was ever released under the name.
r"\bno (?:distributed form|released artefact|hardware dump equivalent)\b"
r"|\bno file of this name is distributed\b",
]), re.I)
def shareable(reason: str) -> bool:
"""False when a reason says no copy of the file can be shared."""
return not NOT_SHAREABLE.search(reason)
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 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:
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, systems: Iterable[str] = (),
directory: str = "") -> Placement:
"""A declaration that writes no hash is known by its name alone,
as the review knows a file whose hashes nothing declares, and its
folder comes from its systems and its declared directory."""
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=bool(hashes), exists=self.paths.__contains__,
systems=sorted(systems), directory=directory)
def folder(self, entry: dict, system: str = "") -> str:
"""The folder an upload of a profile or platform entry goes to."""
system = str(entry.get("system") or system)
return self.place(declared_hashes(entry), str(entry.get("name", "")),
[system] if system else [], _directory(entry)).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 _order(record: dict) -> tuple:
"""Most useful first: firmware, then the files no core reads, required
first in each, then by how many setups and emulators read the file."""
return (RANK[record["category"]], not record["required"], -len(record["readers"]),
record["name"].casefold(), sorted(record["readers"]))
def reader_page(kind: str, key: str, entry: dict) -> str:
"""Where a reader's page is, below the site root: the page a row of
the list links when no card anchor is given."""
return f"{'emulators' if kind == 'emulator' else 'platforms'}/{key}/"
def build_wanted(
profiles: dict,
coverages: dict,
gap_report: dict,
db: dict,
placer: Placer,
system_name: Callable[[str], str],
ledger: Iterable[dict] = (),
link: Callable[[str, str, dict], str] = reader_page,
) -> 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 (absent when the declarations write none:
the file is known by its name only), c a crc32 a declaration writes
beside a stronger hash (shown, never matched), w readers, s systems,
r required, z sizes, a the page holding its details (*link*: the card
of the first emulator that reads it, else the page of the first setup
that lists 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 (_order). A file no one can share
(the reason says so, NOT_SHAREABLE) is left out.
"""
held = Held(db, ledger)
records: dict[tuple, dict] = {}
for declaration in wanted_declarations(profiles, coverages, gap_report):
if PATTERN.search(declaration["name"]) or not shareable(declaration["reason"]):
continue
entry = declaration["entry"]
sizes = _sizes(entry)
for hashes in _alternatives(declared_hashes(entry)):
if hashes and held.holds(hashes, sizes):
continue
key = ((declaration["name"], tuple(sorted((a, tuple(v)) for a, v in hashes.items())),
tuple(sizes)) if hashes
else (declaration["name"].casefold(), declaration["system"],
declaration["directory"]))
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(),
"category": UNREAD, "directory": declaration["directory"],
"crc": set(), "links": {},
})
if RANK[declaration["category"]] < RANK[record["category"]]:
record["category"] = declaration["category"]
if declaration["system"]:
record["systems"].add(declaration["system"])
record["required"] = record["required"] or declaration["required"]
record["readers"].add(declaration["reader"])
record["crc"] |= {v.zfill(8) for v in parse_hash_list(entry.get("crc32")) if len(v) <= 8}
kind, reader_key, _label = declaration["reader"]
record["links"].setdefault((kind != "emulator", reader_key), link(kind, reader_key, entry))
_merge_named(records)
ordered = sorted(records.values(), key=_order)
_settle_cut(ordered)
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] = {}
entries = []
for record in ordered:
spot = placer.place(record["hashes"], record["name"], record["systems"],
record["directory"])
if spot.folder and spot.folder not in folder_at:
folder_at[spot.folder] = len(folders)
folders.append(spot.folder)
item: dict = {"n": record["name"]}
if record["hashes"]:
item["h"] = {algo: record["hashes"][algo] for algo in ALGORITHMS if algo in record["hashes"]}
if record["crc"] and "crc32" not in record["hashes"]:
item["c"] = sorted(record["crc"])
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"] = systems
if record["required"]:
item["r"] = 1
if record["sizes"]:
item["z"] = record["sizes"]
item["a"] = record["links"][min(record["links"])]
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],
"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[:2], [])
if len(targets) != 1:
continue
record = records.pop(key)
target = targets[0]
target["readers"] |= record["readers"]
target["required"] = target["required"] or record["required"]
target["crc"] |= record["crc"]
for where, href in record["links"].items():
target["links"].setdefault(where, href)
if RANK[record["category"]] < RANK[target["category"]]:
target["category"] = record["category"]
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(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 the table of 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, missing bios",
"---",
"",
"# Wanted",
"",
"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 />",
"",
"Several files at once? Drop them all. Each gets its own answer and upload button.",
"",
"## Where a file comes from",
"",
"- 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.",
"",
"To check any other file, use [Find or check a file](files/index.md).",
"",
"## Send it",
"",
"1. Make a free GitHub account once: [sign up](https://github.com/signup).",
"2. Drop the file at the top. If it is wanted, its button opens the right folder on GitHub.",
"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"{total:,} files, required firmware first. A name opens its details. "
f"{known:,} have a fingerprint (a hash), so a dropped copy is recognised."),
"",
"The others are known by name only: a dropped file of that name gets a button too.",
"",
"<WantedList />",
"",
"More ways to help are on [Contributing](contributing.md).",
"",
])
+227 -55
View File
@@ -27,7 +27,10 @@ import subprocess
import sys
import urllib.parse
import zipfile
from collections.abc import Callable, Iterable
from dataclasses import dataclass
from pathlib import Path
from typing import Any
sys.path.insert(0, os.path.dirname(__file__))
from common import (
@@ -179,8 +182,9 @@ def load_platform_hashes(platforms_dir: str, db: dict | None = None) -> dict:
bios/<Manufacturer>/<Console>/ folders the collection files its system
under, read from the other files of that system it holds.
"""
known = {"sha1": set(), "md5": set(), "sha256": set(), "crc32": set(),
"names": set(), "folders": {}, "sizes": {}, "entries": {}, "named": {}}
known: dict[str, Any] = {"sha1": set(), "md5": set(), "sha256": set(), "crc32": set(),
"names": set(), "folders": {}, "sizes": {}, "entries": {}, "named": {},
"name_systems": {}, "system_dirs": {}, "system_folders": {}}
systems_of: dict[str, set[str]] = {}
folders_of: dict[str, dict[str, int]] = {}
files = (db or {}).get("files", {})
@@ -225,32 +229,49 @@ def load_platform_hashes(platforms_dir: str, db: dict | None = None) -> dict:
known["entries"].setdefault(file_entry["name"].lower(), []).append(
(file_entry, mode, rule, name)
)
known["name_systems"].setdefault(file_entry["name"].lower(), set()).add(system_id)
for value in (*sha1s, *md5s):
systems_of.setdefault(value, set()).add(system_id)
for value in (*sha1s, *md5s, *sha256s):
if "name" in file_entry:
known["named"].setdefault(value, set()).add(file_entry["name"])
_note_folder(folders_of, system_id, files, by_md5, sha1s, md5s)
_note_folder(folders_of, system_id, files, by_md5, sha1s, md5s,
known["system_dirs"])
known["folders"] = _system_homes(systems_of, folders_of)
known["system_folders"] = _single_maker_folders(folders_of)
return known
def _note_folder(
folders_of: dict[str, dict[str, int]], system_id: str, files: dict,
by_md5: dict, sha1s: list[str], md5s: list[str],
dirs_of: dict[str, set[str]] | None = None,
) -> None:
"""Count the bios/<Manufacturer>/<Console>/ folder a held file sits in."""
"""Count the bios/<Manufacturer>/<Console>/ folder a held file sits in,
and note the directory it sits in under *dirs_of*."""
held = next((s for s in sha1s if s in files), None) or next(
(by_md5[m] for m in md5s if m in by_md5), None
)
parts = str(files.get(held, {}).get("path", "")).split("/")
path = str(files.get(held, {}).get("path", ""))
if dirs_of is not None and "/" in path and "/.variants/" not in path:
dirs_of.setdefault(system_id, set()).add(path.rsplit("/", 1)[0] + "/")
parts = path.split("/")
if len(parts) >= 4 and parts[0] == "bios" and not parts[2].startswith("."):
folder = "/".join(parts[:3]) + "/"
counts = folders_of.setdefault(system_id, {})
counts[folder] = counts.get(folder, 0) + 1
def _single_maker_folders(folders_of: dict[str, dict[str, int]]) -> dict[str, set[str]]:
"""System id to the folders the collection files it under, for a system
filed under one manufacturer only, the rule _system_homes applies."""
return {
system_id: set(held_in) for system_id, held_in in folders_of.items()
if len({folder.split("/")[1] for folder in held_in}) == 1
}
def _system_homes(
systems_of: dict[str, set[str]], folders_of: dict[str, dict[str, int]]
) -> dict[str, set[str]]:
@@ -287,7 +308,7 @@ def load_profile_hashes(
"""
known: dict[str, dict] = {
"sha1": {}, "sha256": {}, "md5": {}, "crc32": {}, "sizes": {}, "folders": {},
"named": {},
"named": {}, "name_systems": {}, "system_dirs": {}, "system_folders": {},
}
systems_of: dict[str, set[str]] = {}
folders_of: dict[str, dict[str, int]] = {}
@@ -320,10 +341,14 @@ def load_profile_hashes(
if isinstance(system, str):
for value in (v for values in hashes.values() for v in values):
systems_of.setdefault(value, set()).add(system)
for n in names:
if isinstance(n, str):
known["name_systems"].setdefault(n.lower(), set()).add(system)
sha1s = [*hashes["sha1"], *(
by_sha256[v] for v in hashes["sha256"] if v in by_sha256
)]
_note_folder(folders_of, system, files, by_md5, sha1s, hashes["md5"])
_note_folder(folders_of, system, files, by_md5, sha1s, hashes["md5"],
known["system_dirs"])
if not any(entry.get(algo) for algo in ("sha1", "sha256", "md5")):
size = entry.get("size")
sizes = [int(v) for v in size] if isinstance(size, list) else (
@@ -334,6 +359,7 @@ def load_profile_hashes(
key = (value.zfill(8), accepted)
known["crc32"].setdefault(key, set()).add(emulator)
known["folders"] = _system_homes(systems_of, folders_of)
known["system_folders"] = _single_maker_folders(folders_of)
return known
@@ -554,18 +580,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 +594,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 +603,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, []),
@@ -633,13 +642,23 @@ def validate_file(
if (name_known and not (sha1_known or md5_known or other_known or accepted_by)
and not by_profile and size_fits):
home = _variant_home(db, result.filename)
owners = name_systems(result.filename, platform_hashes, profile_hashes)
home = _variant_home(db, result.filename, "", set() if len(owners) > 1 else {
d for table in (platform_hashes, profile_hashes or {}) for s in owners
for d in table.get("system_dirs", {}).get(s, ())
} if owners else None)
if not home and normalized.startswith("bios" + os.sep):
# Beside the file, in the folder the contributor chose.
home = os.path.dirname(normalized).replace(os.sep, "/") + "/"
slot = f"{home}.variants/{result.filename}.{result.sha1[:8]}"
if home and not normalized.startswith("bios" + os.sep):
result.destination = slot
result.add_info(
f"This may be a valid variant. If accepted, it will be placed in `{slot}`"
)
if home:
result.add_info(
f"This may be a valid variant. If accepted, it will be placed in `{slot}`"
)
else:
result.add_info("This may be a valid variant of a file the collection lacks")
return result
@@ -671,19 +690,172 @@ def _platforms_accepting(filepath: str, filename: str, platform_hashes: dict) ->
return accepted
def _variant_home(db: dict | None, name: str, held: str = "") -> str:
def expected_folders(
values: Iterable[str], platform_hashes: dict, profile_hashes: dict | None
) -> list[str]:
"""The bios/<Manufacturer>/<Console>/ folders the files of a hash's
system are in, read from the first of *values* a table knows.
A platform's declaration first, then a profile's: most files the gaps
page lists are declared by a profile alone.
"""
for table in (platform_hashes, profile_hashes or {}):
for value in values:
if value and value in table.get("folders", {}):
return sorted(table["folders"][value])
return []
@dataclass(frozen=True)
class Placement:
"""Where a file not under bios/ yet goes.
``folders`` are those of its system, ``home`` the folder the collection
keeps its name in when its system names none. ``name`` is the name it
is copied under, empty when the declarations do not settle one.
``variant`` says a file of that name is already in the folder: a copy
goes beside it in .variants/, never over it.
"""
folders: tuple[str, ...] = ()
home: str = ""
name: str = ""
variant: bool = False
@property
def folder(self) -> str:
return self.folders[0] if self.folders else self.home
def destination(self, sha1: str) -> str:
if not self.name:
return ""
if self.variant:
return f"{self.folder}.variants/{self.name}.{sha1[:8]}"
return self.folder + self.name
def placement(
values: Iterable[str],
filename: str,
db: dict | None,
platform_hashes: dict,
profile_hashes: dict | None,
declared: bool,
exists: Callable[[str], bool] = os.path.exists,
systems: Iterable[str] = (),
directory: str = "",
) -> 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.
Without a folder from its hashes, the folder comes from its system:
*systems*, or every system that declares the name (several of them
name no copy to sit beside). A file of that name held elsewhere is a
homonym and says nothing: AmberELEC's MSX config.ini
was sent beside msx.emu's ColecoVision config.ini. A declared
*directory* (Machines/MSX2/ for one machine's config.ini) narrows it: a
copy by name counts only in a directory of that tail, and a held
directory of that tail is the folder.
"""
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", {})), "")
owners = set(systems) or name_systems(filename, platform_hashes, profile_hashes)
tables = (platform_hashes, profile_hashes or {})
# A name several systems declare does not say which one a file is:
# a copy held for one of them is no answer.
dirs: set[str] = set() if not systems and len(owners) > 1 else {
d for table in tables for s in owners for d in table.get("system_dirs", {}).get(s, ())
}
tail = _directory_tail(db, directory)
within: set[str] | None = dirs
if tail:
within = {d for d in dirs if d.endswith("/" + tail) or d == tail} if owners else None
home = _variant_home(db, filename, held, within if owners or tail else None)
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)
if home:
return Placement(home=home)
if tail:
return Placement(home=next(d for d in _held_directories(db) if d.endswith("/" + tail) or d == tail))
homes = {f for table in tables for s in owners for f in table.get("system_folders", {}).get(s, ())}
return Placement(tuple(sorted(homes)))
_HELD_DIRECTORIES: dict[int, frozenset[str]] = {}
def _held_directories(db: dict | None) -> frozenset[str]:
"""Every directory a file of the database sits in, .variants/ aside."""
key = id(db)
if key not in _HELD_DIRECTORIES:
_HELD_DIRECTORIES[key] = frozenset(
path.rsplit("/", 1)[0] + "/"
for record in (db or {}).get("files", {}).values()
for path in [record.get("path"), *(record.get("paths") or [])]
if path and "/" in path and "/.variants/" not in path
)
return _HELD_DIRECTORIES[key]
def _directory_tail(db: dict | None, directory: str) -> str:
"""The longest tail of a declared directory, two segments at least,
that exactly one held directory ends with, empty when none does."""
parts = [p for p in directory.strip("/").split("/") if p]
held = _held_directories(db)
for size in range(len(parts), 1, -1):
tail = "/".join(parts[-size:]) + "/"
found = [d for d in held if d.endswith("/" + tail) or d == tail]
if len(found) == 1:
return tail
if found:
return ""
return ""
def name_systems(filename: str, platform_hashes: dict, profile_hashes: dict | None) -> set[str]:
"""The systems whose platform or profile entries declare this name."""
return {
system for table in (platform_hashes, profile_hashes or {})
for system in table.get("name_systems", {}).get(filename.lower(), ())
}
def _variant_home(db: dict | None, name: str, held: str = "",
within: set[str] | None = None) -> str:
"""The folder the collection keeps a name in, for its variants beside it.
The folder of an identical copy comes first: adam_fdc.zip, held in
bios/Coleco/Adam/, was sent to bios/Arcade/MAME/, the first folder
the name index gave.
the name index gave. A copy found by name alone counts only in a
directory of *within*, those the file's own systems are held in, when
the systems are known.
"""
files = (db or {}).get("files", {})
by_name = (db or {}).get("indexes", {}).get("by_name", {}).get(name, [])
for sha1 in ([held] if held in files else []) + list(by_name):
copies = [(held, True)] if held in files else []
for sha1, identical in copies + [(sha1, False) for sha1 in by_name]:
path = str(files.get(sha1, {}).get("path", ""))
folder = path.rsplit("/", 1)[0] + "/" if "/" in path else ""
if folder and "/.variants" not in "/" + folder:
if not folder or "/.variants" in "/" + folder:
continue
if identical or within is None or folder in within:
return folder
return ""