refactor: hold the run's link tables in one place

This commit is contained in:
Abdessamad Derraz committed 2026-11-23 23:07:44 +01:00
1 parent 6e8ef2650f
commit 7ad22248b5
25 files changed
+534 -492

No files matched your search

+1
View File
@@ -190,6 +190,7 @@ on:
- "scripts/sitegen/reference.py"
- "scripts/sitegen/releasepacks.py"
- "scripts/sitegen/render.py"
- "scripts/sitegen/runlinks.py"
- "scripts/sitegen/sources.py"
- "scripts/sitegen/starlight.py"
- "scripts/sitegen/startwith.py"
+4 -2
View File
@@ -12,7 +12,8 @@ from model.profiles import is_emulator
from sitegen.config import SITE_URL
from core.hashing import parse_hash_list
from sitegen.lookup import site_path
from sitegen.render import card_anchor, console_href
from sitegen.render import card_anchor
from sitegen.runlinks import console_href
def system_index_items(db: dict, coverages: dict, profiles: dict) -> list[dict]:
@@ -25,7 +26,8 @@ def system_index_items(db: dict, coverages: dict, profiles: dict) -> list[dict]:
takes the card of its first file, else the page of the emulator naming
it: 28 such ids sent their hashes to no page.
"""
from sitegen.render import card_page, system_ids, system_section
from sitegen.render import system_ids
from sitegen.runlinks import card_page, system_section
files = db.get("files") or {}
by_md5 = (db.get("indexes") or {}).get("by_md5") or {}
+14 -10
View File
@@ -35,6 +35,7 @@ from sitegen import (
diagrams,
handheld as sitehandheld,
measurements as sitemeasurements,
runlinks,
starlight as sitestarlight,
steps as sitesteps,
wanted as sitewanted,
@@ -97,11 +98,9 @@ from sitegen.reference import (
generate_wiki_data_model,
reference_next,
)
from sitegen.render import (
WIKI_SRC_DIR,
console_icon_name,
percent_text,
system_page_map,
from sitegen.render import WIKI_SRC_DIR, console_icon_name, percent_text
from sitegen.runlinks import (
ICON_DIR,
prime_system_icons,
reset_console_pages,
set_system_page_map,
@@ -249,17 +248,20 @@ def _write_home_pages(run: _SiteRun) -> dict:
def _write_system_pages(run: _SiteRun) -> None:
"""The system pages, each manufacturer's, and their API items."""
from sitegen.render import link_coverage, system_ids
from sitegen.render import system_ids
from sitegen.runlinks import link_coverage
docs, public, db = run.docs, run.public, run.db
manufacturers = run.manufacturers
print("Generating system pages...")
prime_system_icons({
missing = prime_system_icons({
console_icon_name(mfr, console)
for mfr, consoles in manufacturers.items()
for console in consoles
})
if missing:
print(f" {missing} systems have no icon in {ICON_DIR.relative_to(ICON_DIR.parents[1])}")
# The arcade boards are recorded before any page links one, the
# system pages and their install commands first among them.
@@ -301,7 +303,7 @@ def _write_measurements(run: _SiteRun) -> sitemeasurements.Built:
print("Compiling the measurements...")
measured = sitemeasurements.build(
run.public, emulators_dir=Path(run.args.emulators_dir), repo=REPO_URL,
system_names={sys_id: system_name(sys_id) for sys_id in sorted(set(system_page_map))},
system_names={sys_id: system_name(sys_id) for sys_id in sorted(set(runlinks.current().system_pages))},
)
for path in measured.paths:
record_written(path)
@@ -627,7 +629,7 @@ def _write_navigation(run: _SiteRun, published_parts: dict[str, str]) -> None:
sort_keys=True) + "\n")
write_if_changed(str(generated / "lastmod.json"),
json.dumps(dict(sorted(lastmod.items())), indent=1) + "\n")
system_ids = set(system_page_map) | {
system_ids = set(runlinks.current().system_pages) | {
sys_id for cov in coverages.values() for sys_id in cov["config"].get("systems", {})
}
titles = {sys_id: system_name(sys_id) for sys_id in sorted(system_ids)}
@@ -646,6 +648,8 @@ def generate_site(args: argparse.Namespace) -> None:
emulators=Path(args.emulators_dir).resolve(),
platforms=Path(args.platforms_dir).resolve(),
))
# Where this run puts systems, consoles and cards, nothing of a run before.
runlinks.use(runlinks.LinkTables())
db = load_database(args.db)
docs = Path(args.docs_dir)
# Files the site serves as they are (data, downloads, images), in the
@@ -682,7 +686,7 @@ def generate_site(args: argparse.Namespace) -> None:
set_system_page_map(
system_pages_from_data(run.manufacturers, coverages, db, profiles)
)
print(f" {len(system_page_map)} system IDs mapped to pages")
print(f" {len(runlinks.current().system_pages)} system IDs mapped to pages")
_write_system_pages(run)
measured = _write_measurements(run)
+2 -3
View File
@@ -22,9 +22,8 @@ from core.ziptools import zip_members
from model.mamerelease import tag_version
from sitegen.fields import search_excluded
from sitegen.install import manifest_systems, platform_display
from sitegen.render import (
SHORT_HASH, card_anchor, code_span, count_text, emulator_card_page, system_section,
)
from sitegen.render import SHORT_HASH, card_anchor, code_span, count_text
from sitegen.runlinks import emulator_card_page, system_section
def emulator_file_anchors(files: list[dict]) -> list[str]:
+1 -1
View File
@@ -201,7 +201,7 @@ _SECTION_ENTRIES: dict[int, tuple[object, dict[tuple[str, str], list]]] = {}
def entries_by_section(consumers: FileConsumers) -> dict[tuple[str, str], list]:
"""Each console section with the (sha1, emulator, entry, system) whose
system leads to it, read once per build."""
from sitegen.render import system_section
from sitegen.runlinks import system_section
cached = _SECTION_ENTRIES.get(id(consumers))
if cached is not None and cached[0] is consumers:
+4 -12
View File
@@ -40,16 +40,8 @@ from sitegen.install import (
data_root_words,
standalone_place,
)
from sitegen.render import (
SHORT_HASH,
WIKI_SRC_DIR,
card_anchor,
code_span,
count_text,
escape_tags,
card_page,
console_href,
)
from sitegen.render import SHORT_HASH, WIKI_SRC_DIR, 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,
@@ -63,12 +55,12 @@ from sitegen.sources import (
def named_system_link(sys_id: str, prefix: str = "") -> str:
"""A system by its display name, linked where _system_link links it.
"""A system by its display name, linked where runlinks.system_link links it.
The emulator pages printed the id ("sony-playstation") where every
other page says "Sony PlayStation". The id stays in the address only.
"""
from sitegen.render import system_section
from sitegen.runlinks import system_section
name = system_name(sys_id).replace("[", r"\[").replace("]", r"\]")
section = system_section(sys_id)
+2 -9
View File
@@ -47,15 +47,8 @@ from sitegen.install import (
)
from sitegen.lookup import data_directory_origin, data_tree_pages
from sitegen.pageregistry import PageRegistry
from sitegen.render import (
admonition_body,
card_anchor,
code_span,
count_text,
escape_tags,
card_page,
record_emulator_cards,
)
from sitegen.render import admonition_body, card_anchor, code_span, count_text, escape_tags
from sitegen.runlinks import card_page, record_emulator_cards
from sitegen.sources import source_ref_markdown, link_prose_citations, revision_markdown
from sitegen.parts import even_runs, weighted_runs
from sitegen.structured import emulator_file_aliases
+2 -1
View File
@@ -20,7 +20,8 @@ from sitegen.cards import PROVENANCE_LABELS, emulator_card_anchor, emulator_file
from sitegen.config import SITE_URL
from core.paths import REPO_ROOT
from core.ziptools import is_archive_path, zip_members
from sitegen.render import card_anchor, code_span, slugify_anchor, card_page, emulator_card_page
from sitegen.render import card_anchor, code_span, slugify_anchor
from sitegen.runlinks import card_page, emulator_card_page
from sitegen.write import write_if_changed
+2 -3
View File
@@ -36,9 +36,8 @@ from sitegen.render import (
count_text,
emulator_link,
escape_tags,
card_page,
console_href,
)
from sitegen.runlinks import card_page, console_href
def _collection_sha1(path: str) -> str:
@@ -63,7 +62,7 @@ def _system_heading_link(sys_id: str, prefix: str = "") -> str:
def _system_named_link(sys_id: str, prefix: str = "") -> str:
"""A system's name, linked to the section system_section gives."""
from sitegen.render import system_section
from sitegen.runlinks import system_section
name = escape_tags(system_name(sys_id))
section = system_section(sys_id)
+3 -306
View File
@@ -3,32 +3,15 @@
from __future__ import annotations
import re
import urllib.parse
from collections.abc import Callable, Mapping
from collections.abc import Callable
from model import siteinputs
from sitegen import markup
from sitegen.arcadeboards import ArcadeBoards, read_arcade_boards
from core.paths import REPO_ROOT
from core.text import count_text as count_text
from model.collection import card_moves, manufacturer_slug
from model.systemnames import (
SYSTEM_PARENTS,
console_anchors,
ensure_console_sections,
section_without_boards,
sections_generation,
system_name,
)
from model.collection import manufacturer_slug
from model.systemnames import console_anchors, system_name
WIKI_SRC_DIR = "wiki" # manually maintained wiki sources
SYSTEM_ICON_BASE = "https://raw.githubusercontent.com/libretro/retroarch-assets/master/xmb/systematic/png"
# Local copies of the upstream icons, named as upstream names them.
ICON_DIR = REPO_ROOT / "docs_assets" / "system-icons"
# Icon names the site holds a copy of. A name mapped to False has none.
_icon_available: dict[str, bool] = {}
_CODE_SPAN = re.compile(r"(`+).+?\1", re.S)
@@ -85,86 +68,14 @@ def admonition_body(text: str) -> str:
def console_icon_name(manufacturer: str, console_name: str) -> str:
return f"{manufacturer} - {console_name}".replace("/", " ")
def _icon_url(icon_name: str) -> str:
return f"{SYSTEM_ICON_BASE}/{urllib.parse.quote(icon_name)}.png"
def prime_system_icons(names: set[str]) -> None:
"""Record which system icons the site holds a copy of.
The icons are copied once into ``docs_assets/system-icons/`` by
``scripts/fetch_site_images.py``: the build reads that folder and never
the network. A system without a copy gets no icon, because a heading
with a broken image reads worse than a heading without one.
"""
held = {path.stem for path in ICON_DIR.glob("*.png")}
_icon_available.update({name: name in held for name in names})
missing = sum(1 for name in names if name not in held)
if missing:
print(f" {missing} systems have no icon in {ICON_DIR.relative_to(ICON_DIR.parents[1])}")
def system_icon_markdown(manufacturer: str, console_name: str) -> str:
"""Icon image for a system heading, empty when the site holds none.
The link names the upstream file: ``sitegen.pageprep.localize_images``
points it at the local copy, whose source is recorded beside it.
"""
name = console_icon_name(manufacturer, console_name)
if not _icon_available.get(name):
return ""
return markup.image(console_name, _icon_url(name), width="24") + " "
# The system ids the collection's folders place (sitegen.places), by the
# folder each is placed in. Read as the run's set of system ids: a link, an
# install command and a card's maker go where system_section() says.
system_page_map: dict[str, tuple[str, str]] = {}
def slugify_anchor(text: str) -> str:
"""Slugify text for MkDocs anchor compatibility."""
import re
slug = text.lower()
slug = re.sub(r"[^\w\s-]", "", slug)
slug = re.sub(r"[\s]+", "-", slug)
slug = slug.strip("-")
return slug
def set_system_page_map(mapping: dict[str, tuple[str, str]]) -> None:
"""Install the run's placed system ids, replacing the previous table."""
system_page_map.clear()
system_page_map.update(mapping)
# A manufacturer page too large for one page is a summary, each console on
# pages of its own: (slug, console) -> its page stems under systems/, and
# (slug, console, sha1) -> the stem holding that card. A console of a page
# kept whole has no entry, its section is on the manufacturer's page.
_console_pages: dict[tuple[str, str], list[str]] = {}
_card_pages: dict[tuple[str, str, str], str] = {}
def reset_console_pages() -> None:
"""Forget where the system pages put consoles, cards and boards."""
_console_pages.clear()
_card_pages.clear()
_board_sections.clear()
def record_console_pages(
slug: str, console: str, stems: list[str], sha1s: list[list[str]]
) -> None:
"""Where a split manufacturer page put one console: its page stems, in
order, and the sha1 of each card on each of them."""
_console_pages[(slug, console)] = list(stems)
for stem, part in zip(stems, sha1s):
for sha1 in part:
_card_pages.setdefault((slug, console, sha1), stem)
def split_system_stems() -> set[str]:
"""Every page stem of a console moved to a page of its own."""
return {stem for stems in _console_pages.values() for stem in stems}
def console_anchor(manufacturer: str, console: str) -> str:
"""The id of a console's heading on its manufacturer's page."""
from core.anchors import toc_slug
@@ -173,144 +84,6 @@ def console_anchor(manufacturer: str, console: str) -> str:
return console_anchors.get(key) or toc_slug(console)
def console_href(slug: str, console: str, prefix: str = "") -> str:
"""Where a console's files are: its own page, or its section of the
manufacturer's page (also where a console cut into parts lists them).
An arcade board's section is the page of its own name, no heading
repeating its title."""
if slug == "arcade" and _board_sections:
board = _board_ids_by_name().get(console.casefold())
if board in _board_sections:
return f"{prefix}systems/arcade-{urllib.parse.quote(board_slug(board))}.md"
stems = _console_pages.get((slug, console))
if stems and len(stems) == 1:
return f"{prefix}systems/{urllib.parse.quote(stems[0])}.md"
return f"{prefix}systems/{urllib.parse.quote(slug)}.md#{console_anchor(slug, console)}"
def card_page(path: str, sha1: str) -> str:
"""The systems/ page stem holding the card of the copy at ``path``
(bios/<Manufacturer>/<Console>/...). A board's set is on the board's
page whatever folder holds the copy."""
parts = path.split("/")
slug = parts[1].lower().replace(" ", "-")
console = parts[2] if len(parts) > 2 else ""
if _board_sections:
board = arcade_board(sha1)
if board in _board_sections:
return f"arcade-{board_slug(board)}"
slug, console = card_moves.get((slug, console, str(sha1)), (slug, console))
return _card_pages.get((slug, console, sha1), slug)
# Emulator cards moved off a page too long for one: (emulator, anchor) ->
# the page stem under emulators/ that holds the card.
_emulator_card_pages: dict[tuple[str, str], str] = {}
def record_emulator_cards(emulator: str, stem: str, anchors: list[str]) -> None:
for anchor in anchors:
_emulator_card_pages[(emulator, anchor)] = stem
def emulator_card_page(emulator: str, anchor: str) -> str:
"""The emulators/ page stem holding a card: the emulator's own page, or
the page its cards went to."""
return _emulator_card_pages.get((emulator, anchor), emulator)
def system_section(sys_id: str) -> tuple[str, str] | None:
"""The console section a system id leads to, as (manufacturer slug,
console): its own section, else the parent SYSTEM_PARENTS names, else
the arcade board it names once record_board_section() wrote it
(``("arcade", <board name>)``, which console_href turns into
``systems/arcade-<board slug>.md#<board slug>``), else the one section
whose heading reads system_name(). The folder a system's files sit in
is no answer by itself: Emerson's Arcadia 2001 led to the Saturn and
Sega's NAOMI to the Dreamcast.
A heading under Arcade counts when it reads the name exactly (Namco
System 246). One under Other never does, its headings name programs."""
if sys_id in BOARD_PARENTS and _board_sections:
board = _board_of_id(BOARD_PARENTS[sys_id])
if board in _board_sections:
return "arcade", system_name(board)
section = section_without_boards(sys_id)
if (not _board_sections or sys_id in SYSTEM_PARENTS
or (section is not None and section[0] != "arcade")):
return section
board = _board_of_id(sys_id)
if board in _board_sections:
return "arcade", system_name(board)
return section
def _system_link(sys_id: str, prefix: str = "") -> str:
"""A system id linked to the section named after it, or the bare id."""
section = system_section(sys_id)
if section:
slug, console = section
return f"[{sys_id}]({console_href(slug, console, prefix)})"
return sys_id
# The arcade boards elected (sitegen.arcadeboards) for the sections
# installed, with the sections_generation they were elected under.
_arcade: list[tuple[int, ArcadeBoards] | None] = [None]
def use_arcade_boards(boards: ArcadeBoards) -> None:
"""Install the boards elected for the sections installed now. Without
it, or once the sections change, they are read from the site inputs on
first use."""
ensure_console_sections()
_arcade[0] = (sections_generation[0], boards)
def _boards() -> ArcadeBoards:
ensure_console_sections()
held = _arcade[0]
if held is not None and held[0] == sections_generation[0]:
return held[1]
boards = read_arcade_boards()
_arcade[0] = (sections_generation[0], boards)
return boards
def archive_machine(sha1: str) -> tuple[str, str] | None:
"""The (manufacturer, console) section of the machine an archive is
the set of, when a profile declares it for one machine only: the Neo
Geo's neogeo.zip, the MZ-2000's mz2000.zip. Read from the same
``category: bios_zip`` entries as arcade_board(), never the folder."""
places = _boards().archive_machines.get(str(sha1), frozenset())
return next(iter(places)) if len(places) == 1 else None
def _board_ids_by_name() -> Mapping[str, str]:
return _boards().board_names
def _board_of_id(sys_id: str) -> str | None:
"""The board an id names, by its display name: naomi2 and sega-naomi2
are one board."""
try:
name = system_name(sys_id)
except KeyError:
return None
return _board_ids_by_name().get(name.casefold())
def arcade_board(sha1: str) -> str | None:
"""The system id an arcade archive is the BIOS of, or None.
Read from the profiles' ``system``/``systems`` and ``contents:``,
never from the folder. An archive several boards share as often (a
device ROM), or one a machine with its own section names (neogeo.zip
for the Neo Geo, cd32.zip for the CD32), has no board. Every id of a
board's name returns the same id, the first in sort order."""
return _boards().archive_boards.get(str(sha1))
def board_slug(sys_id: str) -> str:
"""The slug of a board's section: its page is systems/arcade-<slug>/
and its heading's id is <slug>. Read from the board's display name,
@@ -320,29 +93,6 @@ def board_slug(sys_id: str) -> str:
return toc_slug(system_name(str(sys_id)))
# Boards whose section the system pages wrote. A link waits for its
# section: before the Arcade pages were grouped by board, 8,606 links on
# 141 pages led to pages nobody wrote and the build stopped.
_board_sections: set[str] = set()
def record_board_section(board: str) -> None:
"""Mark a board's section as written, at systems/arcade-<board_slug>/
under the heading <board_slug>. From then on system_section() leads
every id of the board there, and card_page() sends its Arcade cards
there. The system pages call it for each board they give a section,
before any other page links one."""
canonical = _board_of_id(str(board))
if canonical is None:
raise KeyError(f"{board!r} is not an arcade board")
_board_sections.add(canonical)
def arcade_boards() -> dict[str, str]:
"""Every board, by board id -> display name."""
return {board: system_name(board) for board in sorted(set(_boards().board_names.values()))}
def scalar_text(key: object, value: object) -> str:
"""A scalar of a structured block. A source reference reads as code."""
if isinstance(value, bool):
@@ -429,15 +179,6 @@ def by_mode(value: str | dict, mode: str) -> str:
return str(value or "")
# A system id that names a family of arcade boards -> the board its link
# leads to. RetroArch's sega-dreamcast-arcade lists the NAOMI, NAOMI 2 and
# Atomiswave BIOS: the NAOMI page comes first, the Dreamcast section links
# the others.
BOARD_PARENTS: dict[str, str] = {
"sega-dreamcast-arcade": "sega-naomi",
}
def system_ids(profiles: dict[str, dict], platforms: list[dict]) -> set[str]:
"""Every system id a page can name: the platforms' and the profiles'."""
ids = {str(sys_id) for config in platforms for sys_id in config.get("systems", {})}
@@ -450,47 +191,3 @@ def system_ids(profiles: dict[str, dict], platforms: list[dict]) -> set[str]:
ids.add(str(entry["system"]))
ids.update(str(sys_id) for sys_id in entry.get("systems") or [])
return ids
def link_coverage(ids: set[str]) -> tuple[int, int]:
"""How many of ``ids`` lead to a section, and how many there are."""
return sum(1 for sys_id in ids if system_section(sys_id)), len(ids)
# A system id -> the names the platforms' own files give it, built once.
_search_aliases: dict[str, list[str]] = {}
_search_aliases_built = [False]
# A native name as a person types it: no space, no comma. RetroArch's
# native names are No-Intro titles ("Sony - PlayStation") and stay out.
_ALIAS_SHAPE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.+-]*")
def system_search_aliases(sys_id: str) -> list[str]:
"""The native system ids the platform YAMLs file ``sys_id`` under
(psx, dreamcast, gba), sorted, for search. Read from each platform's
own entries by common.platform_system_names, never typed by hand."""
if not _search_aliases_built[0]:
from model.registry import list_registered_platforms
from model.platforms import load_platform_config
from model.systems import platform_system_names
platforms_dir = str(siteinputs.current().platforms)
index: dict[str, set[str]] = {}
for platform in list_registered_platforms(platforms_dir):
config = load_platform_config(platform, platforms_dir)
names = platform_system_names(config, list(config.get("systems", {})))
for owner, spelled in names.items():
index.setdefault(owner, set()).update(
name for name in spelled if _ALIAS_SHAPE.fullmatch(name)
)
# Search ignores case: one spelling per word, the lower-case one
# when a platform writes it (psx, not PSX).
_search_aliases.clear()
for owner, names in index.items():
spellings: dict[str, str] = {}
for name in sorted(names, key=lambda n: (n != n.lower(), n)):
spellings.setdefault(name.casefold(), name)
if spellings:
_search_aliases[owner] = sorted(spellings.values(), key=str.casefold)
_search_aliases_built[0] = True
return list(_search_aliases.get(str(sys_id), []))
+361
View File
@@ -0,0 +1,361 @@
"""Where one run's pages put systems, consoles, cards and boards."""
from __future__ import annotations
import re
import urllib.parse
from collections.abc import Mapping
from dataclasses import dataclass, field
from core.paths import REPO_ROOT
from model import siteinputs
from model.collection import card_moves
from model.systemnames import (
SYSTEM_PARENTS,
ensure_console_sections,
section_without_boards,
sections_generation,
system_name,
)
from sitegen import markup
from sitegen.arcadeboards import ArcadeBoards, read_arcade_boards
from sitegen.render import SYSTEM_ICON_BASE, board_slug, console_anchor, console_icon_name
# Local copies of the upstream icons, named as upstream names them.
ICON_DIR = REPO_ROOT / "docs_assets" / "system-icons"
@dataclass
class LinkTables:
"""The answers one run gives to where a page is.
``system_pages``: the system ids the collection's folders place
(sitegen.places), by the folder each is placed in. ``console_pages``:
(slug, console) -> its page stems under systems/ when a manufacturer page
too large for one is cut, and ``card_pages`` (slug, console, sha1) -> the
stem holding that card. ``board_sections``: boards whose section the
system pages wrote. ``emulator_card_pages``: (emulator, anchor) -> the
emulators/ stem a card moved to. ``icons``: icon name -> whether the site
holds a copy. ``arcade``: the boards elected, with the sections_generation
they were elected under. ``aliases``: page_aliases() built from the rest,
with the sections_generation it read, dropped whenever a table it reads
changes.
"""
system_pages: dict[str, tuple[str, str]] = field(default_factory=dict)
console_pages: dict[tuple[str, str], list[str]] = field(default_factory=dict)
card_pages: dict[tuple[str, str, str], str] = field(default_factory=dict)
board_sections: set[str] = field(default_factory=set)
emulator_card_pages: dict[tuple[str, str], str] = field(default_factory=dict)
icons: dict[str, bool] = field(default_factory=dict)
arcade: tuple[int, ArcadeBoards] | None = None
aliases: tuple[int, dict[str, list[str]]] | None = None
_current = [LinkTables()]
def current() -> LinkTables:
return _current[0]
def use(tables: LinkTables) -> None:
"""Install a run's tables, the previous run's forgotten."""
_current[0] = tables
def prime_system_icons(names: set[str]) -> int:
"""Record which system icons the site holds a copy of, and return how
many of ``names`` have none.
The icons are copied once into ``docs_assets/system-icons/`` by
``scripts/fetch_site_images.py``: the build reads that folder and never
the network. A system without a copy gets no icon, because a heading
with a broken image reads worse than a heading without one.
"""
held = {path.stem for path in ICON_DIR.glob("*.png")}
current().icons.update({name: name in held for name in names})
return sum(1 for name in names if name not in held)
def system_icon_markdown(manufacturer: str, console_name: str) -> str:
"""Icon image for a system heading, empty when the site holds none.
The link names the upstream file: ``sitegen.pageprep.localize_images``
points it at the local copy, whose source is recorded beside it.
"""
name = console_icon_name(manufacturer, console_name)
if not current().icons.get(name):
return ""
url = f"{SYSTEM_ICON_BASE}/{urllib.parse.quote(name)}.png"
return markup.image(console_name, url, width="24") + " "
def set_system_page_map(mapping: dict[str, tuple[str, str]]) -> None:
"""Install the run's placed system ids, replacing the previous table."""
tables = current()
tables.system_pages = dict(mapping)
tables.aliases = None
def reset_console_pages() -> None:
"""Forget where the system pages put consoles, cards and boards."""
tables = current()
tables.console_pages.clear()
tables.card_pages.clear()
tables.board_sections.clear()
tables.aliases = None
def record_console_pages(
slug: str, console: str, stems: list[str], sha1s: list[list[str]]
) -> None:
"""Where a split manufacturer page put one console: its page stems, in
order, and the sha1 of each card on each of them."""
tables = current()
tables.console_pages[(slug, console)] = list(stems)
for stem, part in zip(stems, sha1s):
for sha1 in part:
tables.card_pages.setdefault((slug, console, sha1), stem)
tables.aliases = None
def split_system_stems() -> set[str]:
"""Every page stem of a console moved to a page of its own."""
return {stem for stems in current().console_pages.values() for stem in stems}
def console_href(slug: str, console: str, prefix: str = "") -> str:
"""Where a console's files are: its own page, or its section of the
manufacturer's page (also where a console cut into parts lists them).
An arcade board's section is the page of its own name, no heading
repeating its title."""
tables = current()
if slug == "arcade" and tables.board_sections:
board = _board_ids_by_name().get(console.casefold())
if board in tables.board_sections:
return f"{prefix}systems/arcade-{urllib.parse.quote(board_slug(board))}.md"
stems = tables.console_pages.get((slug, console))
if stems and len(stems) == 1:
return f"{prefix}systems/{urllib.parse.quote(stems[0])}.md"
return f"{prefix}systems/{urllib.parse.quote(slug)}.md#{console_anchor(slug, console)}"
def card_page(path: str, sha1: str) -> str:
"""The systems/ page stem holding the card of the copy at ``path``
(bios/<Manufacturer>/<Console>/...). A board's set is on the board's
page whatever folder holds the copy."""
tables = current()
parts = path.split("/")
slug = parts[1].lower().replace(" ", "-")
console = parts[2] if len(parts) > 2 else ""
if tables.board_sections:
board = arcade_board(sha1)
if board in tables.board_sections:
return f"arcade-{board_slug(board)}"
slug, console = card_moves.get((slug, console, str(sha1)), (slug, console))
return tables.card_pages.get((slug, console, sha1), slug)
def record_emulator_cards(emulator: str, stem: str, anchors: list[str]) -> None:
"""Emulator cards moved off a page too long for one, to ``stem``."""
for anchor in anchors:
current().emulator_card_pages[(emulator, anchor)] = stem
def emulator_card_page(emulator: str, anchor: str) -> str:
"""The emulators/ page stem holding a card: the emulator's own page, or
the page its cards went to."""
return current().emulator_card_pages.get((emulator, anchor), emulator)
# A system id that names a family of arcade boards -> the board its link
# leads to. RetroArch's sega-dreamcast-arcade lists the NAOMI, NAOMI 2 and
# Atomiswave BIOS: the NAOMI page comes first, the Dreamcast section links
# the others.
BOARD_PARENTS: dict[str, str] = {
"sega-dreamcast-arcade": "sega-naomi",
}
def system_section(sys_id: str) -> tuple[str, str] | None:
"""The console section a system id leads to, as (manufacturer slug,
console): its own section, else the parent SYSTEM_PARENTS names, else
the arcade board it names once record_board_section() wrote it
(``("arcade", <board name>)``, which console_href turns into
``systems/arcade-<board slug>.md#<board slug>``), else the one section
whose heading reads system_name(). The folder a system's files sit in
is no answer by itself: Emerson's Arcadia 2001 led to the Saturn and
Sega's NAOMI to the Dreamcast.
A heading under Arcade counts when it reads the name exactly (Namco
System 246). One under Other never does, its headings name programs."""
sections = current().board_sections
if sys_id in BOARD_PARENTS and sections:
board = _board_of_id(BOARD_PARENTS[sys_id])
if board in sections:
return "arcade", system_name(board)
section = section_without_boards(sys_id)
if (not sections or sys_id in SYSTEM_PARENTS
or (section is not None and section[0] != "arcade")):
return section
board = _board_of_id(sys_id)
if board in sections:
return "arcade", system_name(board)
return section
def system_link(sys_id: str, prefix: str = "") -> str:
"""A system id linked to the section named after it, or the bare id."""
section = system_section(sys_id)
if section:
slug, console = section
return f"[{sys_id}]({console_href(slug, console, prefix)})"
return sys_id
def link_coverage(ids: set[str]) -> tuple[int, int]:
"""How many of ``ids`` lead to a section, and how many there are."""
return sum(1 for sys_id in ids if system_section(sys_id)), len(ids)
def use_arcade_boards(boards: ArcadeBoards) -> None:
"""Install the boards elected for the sections installed now. Without
it, or once the sections change, they are read from the site inputs on
first use."""
ensure_console_sections()
tables = current()
tables.arcade = (sections_generation[0], boards)
tables.aliases = None
def _boards() -> ArcadeBoards:
ensure_console_sections()
tables = current()
held = tables.arcade
if held is not None and held[0] == sections_generation[0]:
return held[1]
boards = read_arcade_boards()
tables.arcade = (sections_generation[0], boards)
return boards
def archive_machine(sha1: str) -> tuple[str, str] | None:
"""The (manufacturer, console) section of the machine an archive is
the set of, when a profile declares it for one machine only: the Neo
Geo's neogeo.zip, the MZ-2000's mz2000.zip. Read from the same
``category: bios_zip`` entries as arcade_board(), never the folder."""
places = _boards().archive_machines.get(str(sha1), frozenset())
return next(iter(places)) if len(places) == 1 else None
def _board_ids_by_name() -> Mapping[str, str]:
return _boards().board_names
def _board_of_id(sys_id: str) -> str | None:
"""The board an id names, by its display name: naomi2 and sega-naomi2
are one board."""
try:
name = system_name(sys_id)
except KeyError:
return None
return _board_ids_by_name().get(name.casefold())
def arcade_board(sha1: str) -> str | None:
"""The system id an arcade archive is the BIOS of, or None.
Read from the profiles' ``system``/``systems`` and ``contents:``,
never from the folder. An archive several boards share as often (a
device ROM), or one a machine with its own section names (neogeo.zip
for the Neo Geo, cd32.zip for the CD32), has no board. Every id of a
board's name returns the same id, the first in sort order."""
return _boards().archive_boards.get(str(sha1))
def record_board_section(board: str) -> None:
"""Mark a board's section as written, at systems/arcade-<board_slug>/
under the heading <board_slug>. From then on system_section() leads
every id of the board there, and card_page() sends its Arcade cards
there. The system pages call it for each board they give a section,
before any other page links one. A link waits for its section: before
the Arcade pages were grouped by board, 8,606 links on 141 pages led to
pages nobody wrote and the build stopped."""
canonical = _board_of_id(str(board))
if canonical is None:
raise KeyError(f"{board!r} is not an arcade board")
tables = current()
tables.board_sections.add(canonical)
tables.aliases = None
def arcade_boards() -> dict[str, str]:
"""Every board, by board id -> display name."""
return {board: system_name(board) for board in sorted(set(_boards().board_names.values()))}
# platforms folder -> system id -> the names its platform files give it.
_search_aliases: dict[str, dict[str, list[str]]] = {}
# A native name as a person types it: no space, no comma. RetroArch's
# native names are No-Intro titles ("Sony - PlayStation") and stay out.
_ALIAS_SHAPE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.+-]*")
def _read_search_aliases(platforms_dir: str) -> dict[str, list[str]]:
from model.registry import list_registered_platforms
from model.platforms import load_platform_config
from model.systems import platform_system_names
index: dict[str, set[str]] = {}
for platform in list_registered_platforms(platforms_dir):
config = load_platform_config(platform, platforms_dir)
names = platform_system_names(config, list(config.get("systems", {})))
for owner, spelled in names.items():
index.setdefault(owner, set()).update(
name for name in spelled if _ALIAS_SHAPE.fullmatch(name)
)
# Search ignores case: one spelling per word, the lower-case one
# when a platform writes it (psx, not PSX).
aliases: dict[str, list[str]] = {}
for owner, names in index.items():
spellings: dict[str, str] = {}
for name in sorted(names, key=lambda n: (n != n.lower(), n)):
spellings.setdefault(name.casefold(), name)
if spellings:
aliases[owner] = sorted(spellings.values(), key=str.casefold)
return aliases
def system_search_aliases(sys_id: str) -> list[str]:
"""The native system ids the platform YAMLs file ``sys_id`` under
(psx, dreamcast, gba), sorted, for search. Read from each platform's
own entries by common.platform_system_names, never typed by hand, in
the platforms folder the site inputs name."""
platforms_dir = str(siteinputs.current().platforms)
if platforms_dir not in _search_aliases:
_search_aliases[platforms_dir] = _read_search_aliases(platforms_dir)
return list(_search_aliases[platforms_dir].get(str(sys_id), []))
def page_aliases(rel: str) -> list[str]:
"""The names the platforms file the consoles of a system page under
(psx, dreamcast, gba), from system_search_aliases(): "psx bios" finds
the PlayStation page though the page never says psx. Built from the
run's tables, again once one of them changes."""
tables = current()
if not tables.system_pages:
return []
ensure_console_sections()
if tables.aliases is None or tables.aliases[0] != sections_generation[0]:
by_page: dict[str, set[str]] = {}
for sys_id in list(tables.system_pages):
section = system_section(sys_id)
names = system_search_aliases(sys_id)
if not section or not names:
continue
target = console_href(*section).partition("#")[0]
by_page.setdefault(urllib.parse.unquote(target), set()).update(names)
tables.aliases = (sections_generation[0], {
page: sorted(names, key=str.casefold) for page, names in by_page.items()})
return list(tables.aliases[1].get(rel, []))
+2 -28
View File
@@ -419,34 +419,6 @@ def file_names_meta(body: str) -> str:
return search_field("files", list(parts.values()))
# systems/ page -> the platforms' own ids for the consoles it holds, built
# on the first system page, once the generator has installed the sections.
_page_aliases: dict[str, list[str]] = {}
_page_aliases_built = [False]
def page_aliases(rel: str) -> list[str]:
"""The names the platforms file the consoles of a system page under
(psx, dreamcast, gba), from sitegen.render.system_search_aliases(): "psx
bios" finds the PlayStation page though the page never says psx."""
if not _page_aliases_built[0]:
from sitegen import render as siterender
by_page: dict[str, set[str]] = {}
for sys_id in list(siterender.system_page_map):
section = siterender.system_section(sys_id)
names = siterender.system_search_aliases(sys_id)
if not section or not names:
continue
target = siterender.console_href(*section).partition("#")[0]
by_page.setdefault(urllib.parse.unquote(target), set()).update(names)
_page_aliases.clear()
_page_aliases.update({page: sorted(names, key=str.casefold)
for page, names in by_page.items()})
_page_aliases_built[0] = bool(siterender.system_page_map)
return list(_page_aliases.get(rel, []))
def field_words(value: object) -> list[str]:
"""The words of a front matter search field: a list, or one string
with its words or phrases split at commas."""
@@ -585,6 +557,8 @@ def _page_body(rel: str, markdown: str, terms: dict[str, str], authored: dict,
body = _NEXT_STEPS.sub(
lambda match: f"<div data-pagefind-ignore>\n\n{match[0].rstrip()}\n\n</div>\n\n", body, count=1)
if rel.startswith("systems/"):
from sitegen.runlinks import page_aliases
body += file_names_meta(body) + search_field("aliases", page_aliases(rel))
consoles = field_words(authored.get("consoles"))
body += search_field("consoles", consoles)
+1 -1
View File
@@ -129,7 +129,7 @@ def _section_reads(
"""The reads of each file the section names, by sha1, and the files the
start line may name: the section's primaries, then the Arcade files
its systems require."""
from sitegen.render import system_section
from sitegen.runlinks import system_section
held = {str(f.get("sha1", "")) for f in files}
primaries = [f for f in files if "/.variants/" not in f["path"]]
+2 -1
View File
@@ -18,7 +18,8 @@ from sitegen.pageregistry import PageRegistry
from sitegen.emulatorcards import snippet_noun
from sitegen.install import comes_with_app
from sitegen.lookup import data_member_digests, hash_pairs
from sitegen.render import card_anchor, system_section
from sitegen.render import card_anchor
from sitegen.runlinks import system_section
from sitegen.write import write_if_changed
+6 -5
View File
@@ -30,7 +30,8 @@ from sitegen.fields import search_excluded
from sitegen.home import next_block
from sitegen.install import console_install_block, manifest_systems, platform_display
from sitegen.parts import character_count, even_runs, parent_front_matter, part_stems, weighted_runs
from sitegen.render import count_text, slugify_anchor, console_href, record_console_pages
from sitegen.render import count_text, slugify_anchor
from sitegen.runlinks import console_href, record_console_pages
from sitegen.startwith import (
OTHER_ARCADE,
cards_markdown,
@@ -83,7 +84,7 @@ class _BoardSort:
def arcade_folders(self, arcade: dict[str, list], by_name: dict[str, str]) -> None:
"""The folders of bios/Arcade/, each file to its board or machine."""
from sitegen.render import arcade_board, archive_machine
from sitegen.runlinks import arcade_board, archive_machine
from model.collection import record_card_move
for console in sorted(arcade):
@@ -104,7 +105,7 @@ class _BoardSort:
"""A board's set filed under a machine's folder is on the board's page
too, whatever the folder: naomi.zip under the Dreamcast was the copy
five setups list, and the NAOMI page did not name it."""
from sitegen.render import arcade_board, archive_machine
from sitegen.runlinks import arcade_board, archive_machine
from model.collection import record_card_move
for mfr, consoles in manufacturers.items():
@@ -153,7 +154,7 @@ def arcade_board_sections(
any page links one, so the install commands placed after it
(sitegen.cards.system_install_choices) follow a system's link to the
board's section. Call after reset_console_pages()."""
from sitegen.render import arcade_boards, record_board_section
from sitegen.runlinks import arcade_boards, record_board_section
_BOARD_CONSOLES.clear()
_BOARDS_FROM.clear()
@@ -178,7 +179,7 @@ def arcade_board_sections(
def _boards_line(manufacturer: str, console: str) -> list[str]:
"""The line of a section whose board sets went to the boards' pages:
the Dreamcast folder holds NAOMI's and Atomiswave's."""
from sitegen.render import arcade_boards
from sitegen.runlinks import arcade_boards
boards = _BOARDS_FROM.get((manufacturer, console))
if not boards:
+2 -1
View File
@@ -6,7 +6,8 @@ from model.collection import SECTION_LABELS, profiles_on_disk, manufacturer_slug
from model.composition import GAME_DATA_TOPS
from model.profiles import is_emulator
from sitegen import starlight as sitestarlight
from sitegen.render import count_text, console_href
from sitegen.render import count_text
from sitegen.runlinks import console_href
from sitegen.startwith import section_label
+39 -38
View File
@@ -3,7 +3,7 @@
The Arcade pages were cut by storage folder, so NAOMI, ZN-1, PGM and the
other boards had no section and stayed plain on 987 emulator rows.
sitegen.arcadeboards elects the board each set archive is the BIOS of,
read from the profiles, and siterender.arcade_board() names it, and system_section() leads every id of that board
read from the profiles, and runlinks.arcade_board() names it, and system_section() leads every id of that board
to ``systems/arcade-<board_slug>/#<board_slug>``, the section the system
pages write. The 28 ids that systems.json gave files and no page either
link or carry their reason below.
@@ -22,6 +22,7 @@ from pathlib import Path
from sitegen import arcadeboards
from sitegen import render as siterender
from sitegen import runlinks
from model import systemnames
from core.anchors import toc_slug
@@ -68,15 +69,15 @@ STAYS_PLAIN = {
def _reset() -> None:
"""Back to the repository's sections and boards, none written."""
siterender._arcade[0] = None
runlinks.current().arcade = None
systemnames._sections_installed[0] = False
siterender.reset_console_pages()
runlinks.reset_console_pages()
def _write_every_board() -> None:
"""What the system pages do once they give each board a section."""
for board in siterender.arcade_boards():
siterender.record_board_section(board)
for board in runlinks.arcade_boards():
runlinks.record_board_section(board)
@unittest.skipUnless((REPO_ROOT / "database.json").exists(), "database.json is not built")
@@ -97,7 +98,7 @@ class Boards(unittest.TestCase):
return self.db["indexes"]["by_name"][name]
def test_named_boards_exist(self) -> None:
boards = siterender.arcade_boards()
boards = runlinks.arcade_boards()
names = set(boards.values())
for sys_id, name in NAMED_BOARDS.items():
with self.subTest(sys_id=sys_id):
@@ -119,7 +120,7 @@ class Boards(unittest.TestCase):
for name, board in expect.items():
for sha1 in self._copies(name):
with self.subTest(name=name, path=self.db["files"][sha1]["path"]):
self.assertEqual(siterender.arcade_board(sha1), board)
self.assertEqual(runlinks.arcade_board(sha1), board)
def test_no_board(self) -> None:
"""neogeo.zip and cd32.zip are the BIOS of machines with a section of
@@ -127,10 +128,10 @@ class Boards(unittest.TestCase):
for name in ("neogeo.zip", "cd32.zip", "mie.zip", "jvs13551.zip"):
for sha1 in self._copies(name):
with self.subTest(name=name, path=self.db["files"][sha1]["path"]):
self.assertIsNone(siterender.arcade_board(sha1))
self.assertIsNone(runlinks.arcade_board(sha1))
def test_slug_contract(self) -> None:
boards = siterender.arcade_boards()
boards = runlinks.arcade_boards()
slugs = {siterender.board_slug(board) for board in boards}
self.assertEqual(len(slugs), len(boards), "two boards share a slug")
for board, name in boards.items():
@@ -141,7 +142,7 @@ class Boards(unittest.TestCase):
# The board's page is its section: no heading repeats its
# title.
self.assertEqual(
siterender.console_href(*siterender.system_section(board)),
runlinks.console_href(*runlinks.system_section(board)),
f"systems/arcade-{slug}.md")
def test_aliases_share_a_board(self) -> None:
@@ -158,15 +159,15 @@ class Boards(unittest.TestCase):
with self.subTest(alias=alias):
self.assertEqual(siterender.board_slug(alias), siterender.board_slug(board))
self.assertEqual(
siterender.system_section(alias), siterender.system_section(board))
runlinks.system_section(alias), runlinks.system_section(board))
def test_machines_keep_their_section(self) -> None:
self.assertEqual(siterender.system_section("snk-neogeo-mvs"), ("snk", "Neo Geo"))
self.assertEqual(siterender.system_section("sega-hikaru"), ("sega", "Hikaru"))
self.assertEqual(siterender.system_section("arcade"), ("arcade", "Arcade"))
self.assertEqual(runlinks.system_section("snk-neogeo-mvs"), ("snk", "Neo Geo"))
self.assertEqual(runlinks.system_section("sega-hikaru"), ("sega", "Hikaru"))
self.assertEqual(runlinks.system_section("arcade"), ("arcade", "Arcade"))
def test_systems_json_gaps(self) -> None:
plain = sorted(i for i in SYSTEMS_JSON_GAPS if siterender.system_section(i) is None)
plain = sorted(i for i in SYSTEMS_JSON_GAPS if runlinks.system_section(i) is None)
self.assertEqual(plain, sorted(STAYS_PLAIN))
def test_parents_named_by_the_plan(self) -> None:
@@ -178,7 +179,7 @@ class Boards(unittest.TestCase):
}
for sys_id, section in expect.items():
with self.subTest(sys_id=sys_id):
self.assertEqual(siterender.system_section(sys_id), section)
self.assertEqual(runlinks.system_section(sys_id), section)
@unittest.skipUnless((REPO_ROOT / "database.json").exists(), "database.json is not built")
@@ -191,32 +192,32 @@ class LinksWaitForTheSection(unittest.TestCase):
self.addCleanup(_reset)
def test_unwritten_board_stays_plain(self) -> None:
self.assertIsNone(siterender.system_section("igs-pgm"))
self.assertIsNone(siterender.system_section("naomi2"))
self.assertEqual(siterender.console_href("arcade", "IGS PolyGame Master"),
self.assertIsNone(runlinks.system_section("igs-pgm"))
self.assertIsNone(runlinks.system_section("naomi2"))
self.assertEqual(runlinks.console_href("arcade", "IGS PolyGame Master"),
"systems/arcade.md#igs-polygame-master")
def test_written_board_links_and_takes_its_cards(self) -> None:
siterender.record_board_section("igs-pgm")
self.assertEqual(siterender.system_section("igs-pgm"),
runlinks.record_board_section("igs-pgm")
self.assertEqual(runlinks.system_section("igs-pgm"),
("arcade", "IGS PolyGame Master"))
self.assertIsNone(siterender.system_section("sega-naomi"))
self.assertIsNone(runlinks.system_section("sega-naomi"))
sha1 = next(s for s, e in json.loads(
(REPO_ROOT / "database.json").read_text(encoding="utf-8"))["files"].items()
if e["path"] == "bios/Arcade/Arcade/pgm.zip")
self.assertEqual(siterender.card_page("bios/Arcade/Arcade/pgm.zip", sha1),
self.assertEqual(runlinks.card_page("bios/Arcade/Arcade/pgm.zip", sha1),
"arcade-igs-polygame-master")
siterender.reset_console_pages()
self.assertIsNone(siterender.system_section("igs-pgm"))
runlinks.reset_console_pages()
self.assertIsNone(runlinks.system_section("igs-pgm"))
def test_an_alias_records_its_board(self) -> None:
siterender.record_board_section("sega-atomiswave")
self.assertEqual(siterender.system_section("sammy-atomiswave"),
runlinks.record_board_section("sega-atomiswave")
self.assertEqual(runlinks.system_section("sammy-atomiswave"),
("arcade", "Sammy Atomiswave"))
def test_no_board_refused(self) -> None:
with self.assertRaises(KeyError):
siterender.record_board_section("sony-playstation")
runlinks.record_board_section("sony-playstation")
class BoardRules(unittest.TestCase):
@@ -248,15 +249,15 @@ class BoardRules(unittest.TestCase):
for sha1, path in files.items():
db["indexes"]["by_name"].setdefault(Path(path).name, []).append(sha1)
profiles = {key: {"systems": [], "files": rows} for key, rows in entries.items()}
siterender.use_arcade_boards(arcadeboards.elect_arcade_boards(profiles, db))
runlinks.use_arcade_boards(arcadeboards.elect_arcade_boards(profiles, db))
def test_folder_decides_nothing(self) -> None:
self._install(
{"core": [{"name": "pgm.zip", "category": "bios_zip", "system": "igs-pgm"}]},
{"a" * 40: "bios/Arcade/MAME/pgm.zip", "b" * 40: "bios/Other/x/pgm.zip"},
)
self.assertEqual(siterender.arcade_board("a" * 40), "igs-pgm")
self.assertEqual(siterender.arcade_board("b" * 40), "igs-pgm")
self.assertEqual(runlinks.arcade_board("a" * 40), "igs-pgm")
self.assertEqual(runlinks.arcade_board("b" * 40), "igs-pgm")
def test_tie_is_no_board(self) -> None:
self._install(
@@ -266,7 +267,7 @@ class BoardRules(unittest.TestCase):
},
{"c" * 40: "bios/Arcade/MAME/dev.zip"},
)
self.assertIsNone(siterender.arcade_board("c" * 40))
self.assertIsNone(runlinks.arcade_board("c" * 40))
def test_majority_wins(self) -> None:
self._install(
@@ -277,7 +278,7 @@ class BoardRules(unittest.TestCase):
},
{"c" * 40: "bios/Arcade/MAME/dev.zip"},
)
self.assertEqual(siterender.arcade_board("c" * 40), "igs-pgm")
self.assertEqual(runlinks.arcade_board("c" * 40), "igs-pgm")
def test_machine_set_is_no_board(self) -> None:
self._install(
@@ -287,7 +288,7 @@ class BoardRules(unittest.TestCase):
},
{"d" * 40: "bios/Arcade/MAME/neogeo.zip"},
)
self.assertIsNone(siterender.arcade_board("d" * 40))
self.assertIsNone(runlinks.arcade_board("d" * 40))
def test_contents_reject_a_homonym(self) -> None:
good = self._zip("good.zip", b"good")
@@ -304,8 +305,8 @@ class BoardRules(unittest.TestCase):
# Both copies filed under Arcade, as by_path_suffix records it.
{"Arcade/MAME/good.zip": ["e" * 40], "Arcade/FBNeo/good.zip": ["f" * 40]},
)
self.assertEqual(siterender.arcade_board("e" * 40), "igs-pgm")
self.assertIsNone(siterender.arcade_board("f" * 40))
self.assertEqual(runlinks.arcade_board("e" * 40), "igs-pgm")
self.assertIsNone(runlinks.arcade_board("f" * 40))
def test_no_copy_under_arcade_no_section(self) -> None:
"""A board with no set under Arcade has no section there to lead to."""
@@ -313,9 +314,9 @@ class BoardRules(unittest.TestCase):
{"core": [{"name": "pgm.zip", "category": "bios_zip", "system": "igs-pgm"}]},
{"a" * 40: "bios/IGS/PGM/pgm.zip"},
)
self.assertIsNone(siterender.arcade_board("a" * 40))
self.assertIsNone(runlinks.arcade_board("a" * 40))
with self.assertRaises(KeyError):
siterender.record_board_section("igs-pgm")
runlinks.record_board_section("igs-pgm")
if __name__ == "__main__":
+3 -6
View File
@@ -44,7 +44,7 @@ from sitegen import emulatorpage
from sitegen import emulatorsindex
from sitegen import install as sitegen_install
from sitegen import lookup
from sitegen import render as siterender
from sitegen import runlinks
from model import systemnames
from sitegen import validate
from resolve import layout
@@ -217,11 +217,8 @@ class TheSummaryLineIsProse(unittest.TestCase):
class TheIndexNamesEmulatorsAndSystems(unittest.TestCase):
def test_columns_and_counts(self):
# Pages another test split off would send the console elsewhere.
siterender.reset_console_pages()
self.addCleanup(siterender.reset_console_pages)
saved = dict(siterender.system_page_map)
self.addCleanup(siterender.set_system_page_map, saved)
siterender.set_system_page_map({"sony-playstation": ("sony", "PlayStation")})
self.addCleanup(runlinks.use, runlinks.current())
runlinks.use(runlinks.LinkTables(system_pages={"sony-playstation": ("sony", "PlayStation")}))
page = emulatorsindex.generate_emulators_index({
"duckstation": {"emulator": "DuckStation", "core_classification": "official_port",
"systems": ["sony-playstation"], "files": _files(3)},
+3 -3
View File
@@ -1218,14 +1218,14 @@ class TheOneLinerIsWhereUsersLand(unittest.TestCase):
def test_a_system_is_offered_only_where_the_manifest_records_it(self):
from sitegen import cards
from sitegen import render as siterender
from sitegen import runlinks
from model import systemnames
systemnames.set_console_sections({("Sony", "PlayStation")})
self.addCleanup(systemnames._sections_installed.__setitem__, 0, False)
siterender.reset_console_pages()
self.addCleanup(siterender.reset_console_pages)
runlinks.reset_console_pages()
self.addCleanup(runlinks.reset_console_pages)
# "playstation" leads to the same section, but the manifest records
# retroarch's own spelling only.
cov = {"retroarch": {"config": {"systems": {"sony-playstation": {}, "playstation": {}}}}}
+2 -1
View File
@@ -69,6 +69,7 @@ from sitegen import platformpage
from sitegen import provenance
from sitegen import publish
from sitegen import render
from sitegen import runlinks
from sitegen import wanted as sitewanted
from model import systemnames
from model.registry import list_registered_platforms, list_release_pack_platforms
@@ -1128,7 +1129,7 @@ class EverySystemIdWithFilesHasAPage(unittest.TestCase):
def test_first_file_then_emulator(self):
files = {"f" * 40: {"path": "bios/DOS/DOS/a.bin"}}
with mock.patch("sitegen.render._card_pages", {}):
with mock.patch.object(runlinks.current(), "card_pages", {}):
place = apiitems._first_file_place(
"dos", ["f" * 40], files, {}, lambda path, sha1: "dos")
self.assertEqual(place, ("DOS", "/retrobios/systems/dos/#sha1-ffffffffffff"))
+9 -10
View File
@@ -13,6 +13,7 @@ import yaml
from sitegen import arcadeboards
from sitegen import render as siterender
from sitegen import runlinks
from model import systemnames
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -24,9 +25,8 @@ class IconsComeFromTheLocalCopies(unittest.TestCase):
in docs_assets/system-icons and makes no request."""
def setUp(self) -> None:
saved = dict(siterender._icon_available)
self.addCleanup(lambda: (siterender._icon_available.clear(),
siterender._icon_available.update(saved)))
self.addCleanup(runlinks.use, runlinks.current())
runlinks.use(runlinks.LinkTables())
def test_availability_is_the_folder(self):
tmp = tempfile.TemporaryDirectory()
@@ -34,13 +34,12 @@ class IconsComeFromTheLocalCopies(unittest.TestCase):
folder = Path(tmp.name) / "docs_assets" / "system-icons"
folder.mkdir(parents=True)
(folder / "A - One.png").write_bytes(b"png")
with mock.patch.object(siterender, "ICON_DIR", folder), \
mock.patch("builtins.print"):
siterender.prime_system_icons({"A - One", "B - Two"})
self.assertTrue(siterender._icon_available["A - One"])
self.assertFalse(siterender._icon_available["B - Two"])
self.assertEqual(siterender.system_icon_markdown("B", "Two"), "")
self.assertIn("A%20-%20One.png", siterender.system_icon_markdown("A", "One"))
with mock.patch.object(runlinks, "ICON_DIR", folder):
self.assertEqual(runlinks.prime_system_icons({"A - One", "B - Two"}), 1)
self.assertTrue(runlinks.current().icons["A - One"])
self.assertFalse(runlinks.current().icons["B - Two"])
self.assertEqual(runlinks.system_icon_markdown("B", "Two"), "")
self.assertIn("A%20-%20One.png", runlinks.system_icon_markdown("A", "One"))
def test_no_request_is_made(self):
self.assertNotIn("urllib.request", (REPO_ROOT / "scripts" / "sitegen" / "render.py").read_text())
+4 -4
View File
@@ -24,7 +24,7 @@ from sitegen import startwith
from sitegen import systempages
from sitegen import systemsindex
from sitegen import whichpack
from sitegen import render as siterender
from sitegen import runlinks
from model import systemnames
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -352,7 +352,7 @@ class EverySystemLinkLandsOnItsSection(unittest.TestCase):
linked = 0
for sys_id in self.ids:
link = siterender._system_link(sys_id)
link = runlinks.system_link(sys_id)
match = re.fullmatch(r"\[[^\]]*\]\(systems/(?P<page>[^)#]+)\.md(?:#(?P<anchor>[^)]+))?\)", link)
if not match:
self.assertEqual(link, sys_id)
@@ -363,7 +363,7 @@ class EverySystemLinkLandsOnItsSection(unittest.TestCase):
self.assertIn(page, self.headings)
if match["anchor"]:
self.assertIn(match["anchor"], self.headings[page])
slug, console = siterender.system_section(sys_id)
slug, console = runlinks.system_section(sys_id)
# The Arcade folder of sets no board claims is headed by
# what it holds, its id staying the folder's.
if slug == "arcade":
@@ -374,7 +374,7 @@ class EverySystemLinkLandsOnItsSection(unittest.TestCase):
def test_a_system_without_a_section_of_its_name_is_not_sent_elsewhere(self):
for sys_id in ("emerson-arcadia-2001", "sega-naomi"):
with self.subTest(system=sys_id):
link = siterender._system_link(sys_id)
link = runlinks.system_link(sys_id)
self.assertNotIn("#saturn", link)
self.assertNotIn("#dreamcast", link)
+40 -22
View File
@@ -24,7 +24,8 @@ from collections.abc import Iterable
from pathlib import Path
from sitegen import render as siterender
from model import systemnames
from sitegen import runlinks
from model import siteinputs, systemnames
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -164,7 +165,7 @@ class SystemLinks(unittest.TestCase):
# The system pages give every arcade board a section of its own
# and record it. The built pages are checked by
# test_site_built_gate.
siterender.reset_console_pages()
runlinks.reset_console_pages()
# The sections as the system pages hold them: each board, the
# sets a reviewed machine owns under that machine.
cls.sections = arcade_board_sections(cls.manufacturers)
@@ -184,17 +185,17 @@ class SystemLinks(unittest.TestCase):
@classmethod
def tearDownClass(cls) -> None:
siterender.reset_console_pages()
runlinks.reset_console_pages()
def test_every_id_with_files_links(self) -> None:
linked, total = siterender.link_coverage(self.ids)
linked, total = runlinks.link_coverage(self.ids)
with_files = set(self.held)
print(f"\n {linked} of {total} system ids linked, "
f"{len(with_files - set(UNLINKED))} of {len(with_files)} with files, "
f"{len(self.ids - with_files)} with no file")
plain = sorted(
sys_id for sys_id in with_files - set(UNLINKED)
if siterender.system_section(sys_id) is None
if runlinks.system_section(sys_id) is None
)
self.assertEqual(plain, [], "link these or name them in UNLINKED with the reason")
@@ -213,23 +214,23 @@ class SystemLinks(unittest.TestCase):
for platform, sys_id in pairs
}
wrong = sorted(
(pair, place, siterender.system_section(pair[1]))
(pair, place, runlinks.system_section(pair[1]))
for pair, place in placed.items()
if siterender.system_section(pair[1]) != place
if runlinks.system_section(pair[1]) != place
)
self.assertEqual(wrong, [])
unplaced = sorted(
(name, sys_id)
for name, cov in self.coverages.items()
for sys_id in set(cov["config"].get("systems") or {}) & manifest_systems(name)
if siterender.system_section(sys_id) and (name, sys_id) not in placed
if runlinks.system_section(sys_id) and (name, sys_id) not in placed
)
self.assertEqual(unplaced, [])
def test_unlinked_list_is_current(self) -> None:
stale = sorted(
sys_id for sys_id in UNLINKED
if sys_id not in self.held or siterender.system_section(sys_id) is not None
if sys_id not in self.held or runlinks.system_section(sys_id) is not None
)
self.assertEqual(stale, [])
@@ -250,7 +251,7 @@ class SystemLinks(unittest.TestCase):
mfr == "Arcade" and console.casefold() in systemnames.known_program_names
):
continue
if siterender.system_section(sys_id) is None:
if runlinks.system_section(sys_id) is None:
missed.append(sys_id)
self.assertEqual(missed, [])
@@ -291,22 +292,22 @@ class SystemLinks(unittest.TestCase):
}
for sys_id, section in expect.items():
with self.subTest(sys_id=sys_id):
self.assertEqual(siterender.system_section(sys_id), section)
self.assertEqual(runlinks.system_section(sys_id), section)
def test_arcade_heading_by_exact_name(self) -> None:
self.assertEqual(
siterender.system_section("namco-system246"), ("arcade", "Namco System 246"))
runlinks.system_section("namco-system246"), ("arcade", "Namco System 246"))
# A board leads to its own section, never a folder of copies a core
# loads (Arcade > FBNeo).
self.assertEqual(siterender.system_section("sega-naomi"), ("arcade", "Sega NAOMI"))
self.assertEqual(runlinks.system_section("sega-naomi"), ("arcade", "Sega NAOMI"))
self.assertEqual(
siterender.system_section("igs-pgm"), ("arcade", "IGS PolyGame Master"))
runlinks.system_section("igs-pgm"), ("arcade", "IGS PolyGame Master"))
def test_folder_votes_stay_out(self) -> None:
"""A copy filed with another machine names no section: the Arcadia
stays plain, NAOMI 2 goes to its board, never to the Dreamcast."""
self.assertIsNone(siterender.system_section("emerson-arcadia-2001"))
self.assertEqual(siterender.system_section("naomi2"), ("arcade", "Sega NAOMI 2"))
self.assertIsNone(runlinks.system_section("emerson-arcadia-2001"))
self.assertEqual(runlinks.system_section("naomi2"), ("arcade", "Sega NAOMI 2"))
for sys_id in ("emerson-arcadia-2001", "naomi2"):
with self.subTest(sys_id=sys_id):
self.assertNotIn(sys_id, systemnames.SYSTEM_PARENTS)
@@ -322,13 +323,13 @@ class SystemLinks(unittest.TestCase):
class SearchAliases(unittest.TestCase):
def test_platform_names(self) -> None:
self.assertIn("psx", siterender.system_search_aliases("sony-playstation"))
self.assertIn("dc", siterender.system_search_aliases("sega-dreamcast"))
self.assertIn("gba", siterender.system_search_aliases("nintendo-gba"))
self.assertIn("psx", runlinks.system_search_aliases("sony-playstation"))
self.assertIn("dc", runlinks.system_search_aliases("sega-dreamcast"))
self.assertIn("gba", runlinks.system_search_aliases("nintendo-gba"))
def test_one_typed_word_per_name(self) -> None:
siterender.system_search_aliases("sony-playstation")
for sys_id, names in siterender._search_aliases.items():
runlinks.system_search_aliases("sony-playstation")
for sys_id, names in runlinks._search_aliases[str(siteinputs.current().platforms)].items():
with self.subTest(sys_id=sys_id):
self.assertNotIn(sys_id, names)
self.assertEqual(len({n.casefold() for n in names}), len(names))
@@ -336,7 +337,24 @@ class SearchAliases(unittest.TestCase):
self.assertNotRegex(name, r"[\s,]")
def test_unknown_id(self) -> None:
self.assertEqual(siterender.system_search_aliases("no-such-system"), [])
self.assertEqual(runlinks.system_search_aliases("no-such-system"), [])
def test_page_aliases_follow_the_run(self) -> None:
"""Built once and never dropped, a second run's pages carried the
first run's names, and a console split after the first call kept
its names on the manufacturer's page."""
self.addCleanup(runlinks.use, runlinks.current())
runlinks.use(runlinks.LinkTables())
runlinks.set_system_page_map({"sony-playstation": ("sony", "PlayStation")})
self.assertIn("psx", runlinks.page_aliases("systems/sony.md"))
runlinks.record_console_pages("sony", "PlayStation", ["sony-playstation"], [[]])
self.assertEqual(runlinks.page_aliases("systems/sony.md"), [])
self.assertIn("psx", runlinks.page_aliases("systems/sony-playstation.md"))
runlinks.use(runlinks.LinkTables())
runlinks.set_system_page_map({"nintendo-gba": ("nintendo", "Game Boy Advance")})
self.assertEqual(runlinks.page_aliases("systems/sony.md"), [])
self.assertEqual(runlinks.page_aliases("systems/sony-playstation.md"), [])
self.assertIn("gba", runlinks.page_aliases("systems/nintendo.md"))
class BuildCount(unittest.TestCase):
+16 -16
View File
@@ -52,6 +52,7 @@ from sitegen import startwith
from sitegen import systempages
from sitegen import systemsindex
from sitegen import render as siterender
from sitegen import runlinks
from model import systemnames
from packs.consumers import FileConsumers
from sitegen import ogcards
@@ -292,13 +293,13 @@ class ConsoleHeadingsStartWithTheName(unittest.TestCase):
def test_no_icon_even_when_one_exists(self):
icon = siterender.console_icon_name("Sony", "PlayStation")
with mock.patch.dict(siterender._icon_available, {icon: True}):
with mock.patch.dict(runlinks.current().icons, {icon: True}):
self.assertEqual(startwith.console_heading("Sony", "PlayStation"),
"## PlayStation { #playstation }")
def test_no_icon_no_image(self):
icon = siterender.console_icon_name("Nobody", "Nothing")
with mock.patch.dict(siterender._icon_available, {icon: False}):
with mock.patch.dict(runlinks.current().icons, {icon: False}):
self.assertEqual(startwith.console_heading("Nobody", "Nothing"), "## Nothing { #nothing }")
@@ -307,8 +308,8 @@ class TheSystemsIndexListsConsoles(unittest.TestCase):
be known to be under Sony."""
def test_one_row_per_console_by_its_name(self):
siterender.reset_console_pages()
self.addCleanup(siterender.reset_console_pages)
runlinks.reset_console_pages()
self.addCleanup(runlinks.reset_console_pages)
groups = {
"Sony": {"PlayStation": [_sony_file("a.bin", "a")], "PlayStation 2": [_sony_file("b.bin", "b")]},
"Other": {"ScummVM": [_sony_file("c.bin", "c")]},
@@ -650,10 +651,9 @@ class InstallBoxesCountTowardTheSummary(unittest.TestCase):
and the page passed its 600 KB budget once the DS files were refiled."""
def setUp(self) -> None:
from sitegen import render as siterender
siterender.reset_console_pages()
self.addCleanup(siterender.reset_console_pages)
runlinks.reset_console_pages()
self.addCleanup(runlinks.reset_console_pages)
self.consoles = {
name: [_file_at(f"{name}{i}.bin", "0123456789"[index * 3 + i],
f"bios/Maker/{name}/{name}{i}.bin") for i in range(3)]
@@ -874,7 +874,7 @@ class CardsNameEmulatorsByName(unittest.TestCase):
class PartPagesKnowWhereTheyAre(unittest.TestCase):
def tearDown(self) -> None:
# system_pages records where consoles went, for every later page.
siterender.reset_console_pages()
runlinks.reset_console_pages()
"""6.7: 128 system pages had no parent, parts were "part 3 of 5"."""
@@ -923,7 +923,7 @@ def _consoles(page: str) -> list[str]:
class ConsolesFieldNamesMachinesOnce(unittest.TestCase):
def tearDown(self) -> None:
# system_pages records where consoles went, for every later page.
siterender.reset_console_pages()
runlinks.reset_console_pages()
"""The consoles search field: only machine sections, and a console
with a page of its own is that page's, or "dolphin" found Other and
@@ -947,7 +947,7 @@ class ConsolesFieldNamesMachinesOnce(unittest.TestCase):
self.assertIn("sega-saturn", pages)
self.assertEqual(_consoles(pages["sega"][0]), ["Pico"])
self.assertEqual(_consoles(pages["sega-saturn"][0]), ["Saturn"])
self.addCleanup(siterender.reset_console_pages)
self.addCleanup(runlinks.reset_console_pages)
sony = systempages.system_pages("Sony", {"PlayStation": big, "PocketStation": small},
consumers, budget=one * 12)
self.assertEqual(_consoles(sony["sony"][0]), [])
@@ -1147,7 +1147,7 @@ class ABoardIsAnArcadeMachine(unittest.TestCase):
"""6.4: computers, a sound chip and a toy had board pages."""
def test_no_board_has_a_parent_outside_arcade(self) -> None:
wrong = sorted(board for board in siterender.arcade_boards()
wrong = sorted(board for board in runlinks.arcade_boards()
if board in systemnames.SYSTEM_PARENTS)
self.assertEqual(wrong, [])
@@ -1185,14 +1185,14 @@ class TheDreamcastBoardsAreFiledByBoard(unittest.TestCase):
self.assertEqual(missing, [])
def test_the_dreamcast_arcade_id_leads_to_naomi(self) -> None:
siterender.reset_console_pages()
for board in siterender.arcade_boards():
siterender.record_board_section(board)
runlinks.reset_console_pages()
for board in runlinks.arcade_boards():
runlinks.record_board_section(board)
try:
self.assertEqual(siterender.system_section("sega-dreamcast-arcade"),
self.assertEqual(runlinks.system_section("sega-dreamcast-arcade"),
("arcade", "Sega NAOMI"))
finally:
siterender.reset_console_pages()
runlinks.reset_console_pages()
class EnginesGoByEngine(unittest.TestCase):
+9 -9
View File
@@ -19,7 +19,7 @@ from sitegen import nav as sitegen_nav
from sitegen import platformfiles
from sitegen import systempages
from sitegen import starlight as sitestarlight
from sitegen import render as siterender
from sitegen import runlinks
from sitegen import markup
from packs.consumers import FileConsumers
@@ -32,8 +32,8 @@ def _file(name: str, index: int, console: str, maker: str = "Maker") -> dict:
class ASystemPageOverItsBudgetIsSplit(unittest.TestCase):
def setUp(self) -> None:
siterender.reset_console_pages()
self.addCleanup(siterender.reset_console_pages)
runlinks.reset_console_pages()
self.addCleanup(runlinks.reset_console_pages)
self.consoles = {
"Big": [_file(f"big{i:03d}.bin", i, "Big") for i in range(60)],
"Small": [_file("small.bin", 900, "Small")],
@@ -67,10 +67,10 @@ class ASystemPageOverItsBudgetIsSplit(unittest.TestCase):
held = [f["sha1"] for stem in parts for f in pages[stem][1]["Big"]]
self.assertEqual(sorted(held), sorted(f["sha1"] for f in self.consoles["Big"]))
last = self.consoles["Big"][-1]
self.assertEqual(siterender.card_page(last["path"], last["sha1"]), parts[-1])
self.assertEqual(runlinks.card_page(last["path"], last["sha1"]), parts[-1])
small = self.consoles["Small"][0]
self.assertEqual(siterender.card_page(small["path"], small["sha1"]), "maker")
self.assertEqual(siterender.console_href("maker", "Big"), "systems/maker.md#big")
self.assertEqual(runlinks.card_page(small["path"], small["sha1"]), "maker")
self.assertEqual(runlinks.console_href("maker", "Big"), "systems/maker.md#big")
def test_a_console_on_one_page_is_linked_directly(self):
self.consoles["Big"] = self.consoles["Big"][:12]
@@ -80,7 +80,7 @@ class ASystemPageOverItsBudgetIsSplit(unittest.TestCase):
pages = self._pages(len(whole) - 1)
self.assertIn("maker-big", pages)
self.assertNotIn("maker-big-2", pages)
self.assertEqual(siterender.console_href("maker", "Big", "../"),
self.assertEqual(runlinks.console_href("maker", "Big", "../"),
"../systems/maker-big.md")
@@ -109,8 +109,8 @@ class AnEmulatorWithTooManyCardsIsSplit(unittest.TestCase):
files = [{"name": f"set{i:04d}.zip"} for i in range(emulatorpage.EMULATOR_CARDS_PER_PAGE + 1)]
emulatorpage.plan_emulator_pages({"big": {"files": files}})
anchors = cards.emulator_file_anchors(files)
self.assertEqual(siterender.emulator_card_page("big", anchors[-1]), "big-files-2")
self.assertEqual(siterender.emulator_card_page("other", "file-x"), "other")
self.assertEqual(runlinks.emulator_card_page("big", anchors[-1]), "big-files-2")
self.assertEqual(runlinks.emulator_card_page("other", "file-x"), "other")
class APlatformSystemOverItsBudgetMoves(unittest.TestCase):