refactor: carry the site's page state on the run

Eleven module globals in descriptions, decorate, emulatorpage and
emulatorcards held what one build records about its pages, filled by
build.py and as a side effect of two renderers. They now live on a
PageRegistry the run carries and passes to the renderers and to
decorate_markdown_pages. get/ pages return their date (get_page_data)
instead of writing it, and a card reads the data directory members
from its CardSources. A second build in one process no longer inherits
the first one's maps, and tests build the input instead of patching
globals.
This commit is contained in:
Abdessamad Derraz committed 2026-11-23 23:07:32 +01:00
1 parent 6f8e2f90c1
commit 6e8ef2650f
19 files changed
+253 -242

No files matched your search

+33 -33
View File
@@ -52,21 +52,17 @@ from sitegen.dataexports import (
write_single_item,
)
from sitegen.datapage import generate_data_page
from sitegen.decorate import SEARCH_DEMOTED, front_matter, decorate_markdown_pages
from sitegen.descriptions import PAGE_DATA, PART_PAGES, TITLE_NOUNS, title_noun
from sitegen.pageregistry import PageRegistry
from sitegen.decorate import front_matter, decorate_markdown_pages
from sitegen.descriptions import title_noun
from sitegen.emulatorcards import (
ARCHIVE_RECIPES_PAGE,
ROMSET_FAQ_PAGE,
DATA_MEMBERS,
emulator_setups,
with_archive_counts,
with_romset_table,
)
from sitegen.emulatorpage import (
DATA_READERS,
DATA_REVISIONS,
EMULATOR_SETUPS,
MEASUREMENT_ITEMS,
availability_check,
emulator_pages,
emulator_parts,
@@ -75,7 +71,7 @@ from sitegen.emulatorpage import (
from sitegen.emulatorsindex import generate_emulators_index
from sitegen.exports import generate_exports_page, load_export_reports
from sitegen.gaps import PlatformRegistries, SourceListing, generate_gap_analysis
from sitegen.getpages import generate_get_index, generate_get_page
from sitegen.getpages import generate_get_index, generate_get_page, get_page_data
from sitegen.guidepage import DEMO_ASSETS, generate_handheld_guide
from sitegen.home import generate_explore_index, generate_home
from sitegen.lookup import (
@@ -189,6 +185,8 @@ class _SiteRun:
gap_report: dict = dataclasses.field(default_factory=dict)
file_held: Callable[[dict], bool] = bool
manufacturers: dict = dataclasses.field(default_factory=dict)
# What the pages record for the pages written after them and the decorator.
pages: PageRegistry = dataclasses.field(default_factory=PageRegistry)
def _load_site_run(args: argparse.Namespace, db: dict, docs: Path, public: Path) -> _SiteRun:
@@ -281,11 +279,11 @@ def _write_system_pages(run: _SiteRun) -> None:
slug = mfr.lower().replace(" ", "-")
pages = system_pages(mfr, consoles, run.consumers, console_installs.get(slug))
for stem, (page, held) in pages.items():
PAGE_DATA[f"systems/{stem}.md"] = system_structured_data(stem, held)
TITLE_NOUNS[f"systems/{stem}.md"] = title_noun(
run.pages.page_data[f"systems/{stem}.md"] = system_structured_data(stem, held)
run.pages.title_nouns[f"systems/{stem}.md"] = title_noun(
str(entry.get("name", "")) for entries in held.values() for entry in entries)
if stem != slug:
PART_PAGES.add(f"systems/{stem}.md")
run.pages.part_pages.add(f"systems/{stem}.md")
write_if_changed(str(docs / "systems" / f"{stem}.md"), page)
write_single_item(
public / "api" / "v1" / "systems" / f"{slug}.json", "systems",
@@ -307,8 +305,7 @@ def _write_measurements(run: _SiteRun) -> sitemeasurements.Built:
)
for path in measured.paths:
record_written(path)
MEASUREMENT_ITEMS.clear()
MEASUREMENT_ITEMS.update(sitemeasurements.by_emulator(measured.index))
run.pages.measurement_items = sitemeasurements.by_emulator(measured.index)
print(f" {measured.index['records']} records, {measured.index['count']} tests")
write_if_changed(str(run.docs / sitemeasurements.EXPLORER_PAGE),
sitemeasurements.generate_explorer_page(measured.index) + reference_next())
@@ -326,7 +323,7 @@ def _write_data_exports(run: _SiteRun, stats: dict, dumps: WantedDumps) -> None:
write_if_changed(str(run.docs / "data.md"),
generate_data_page(exports, run.public / sitemeasurements.SQLITE_PATH)
+ reference_next())
PAGE_DATA["data.md"] = dataset_structured_data(exports, run.db)
run.pages.page_data["data.md"] = dataset_structured_data(exports, run.db)
def _write_platform_pages(run: _SiteRun) -> dict[str, str]:
@@ -356,7 +353,7 @@ def _write_platform_pages(run: _SiteRun) -> dict[str, str]:
for stem, page in moved.items():
if stem in coverages:
raise RuntimeError(f"a system page takes the platform {stem}'s address")
PART_PAGES.add(f"platforms/{stem}.md")
run.pages.part_pages.add(f"platforms/{stem}.md")
anchor = re.search(rf"\]\({re.escape(name)}\.md#([^)\s]+)\)", page)
if anchor:
published_parts[f"platforms/{stem}.md"] = f"platforms/{name}.md#{anchor[1]}"
@@ -366,7 +363,7 @@ def _write_platform_pages(run: _SiteRun) -> dict[str, str]:
# weight does not reach, and their file list is already kept out
# of the index: the title alone, found again on the setup's page
# and the console's, is all the search held of them.
SEARCH_DEMOTED.add(f"platforms/{stem}.md")
run.pages.search_demoted.add(f"platforms/{stem}.md")
front = front_matter(page)
if front:
page = page[page.find("\n---\n", 4) + 5:].lstrip("\n")
@@ -375,34 +372,34 @@ def _write_platform_pages(run: _SiteRun) -> dict[str, str]:
page = "---\n" + yaml.safe_dump(front, sort_keys=False, allow_unicode=True) \
+ "---\n\n" + page
write_if_changed(str(docs / "platforms" / f"{stem}.md"), page)
PAGE_DATA[f"platforms/{name}.md"] = platform_structured_data(name, cov)
run.pages.page_data[f"platforms/{name}.md"] = platform_structured_data(name, cov)
return published_parts
def _record_data_trees(profiles: dict) -> None:
"""The data directories: their members, revisions and readers, and the
pages their member lists go to."""
DATA_MEMBERS.update(data_directory_members())
DATA_REVISIONS.update(data_directory_revisions())
def _record_data_trees(profiles: dict, pages: PageRegistry) -> None:
"""Record in ``pages`` the data directories: their members, revisions
and readers, and the pages their member lists go to."""
pages.data_members.update(data_directory_members())
pages.data_revisions.update(data_directory_revisions())
for key in sorted(profiles):
if not is_emulator(profiles[key]):
continue
display = str(profiles[key].get("emulator", key))
for tree in page_data_directories(key, profiles):
readers = DATA_READERS.setdefault(str(tree.get("ref", "")), [])
readers = pages.data_readers.setdefault(str(tree.get("ref", "")), [])
if (key, display) not in readers:
readers.append((key, display))
for ref, members in DATA_MEMBERS.items():
for ref, members in pages.data_members.items():
for stem, _names in data_tree_pages(ref, members):
PART_PAGES.add(f"emulators/{stem}.md")
pages.part_pages.add(f"emulators/{stem}.md")
def _write_emulator_pages(run: _SiteRun) -> None:
"""The emulator index, and each emulator's page and API item."""
profiles = run.profiles
print("Generating emulator pages...")
EMULATOR_SETUPS.update(emulator_setups(run.coverages, profiles))
_record_data_trees(profiles)
run.pages.emulator_setups.update(emulator_setups(run.coverages, profiles))
_record_data_trees(profiles, run.pages)
write_if_changed(
str(run.docs / "emulators" / "index.md"), generate_emulators_index(profiles)
)
@@ -432,21 +429,21 @@ def _write_emulator_page(run: _SiteRun, name: str, profile: dict) -> None:
)
pages = emulator_pages(
name, profile, db, run.consumers, run.suppl_names, run.data_registry,
data_dirs=page_data_directories(name, run.profiles),
data_dirs=page_data_directories(name, run.profiles), registry=run.pages,
)
record_emulator_page(name, profile)
record_emulator_page(name, profile, run.pages)
# A frozen copy answers after the emulator: a frozen_snapshot, and a
# profile pinned to the revision one platform builds (pin_frozen).
# Reicast and Flycast 2021 LE answered "dc bios missing" before Flycast.
if (not lists_files(profile)
or profile.get("core_classification") in ("launcher", "alias", "frozen_snapshot")
or profile.get("pin_frozen")):
SEARCH_DEMOTED.add(f"emulators/{name}.md")
run.pages.search_demoted.add(f"emulators/{name}.md")
files = profile.get("files") or []
for stem, entries in emulator_parts(name, files, profile, run.file_held):
PAGE_DATA[f"emulators/{stem}.md"] = emulator_structured_data(
run.pages.page_data[f"emulators/{stem}.md"] = emulator_structured_data(
{**profile, "files": [files[i] for i in entries]})
PART_PAGES.add(f"emulators/{stem}.md")
run.pages.part_pages.add(f"emulators/{stem}.md")
for stem, page in pages.items():
write_if_changed(str(docs / "emulators" / f"{stem}.md"), page)
@@ -584,6 +581,9 @@ def _write_guide_pages(run: _SiteRun) -> None:
get_dir.mkdir(parents=True, exist_ok=True)
for name in run.platform_names:
write_if_changed(str(get_dir / f"{name}.md"), generate_get_page(name))
dated = get_page_data(name)
if dated:
run.pages.page_data[f"{releaserecord.GET_DIR}/{name}.md"] = dated
write_if_changed(str(get_dir / f"{GROUP_PAGE}.md"),
sitehandheld.group_page(REPO_ROOT))
write_if_changed(str(get_dir / "index.md"), generate_get_index())
@@ -605,7 +605,7 @@ def _write_navigation(run: _SiteRun, published_parts: dict[str, str]) -> None:
stale += sweep_top_pages(docs)
print("Adding page metadata and structured data...")
lastmod = decorate_markdown_pages(docs)
lastmod = decorate_markdown_pages(docs, run.pages)
nav = generate_nav(coverages, run.manufacturers, run.profiles, run.registry,
Path(WIKI_SRC_DIR))
+14 -11
View File
@@ -14,7 +14,8 @@ from model.database import load_database
from sitegen import markup, measurements as sitemeasurements, starlight as sitestarlight
from sitegen.config import SITE_NAME, SITE_URL, yaml
from core.paths import REPO_ROOT
from sitegen.descriptions import PAGE_DATA, page_browser_title, page_description, page_title
from sitegen.descriptions import page_browser_title, page_description, page_title
from sitegen.pageregistry import PageRegistry
from sitegen.pageprep import prepare_page, unresolved_images
from sitegen.render import CARD_ANCHOR, WIKI_SRC_DIR, card_anchor
from sitegen.write import undecorated, write_decorated
@@ -50,21 +51,21 @@ LEVELS = {
SEARCH_WEIGHT = {"start": 10, "setup": 1.5, "reference": 0.5, "contribute": 0.5, "part": 0.5}
SYSTEM_PAGE_WEIGHT = 5
DEEP_GUIDE_WEIGHT = 0.5
SEARCH_DEMOTED: set[str] = set()
# A tool page a reader reaches by a task, not its name: "check my dump",
# "md5 check" found emulator pages and never the page that checks a file.
SEARCH_WEIGHT_OF_PAGE = {"files/index.md": 2}
DEMOTED_WEIGHT = 0.5
def search_weight(relative: Path, level: str) -> float | None:
def search_weight(relative: Path, level: str, demoted: set[str] | frozenset[str] = frozenset()) -> float | None:
"""The search weight of a page, None for the default. A part page
states its own in its front matter: search_weight(path, "part")."""
states its own in its front matter: search_weight(path, "part").
``demoted`` pages answer a name after the page that owns it."""
if level == "part":
return SEARCH_WEIGHT["part"]
if relative.as_posix() in SEARCH_WEIGHT_OF_PAGE:
return SEARCH_WEIGHT_OF_PAGE[relative.as_posix()]
if relative.as_posix() in SEARCH_DEMOTED:
if relative.as_posix() in demoted:
return DEMOTED_WEIGHT
if relative.parts[0] == "systems":
return SYSTEM_PAGE_WEIGHT
@@ -131,13 +132,15 @@ def _cards_elsewhere(markdown: str) -> str:
return markdown
def decorate_markdown_pages(docs: Path) -> dict[str, str]:
def decorate_markdown_pages(docs: Path, pages: PageRegistry | None = None) -> dict[str, str]:
"""Add per-page descriptions and machine-readable structured data.
Under Starlight each page is written in its final form (front matter,
site addresses, pinned heading ids) and the dates a page states are
returned by address, for the sitemap.
returned by address, for the sitemap. ``pages`` is what the build
recorded about its pages.
"""
pages = pages or PageRegistry()
lastmod: dict[str, str] = {}
terms = sitestarlight.glossary_terms(REPO_ROOT / WIKI_SRC_DIR / "glossary.md")
# The console words of every system page, decorated or not: a console
@@ -170,8 +173,8 @@ def decorate_markdown_pages(docs: Path) -> dict[str, str]:
level = authored.get("level") or page_level(relative)
title = page_title(markdown, relative)
browser_title = page_browser_title(relative, title)
description = str(authored.get("description") or page_description(markdown, relative, title))
browser_title = page_browser_title(relative, title, pages)
description = str(authored.get("description") or page_description(markdown, relative, title, pages))
if relative.name == "index.md":
page_path = "" if len(relative.parts) == 1 else "/".join(relative.parts[:-1]) + "/"
else:
@@ -193,7 +196,7 @@ def decorate_markdown_pages(docs: Path) -> dict[str, str]:
"name": SITE_NAME,
"url": SITE_URL,
},
**PAGE_DATA.get(relative.as_posix(), {}),
**pages.page_data.get(relative.as_posix(), {}),
}
if schema_type == "WebSite":
# The home page is the site: named as the site, part of nothing.
@@ -202,7 +205,7 @@ def decorate_markdown_pages(docs: Path) -> dict[str, str]:
target, text = sitestarlight.render_page(
relative.as_posix(), markdown, sitestarlight.PageMeta(
level=level,
weight=search_weight(relative, level),
weight=search_weight(relative, level, pages.search_demoted),
browser_title=browser_title,
description=description, structured=structured, terms=terms,
search=authored.get("search") != "exclude",
+27 -38
View File
@@ -11,6 +11,7 @@ from pathlib import Path
from core.text import series
from sitegen import measurements as sitemeasurements
from sitegen.config import SITE_NAME
from sitegen.pageregistry import PageRegistry
def page_title(markdown: str, path: Path) -> str:
@@ -21,8 +22,10 @@ def page_title(markdown: str, path: Path) -> str:
return path.stem.replace("-", " ").title()
def page_browser_title(relative: Path, title: str) -> str:
"""Return a concise, unique browser/search title for a generated page."""
def page_browser_title(relative: Path, title: str, pages: PageRegistry | None = None) -> str:
"""Return a concise, unique browser/search title for a generated page.
``pages`` is what the build recorded about its pages."""
pages = pages or PageRegistry()
key = relative.as_posix()
index_titles = {
# Material appends " - RetroBIOS": the home title says what the site
@@ -38,7 +41,7 @@ def page_browser_title(relative: Path, title: str) -> str:
return index_titles[key]
# A console page is filed with the parts of its manufacturer's page, and
# titled "Sega: Dreamcast". A part names its range of files.
part = key in PART_PAGES and (
part = key in pages.part_pages and (
not key.startswith("systems/") or ": " not in title
or re.search(r", part \d+ of \d+$", title))
if part:
@@ -46,12 +49,13 @@ def page_browser_title(relative: Path, title: str) -> str:
# The words a web search for a console or an emulator types: "dreamcast
# bios", "duckstation bios". The h1 and the sidebar keep the name.
if key.startswith("emulators/"):
has_files = PAGE_DATA.get(key, {}).get("hasPart") and key not in NOTHING_TO_FETCH
has_files = pages.page_data.get(key, {}).get("hasPart") and key not in pages.nothing_to_fetch
# Lexaloffle, QEMU and ScummVM name a system page too.
own = " emulator" if f"systems/{relative.name}" in PAGE_DATA else ""
return f"{title}{own} {TITLE_NOUNS.get(key, BIOS_FILES)}" if has_files else f"{title} emulator"
own = " emulator" if f"systems/{relative.name}" in pages.page_data else ""
return (f"{title}{own} {pages.title_nouns.get(key, BIOS_FILES)}" if has_files
else f"{title} emulator")
if key.startswith("systems/"):
noun = TITLE_NOUNS.get(key, BIOS_FILES)
noun = pages.title_nouns.get(key, BIOS_FILES)
maker, _, console = title.partition(": ")
return f"{console} {noun} ({maker})" if console else f"{title} {noun}"
return title
@@ -118,7 +122,9 @@ def _shorten(plain: str, limit: int = 157) -> str:
return cut.rstrip(" ,;:-(.") + "..."
def page_description(markdown: str, relative: Path, title: str) -> str:
def page_description(markdown: str, relative: Path, title: str,
pages: PageRegistry | None = None) -> str:
pages = pages or PageRegistry()
key = relative.as_posix()
specific = {
"index.md": "The BIOS files emulators need, for RetroArch, Batocera, EmuDeck and more: the folder they go in, one command that installs and checks them, and packs to download.",
@@ -137,16 +143,16 @@ def page_description(markdown: str, relative: Path, title: str) -> str:
return specific[key]
# What a search engine shows is the page's own first sentence: 707 pages
# shared five templates of level 3 words ("source-pinned", "provenance").
browser = page_browser_title(relative, title)
browser = page_browser_title(relative, title, pages)
held = re.search(r"\bThis part holds (.+?)\.(?: |$)", markdown, re.M)
if key in PART_PAGES and held:
if key in pages.part_pages and held:
return _shorten(f"{browser}. This part holds {_plain_markdown(held[1])}.", 155)
lead = _lead(markdown)
if key in PART_PAGES and re.search(r"\bpart \d+ of \d+", title):
if key in pages.part_pages and re.search(r"\bpart \d+ of \d+", title):
# The parts of one list open on the same sentence.
first = _first_paragraph(lead) or _first_paragraph(markdown)
return _shorten(f"{title}. {first}", 155)
described = _section_description(markdown, relative, title, browser, lead)
described = _section_description(markdown, relative, title, browser, lead, pages)
if described is not None:
return described
first = _first_paragraph(lead, minimum=35)
@@ -163,14 +169,14 @@ def page_description(markdown: str, relative: Path, title: str) -> str:
def _section_description(markdown: str, relative: Path, title: str, browser: str,
lead: str) -> str | None:
lead: str, pages: PageRegistry) -> str | None:
"""The description of a system, emulator or platform page, or None for
a page of another section. A download page writes its own (getpages)."""
key = relative.as_posix()
if key.startswith("systems/") and relative.stem != "index":
return _system_description(markdown, browser)
if key.startswith("emulators/") and relative.stem != "index":
return _emulator_description(markdown, key, title, _first_paragraph(lead))
return _emulator_description(markdown, key, title, _first_paragraph(lead), pages)
if key.startswith("platforms/") and relative.stem != "index":
# The summary ends on a link to the platform's site, whose label
# alone was left: "A system for handhelds. ROCKNIX website."
@@ -186,7 +192,8 @@ def _lead(markdown: str) -> str:
return re.split(r"^(?:## |<details|<section)", markdown, maxsplit=1, flags=re.M)[0]
def _emulator_description(markdown: str, key: str, title: str, intro: str) -> str:
def _emulator_description(markdown: str, key: str, title: str, intro: str,
pages: PageRegistry) -> str:
"""An emulator page by its intro sentence ("DuckStation emulates Sony
PlayStation. It picks the BIOS for the game's region: ..."), or by
its profile table when the profile names no system."""
@@ -208,10 +215,10 @@ def _emulator_description(markdown: str, key: str, title: str, intro: str) -> st
elif title not in intro:
# "It reads 1 file": the profile names no system to open on.
intro = f"{title}: {intro[:1].lower()}{intro[1:]}"
if key in NOTHING_TO_FETCH:
if key in pages.nothing_to_fetch:
return _shorten(f"{intro} Every file it reads comes with the app.", 155)
if PAGE_DATA.get(key, {}).get("hasPart"):
return _shorten(_files_snippet(markdown, key, title, intro), 155)
if pages.page_data.get(key, {}).get("hasPart"):
return _shorten(_files_snippet(markdown, title, intro, pages.emulator_snippets.get(key)), 155)
# An alias page sends the reader to the core whose files it shares.
if "uses the same firmware as" in intro:
return _shorten(intro, 155)
@@ -221,7 +228,8 @@ def _emulator_description(markdown: str, key: str, title: str, intro: str) -> st
return _shorten(f"{intro} {needs}", 155)
def _files_snippet(markdown: str, key: str, title: str, intro: str) -> str:
def _files_snippet(markdown: str, title: str, intro: str,
snippet: tuple[str, list[str], int, str] | None) -> str:
"""The snippet of an emulator page with files to get.
A search for "gba_bios.bin" or "scph5500.bin" landed on a page described
@@ -236,7 +244,6 @@ def _files_snippet(markdown: str, key: str, title: str, intro: str) -> str:
head = f"{intro.split(' any region.')[0]} any region."
forms = [f"{head} {step} Any file name works.", f"{head} {step}"]
return next((form for form in forms if len(form) <= 155), intro)
snippet = EMULATOR_SNIPPETS.get(key)
if not snippet or not snippet[1] or "It reads " not in intro:
return intro
system, names, required, noun = snippet
@@ -315,21 +322,3 @@ def _system_description(markdown: str, browser: str) -> str:
"emulators that read them.", 155)
return _shorten(f"{browser}, one card per file with its hashes and the emulators "
"that read it.", 155)
# Structured data a page generator knows beyond its text, by page path
# relative to docs/: read by decorate_markdown_pages.
PAGE_DATA: dict[str, dict] = {}
# Emulator pages whose every file comes with the app: no "BIOS files" in
# their title, and their description says so (DaedalusX64, ZEsarUX).
NOTHING_TO_FETCH: set[str] = set()
# The first system, the file names, the count of required names and the
# word for them ("BIOS" or "files") of each emulator page, for its snippet.
EMULATOR_SNIPPETS: dict[str, tuple[str, list[str], int, str]] = {}
# The noun of the title of an emulator or system page, by page path
# relative to docs/ (title_noun): "BIOS files" when absent.
TITLE_NOUNS: dict[str, str] = {}
# Pages that hold part of a page too long for one (a console of a split
# manufacturer, a run of an emulator's cards), by path relative to docs/:
# their H1 already says what they are.
PART_PAGES: set[str] = set()
+23 -13
View File
@@ -6,7 +6,8 @@ import html
import os
import re
import urllib.parse
from collections.abc import Callable, Iterable
from collections.abc import Callable, Iterable, Mapping
import dataclasses
from dataclasses import dataclass
from pathlib import Path
@@ -499,14 +500,23 @@ def _card_reading_details(f: dict, profile: dict) -> list[str]:
return details
@dataclass(frozen=True)
class CardSources:
"""What a card reads besides its profile: who reads each collected file,
and each data directory's members by ref."""
consumers: FileConsumers
data_members: Mapping[str, dict[str, dict]] = dataclasses.field(default_factory=dict)
def _card_copy_line(
f: dict, consumers: FileConsumers, held: str, sha1: str, in_repo: bool, details: list[str],
f: dict, sources: CardSources, held: str, sha1: str, in_repo: bool, details: list[str],
) -> list[str]:
"""Which collection copy answers the entry. `details` are the lines said
before, read for copies already named."""
parts = held.split("/")
if len(parts) >= 3 and parts[0] == "bios" and f.get("archive"):
return [_held_copy_line((held, f["name"]), consumers)]
return [_held_copy_line((held, f["name"]), sources)]
if len(parts) >= 3 and parts[0] == "bios":
# Which copy answers this entry, linked to its collection card
# (provenance, every hash, download): an entry declaring no hash
@@ -519,25 +529,26 @@ def _card_copy_line(
if in_repo and not any(d.startswith("Collection copies:") for d in details):
copy = held_copy(f)
if copy:
return [_held_copy_line(copy, consumers)]
return [_held_copy_line(copy, sources)]
return []
def _card_copy_details(
f: dict, profile: dict, consumers: FileConsumers | None, owner: str, in_repo: bool,
f: dict, profile: dict, sources: CardSources | None, owner: str, in_repo: bool,
details: list[str],
) -> list[str]:
"""The collection copy that answers the entry and the setups that list
it. `details` are the lines said before."""
if not consumers:
if not sources:
return []
consumers = sources.consumers
added = []
if f.get("type") == "directory":
added.extend(_directory_copies(f, consumers))
sha1 = consumers.sha1_of(
*entry_target(f, profile.get("files") or []), owner=owner)
held = consumers.path_of(sha1) if sha1 and in_repo else ""
added.extend(_card_copy_line(f, consumers, held, sha1, in_repo, details + added))
added.extend(_card_copy_line(f, sources, held, sha1, in_repo, details + added))
plat_links = platform_links(sha1, consumers) if sha1 else []
if plat_links and markup.starlight():
# Grouped by where the setups put the file, as the system card
@@ -603,7 +614,7 @@ def _card_heading(f: dict, profile: dict, in_repo: bool, anchor: str, layout: Ca
def render_emulator_file(
f: dict,
profile: dict,
consumers: FileConsumers | None,
sources: CardSources | None,
files: list,
_file_available: Callable[[dict], bool],
anchor: str = "",
@@ -631,7 +642,7 @@ def render_emulator_file(
details.extend(_card_size_details(f))
details.extend(_card_hash_details(f))
details.extend(_card_reading_details(f, profile))
details.extend(_card_copy_details(f, profile, consumers, owner, in_repo, details))
details.extend(_card_copy_details(f, profile, sources, owner, in_repo, details))
details.extend(_card_extra_details(f))
if markup.starlight():
@@ -789,9 +800,10 @@ def _emulator_card_folds(
return lines
def _held_copy_line(copy: tuple[str, str], consumers: FileConsumers) -> str:
def _held_copy_line(copy: tuple[str, str], sources: CardSources) -> str:
"""Where a copy the database does not index sits: a ZIP member under
bios/, or a file or tree of a data directory the packs fetch."""
consumers = sources.consumers
path, member = copy
parts = path.rstrip("/").split("/")
if member:
@@ -806,7 +818,7 @@ def _held_copy_line(copy: tuple[str, str], consumers: FileConsumers) -> str:
if path.endswith("/"):
where = code_span(inside + "/") if inside else "the tree"
return f"Collection copy: {where} in the {code_span(ref)} data directory"
info = (DATA_MEMBERS.get(ref) or {}).get(inside) or {}
info = (sources.data_members.get(ref) or {}).get(inside) or {}
shown = code_span(inside)
if info.get("sha1"):
shown = (f'<a href="../../files/?sha1={info["sha1"]}">'
@@ -1058,8 +1070,6 @@ def render_metadata_rows(profile: dict) -> list[str]:
return lines
# Data directory members and revisions, read once per build.
DATA_MEMBERS: dict[str, dict[str, dict]] = {}
def any_name_bios(profile: dict) -> dict | None:
+30 -30
View File
@@ -21,7 +21,7 @@ from sitegen.decorate import DEMOTED_WEIGHT, SEARCH_WEIGHT
from core.text import series
from sitegen.emulatorcards import (
CardLayout,
DATA_MEMBERS,
CardSources,
build_rows,
entry_label,
file_badges,
@@ -46,6 +46,7 @@ from sitegen.install import (
standalone_place,
)
from sitegen.lookup import data_directory_origin, data_tree_pages
from sitegen.pageregistry import PageRegistry
from sitegen.render import (
admonition_body,
card_anchor,
@@ -222,15 +223,6 @@ def _emulator_held_line(files: list[dict], available: Callable[[dict], bool]) ->
return [f"<p><small>In this collection: {series(held)}.</small></p>", ""]
DATA_REVISIONS: dict[str, dict] = {}
# Emulator -> the platforms that run it, as resolve_platform_cores answers.
EMULATOR_SETUPS: dict[str, list[str]] = {}
# The measurement index items of each emulator, for the proof lines of its page.
MEASUREMENT_ITEMS: dict[str, list[dict]] = {}
# The emulator pages that list each data directory, by ref.
DATA_READERS: dict[str, list[tuple[str, str]]] = {}
def _data_member_table(members: dict[str, dict], names: list[str], anchors: set[str]) -> list[str]:
"""A data directory's files with their size and sha1, each sha1 an
anchor the first time the page lists it (``anchors``, the page's ids)."""
@@ -248,19 +240,19 @@ def _data_member_table(members: dict[str, dict], names: list[str], anchors: set[
def _data_tree_page(ref: str, entry: dict, pages: list[tuple[str, list[str]]],
index: int) -> str:
index: int, registry: PageRegistry) -> str:
"""One page of a large data directory's file list."""
stem, names = pages[index]
members = DATA_MEMBERS.get(ref) or {}
members = registry.data_members.get(ref) or {}
part = f" (part {index + 1} of {len(pages)})" if len(pages) > 1 else ""
read_by = series([f"[{escape_tags(display)}]({key}.md#data-directories)"
for key, display in DATA_READERS.get(ref, [])])
for key, display in registry.data_readers.get(ref, [])])
# A file list out of the search: "dolphin" found three parts of the
# dolphin-sys tree, on their title, before the Dolphin page.
front: dict = {"level": "reference", "search": "exclude"}
# The reader the tree is named after (dolphin for dolphin-sys), else
# the first by name.
readers = DATA_READERS.get(ref) or []
readers = registry.data_readers.get(ref) or []
owner = max(readers, default=None,
key=lambda reader: len(reader[0]) if ref.startswith(f"{reader[0]}-") else 0)
if owner:
@@ -506,10 +498,11 @@ def generate_emulator_page(
data_names: SupplementalIndex | None = None,
data_registry: dict | None = None,
data_dirs: list[dict] | None = None,
registry: PageRegistry | None = None,
) -> str:
"""One emulator's page. ``data_dirs`` defaults to the profile's own."""
return emulator_pages(
name, profile, db, consumers, data_names, data_registry, data_dirs)[name]
name, profile, db, consumers, data_names, data_registry, data_dirs, registry)[name]
def _collection_card_href(entry: dict, consumers: FileConsumers | None, owner: str) -> str:
@@ -723,8 +716,9 @@ def _source_rows(profile: dict) -> list[str]:
return rows
def _emulator_meta_rows(name: str, profile: dict) -> list[str]:
"""The rows of the "About this profile" card, after its header."""
def _emulator_meta_rows(name: str, profile: dict, setups: list[str] | None) -> list[str]:
"""The rows of the "About this profile" card, after its header.
``setups`` are the platforms that run the emulator."""
rows = [f"| Type | {profile.get('type', 'unknown')} |"]
classification = profile.get("core_classification", "")
if classification:
@@ -736,7 +730,6 @@ def _emulator_meta_rows(name: str, profile: dict) -> list[str]:
if revision:
rows.append(f"| Revision | {revision} |")
rows.extend(build_rows(profile))
setups = EMULATOR_SETUPS.get(name)
if setups:
# The file cards name the setups whose own list holds a file: the
# ones that run the emulator and pack its files were said nowhere.
@@ -776,6 +769,7 @@ class _EmulatorSources:
db: dict
consumers: FileConsumers | None
data_names: SupplementalIndex | None
data_members: dict[str, dict[str, dict]]
def _emulator_files_section(
@@ -784,7 +778,8 @@ def _emulator_files_section(
"""The Files section, and the pages its cards went to."""
files = profile.get("files", [])
systems = profile.get("systems", [])
consumers = sources.consumers
cards_from = (CardSources(sources.consumers, sources.data_members)
if sources.consumers else None)
part_pages: dict[str, str] = {}
lines: list[str] = []
_file_available = availability_check(sources.db, sources.data_names, name)
@@ -799,7 +794,7 @@ def _emulator_files_section(
data_href = f"{name}.md#data-folder" if parts else "#data-folder"
table_form = markup.starlight() and (bool(parts) or len(files) >= EMULATOR_TABLE_MIN)
cards = [
render_emulator_file(f, profile, consumers, files, _file_available, anchor, name,
render_emulator_file(f, profile, cards_from, files, _file_available, anchor, name,
CardLayout(alias, data_href, badges_apart=table_form))
for f, anchor, alias in zip(files, anchors, aliases)
]
@@ -826,6 +821,7 @@ def _emulator_files_section(
def _data_directory_lines(
dd: dict, profile: dict, data_registry: dict | None, member_anchors: set[str],
registry: PageRegistry,
) -> tuple[list[str], dict[str, str]]:
"""One data directory: what it holds, where it comes from, which build
reads it, and the pages its member list went to."""
@@ -841,14 +837,14 @@ def _data_directory_lines(
line += f": {entry['description']}"
lines.append(line)
lines.extend(f" - {line}" for line in data_directory_origin(
entry, DATA_REVISIONS.get(ref) or {}))
entry, registry.data_revisions.get(ref) or {}))
if dd.get("mode"):
lines.append(f" - Read by the {dd['mode']} build only")
if dd.get("bundled"):
lines.append(" - Installed with the emulator, so packs leave it out")
if dd.get("source_ref"):
lines.append(f" - Source: {source_ref_markdown(profile, dd['source_ref'])}")
members = DATA_MEMBERS.get(ref) or {}
members = registry.data_members.get(ref) or {}
tree_pages = data_tree_pages(ref, members)
if tree_pages:
where = (f"[a page of their own]({tree_pages[0][0]}.md)" if len(tree_pages) == 1
@@ -856,7 +852,7 @@ def _data_directory_lines(
f"[part {i}]({stem}.md)" for i, (stem, _names) in enumerate(tree_pages, 1)))
lines.append(f" - {count_text(len(members), 'file')}, listed on {where}")
for index, (stem, _names) in enumerate(tree_pages):
part_pages[stem] = _data_tree_page(ref, entry, tree_pages, index)
part_pages[stem] = _data_tree_page(ref, entry, tree_pages, index, registry)
elif members:
table = _data_member_table(members, sorted(members), member_anchors)
lines.append("")
@@ -867,7 +863,7 @@ def _data_directory_lines(
def _data_directories_section(
profile: dict, data_dirs: list[dict], data_registry: dict | None,
profile: dict, data_dirs: list[dict], data_registry: dict | None, registry: PageRegistry,
) -> tuple[list[str], dict[str, str]]:
"""The Data directories section, and the pages its member lists went to."""
# The member tables are a file list with hashes: out of the search,
@@ -879,7 +875,7 @@ def _data_directories_section(
# it and the code that does: these trees put thousands of files in
# the packs, and the page said only `dolphin-sys` > `Sys`.
for dd in data_dirs:
lines, pages = _data_directory_lines(dd, profile, data_registry, member_anchors)
lines, pages = _data_directory_lines(dd, profile, data_registry, member_anchors, registry)
trees.extend(lines)
part_pages.update(pages)
trees.append("")
@@ -895,9 +891,12 @@ def emulator_pages(
data_names: SupplementalIndex | None = None,
data_registry: dict | None = None,
data_dirs: list[dict] | None = None,
registry: PageRegistry | None = None,
) -> dict[str, str]:
"""An emulator's page by stem under emulators/, and the pages its cards
went to when there are more than EMULATOR_CARDS_PER_PAGE."""
went to when there are more than EMULATOR_CARDS_PER_PAGE. ``registry``
is what the build recorded about its pages."""
registry = registry or PageRegistry()
if profile.get("type") == "alias":
return {name: _alias_page(name, profile)}
@@ -934,7 +933,7 @@ def emulator_pages(
"",
"| Detail | Value |",
"|---|---|",
*_emulator_meta_rows(name, profile),
*_emulator_meta_rows(name, profile, registry.emulator_setups.get(name)),
"",
"</div>",
"",
@@ -959,18 +958,19 @@ def emulator_pages(
lines.extend(markup.aside("info", "Why no files", [escape_tags(str(exclusion))])[:-1])
else:
section, pages = _emulator_files_section(
name, emu_name, profile, _EmulatorSources(db, consumers, data_names))
name, emu_name, profile,
_EmulatorSources(db, consumers, data_names, registry.data_members))
lines.extend(section)
part_pages.update(pages)
lines.extend(sitemeasurements.proof_section(MEASUREMENT_ITEMS.get(name, [])))
lines.extend(sitemeasurements.proof_section(registry.measurement_items.get(name, [])))
blocks = render_structured_blocks(profile)
if blocks:
lines.extend(["## Profile data", "", *blocks])
if data_dirs:
section, pages = _data_directories_section(profile, data_dirs, data_registry)
section, pages = _data_directories_section(profile, data_dirs, data_registry, registry)
lines.extend(section)
part_pages.update(pages)
+11 -6
View File
@@ -15,7 +15,6 @@ from sitegen import handheld as sitehandheld, markup
from sitegen.config import RELEASE_URL, REPO_URL
from core.paths import REPO_ROOT
from core.sizes import size_text
from sitegen.descriptions import PAGE_DATA
from sitegen.guidepage import (
NO_ZIP_FAQ,
folder_words,
@@ -85,6 +84,17 @@ def _pack_lines(platform_name: str, display: str, record: dict, pack: dict) -> l
]
def get_page_data(platform_name: str) -> dict:
"""The structured data of get/<platform>/: the page changes with the
release it lists, so its tag is its date, the one the sitemap gives
(vYYYY.MM.DD). Empty when no release publishes the platform's pack."""
record = releaserecord.load_advertised()
tag_date = re.fullmatch(r"v(\d{4})\.(\d{2})\.(\d{2})", str(record.get("tag", "")))
if has_release_pack(platform_name) and releaserecord.pack_for(platform_name, record) and tag_date:
return {"dateModified": "-".join(tag_date.groups())}
return {}
def generate_get_page(platform_name: str) -> str:
"""get/<platform>/: the address a link outside the site can keep.
@@ -99,11 +109,6 @@ def generate_get_page(platform_name: str) -> str:
pack = releaserecord.pack_for(platform_name, record)
released = has_release_pack(platform_name)
title = get_page_title(platform_name, display)
# The page changes with the release it lists: its tag is its date, the
# one the sitemap gives (vYYYY.MM.DD).
tag_date = re.fullmatch(r"v(\d{4})\.(\d{2})\.(\d{2})", str(record.get("tag", "")))
if released and pack and tag_date:
PAGE_DATA[f"{releaserecord.GET_DIR}/{platform_name}.md"] = {"dateModified": "-".join(tag_date.groups())}
if released and pack and pack.get("assets"):
description = (f"The BIOS pack for {display}: {size_text(pack['download_size'])} to "
"download. The address stays the same and always gives the latest ZIP.")
+39
View File
@@ -0,0 +1,39 @@
"""What one site build records about its pages, for the renderers and the decorator that read it."""
from __future__ import annotations
from dataclasses import dataclass, field
@dataclass
class PageRegistry:
"""The maps a build fills as it writes pages, read by later pages and by
the decorator. Keys are page paths relative to docs/ unless said."""
# Structured data a page generator knows beyond its text.
page_data: dict[str, dict] = field(default_factory=dict)
# Emulator pages whose every file comes with the app: no "BIOS files" in
# their title, and their description says so (DaedalusX64, ZEsarUX).
nothing_to_fetch: set[str] = field(default_factory=set)
# The first system, the file names, the count of required names and the
# word for them ("BIOS" or "files") of each emulator page, for its snippet.
emulator_snippets: dict[str, tuple[str, list[str], int, str]] = field(default_factory=dict)
# The noun of the title of an emulator or system page (title_noun):
# "BIOS files" when absent.
title_nouns: dict[str, str] = field(default_factory=dict)
# Pages that hold part of a page too long for one (a console of a split
# manufacturer, a run of an emulator's cards): their H1 already says
# what they are.
part_pages: set[str] = field(default_factory=set)
# Pages that answer a name after the page that owns it.
search_demoted: set[str] = field(default_factory=set)
# Data directory members by ref, then by path inside the tree.
data_members: dict[str, dict[str, dict]] = field(default_factory=dict)
# Data directory revisions by ref.
data_revisions: dict[str, dict] = field(default_factory=dict)
# The emulator pages that list each data directory, by ref.
data_readers: dict[str, list[tuple[str, str]]] = field(default_factory=dict)
# Emulator -> the platforms that run it, as resolve_platform_cores answers.
emulator_setups: dict[str, list[str]] = field(default_factory=dict)
# The measurement index items of each emulator, for the proof lines of its page.
measurement_items: dict[str, list[dict]] = field(default_factory=dict)
+9 -8
View File
@@ -13,7 +13,8 @@ from model.systemnames import system_name
from sitegen import starlight as sitestarlight
from sitegen.cards import emulator_file_anchors
from sitegen.config import REPO_URL, SITE_NAME, SITE_URL
from sitegen.descriptions import EMULATOR_SNIPPETS, NOTHING_TO_FETCH, PAGE_DATA, TITLE_NOUNS, title_noun
from sitegen.descriptions import title_noun
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
@@ -294,10 +295,10 @@ def release_versions(profile: dict) -> dict[str, str]:
if re.search(r"[0-9]", value) and not names_a_commit(value)}
def record_emulator_page(name: str, profile: dict) -> None:
"""What the title and the description of an emulator page read."""
def record_emulator_page(name: str, profile: dict, pages: PageRegistry) -> None:
"""Record in ``pages`` what the title and the description of an emulator page read."""
key = f"emulators/{name}.md"
PAGE_DATA[key] = emulator_structured_data(profile)
pages.page_data[key] = emulator_structured_data(profile)
listed = [f for f in profile.get("files") or [] if isinstance(f, dict)]
fetched = [f for f in listed if f.get("name") and not comes_with_app(f)]
systems = profile.get("systems") or []
@@ -317,8 +318,8 @@ def record_emulator_page(name: str, profile: dict) -> None:
base = Path(str(f["name"])).name
names.setdefault(base.casefold(), base)
firmware = [f for f in fetched if f.get("category", "bios") in ("bios", "bios_zip")]
TITLE_NOUNS[key] = title_noun(str(f["name"]) for f in firmware)
EMULATOR_SNIPPETS[key] = (
pages.title_nouns[key] = title_noun(str(f["name"]) for f in firmware)
pages.emulator_snippets[key] = (
# One console names an emulator of five systems, not BizHawk of 40.
system_name(first) if 0 < len(systems) <= 5 else "",
list(names.values()),
@@ -326,9 +327,9 @@ def record_emulator_page(name: str, profile: dict) -> None:
snippet_noun(names.values(), len(firmware), len(fetched)),
)
if listed and all(comes_with_app(f) for f in listed):
NOTHING_TO_FETCH.add(key)
pages.nothing_to_fetch.add(key)
else:
NOTHING_TO_FETCH.discard(key)
pages.nothing_to_fetch.discard(key)
def emulator_structured_data(profile: dict) -> dict: