chore: merge the wanted files page

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

No files matched your search

+3
View File
@@ -856,6 +856,9 @@ def contributing_text(
Have a file the collection lacks? Add it from the browser. It is checked on arrival.
Not sure? Drop it on [the wanted page]({link("wanted")}). It reads the file on
your device, says if it is wanted, and opens the upload in the right folder.
[Upload it into `bios/`]({UPLOAD_URL}), 25 MB at most per file. GitHub
writes it to a fork and opens the pull request.
+41 -24
View File
@@ -130,6 +130,8 @@ import release_record
import sitebootstrap
import sitehandheld
import sitemeasurements
import sitewanted
from validate_pr import load_platform_hashes, load_profile_hashes
# The Starlight project, and where its pages go inside it.
STARLIGHT_DIR = "website"
@@ -2536,6 +2538,7 @@ def _page_description(markdown: str, relative: Path, title: str) -> str:
"explore.md": "Systems, emulators and installer options to explore, with the figures of the BIOS collection.",
"which-pack.md": "Pick a device or setup and get its BIOS files: the folder they go in, one command that installs and checks them, or a ZIP pack to extract.",
"contributing.md": "Add a BIOS file the collection lacks from the browser, checked on arrival, or add a platform or an emulator profile.",
"wanted.md": "Drop files on the page to learn if the collection wants them, then upload a wanted one to its folder on GitHub. Files are read on your device.",
}
if key in specific:
return specific[key]
@@ -3237,7 +3240,7 @@ def page_level(relative: Path) -> str:
return "explore"
if path in _REFERENCE_PAGES:
return "reference"
if path == "contributing.md":
if path in ("contributing.md", "wanted.md"):
return "contribute"
return ""
@@ -4884,6 +4887,8 @@ def generate_files_page() -> str:
"`scph5501.bin`, the PlayStation BIOS v3.0. "
"To look a file up by its name, use the search at the top of the page.",
"",
"Have a file the collection lacks? [See if it is wanted](../wanted.md).",
"",
"## Permanent links",
"",
"A file's card lives on its manufacturer's page, and a file refiled "
@@ -10924,24 +10929,12 @@ def _ratio_cell(done: int, total: int, alarm: int = 0) -> str:
# GitHub's upload page for a folder of bios/: a browser upload by someone
# without write access lands on a fork and opens a pull request.
UPLOAD_URL = f"{REPO_URL}/upload/main/bios"
UPLOAD_URL = f"{sitewanted.UPLOAD_ROOT}bios"
# Rows of Files to source on one page: 601 on one page made a phone page
# 274,509 px long.
FILES_TO_SOURCE_PART = 100
def _upload_folder(profile: dict) -> str:
"""The bios/ folder a file the emulator loads is uploaded into: the
console folder of its first system that has one, else none."""
from siterender import _own_section
for sys_id in profile.get("systems") or []:
own = _own_section(str(sys_id))
if own is not None:
return "/".join(own)
return ""
def reading_platforms(emu_name: str, profile: dict, name: str,
configs: dict[str, dict]) -> set[str]:
"""Of the platforms running an emulator (name -> config), those whose
@@ -10967,9 +10960,13 @@ def generate_gap_analysis(
gap_report: dict | None = None,
moved: dict[str, str] | None = None,
catalogued: dict | None = None,
placer: sitewanted.Placer | None = None,
) -> str:
"""Generate a unified gap analysis page.
``placer`` gives each file to source the folder its upload goes to,
the one validate_pr asks for. Without it the link opens bios/.
``catalogued`` is a provenance report built with the profiles' needs:
a file the collection does not hold yet names the catalog or romset
that lists it.
@@ -11044,7 +11041,8 @@ def generate_gap_analysis(
"",
"Each file here is a request: for a file under \"Files to source\", "
"[adding it](contributing.md) fills the gap for "
"every platform at once.",
"every platform at once. Have some of these? [Drop them on the wanted "
"page](wanted.md): it says which ones are wanted and where each goes.",
"",
" ".join([
markup.button("Download gaps CSV", "downloads/gaps.csv"),
@@ -11265,10 +11263,10 @@ def generate_gap_analysis(
for emu_name, data in sorted(emulator_gaps, key=lambda x: -x[1]["gaps"]):
display = data["emulator"]
sources = _gap_sources(data)
m = sources["missing"]
to_source = sources["missing"]
missing_str = (
f'<span class="rb-badge rb-badge-danger">{m}</span>'
if m > 0
f'<span class="rb-badge rb-badge-danger">{to_source}</span>'
if to_source > 0
else '<span class="rb-badge rb-badge-success">0</span>'
)
lines.append(
@@ -11374,14 +11372,17 @@ def generate_gap_analysis(
f"[{_escape_tags(display)}](emulators/{key}.md)"
for display, key in zip(m["emulators"], m["emu_keys"])
)
folder = _upload_folder(profiles[m["emu_keys"][0]])
upload = f"{UPLOAD_URL}/{urllib.parse.quote(folder)}" if folder else UPLOAD_URL
owner = profiles[m["emu_keys"][0]]
declared = sitewanted.gap_entries(owner, m["name"], m["identity"], False)
folder = placer.folder(declared[0]) if placer and declared else ""
upload = sitewanted.upload_href(sitewanted.UPLOAD_ROOT, folder)
rows.append(
f"| `{m['name']}` [Have it? Upload]({upload}) | {destination} | {expected} "
f"| {emulators} | {req} | {plat_badges} | "
f"{_source_ref_markdown(profiles[m['emu_keys'][0]], m['source_ref'])} |"
f"{_source_ref_markdown(owner, m['source_ref'])} |"
)
lines.extend(["### Files to source", "", counted, ""])
lines.extend(["### Files to source", "", counted,
"[The wanted page](wanted.md) recognises the ones with a known hash.", ""])
if moved is None:
lines.extend([*head, *rows, ""])
else:
@@ -12427,7 +12428,7 @@ def generate_nav(
(68, {"Updated platform files": "exports.md"}, "Data"),
(69, {"Measurements": sitemeasurements.EXPLORER_PAGE}, "Data"),
],
"contribute": [(0, "contributing.md")],
"contribute": [(0, "contributing.md"), (5, {"Wanted": "wanted.md"})],
}
wiki = wiki_nav(wiki_dir)
nav = []
@@ -12814,18 +12815,34 @@ def _generate(args: argparse.Namespace) -> None:
provenance_report = build_report(
db, load_provenance_snapshots(), needs=profile_needs(profiles, db))
# Where an upload goes, by validate_pr's own rule: the gaps page and the
# wanted page send a file to the folder the review asks for.
placer = sitewanted.Placer(
db, load_platform_hashes(args.platforms_dir, db),
load_profile_hashes(args.emulators_dir, db),
)
print("Generating gap analysis page...")
gap_pages: dict[str, str] = {}
write_if_changed(
str(docs / "gaps.md"),
tables_out_of_search(generate_gap_analysis(
profiles, coverages, db, suppl_names, registry, gap_report, gap_pages,
catalogued=provenance_report,
catalogued=provenance_report, placer=placer,
)) + reference_next(),
)
for stem, page in gap_pages.items():
write_if_changed(str(docs / f"{stem}.md"), tables_out_of_search(page))
print("Generating the wanted page...")
wanted = sitewanted.build_wanted(
profiles, coverages, gap_report, db, placer, system_name,
sitewanted.load_ledger(archive_build.ARCHIVES_FILE),
)
(public / "data").mkdir(parents=True, exist_ok=True)
write_if_changed(str(public / sitewanted.DATA_FILE),
json.dumps(wanted, ensure_ascii=False, separators=(",", ":")) + "\n")
write_if_changed(str(docs / "wanted.md"), sitewanted.page(len(wanted["entries"])))
print("Generating updated platform files page...")
write_if_changed(
str(docs / "exports.md"),
+1
View File
@@ -28,6 +28,7 @@ COMPONENTS = {
"Tabs": "@astrojs/starlight/components",
"TabItem": "@astrojs/starlight/components",
"FilePicker": "components/FilePicker.astro",
"WantedFiles": "components/WantedFiles.astro",
"MeasurementsExplorer": "components/MeasurementsExplorer.astro",
"InstallDemo": "components/InstallDemo.astro",
}
+344
View File
@@ -0,0 +1,344 @@
"""The files the collection lacks, as the wanted page reads them.
A visitor drops files on wanted/, each is hashed in the browser and
compared with this list. The list is the gaps page's: a file a platform
lists that its own check finds missing or under another hash, a file an
emulator loads that no platform lists and the collection does not hold,
and a file not collected yet. A declaration that names no hash cannot be
recognised by its bytes and is left out.
Each entry keeps the hashes its declaration writes, read as the resolver
reads them (comma lists split, a crc32 counted only where no stronger hash
is declared), and the folder validate_pr.placement() gives those hashes:
the review of the pull request asks for that same folder.
"""
from __future__ import annotations
import urllib.parse
from collections.abc import Callable, Iterable
from pathlib import Path
import archive_build
from common import unique_emulator_profiles
from cross_reference import _first_hash
from hashing import cut_md5_owner, parse_hash_list
from validate_pr import LARGE_FILE_ISSUE_URL, Placement, placement
ALGORITHMS = ("sha1", "sha256", "md5", "crc32")
# GitHub's upload page takes 25 MB per file. A larger file goes in by a
# push or, past 100 MB, through the issue form (CONTRIBUTING.md).
BROWSER_UPLOAD_LIMIT = 25 * 1024 * 1024
# The upload page of a folder is this followed by the folder.
UPLOAD_ROOT = "https://github.com/Abdess/retrobios/upload/main/"
# Under the site's public folder, read by WantedFiles.astro.
DATA_FILE = "data/wanted.json"
def _sizes(entry: dict) -> list[int]:
size = entry.get("size")
values = size if isinstance(size, list) else [size]
return sorted({int(v) for v in values if isinstance(v, int) and not isinstance(v, bool) and v > 0})
def declared_hashes(entry: dict) -> dict[str, list[str]]:
"""The hashes that identify an entry's own bytes, by algorithm.
A zipped_file md5 is the md5 of a ROM inside the archive, not of the
archive, so it says nothing about the file a visitor drops. A crc32
counts only where no stronger hash is declared, as in
resolve_local_file.
"""
hashes = {algo: parse_hash_list(entry.get(algo)) for algo in ALGORITHMS}
if entry.get("zipped_file"):
hashes["md5"] = []
hashes["md5"] = [v for v in hashes["md5"] if 0 < len(v) <= 32]
hashes["sha1"] = [v for v in hashes["sha1"] if len(v) == 40]
hashes["sha256"] = [v for v in hashes["sha256"] if len(v) == 64]
hashes["crc32"] = [v.zfill(8) for v in hashes["crc32"] if len(v) <= 8]
if hashes["sha1"] or hashes["sha256"] or hashes["md5"]:
hashes["crc32"] = []
return {algo: values for algo, values in hashes.items() if values}
def _alternatives(hashes: dict[str, list[str]]) -> list[dict[str, list[str]]]:
"""One declaration per file it accepts.
A Recalbox entry lists every revision its check takes in one md5 field:
each is a file of its own, with a folder of its own. Values of two
algorithms cannot be paired, so such an entry stays whole.
"""
listed = [algo for algo, values in hashes.items() if len(values) > 1]
if len(hashes) == 1 and listed:
algo = listed[0]
return [{algo: [value]} for value in hashes[algo]]
return [hashes]
class Held:
"""What the collection holds, by every hash a file or an archive
member is known under."""
def __init__(self, db: dict, ledger: Iterable[dict] = ()) -> None:
files = db.get("files", {})
indexes = db.get("indexes", {})
self.sha1 = set(files)
self.md5 = set(indexes.get("by_md5", {}))
self.sha256 = set(indexes.get("by_sha256", {}))
self.crc32: dict[str, set[int]] = {}
for record in files.values():
crc = str(record.get("crc32") or "").lower()
if crc:
self.crc32.setdefault(crc, set()).add(int(record.get("size") or 0))
# A ROM held only inside one of the collection's archives.
for archive in ledger:
for member in archive.get("members") or []:
if member.get("sha1"):
self.sha1.add(str(member["sha1"]).lower())
crc = str(member.get("crc32") or "").lower()
if crc:
self.crc32.setdefault(crc, set()).add(int(member.get("size") or 0))
def holds(self, hashes: dict[str, list[str]], sizes: list[int]) -> bool:
if any(v in self.sha1 for v in hashes.get("sha1", [])):
return True
if any(v in self.sha256 for v in hashes.get("sha256", [])):
return True
for value in hashes.get("md5", []):
if value in self.md5 or (len(value) < 32 and cut_md5_owner(value, self.md5)):
return True
for value in hashes.get("crc32", []):
held = self.crc32.get(value, set())
if held and (not sizes or held & set(sizes)):
return True
return False
def gap_entries(profile: dict, name: str, identity: str, unsourceable: bool) -> list[dict]:
"""The profile entries behind one row of the gap report."""
named = [f for f in profile.get("files") or []
if isinstance(f, dict) and f.get("name") == name]
if unsourceable:
return [f for f in named if f.get("unsourceable")] or named
if identity:
return [f for f in named if _first_hash(f) == identity] or named
return named
def wanted_declarations(profiles: dict, coverages: dict, gap_report: dict) -> list[dict]:
"""Every declaration of a file the gaps page reports as lacking.
Each is {name, system, required, reader: (kind, key, label), entry}.
"""
found: list[dict] = []
for key, coverage in sorted(coverages.items()):
systems = coverage.get("config", {}).get("systems") or {}
for detail in coverage.get("details", []):
if detail.get("settled_by") or detail.get("status") not in ("missing", "untested"):
continue
system = detail.get("system", "")
for entry in (systems.get(system) or {}).get("files") or []:
if isinstance(entry, dict) and entry.get("name") == detail.get("name"):
found.append({
"name": str(entry["name"]), "system": system,
"required": bool(detail.get("required", True)),
"reader": ("platform", key, coverage["platform"]), "entry": entry,
})
unique = unique_emulator_profiles(profiles)
for key, data in sorted(gap_report.items()):
profile = unique.get(key)
if profile is None:
continue
systems = [str(s) for s in data.get("systems") or profile.get("systems") or []]
rows = [(gap, False) for gap in data.get("gap_details") or []
if gap.get("source") == "missing" and not gap.get("bundled")]
rows += [(row, True) for row in data.get("unsourceable") or []]
for row, unsourceable in rows:
for entry in gap_entries(profile, str(row.get("name", "")),
str(row.get("identity") or ""), unsourceable):
system = entry.get("system") or (systems[0] if len(systems) == 1 else "")
found.append({
"name": str(entry["name"]), "system": str(system),
"required": bool(row.get("required", False)),
"reader": ("emulator", key, str(data.get("emulator", key))), "entry": entry,
})
return found
def _settle_cut(records: list[dict]) -> None:
"""A cut md5 names a dump only if exactly one md5 starts with it.
Matched against the wanted md5s: one of them, and the cut is that md5;
several, and it names none; none, and the page compares by prefix.
"""
full = {v for r in records for v in r["hashes"].get("md5", []) if len(v) == 32}
for record in records:
kept = []
for value in record["hashes"].get("md5", []):
if len(value) == 32:
kept.append(value)
continue
starting = {md5 for md5 in full if md5.startswith(value)}
if len(starting) == 1:
kept.append(starting.pop())
elif not starting:
kept.append(value)
if kept:
record["hashes"]["md5"] = sorted(set(kept))
else:
record["hashes"].pop("md5", None)
class Placer:
"""validate_pr's placement for a declaration: its declared hashes,
strongest first, and its name.
The database stands in for the disk validate_pr reads: the site is
built from a checkout whose release assets are not on disk.
"""
def __init__(self, db: dict, platform_hashes: dict, profile_hashes: dict) -> None:
self.db = db
self.platform_hashes = platform_hashes
self.profile_hashes = profile_hashes
self.paths = {
path for record in db.get("files", {}).values()
for path in [record.get("path"), *(record.get("paths") or [])] if path
}
def place(self, hashes: dict[str, list[str]], name: str) -> Placement:
values = [value for algo in ("sha1", "md5", "sha256") for value in hashes.get(algo, [])
if len(value) == FULL_LENGTH[algo]]
return placement(values, name, self.db, self.platform_hashes, self.profile_hashes,
declared=True, exists=self.paths.__contains__)
def folder(self, entry: dict) -> str:
"""The folder an upload of a profile or platform entry goes to."""
return self.place(declared_hashes(entry), str(entry.get("name", ""))).folder
FULL_LENGTH = {"sha1": 40, "md5": 32, "sha256": 64}
def upload_href(root: str, folder: str) -> str:
"""GitHub's upload page for a folder of the repository, bios/ when the
placement names none."""
return root + urllib.parse.quote((folder or "bios/").rstrip("/"))
def build_wanted(
profiles: dict,
coverages: dict,
gap_report: dict,
db: dict,
placer: Placer,
system_name: Callable[[str], str],
ledger: Iterable[dict] = (),
) -> dict:
"""The wanted list, compact, as public/data/wanted.json carries it.
Readers, systems and folders are written once and named by position.
An entry: n name, h hashes, w readers, s systems, r required, z sizes,
f folder, t the name it is uploaded under, v that name goes to the
folder's .variants/ with the first 8 characters of its sha1.
"""
held = Held(db, ledger)
records: dict[tuple, dict] = {}
for declaration in wanted_declarations(profiles, coverages, gap_report):
entry = declaration["entry"]
sizes = _sizes(entry)
for hashes in _alternatives(declared_hashes(entry)):
if held.holds(hashes, sizes):
continue
key = (declaration["name"], tuple(sorted((a, tuple(v)) for a, v in hashes.items())),
tuple(sizes))
record = records.setdefault(key, {
"name": declaration["name"], "hashes": {a: list(v) for a, v in hashes.items()},
"sizes": sizes, "systems": set(), "required": False, "readers": set(),
})
if declaration["system"]:
record["systems"].add(declaration["system"])
record["required"] = record["required"] or declaration["required"]
record["readers"].add(declaration["reader"])
ordered = sorted(records.values(), key=lambda r: (r["name"].casefold(), sorted(r["readers"])))
_settle_cut(ordered)
ordered = [r for r in ordered if r["hashes"]]
readers = sorted({reader for r in ordered for reader in r["readers"]},
key=lambda reader: (reader[0], reader[2].casefold(), reader[1]))
reader_at = {reader: i for i, reader in enumerate(readers)}
folders: list[str] = []
folder_at: dict[str, int] = {}
titles: dict[str, str] = {}
entries = []
for record in ordered:
spot = placer.place(record["hashes"], record["name"])
if spot.folder and spot.folder not in folder_at:
folder_at[spot.folder] = len(folders)
folders.append(spot.folder)
systems = sorted({titles.setdefault(s, system_name(s)) for s in record["systems"]})
item: dict = {
"n": record["name"],
"h": {algo: record["hashes"][algo] for algo in ALGORITHMS if algo in record["hashes"]},
"w": sorted(reader_at[reader] for reader in record["readers"]),
}
if systems:
item["s"] = ", ".join(systems)
if record["required"]:
item["r"] = 1
if record["sizes"]:
item["z"] = record["sizes"]
if spot.folder:
item["f"] = folder_at[spot.folder]
if spot.name:
item["t"] = spot.name
if spot.variant:
item["v"] = 1
entries.append(item)
return {
"upload": UPLOAD_ROOT,
"issue": LARGE_FILE_ISSUE_URL,
"limit": BROWSER_UPLOAD_LIMIT,
"readers": [[kind[0], key, label] for kind, key, label in readers],
"folders": folders,
"entries": entries,
}
def load_ledger(path: Path) -> list[dict]:
"""The archive records of recipes/archives.json, empty when absent."""
return list(archive_build.load_ledger(path).values())
def page(known: int) -> str:
"""The wanted page: the drop box, then what happens after an upload.
Held to the Start here budgets (tests/test_site_copy.py): anyone with a
file in hand reads it.
"""
return "\n".join([
"---",
"terms: wanted list, donate, give a file, upload to github, help the collection",
"---",
"",
"# Wanted",
"",
"Have a file the collection lacks? Drop it below. The page says if we want it.",
"",
"<WantedFiles />",
"",
"Your files are read on this device. Nothing is sent until you upload one to GitHub.",
"",
"## After the upload",
"",
"1. The button opens GitHub's upload page in the right folder. Sign in and drop the file there.",
"2. GitHub puts it in your own copy of the project and opens a pull request.",
"3. A check reads the file and says if it fits. Then we add it.",
"",
(f"The page knows {known:,} wanted files by their hash, a fingerprint of the contents. "
"The rest are listed on [the gaps page](gaps.md)."),
"",
("To look up any file, use [Find or check a file](files/index.md). "
"More ways to help are on [Contributing](contributing.md)."),
"",
])
+106 -40
View File
@@ -27,6 +27,8 @@ import subprocess
import sys
import urllib.parse
import zipfile
from collections.abc import Callable, Iterable
from dataclasses import dataclass
from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
@@ -554,18 +556,8 @@ def validate_file(
)
normalized = os.path.normpath(relative)
# A platform's declaration first, then a profile's: most files the gaps
# page lists are declared by a profile alone.
expected = next(
(
table["folders"][value]
for table in (platform_hashes, profile_hashes)
for value in (result.sha1, result.md5, hashes.get("sha256", ""))
if value in table.get("folders", {})
),
set(),
)
expected_folders = sorted(expected)
values = (result.sha1, result.md5, hashes.get("sha256", ""))
expected = expected_folders(values, platform_hashes, profile_hashes)
if too_large:
# The file stays out of the pull request, so no folder of bios/ is
# the contributor's to choose: the release asset is placed by hand.
@@ -578,7 +570,7 @@ def validate_file(
# Depth alone passed a PS1 BIOS filed under bios/Nintendo/Game Boy/.
result.add_warning(
"Placed under " + (here or "the bios/ root") + ", while the other files of "
"its system are in " + " or ".join(f"`{f}`" for f in sorted(expected))
"its system are in " + " or ".join(f"`{f}`" for f in expected)
)
elif len(parts) >= 4:
result.add_check(True, f"Correct placement: bios/{parts[1]}/{parts[2]}/")
@@ -587,35 +579,28 @@ def validate_file(
elif result.outcome == "held" or members is not None:
# Nothing to place: a copy, or an archive whose files go in unzipped.
pass
elif expected_folders:
# The contributor asks before forking: say where it goes.
names = {
name
for table in (platform_hashes, profile_hashes)
for value in (result.sha1, result.md5, hashes.get("sha256", ""))
for name in table.get("named", {}).get(value, ())
}
name = next(iter(names)) if len(names) == 1 else ""
if len(expected_folders) == 1 and name and "/" not in name:
folder = expected_folders[0]
result.destination = (
f"{folder}.variants/{name}.{result.sha1[:8]}"
if os.path.exists(folder + name) else folder + name
)
result.add_warning(
"File is not under bios/ yet. Its system's files are in "
+ " or ".join(f"`{f}`" for f in expected_folders)
+ (f". --place copies it to `{result.destination}`" if result.destination else "")
)
elif _variant_home(db, result.filename, result.sha1):
result.add_warning(
"File is not under bios/ yet. The collection keeps this name in "
f"`{_variant_home(db, result.filename, result.sha1)}`"
)
else:
result.add_warning(
"File is not under bios/ yet. Place it in bios/Manufacturer/Console/"
# The contributor asks before forking: say where it goes.
spot = placement(
values, result.filename, db, platform_hashes, profile_hashes,
declared=bool(sha1_known or md5_known or other_known or accepted_by or by_profile),
)
result.destination = spot.destination(result.sha1)
copies = f". --place copies it to `{result.destination}`" if result.destination else ""
if spot.folders:
result.add_warning(
"File is not under bios/ yet. Its system's files are in "
+ " or ".join(f"`{f}`" for f in spot.folders) + copies
)
elif spot.home:
result.add_warning(
f"File is not under bios/ yet. The collection keeps this name in `{spot.home}`"
+ copies
)
else:
result.add_warning(
"File is not under bios/ yet. Place it in bios/Manufacturer/Console/"
)
declared = [
*platform_hashes.get("sizes", {}).get(result.filename, []),
@@ -671,6 +656,87 @@ def _platforms_accepting(filepath: str, filename: str, platform_hashes: dict) ->
return accepted
def expected_folders(
values: Iterable[str], platform_hashes: dict, profile_hashes: dict | None
) -> list[str]:
"""The bios/<Manufacturer>/<Console>/ folders the files of a hash's
system are in, read from the first of *values* a table knows.
A platform's declaration first, then a profile's: most files the gaps
page lists are declared by a profile alone.
"""
for table in (platform_hashes, profile_hashes or {}):
for value in values:
if value and value in table.get("folders", {}):
return sorted(table["folders"][value])
return []
@dataclass(frozen=True)
class Placement:
"""Where a file not under bios/ yet goes.
``folders`` are those of its system, ``home`` the folder the collection
keeps its name in when its system names none. ``name`` is the name it
is copied under, empty when the declarations do not settle one.
``variant`` says a file of that name is already in the folder: a copy
goes beside it in .variants/, never over it.
"""
folders: tuple[str, ...] = ()
home: str = ""
name: str = ""
variant: bool = False
@property
def folder(self) -> str:
return self.folders[0] if self.folders else self.home
def destination(self, sha1: str) -> str:
if not self.name:
return ""
if self.variant:
return f"{self.folder}.variants/{self.name}.{sha1[:8]}"
return self.folder + self.name
def placement(
values: Iterable[str],
filename: str,
db: dict | None,
platform_hashes: dict,
profile_hashes: dict | None,
declared: bool,
exists: Callable[[str], bool] = os.path.exists,
) -> Placement:
"""Where a file goes, by its hashes and its name.
The review and the site's wanted page both read this one rule, so the
folder a contributor is sent to is the folder the review accepts.
*declared* says a list or a profile declares one of the hashes: a file
known by its name alone gets a slot only once its size fits.
"""
values = [value for value in values if value]
folders = expected_folders(values, platform_hashes, profile_hashes)
if folders:
names = {
name
for table in (platform_hashes, profile_hashes or {})
for value in values
for name in table.get("named", {}).get(value, ())
}
name = next(iter(names)) if len(names) == 1 else ""
if len(folders) == 1 and name and "/" not in name:
return Placement(tuple(folders), name=name, variant=exists(folders[0] + name))
return Placement(tuple(folders))
held = next((value for value in values if value in (db or {}).get("files", {})), "")
home = _variant_home(db, filename, held)
if declared and home and filename and "/" not in filename:
# The folder holds a file of that name already.
return Placement(home=home, name=filename, variant=True)
return Placement(home=home)
def _variant_home(db: dict | None, name: str, held: str = "") -> str:
"""The folder the collection keeps a name in, for its variants beside it.