From 2786b3be34ce3fb3b8d68cb6d02ada4583d65b51 Mon Sep 17 00:00:00 2001
From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com>
Date: Tue, 24 Nov 2026 05:41:28 +0100
Subject: [PATCH] refactor: split the emulator card module
File badges and the romset and version rows get modules of their own.
---
.github/workflows/deploy-site.yml | 2 +
scripts/sitegen/build.py | 7 +-
scripts/sitegen/emulatorcards.py | 324 +---------------------------
scripts/sitegen/emulatormetadata.py | 211 ++++++++++++++++++
scripts/sitegen/emulatorpage.py | 7 +-
scripts/sitegen/filebadges.py | 122 +++++++++++
scripts/sitegen/startwith.py | 2 +-
tests/sources.py | 1 +
tests/test_audit_regressions.py | 4 +-
tests/test_site_availability.py | 2 +-
tests/test_site_emulator_page.py | 8 +-
tests/test_site_emulators.py | 24 ++-
tests/test_site_exports.py | 2 +-
13 files changed, 364 insertions(+), 352 deletions(-)
create mode 100644 scripts/sitegen/emulatormetadata.py
create mode 100644 scripts/sitegen/filebadges.py
diff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.yml
index 42058d64d..9d06c50d1 100644
--- a/.github/workflows/deploy-site.yml
+++ b/.github/workflows/deploy-site.yml
@@ -176,12 +176,14 @@ on:
- "scripts/sitegen/descriptions.py"
- "scripts/sitegen/diagrams.py"
- "scripts/sitegen/emulatorcards.py"
+ - "scripts/sitegen/emulatormetadata.py"
- "scripts/sitegen/emulatorpage.py"
- "scripts/sitegen/emulatorsindex.py"
- "scripts/sitegen/entries.py"
- "scripts/sitegen/exports.py"
- "scripts/sitegen/extraction.py"
- "scripts/sitegen/fields.py"
+ - "scripts/sitegen/filebadges.py"
- "scripts/sitegen/gaps.py"
- "scripts/sitegen/getpages.py"
- "scripts/sitegen/guidedata.py"
diff --git a/scripts/sitegen/build.py b/scripts/sitegen/build.py
index c386d0043..946b3cfc5 100644
--- a/scripts/sitegen/build.py
+++ b/scripts/sitegen/build.py
@@ -60,11 +60,8 @@ from sitegen.datapage import generate_data_page
from sitegen.pageregistry import PageRegistry
from sitegen.decorate import front_matter, decorate_markdown_pages
from sitegen.descriptions import title_noun
-from sitegen.emulatorcards import (
- ROMSET_FAQ_PAGE,
- emulator_setups,
- with_romset_table,
-)
+from sitegen.emulatormetadata import ROMSET_FAQ_PAGE, with_romset_table
+from sitegen.emulatorcards import emulator_setups
from sitegen.emulatorpage import (
availability_check,
emulator_pages,
diff --git a/scripts/sitegen/emulatorcards.py b/scripts/sitegen/emulatorcards.py
index fe01ac260..30b37cc5a 100644
--- a/scripts/sitegen/emulatorcards.py
+++ b/scripts/sitegen/emulatorcards.py
@@ -9,17 +9,14 @@ import urllib.parse
from collections.abc import Callable, Iterable, Mapping
import dataclasses
from dataclasses import dataclass
-from pathlib import Path
from core.sizes import size_text
from model.manufacturers import manufacturer_slug
from sitegen.runsections import system_name
-from model.profiles import reads_own_files
from packs.consumers import FileConsumers, entry_target, held_copy
from resolve.cores import resolve_platform_cores
from sitegen import markup
from sitegen.cards import (
- ROMSET_FAQ,
SEARCH_SKIPPED,
card_title,
listed_words,
@@ -30,25 +27,22 @@ from sitegen.cards import (
card_fold,
)
from sitegen.config import REPO_URL
-from core.text import series
from sitegen.fields import hash_spans
from sitegen.install import (
- OS_LABELS,
platform_display,
- under_root,
comes_with_app,
data_root_words,
standalone_place,
)
-from sitegen.render import SHORT_HASH, WIKI_SRC_DIR, card_anchor, code_span, count_text, escape_tags
+from sitegen.render import SHORT_HASH, card_anchor, code_span, count_text, escape_tags
from sitegen.runlinks import card_page, console_href
from sitegen.sources import (
source_permalink,
source_ref_markdown,
link_prose_citations,
requested_by,
- version_basis_url,
)
+from sitegen.filebadges import file_badges
# Emulator pages
@@ -70,25 +64,6 @@ def named_system_link(sys_id: str, prefix: str = "") -> str:
return f"[{name}]({console_href(slug, console, prefix)})"
-# Region slugs whose words are not the slug title-cased, beyond region.LABELS.
-_REGION_WORDS = {"world": "every region"}
-
-
-def region_words(value: object, most: int = 0) -> str:
- """A region: value in words. ``most`` caps the regions named, the rest
- counted: one Saturn BIOS serves seven."""
- raw = value if isinstance(value, list) else [value] if value else []
- from model.region import label
-
- words = [_REGION_WORDS.get(str(r)) or label(str(r)) for r in raw]
- if most and len(words) > most:
- words = words[:most] + [f"{len(words) - most} more"]
- return series(words)
-
-
-_CATEGORY_WORDS = {"bios": "BIOS", "game_data": "game data", "bios_zip": "BIOS ZIP"}
-
-
def snippet_noun(names: Iterable[str], firmware: int, fetched: int) -> str:
"""What an emulator's files are called in its snippet. A Switch
emulator reads keys, and "eden keys" is what readers search for. Ship
@@ -102,101 +77,6 @@ def snippet_noun(names: Iterable[str], firmware: int, fetched: int) -> str:
return "BIOS" if firmware * 2 >= fetched else "files"
-def _status_badges(f: dict, in_repo: bool, for_system: str, shipped: bool) -> list[str]:
- """The chips saying whether a file is needed and whether it is held."""
- required = f.get("required", False)
- badges = []
- if shipped:
- # NetherSX2's three interface fonts sat beside the BIOS as
- # "required" and "missing": the app ships them, nobody fetches them.
- # Narrowed to one build, the build is named.
- build = f.get("mode") if f.get("mode") in ("standalone", "libretro") else ""
- label = f"installed with the {build} emulator" if build else "comes with the app"
- badges.append(f'{label}')
- elif required:
- needed = f"required for {html.escape(for_system)}" if for_system else "required"
- badges.append(
- f'{needed}'
- )
- else:
- badges.append(
- 'optional'
- )
- # Whether the collection holds a file the app ships says nothing to
- # the reader: no status chip.
- if shipped:
- status = ""
- elif in_repo:
- status = 'in repo'
- elif f.get("unsourceable"):
- status = 'unsourceable'
- else:
- status = 'missing'
- if status:
- badges.append(status)
- return badges
-
-
-def file_badges(f: dict, in_repo: bool, for_system: str = "") -> list[str]:
- """The status chips shown beside a file name.
-
- Fourteen independent optional fields, each contributing at most one
- chip. Kept apart from the rest of the row so the field-by-field
- rendering stays readable. ``for_system`` names the system a required
- file serves, on a profile that runs more than one.
- """
- hle = f.get("hle_fallback", False)
- mode = f.get("mode", "")
- category = f.get("category", "")
- region = f.get("region", "")
- storage = f.get("storage", "")
- embedded = f.get("embedded", False)
- has_builtin = f.get("has_builtin", False)
- archive = f.get("archive", "")
- ftype = f.get("type", "")
- shipped = comes_with_app(f)
- badges = _status_badges(f, in_repo, for_system, shipped)
- if hle:
- badges.append(
- 'HLE fallback'
- )
- if mode and not (shipped and mode in ("standalone", "libretro")):
- badges.append(
- f'{mode}'
- )
- if category and category != "bios":
- badges.append(
- f'{_CATEGORY_WORDS.get(category, category)}'
- )
- if region:
- # Labelled: "optional in repo japan" read as one run-on phrase.
- badges.append(
- f'Region: {region_words(region)}'
- )
- if storage and storage != "embedded":
- badges.append(
- f'{storage}'
- )
- if embedded:
- badges.append(
- 'embedded'
- )
- if has_builtin:
- badges.append(
- 'built-in fallback'
- )
- if archive:
- badges.append(
- f'in {archive}'
- )
- if ftype and ftype != "bios":
- badges.append(
- f'{ftype}'
- )
-
- return badges
-
-
_LOAD_FROM = {
"system_dir": "the system (BIOS) directory",
"save_dir": "the save directory, not the BIOS directory",
@@ -837,206 +717,6 @@ def _directory_copies(entry: dict, consumers: FileConsumers) -> list[str]:
f"([browse]({tree}))"]
-_MAME_RELEASE = re.compile(r"^0\.\d")
-
-
-def emulator_romset(profile: dict) -> str:
- """The romset an arcade emulator's sets must match, "MAME 0.78", or "".
-
- ``mame_version`` where the profile has one (MAME4droid 2024 is app
- 1.38.1 on MAME 0.289), else the version of a MAME build or of a
- FinalBurn core, whose sets follow its own release.
- """
- if not reads_own_files(profile):
- return ""
- emulator = str(profile.get("emulator", ""))
- version = str(profile.get("core_version") or "")
- if profile.get("mame_version"):
- return f"MAME {profile['mame_version']}"
- # HBMAME's sets are its own homebrew sets, whatever MAME it is based on.
- if "MAME" in emulator and "HBMAME" not in emulator and _MAME_RELEASE.match(version):
- return f"MAME {version}"
- if emulator.startswith("FinalBurn Neo") and version:
- return f"FinalBurn Neo {version}"
- if (emulator.startswith("FB Alpha") or "FBA" in emulator) and version:
- return f"FB Alpha {version}"
- return ""
-
-
-def _version_said(value: object, basis: dict, profile: dict, mode: str = "") -> str:
- """One build's version and where the profile reads it, linked to the
- file or the tag where the source allows."""
- kind = basis.get("kind")
- if kind == "none":
- return "none stated in the source"
- if value is None:
- if kind == "unverified":
- return f"unknown: {_UNVERIFIED.get(str(basis.get('why')), 'unread')}"
- return "none published"
- value = str(value)
- url = version_basis_url(profile, basis, mode) if kind in ("file", "tag") else ""
-
- def shown(text: object) -> str:
- return f"[{code_span(str(text))}]({url})" if url else code_span(str(text))
-
- if kind == "file":
- return f"{value}, stated in {shown(basis.get('path'))}"
- if kind == "tag":
- distance = int(basis.get("distance") or 0)
- if not distance:
- return f"{value}, the tag at this revision"
- return f"{value}, {count_text(distance, 'commit')} after tag {shown(basis.get('tag'))}"
- if kind == "package":
- return f"{value}, read from {basis.get('artifact')}"
- if kind == "unverified":
- return f"{value}, not confirmed: {_UNVERIFIED.get(str(basis.get('why')), 'unread')}"
- return value
-
-
-# Why a profile's version could not be read, said to a reader.
-_UNVERIFIED = {
- "no_pin": "no revision recorded",
- "host_unsupported": "its host cannot be read",
- "host_gone": "its source is gone",
- "host_unreachable": "its host did not answer",
- "pin_off_branch": "its recorded revision is not the build described",
- "no_artifact": "no build recorded as read",
- "no_source": "no source declared",
-}
-
-
-def version_markdown(profile: dict) -> str:
- """The Version cell: core_version and where version_basis reads it.
-
- A null version said "none published" whether the code states none or
- nobody looked. Keyed by build mode like source, each build is named,
- where the page printed the dict's Python repr.
- """
- if "core_version" not in profile and not profile.get("version_basis"):
- return "unknown"
- value = profile.get("core_version")
- raw_basis = profile.get("version_basis")
- basis: dict = raw_basis if isinstance(raw_basis, dict) else {}
- if isinstance(value, dict) or (basis and "kind" not in basis):
- values = value if isinstance(value, dict) else {}
- modes = list(dict.fromkeys([*values, *basis]))
- return ", ".join(
- f"{_version_said(values.get(mode), basis.get(mode) or {}, profile, mode)} ({mode})"
- for mode in modes
- )
- return _version_said(value, basis, profile)
-
-
-ROMSET_FAQ_PAGE = Path(WIKI_SRC_DIR) / "technical-faq.md"
-_ROMSET_BLOCK = re.compile(
- r"(\n)(.*?)()", re.S)
-
-
-def _retroarch_label(profile: dict) -> str:
- """"Arcade (MAME 2003)" gives "MAME 2003", "Arcade (FinalBurn Neo)
- (Neo-Geo)" gives "FinalBurn Neo (Neo-Geo)"."""
- inner = str(profile.get("display_name") or profile.get("emulator") or "").split("(", 1)[-1]
- return inner.replace(")", "", 1).strip()
-
-
-def romset_table(profiles: dict) -> list[str]:
- """The FAQ's arcade table: each MAME and FinalBurn libretro core and the
- romset its profile reads at its pin.
-
- Written by hand, it told readers to collect MAME 0.160 sets for a core
- whose src/version.c states 0.159, and FinalBurn Neo 1.0.0.2 for a source
- at 1.0.0.03. A core whose name gives its version (Recalbox's MAME 0.258)
- needs no row.
- """
- rows: dict[str, list[str]] = {}
- for key, profile in sorted(profiles.items()):
- if not re.match(r"(mame|fbneo|fbalpha)", key) or \
- "libretro" not in str(profile.get("type", "")):
- continue
- romset = emulator_romset(profile)
- label = _retroarch_label(profile)
- if not romset or romset.split(" ", 1)[1].lstrip("v") in label:
- continue
- rows.setdefault(romset, []).append(label)
-
- def order(romset: str) -> tuple:
- family = 0 if romset.startswith("MAME") else 1 if romset.startswith("FB Alpha") else 2
- numbers = tuple(int(n) for n in re.findall(r"\d+", romset.split(" (", 1)[0]))
- return family, numbers
-
- lines = ["| Emulator, as RetroArch names it | Sets from |", "|---|---|"]
- lines.extend(f"| {', '.join(sorted(rows[romset]))} | {romset} |"
- for romset in sorted(rows, key=order))
- return lines
-
-
-def with_romset_table(page: str, profiles: dict) -> str:
- """The FAQ page with its romset table read from the profiles."""
- table = "\n".join(romset_table(profiles)) + "\n"
- if not _ROMSET_BLOCK.search(page):
- raise ValueError(f"{ROMSET_FAQ_PAGE}: no romsets block to write the table in")
- return _ROMSET_BLOCK.sub(lambda m: f"{m.group(1)}{table}{m.group(3)}", page, count=1)
-
-
-def render_metadata_rows(profile: dict) -> list[str]:
- """Scalar profile fields, one table row each.
-
- Anything structured belongs in a collapsible block below, not in a
- row: a dict rendered into a table cell is unreadable.
- """
- lines: list[str] = []
- romset = emulator_romset(profile)
- if romset:
- lines.append(f"| Romset | [{romset}]({ROMSET_FAQ}) |")
- for field, label in [
- ("core", "Core ID"),
- ("core_name", "Core name"),
- ("bios_size", "BIOS size"),
- ("bios_directory", "BIOS directory"),
- ("bios_detection", "BIOS detection"),
- ("bios_selection", "BIOS selection"),
- ("firmware_file", "Firmware file"),
- ("firmware_source", "Firmware source"),
- ("firmware_install", "Firmware install"),
- ("firmware_detection", "Firmware detection"),
- ("resources_directory", "Resources directory"),
- ("rom_path", "ROM path"),
- ("game_count", "Game count"),
- ("verification", "Checks the file by"),
- ("analysis_date", "Analysis date"),
- ("analysis_commit", "Analysis commit"),
- ]:
- val = profile.get(field)
- if val is None or val == "" or isinstance(val, (dict, list)):
- continue
- if field == "bios_directory" and profile.get("type") == "standalone" \
- and not str(val).startswith(("/", "~", "$")) and ":" not in str(val):
- # A bare `bios/` read as a place on the device: it is a folder
- # inside the app's own data folder, which the notes describe.
- lines.append(f"| {label} | {code_span(val)}, inside the app's own data folder |")
- elif field == "bios_size" and isinstance(val, int):
- lines.append(f"| {label} | {size_text(val)} ({val:,} bytes) |")
- elif isinstance(val, str) and val.startswith("http"):
- lines.append(f"| {label} | [{val}]({val}) |")
- else:
- lines.append(f"| {label} | {val} |")
- roots = profile.get("data_root")
- if isinstance(roots, dict):
- # The folder per system, for the reader who checks the profile.
- for key in ("windows", "macos", "linux", "android", "ios"):
- root = roots.get(key)
- if isinstance(root, dict) and root.get("path"):
- lines.append(f"| Data folder ({OS_LABELS[key]}) | "
- f"{under_root(str(root['path']), '')} |")
- if profile.get("source_ref"):
- lines.append(
- f"| Source ref | {source_ref_markdown(profile, profile['source_ref'])} |"
- )
- return lines
-
-
-
-
def any_name_bios(profile: dict) -> dict | None:
"""The one BIOS an emulator needs under any name, or None.
diff --git a/scripts/sitegen/emulatormetadata.py b/scripts/sitegen/emulatormetadata.py
new file mode 100644
index 000000000..9598a2c35
--- /dev/null
+++ b/scripts/sitegen/emulatormetadata.py
@@ -0,0 +1,211 @@
+"""An emulator's romset and version, in its metadata rows and in the FAQ's romset table."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from core.sizes import size_text
+from model.profiles import reads_own_files
+from sitegen.cards import ROMSET_FAQ
+from sitegen.install import OS_LABELS, under_root
+from sitegen.render import WIKI_SRC_DIR, code_span, count_text
+from sitegen.sources import source_ref_markdown, version_basis_url
+
+
+_MAME_RELEASE = re.compile(r"^0\.\d")
+
+
+def emulator_romset(profile: dict) -> str:
+ """The romset an arcade emulator's sets must match, "MAME 0.78", or "".
+
+ ``mame_version`` where the profile has one (MAME4droid 2024 is app
+ 1.38.1 on MAME 0.289), else the version of a MAME build or of a
+ FinalBurn core, whose sets follow its own release.
+ """
+ if not reads_own_files(profile):
+ return ""
+ emulator = str(profile.get("emulator", ""))
+ version = str(profile.get("core_version") or "")
+ if profile.get("mame_version"):
+ return f"MAME {profile['mame_version']}"
+ # HBMAME's sets are its own homebrew sets, whatever MAME it is based on.
+ if "MAME" in emulator and "HBMAME" not in emulator and _MAME_RELEASE.match(version):
+ return f"MAME {version}"
+ if emulator.startswith("FinalBurn Neo") and version:
+ return f"FinalBurn Neo {version}"
+ if (emulator.startswith("FB Alpha") or "FBA" in emulator) and version:
+ return f"FB Alpha {version}"
+ return ""
+
+
+def _version_said(value: object, basis: dict, profile: dict, mode: str = "") -> str:
+ """One build's version and where the profile reads it, linked to the
+ file or the tag where the source allows."""
+ kind = basis.get("kind")
+ if kind == "none":
+ return "none stated in the source"
+ if value is None:
+ if kind == "unverified":
+ return f"unknown: {_UNVERIFIED.get(str(basis.get('why')), 'unread')}"
+ return "none published"
+ value = str(value)
+ url = version_basis_url(profile, basis, mode) if kind in ("file", "tag") else ""
+
+ def shown(text: object) -> str:
+ return f"[{code_span(str(text))}]({url})" if url else code_span(str(text))
+
+ if kind == "file":
+ return f"{value}, stated in {shown(basis.get('path'))}"
+ if kind == "tag":
+ distance = int(basis.get("distance") or 0)
+ if not distance:
+ return f"{value}, the tag at this revision"
+ return f"{value}, {count_text(distance, 'commit')} after tag {shown(basis.get('tag'))}"
+ if kind == "package":
+ return f"{value}, read from {basis.get('artifact')}"
+ if kind == "unverified":
+ return f"{value}, not confirmed: {_UNVERIFIED.get(str(basis.get('why')), 'unread')}"
+ return value
+
+
+# Why a profile's version could not be read, said to a reader.
+_UNVERIFIED = {
+ "no_pin": "no revision recorded",
+ "host_unsupported": "its host cannot be read",
+ "host_gone": "its source is gone",
+ "host_unreachable": "its host did not answer",
+ "pin_off_branch": "its recorded revision is not the build described",
+ "no_artifact": "no build recorded as read",
+ "no_source": "no source declared",
+}
+
+
+def version_markdown(profile: dict) -> str:
+ """The Version cell: core_version and where version_basis reads it.
+
+ A null version said "none published" whether the code states none or
+ nobody looked. Keyed by build mode like source, each build is named,
+ where the page printed the dict's Python repr.
+ """
+ if "core_version" not in profile and not profile.get("version_basis"):
+ return "unknown"
+ value = profile.get("core_version")
+ raw_basis = profile.get("version_basis")
+ basis: dict = raw_basis if isinstance(raw_basis, dict) else {}
+ if isinstance(value, dict) or (basis and "kind" not in basis):
+ values = value if isinstance(value, dict) else {}
+ modes = list(dict.fromkeys([*values, *basis]))
+ return ", ".join(
+ f"{_version_said(values.get(mode), basis.get(mode) or {}, profile, mode)} ({mode})"
+ for mode in modes
+ )
+ return _version_said(value, basis, profile)
+
+
+ROMSET_FAQ_PAGE = Path(WIKI_SRC_DIR) / "technical-faq.md"
+_ROMSET_BLOCK = re.compile(
+ r"(\n)(.*?)()", re.S)
+
+
+def _retroarch_label(profile: dict) -> str:
+ """"Arcade (MAME 2003)" gives "MAME 2003", "Arcade (FinalBurn Neo)
+ (Neo-Geo)" gives "FinalBurn Neo (Neo-Geo)"."""
+ inner = str(profile.get("display_name") or profile.get("emulator") or "").split("(", 1)[-1]
+ return inner.replace(")", "", 1).strip()
+
+
+def romset_table(profiles: dict) -> list[str]:
+ """The FAQ's arcade table: each MAME and FinalBurn libretro core and the
+ romset its profile reads at its pin.
+
+ Written by hand, it told readers to collect MAME 0.160 sets for a core
+ whose src/version.c states 0.159, and FinalBurn Neo 1.0.0.2 for a source
+ at 1.0.0.03. A core whose name gives its version (Recalbox's MAME 0.258)
+ needs no row.
+ """
+ rows: dict[str, list[str]] = {}
+ for key, profile in sorted(profiles.items()):
+ if not re.match(r"(mame|fbneo|fbalpha)", key) or \
+ "libretro" not in str(profile.get("type", "")):
+ continue
+ romset = emulator_romset(profile)
+ label = _retroarch_label(profile)
+ if not romset or romset.split(" ", 1)[1].lstrip("v") in label:
+ continue
+ rows.setdefault(romset, []).append(label)
+
+ def order(romset: str) -> tuple:
+ family = 0 if romset.startswith("MAME") else 1 if romset.startswith("FB Alpha") else 2
+ numbers = tuple(int(n) for n in re.findall(r"\d+", romset.split(" (", 1)[0]))
+ return family, numbers
+
+ lines = ["| Emulator, as RetroArch names it | Sets from |", "|---|---|"]
+ lines.extend(f"| {', '.join(sorted(rows[romset]))} | {romset} |"
+ for romset in sorted(rows, key=order))
+ return lines
+
+
+def with_romset_table(page: str, profiles: dict) -> str:
+ """The FAQ page with its romset table read from the profiles."""
+ table = "\n".join(romset_table(profiles)) + "\n"
+ if not _ROMSET_BLOCK.search(page):
+ raise ValueError(f"{ROMSET_FAQ_PAGE}: no romsets block to write the table in")
+ return _ROMSET_BLOCK.sub(lambda m: f"{m.group(1)}{table}{m.group(3)}", page, count=1)
+
+
+def render_metadata_rows(profile: dict) -> list[str]:
+ """Scalar profile fields, one table row each.
+
+ Anything structured belongs in a collapsible block below, not in a
+ row: a dict rendered into a table cell is unreadable.
+ """
+ lines: list[str] = []
+ romset = emulator_romset(profile)
+ if romset:
+ lines.append(f"| Romset | [{romset}]({ROMSET_FAQ}) |")
+ for field, label in [
+ ("core", "Core ID"),
+ ("core_name", "Core name"),
+ ("bios_size", "BIOS size"),
+ ("bios_directory", "BIOS directory"),
+ ("bios_detection", "BIOS detection"),
+ ("bios_selection", "BIOS selection"),
+ ("firmware_file", "Firmware file"),
+ ("firmware_source", "Firmware source"),
+ ("firmware_install", "Firmware install"),
+ ("firmware_detection", "Firmware detection"),
+ ("resources_directory", "Resources directory"),
+ ("rom_path", "ROM path"),
+ ("game_count", "Game count"),
+ ("verification", "Checks the file by"),
+ ("analysis_date", "Analysis date"),
+ ("analysis_commit", "Analysis commit"),
+ ]:
+ val = profile.get(field)
+ if val is None or val == "" or isinstance(val, (dict, list)):
+ continue
+ if field == "bios_directory" and profile.get("type") == "standalone" \
+ and not str(val).startswith(("/", "~", "$")) and ":" not in str(val):
+ # A bare `bios/` read as a place on the device: it is a folder
+ # inside the app's own data folder, which the notes describe.
+ lines.append(f"| {label} | {code_span(val)}, inside the app's own data folder |")
+ elif field == "bios_size" and isinstance(val, int):
+ lines.append(f"| {label} | {size_text(val)} ({val:,} bytes) |")
+ elif isinstance(val, str) and val.startswith("http"):
+ lines.append(f"| {label} | [{val}]({val}) |")
+ else:
+ lines.append(f"| {label} | {val} |")
+ roots = profile.get("data_root")
+ if isinstance(roots, dict):
+ # The folder per system, for the reader who checks the profile.
+ for key in ("windows", "macos", "linux", "android", "ios"):
+ root = roots.get(key)
+ if isinstance(root, dict) and root.get("path"):
+ lines.append(f"| Data folder ({OS_LABELS[key]}) | "
+ f"{under_root(str(root['path']), '')} |")
+ if profile.get("source_ref"):
+ lines.append(
+ f"| Source ref | {source_ref_markdown(profile, profile['source_ref'])} |"
+ )
+ return lines
diff --git a/scripts/sitegen/emulatorpage.py b/scripts/sitegen/emulatorpage.py
index aa3f4e149..938eafd36 100644
--- a/scripts/sitegen/emulatorpage.py
+++ b/scripts/sitegen/emulatorpage.py
@@ -24,16 +24,13 @@ from sitegen.emulatorcards import (
CardSources,
build_rows,
entry_label,
- file_badges,
named_example,
named_system_link,
- region_words,
render_emulator_file,
- render_metadata_rows,
any_name_bios,
- emulator_romset,
- version_markdown,
)
+from sitegen.filebadges import file_badges, region_words
+from sitegen.emulatormetadata import render_metadata_rows, emulator_romset, version_markdown
from sitegen.emulatorsindex import CLS_LABEL_ONE
from sitegen.fields import render_platform_details, render_structured_blocks, search_excluded
from sitegen.home import next_block
diff --git a/scripts/sitegen/filebadges.py b/scripts/sitegen/filebadges.py
new file mode 100644
index 000000000..639a9f7c4
--- /dev/null
+++ b/scripts/sitegen/filebadges.py
@@ -0,0 +1,122 @@
+"""The chips beside an emulator file's name: need, holding, build, category and region."""
+
+from __future__ import annotations
+
+import html
+
+from core.text import series
+from sitegen.install import comes_with_app
+
+
+# Region slugs whose words are not the slug title-cased, beyond region.LABELS.
+_REGION_WORDS = {"world": "every region"}
+
+
+def region_words(value: object, most: int = 0) -> str:
+ """A region: value in words. ``most`` caps the regions named, the rest
+ counted: one Saturn BIOS serves seven."""
+ raw = value if isinstance(value, list) else [value] if value else []
+ from model.region import label
+
+ words = [_REGION_WORDS.get(str(r)) or label(str(r)) for r in raw]
+ if most and len(words) > most:
+ words = words[:most] + [f"{len(words) - most} more"]
+ return series(words)
+
+
+_CATEGORY_WORDS = {"bios": "BIOS", "game_data": "game data", "bios_zip": "BIOS ZIP"}
+
+
+def _status_badges(f: dict, in_repo: bool, for_system: str, shipped: bool) -> list[str]:
+ """The chips saying whether a file is needed and whether it is held."""
+ required = f.get("required", False)
+ badges = []
+ if shipped:
+ # NetherSX2's three interface fonts sat beside the BIOS as
+ # "required" and "missing": the app ships them, nobody fetches them.
+ # Narrowed to one build, the build is named.
+ build = f.get("mode") if f.get("mode") in ("standalone", "libretro") else ""
+ label = f"installed with the {build} emulator" if build else "comes with the app"
+ badges.append(f'{label}')
+ elif required:
+ needed = f"required for {html.escape(for_system)}" if for_system else "required"
+ badges.append(
+ f'{needed}'
+ )
+ else:
+ badges.append(
+ 'optional'
+ )
+ # Whether the collection holds a file the app ships says nothing to
+ # the reader: no status chip.
+ if shipped:
+ status = ""
+ elif in_repo:
+ status = 'in repo'
+ elif f.get("unsourceable"):
+ status = 'unsourceable'
+ else:
+ status = 'missing'
+ if status:
+ badges.append(status)
+ return badges
+
+
+def file_badges(f: dict, in_repo: bool, for_system: str = "") -> list[str]:
+ """The status chips shown beside a file name.
+
+ Fourteen independent optional fields, each contributing at most one
+ chip. Kept apart from the rest of the row so the field-by-field
+ rendering stays readable. ``for_system`` names the system a required
+ file serves, on a profile that runs more than one.
+ """
+ hle = f.get("hle_fallback", False)
+ mode = f.get("mode", "")
+ category = f.get("category", "")
+ region = f.get("region", "")
+ storage = f.get("storage", "")
+ embedded = f.get("embedded", False)
+ has_builtin = f.get("has_builtin", False)
+ archive = f.get("archive", "")
+ ftype = f.get("type", "")
+ shipped = comes_with_app(f)
+ badges = _status_badges(f, in_repo, for_system, shipped)
+ if hle:
+ badges.append(
+ 'HLE fallback'
+ )
+ if mode and not (shipped and mode in ("standalone", "libretro")):
+ badges.append(
+ f'{mode}'
+ )
+ if category and category != "bios":
+ badges.append(
+ f'{_CATEGORY_WORDS.get(category, category)}'
+ )
+ if region:
+ # Labelled: "optional in repo japan" read as one run-on phrase.
+ badges.append(
+ f'Region: {region_words(region)}'
+ )
+ if storage and storage != "embedded":
+ badges.append(
+ f'{storage}'
+ )
+ if embedded:
+ badges.append(
+ 'embedded'
+ )
+ if has_builtin:
+ badges.append(
+ 'built-in fallback'
+ )
+ if archive:
+ badges.append(
+ f'in {archive}'
+ )
+ if ftype and ftype != "bios":
+ badges.append(
+ f'{ftype}'
+ )
+
+ return badges
diff --git a/scripts/sitegen/startwith.py b/scripts/sitegen/startwith.py
index 4b9f62f52..4a00cfbcc 100644
--- a/scripts/sitegen/startwith.py
+++ b/scripts/sitegen/startwith.py
@@ -25,7 +25,7 @@ from sitegen.consolecards import (
without_files,
)
from core.text import series
-from sitegen.emulatorcards import region_words
+from sitegen.filebadges import region_words
from sitegen.install import comes_with_app
from sitegen.render import card_anchor, code_span, count_text, console_anchor
from sitegen.runsections import section_labels
diff --git a/tests/sources.py b/tests/sources.py
index 8ce35ec49..e350c6037 100644
--- a/tests/sources.py
+++ b/tests/sources.py
@@ -82,6 +82,7 @@ COMMANDS = {
"sitegen/systemsindex.py",
"sitegen/provenance.py", "sitegen/fields.py", "sitegen/consolecards.py",
"sitegen/startwith.py", "sitegen/systempages.py", "sitegen/emulatorcards.py",
+ "sitegen/filebadges.py", "sitegen/emulatormetadata.py",
"sitegen/emulatorpage.py", "sitegen/gaps.py", "sitegen/crossref.py", "sitegen/reference.py",
"sitegen/whichpack.py", "sitegen/nav.py", "sitegen/build.py", "sitegen/coverage.py",
"sitegen/extraction.py", "sitegen/releasepacks.py", "sitegen/archivecounts.py",
diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py
index 965485754..d3b091005 100644
--- a/tests/test_audit_regressions.py
+++ b/tests/test_audit_regressions.py
@@ -1049,13 +1049,13 @@ class FaqRegressions(unittest.TestCase):
# Typed by hand, the table and the prose under it kept MAME 0.160
# and FinalBurn Neo 1.0.0.2, versions no source at the pins states,
# and the test holding them to the profiles kept the errors in step.
- from sitegen import emulatorcards
+ from sitegen import emulatormetadata
from model.profiles import load_emulator_profiles
profiles = load_emulator_profiles(str(ROOT / "emulators"), skip_aliases=False)
page = (ROOT / "wiki" / "technical-faq.md").read_text(encoding="utf-8")
self.assertEqual(
- page, emulatorcards.with_romset_table(page, profiles),
+ page, emulatormetadata.with_romset_table(page, profiles),
"wiki/technical-faq.md romset table is stale: run scripts/generate_site.py",
)
prose = page.split("### How this is known", 1)[1].split("\n## ", 1)[0]
diff --git a/tests/test_site_availability.py b/tests/test_site_availability.py
index f00cc38ba..23bc989fa 100644
--- a/tests/test_site_availability.py
+++ b/tests/test_site_availability.py
@@ -17,7 +17,7 @@ import yaml
from model.database import load_database
from sitegen.emulatorpage import availability_check
-from sitegen.emulatorcards import file_badges
+from sitegen.filebadges import file_badges
REPO_ROOT = Path(__file__).resolve().parent.parent
diff --git a/tests/test_site_emulator_page.py b/tests/test_site_emulator_page.py
index da2a0eca7..2825dfc8a 100644
--- a/tests/test_site_emulator_page.py
+++ b/tests/test_site_emulator_page.py
@@ -76,7 +76,7 @@ class WhoShipsTheBuildAndWhy(unittest.TestCase):
def test_the_version_links_its_proof(self):
"""`0.97, stated in libretro/handy.h` was bare text beside a pinned
Revision link: the #define it reads was one search away."""
- from sitegen import emulatorcards
+ from sitegen import emulatormetadata
from sitegen import sources
import yaml
@@ -84,15 +84,15 @@ class WhoShipsTheBuildAndWhy(unittest.TestCase):
path = handy["version_basis"]["path"]
self.assertIn(path, sources.cited_paths(handy))
self.assertIn(f"stated in [`{path}`](https://github.com/libretro/libretro-handy/blob/"
- f"{handy['source_commit']}/{path})", emulatorcards.version_markdown(handy))
+ f"{handy['source_commit']}/{path})", emulatormetadata.version_markdown(handy))
tagged = {"source": "https://github.com/owner/emu", "source_commit": "a" * 40,
"core_version": "1.2-3-gaaaaaaa",
"version_basis": {"kind": "tag", "tag": "1.2", "distance": 3}}
- self.assertEqual(emulatorcards.version_markdown(tagged), "1.2-3-gaaaaaaa, 3 commits after tag "
+ self.assertEqual(emulatormetadata.version_markdown(tagged), "1.2-3-gaaaaaaa, 3 commits after tag "
"[`1.2`](https://github.com/owner/emu/tree/1.2)")
# A file no recorded tree confirms stays plain: no link beats a 404.
unread = {**tagged, "version_basis": {"kind": "file", "path": "src/none.h"}}
- self.assertEqual(emulatorcards.version_markdown(unread), "1.2-3-gaaaaaaa, stated in `src/none.h`")
+ self.assertEqual(emulatormetadata.version_markdown(unread), "1.2-3-gaaaaaaa, stated in `src/none.h`")
def test_the_upstream_pin_says_why_it_is_held(self):
"""mupen64plus showed its core revision and not that AmberELEC
diff --git a/tests/test_site_emulators.py b/tests/test_site_emulators.py
index 2ceeabe6a..cea25a6df 100644
--- a/tests/test_site_emulators.py
+++ b/tests/test_site_emulators.py
@@ -40,6 +40,8 @@ import json
from sitegen import guidedata
from sitegen import cards
from sitegen import emulatorcards
+from sitegen import emulatormetadata
+from sitegen import filebadges
from sitegen import emulatorpage
from sitegen import emulatorsindex
from sitegen import install as sitegen_install
@@ -210,7 +212,7 @@ class TheSummaryLineIsProse(unittest.TestCase):
self.assertIn("By kind: 1,563 BIOS ZIPs and 2 game data.", text)
def test_category_badge_in_words(self):
- badges = " ".join(emulatorcards.file_badges({"name": "a", "category": "game_data"}, True))
+ badges = " ".join(filebadges.file_badges({"name": "a", "category": "game_data"}, True))
self.assertIn(">game data", badges)
@@ -242,15 +244,15 @@ def _emulator_page(name: str, profile: dict | None = None) -> str:
class EachArcadePageNamesItsRomset(unittest.TestCase):
def test_the_romset_by_profile(self):
- self.assertEqual(emulatorcards.emulator_romset(_profile("mame2003")), "MAME 0.78")
+ self.assertEqual(emulatormetadata.emulator_romset(_profile("mame2003")), "MAME 0.78")
# The app's version is 1.38.1, its MAME is 0.289.
- self.assertEqual(emulatorcards.emulator_romset(_profile("mame4droid-2024")), "MAME 0.289")
- self.assertEqual(emulatorcards.emulator_romset(_profile("mame2003_plus")), "MAME 0.78 (plus backports)")
- self.assertTrue(emulatorcards.emulator_romset(_profile("fbneo")).startswith("FinalBurn Neo "))
- self.assertTrue(emulatorcards.emulator_romset(_profile("fbalpha2012")).startswith("FB Alpha "))
- self.assertEqual(emulatorcards.emulator_romset(_profile("duckstation")), "")
+ self.assertEqual(emulatormetadata.emulator_romset(_profile("mame4droid-2024")), "MAME 0.289")
+ self.assertEqual(emulatormetadata.emulator_romset(_profile("mame2003_plus")), "MAME 0.78 (plus backports)")
+ self.assertTrue(emulatormetadata.emulator_romset(_profile("fbneo")).startswith("FinalBurn Neo "))
+ self.assertTrue(emulatormetadata.emulator_romset(_profile("fbalpha2012")).startswith("FB Alpha "))
+ self.assertEqual(emulatormetadata.emulator_romset(_profile("duckstation")), "")
# HBMAME publishes no MAME release number.
- self.assertEqual(emulatorcards.emulator_romset(_profile("hbmame")), "")
+ self.assertEqual(emulatormetadata.emulator_romset(_profile("hbmame")), "")
def test_a_row_and_a_line_under_the_intro(self):
page = _emulator_page("mame2003")
@@ -275,14 +277,14 @@ class WhatTheAppShipsIsNoFileToGet(unittest.TestCase):
def test_the_badge(self):
font = next(f for f in self.profile["files"] if f["name"] == "Roboto-Regular.ttf")
- badges = " ".join(emulatorcards.file_badges(font, False))
+ badges = " ".join(filebadges.file_badges(font, False))
self.assertIn(">comes with the app", badges)
self.assertNotIn(">required", badges)
self.assertNotIn(">missing", badges)
# Narrowed to one build, the entry is that build's alone, as verify
# and the pack read it: EightyOne installs its ROMs, and the libretro
# core, which embeds them, reads no entry. Nothing to fetch.
- dual = " ".join(emulatorcards.file_badges({"name": "a", "bundled": True, "mode": "standalone",
+ dual = " ".join(filebadges.file_badges({"name": "a", "bundled": True, "mode": "standalone",
"required": True}, False))
self.assertNotIn(">required", dual)
self.assertNotIn(">missing", dual)
@@ -725,7 +727,7 @@ class DataFolderPrinted(unittest.TestCase):
"standalone_path": "a"}), "a")
def test_the_metadata_card_has_a_row_per_system(self) -> None:
- rows = emulatorcards.render_metadata_rows(_profile("cxbx-reloaded"))
+ rows = emulatormetadata.render_metadata_rows(_profile("cxbx-reloaded"))
self.assertIn("| Data folder (Windows) | `%APPDATA%/Cxbx-Reloaded/` |", rows)
self.assertFalse(any("Data folder (Linux)" in row for row in rows))
diff --git a/tests/test_site_exports.py b/tests/test_site_exports.py
index 4d4891db8..2ce6c7569 100644
--- a/tests/test_site_exports.py
+++ b/tests/test_site_exports.py
@@ -1173,7 +1173,7 @@ class ACardSaysWhyAFileIsLeftOut(unittest.TestCase):
could not tell why a RetroArch pack carried PPSSPP's assets."""
def test_the_build_and_the_platforms_are_named(self):
- from sitegen.emulatorcards import file_badges
+ from sitegen.filebadges import file_badges
badges = " ".join(file_badges({"name": "a", "bundled": True, "mode": "standalone"}, True))
self.assertIn("installed with the standalone emulator", badges)