diff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.yml index 970031bee..4608d09e8 100644 --- a/.github/workflows/deploy-site.yml +++ b/.github/workflows/deploy-site.yml @@ -197,6 +197,7 @@ on: - "scripts/sitegen/releasepacks.py" - "scripts/sitegen/render.py" - "scripts/sitegen/runlinks.py" + - "scripts/sitegen/runsections.py" - "scripts/sitegen/sources.py" - "scripts/sitegen/starlight.py" - "scripts/sitegen/startwith.py" diff --git a/scripts/model/systemnames.py b/scripts/model/systemnames.py index 422480fae..4aa19f943 100644 --- a/scripts/model/systemnames.py +++ b/scripts/model/systemnames.py @@ -7,7 +7,6 @@ from collections.abc import Set as AbstractSet from dataclasses import dataclass from pathlib import Path -from model import siteinputs from model.collection import ( SECTION_LABELS, PROGRAM_TOPS, @@ -16,50 +15,35 @@ from model.collection import ( ) -# (manufacturer slug, console) -> the id of the console's heading. Two -# folders spelled alike (Sega's "Mega CD" and "Mega-CD") share a slug, and -# the second heading took "mega-cd_1" while every link said "mega-cd". -console_anchors: dict[tuple[str, str], str] = {} - - -# How many times set_console_sections installed sections: what a page -# derives from them (the arcade boards) is stale once it moves. -sections_generation = [0] - - -# Every (manufacturer, console) section the system pages carry. -section_pairs: set[tuple[str, str]] = set() -# Normalized id -> the console sections spelled that way. -_console_sections: dict[str, set[tuple[str, str]]] = {} -# A console section by the name its heading reads (Bandai WonderSwan). -sections_by_name: dict[str, set[tuple[str, str]]] = {} -# Emulator and engine names. A heading spelled like one (Game Engines > -# Solarus, ZC > ZC210) files that program's copies and names no system. -known_program_names: set[str] = set() - - @dataclass(frozen=True) class ConsoleSections: - """The console sections a collection files, by normalized id, and the - program names (casefolded) whose headings name no system.""" + """The console sections a collection files: every (manufacturer, + console) pair, by normalized id and by the name its heading reads, and + the program names (casefolded) whose headings name no system.""" index: Mapping[str, set[tuple[str, str]]] programs: AbstractSet[str] - - -# The sections the site installed (set_console_sections): the same objects, -# filled in place. -_installed = ConsoleSections(_console_sections, known_program_names) + pairs: AbstractSet[tuple[str, str]] + by_name: Mapping[str, set[tuple[str, str]]] def console_sections( sections: dict[str, dict] | set[tuple[str, str]], programs: Iterable[str] = (), ) -> ConsoleSections: - """The sections ``sections`` carries, as set_console_sections reads - them, without installing anything.""" + """The sections ``sections`` carries: a map of each manufacturer to its + consoles, as the system pages group them, or a set of (manufacturer, + console) pairs. ``programs`` are the emulator names, which never name a + system.""" + pairs = section_pairs_of(sections) + by_name: dict[str, set[tuple[str, str]]] = {} + for mfr, console in pairs: + for name in {heading_name(mfr, console).casefold(), console.casefold()}: + by_name.setdefault(name, set()).add((mfr, console)) return ConsoleSections( - console_index(section_pairs_of(sections)), + console_index(pairs), frozenset(name.casefold() for name in programs), + frozenset(pairs), + by_name, ) @@ -105,58 +89,6 @@ def section_pairs_of(sections: dict[str, dict] | set[tuple[str, str]]) -> set[tu return pairs -def set_console_sections( - sections: dict[str, dict] | set[tuple[str, str]], - programs: set[str] | frozenset[str] = frozenset(), -) -> None: - """Install the console sections the system pages carry. - - ``sections`` maps each manufacturer to its consoles, as the system pages - group them, or is a set of (manufacturer, console) pairs. ``programs`` - are the emulator names, which never name a system. - """ - pairs = section_pairs_of(sections) - from core.anchors import unique_anchor, toc_slug - - _console_sections.clear() - sections_by_name.clear() - console_anchors.clear() - section_pairs.clear() - section_pairs.update(pairs) - by_maker: dict[str, list[str]] = {} - for mfr, console in pairs: - by_maker.setdefault(mfr, []).append(console) - for name in {heading_name(mfr, console).casefold(), console.casefold()}: - sections_by_name.setdefault(name, set()).add((mfr, console)) - # In the order the page lists them, after the page title's own id. - for mfr, consoles in by_maker.items(): - used = {toc_slug(mfr)} - for console in sorted(consoles): - console_anchors[(manufacturer_slug(mfr), console)] = unique_anchor(toc_slug(console), used) - _console_sections.update(console_index(pairs)) - known_program_names.clear() - known_program_names.update(name.casefold() for name in programs) - _sections_installed[0] = True - sections_generation[0] += 1 - - -_sections_installed = [False] - - -def ensure_console_sections() -> None: - """Read the sections from the repository when no generator installed - them, so a page rendered on its own names systems as the site does.""" - if _sections_installed[0]: - return - from model.database import load_database - from model.profiles import load_emulator_profiles - - inputs = siteinputs.current() - db = load_database(str(inputs.db)) - profiles = load_emulator_profiles(str(inputs.emulators), skip_aliases=False) - set_console_sections(group_by_manufacturer(db), program_names(profiles)) - - def console_index(pairs: Iterable[tuple[str, str]]) -> dict[str, set[tuple[str, str]]]: """Normalized system name -> the console sections that spell it. @@ -192,13 +124,6 @@ def spelled_section( return next(iter(places)) if len(places) == 1 else None -def own_section(sys_id: str) -> tuple[str, str] | None: - """The console section that is this id's own among the sections the - site installed, or None (own_section_in).""" - ensure_console_sections() - return own_section_in(sys_id, _installed) - - def own_section_in(sys_id: str, sections: ConsoleSections) -> tuple[str, str] | None: """The console section of ``sections`` that is this id's own, or None. @@ -237,38 +162,33 @@ def heading_name(mfr: str, console: str) -> str: _NAMELESS_TOPS = frozenset({"Other"}) -def section_without_boards(sys_id: str) -> tuple[str, str] | None: - """The console section a system id leads to before arcade boards, as - (manufacturer slug, console): what the folders and the reviewed parents - give.""" - own = own_section(sys_id) +def section_without_boards_in( + sys_id: str, sections: ConsoleSections, +) -> tuple[str, str] | None: + """The console section a system id leads to among ``sections`` before + arcade boards, as (manufacturer slug, console): what the folders and the + reviewed parents give.""" + own = own_section_in(sys_id, sections) if own is not None: return manufacturer_slug(own[0]), own[1] parent = SYSTEM_PARENTS.get(sys_id) - if parent is not None and parent in section_pairs: + if parent is not None and parent in sections.pairs: return manufacturer_slug(parent[0]), parent[1] try: - name = system_name(sys_id) + name = system_name_in(sys_id, sections) except KeyError: return None - places = sections_by_name.get(name.casefold(), set()) + places = sections.by_name.get(name.casefold(), set()) if len(places) != 1: return None mfr, console = next(iter(places)) if mfr in _NAMELESS_TOPS or ( - mfr in PROGRAM_TOPS and console.casefold() in known_program_names + mfr in PROGRAM_TOPS and console.casefold() in sections.programs ): return None return manufacturer_slug(mfr), console -def system_name(sys_id: str) -> str: - """The display name of a system id, the only one a page prints, among - the sections the site installed (system_name_in).""" - ensure_console_sections() - return system_name_in(sys_id, _installed) - - def system_name_in(sys_id: str, sections: ConsoleSections) -> str: """The display name of a system id among ``sections``.""" sys_id = str(sys_id) diff --git a/scripts/sitegen/apiitems.py b/scripts/sitegen/apiitems.py index ffdbd9120..85809567e 100644 --- a/scripts/sitegen/apiitems.py +++ b/scripts/sitegen/apiitems.py @@ -7,7 +7,7 @@ from collections.abc import Callable from model.collection import group_by_manufacturer, manufacturer_slug from model.database import declared_records, sha1_at -from model.systemnames import system_name +from sitegen.runsections import system_name from model.profiles import is_emulator from sitegen.config import SITE_URL from core.hashing import declared_hash_lists diff --git a/scripts/sitegen/arcadeboards.py b/scripts/sitegen/arcadeboards.py index d29e3e365..ce88f73d4 100644 --- a/scripts/sitegen/arcadeboards.py +++ b/scripts/sitegen/arcadeboards.py @@ -7,13 +7,9 @@ from dataclasses import dataclass, field from core.memo import DerivedView from model import siteinputs -from model.systemnames import ( - SYSTEM_PARENTS, - ensure_console_sections, - section_pairs, - section_without_boards, - system_name, -) +from model.systemnames import SYSTEM_PARENTS +from sitegen import runsections +from sitegen.runsections import section_without_boards, system_name # A board is a system id that a profile entry with ``category: bios_zip`` # names, through its ``system:``/``systems:`` or the profile's single @@ -118,7 +114,7 @@ def _machine_section(sys_id: str) -> tuple[str, str] | None: of the folder holding it: an id with a section of its own keeps its archives where the collection files them.""" parent = SYSTEM_PARENTS.get(sys_id) - if parent is None or parent[0] == "Arcade" or parent not in section_pairs: + if parent is None or parent[0] == "Arcade" or parent not in runsections.current().sections.pairs: return None return parent @@ -182,7 +178,7 @@ class _Ballots: def elect_arcade_boards(profiles: dict[str, dict], db: dict) -> ArcadeBoards: """The board of each archive, elected from the profiles' ``bios_zip`` entries against the console sections installed.""" - ensure_console_sections() + runsections.current() files = db.get("files", {}) by_name = db.get("indexes", {}).get("by_name", {}) ballots = _Ballots() diff --git a/scripts/sitegen/build.py b/scripts/sitegen/build.py index ba9c106d1..74dbd0451 100644 --- a/scripts/sitegen/build.py +++ b/scripts/sitegen/build.py @@ -22,7 +22,8 @@ from model.dumpcatalog import load_provenance_snapshots from sitegen.guidedata import handheld_guide from model.profiles import is_emulator, lists_files, load_emulator_profiles from model.registry import list_registered_platforms, load_platform_registry -from model.systemnames import program_names, set_console_sections, system_name +from model.systemnames import program_names +from sitegen.runsections import system_name from packs.consumers import FileConsumers from packs.crossref import whole_tree_gaps from packs.supplemental import SupplementalIndex @@ -37,6 +38,7 @@ from sitegen import ( handheld as sitehandheld, measurements as sitemeasurements, runlinks, + runsections, starlight as sitestarlight, steps as sitesteps, wanted as sitewanted, @@ -649,6 +651,7 @@ def generate_site(args: argparse.Namespace) -> None: )) # Where this run puts systems, consoles and cards, nothing of a run before. runlinks.use(runlinks.LinkTables()) + runsections.reset() db = load_database(args.db) docs = Path(args.docs_dir) # Files the site serves as they are (data, downloads, images), in the @@ -676,7 +679,7 @@ def generate_site(args: argparse.Namespace) -> None: run.file_held = availability_check(db, run.suppl_names) # The plan names systems: the sections must be this run's data first. run.manufacturers = group_by_manufacturer(db) - set_console_sections(run.manufacturers, program_names(profiles)) + runsections.install(run.manufacturers, program_names(profiles)) # Which archive is which board's depends on the sections: elected once # they are this run's. use_arcade_boards(elect_arcade_boards(profiles, db)) diff --git a/scripts/sitegen/crossref.py b/scripts/sitegen/crossref.py index 5fcddf044..f81d68182 100644 --- a/scripts/sitegen/crossref.py +++ b/scripts/sitegen/crossref.py @@ -5,7 +5,7 @@ from __future__ import annotations import re import urllib.parse -from model.systemnames import system_name +from sitegen.runsections import system_name from model.profiles import is_emulator from resolve.cores import resolve_platform_cores from sitegen import markup diff --git a/scripts/sitegen/emulatorcards.py b/scripts/sitegen/emulatorcards.py index a168414f2..2321689de 100644 --- a/scripts/sitegen/emulatorcards.py +++ b/scripts/sitegen/emulatorcards.py @@ -13,7 +13,7 @@ from pathlib import Path from core.sizes import size_text from model.collection import manufacturer_slug -from model.systemnames import system_name +from sitegen.runsections import system_name from model.profiles import reads_own_files from packs.consumers import FileConsumers, entry_target, held_copy from resolve.cores import resolve_platform_cores diff --git a/scripts/sitegen/emulatorpage.py b/scripts/sitegen/emulatorpage.py index 092e1c8c5..aa3f4e149 100644 --- a/scripts/sitegen/emulatorpage.py +++ b/scripts/sitegen/emulatorpage.py @@ -10,7 +10,7 @@ from dataclasses import dataclass from core.hashing import parse_hash_list from core.sizes import size_text -from model.systemnames import system_name +from sitegen.runsections import system_name from model.profiles import is_emulator from packs.consumers import FileConsumers from packs.supplemental import SupplementalIndex diff --git a/scripts/sitegen/lookup.py b/scripts/sitegen/lookup.py index 050f18622..e8ba48ba3 100644 --- a/scripts/sitegen/lookup.py +++ b/scripts/sitegen/lookup.py @@ -14,7 +14,7 @@ from model import siteinputs from model.collection import manufacturer_slug from model.database import declared_records from model.registry import load_versions, versions_file_for -from model.systemnames import system_name +from sitegen.runsections import system_name from model.profiles import is_emulator from packs.consumers import FileConsumers from sitegen.cards import PROVENANCE_LABELS, emulator_card_anchor, emulator_file_anchors @@ -260,7 +260,7 @@ def _console_system_names(profiles: dict, coverages: dict) -> dict[tuple[str, st own section that folder is: a collection file is named after the console it is filed under. A folder no id owns, or that two names own, is left out. """ - from model.systemnames import own_section + from sitegen.runsections import own_section from sitegen.render import system_ids found: dict[tuple[str, str], set[str]] = {} diff --git a/scripts/sitegen/platformfiles.py b/scripts/sitegen/platformfiles.py index d19612521..382ca2a8d 100644 --- a/scripts/sitegen/platformfiles.py +++ b/scripts/sitegen/platformfiles.py @@ -12,7 +12,7 @@ from model import siteinputs from model.collection import profiles_in, profiles_on_disk from model.database import load_database, sha1_at from model.profiles import is_emulator, upstream_profile_index -from model.systemnames import system_name +from sitegen.runsections import system_name from sitegen import entries as siteentries, markup from sitegen.config import REPO_URL, date_line from core.sizes import size_text diff --git a/scripts/sitegen/platformpage.py b/scripts/sitegen/platformpage.py index ae33db6bb..09856ce34 100644 --- a/scripts/sitegen/platformpage.py +++ b/scripts/sitegen/platformpage.py @@ -6,7 +6,7 @@ import json import re from sitegen.guidedata import platform_guides -from model.systemnames import system_name +from sitegen.runsections import system_name from resolve.nativemode import check_label, reads_file_contents from sitegen import markup from sitegen.config import REPO_URL, date_line diff --git a/scripts/sitegen/render.py b/scripts/sitegen/render.py index 7e75396a0..a459b1a98 100644 --- a/scripts/sitegen/render.py +++ b/scripts/sitegen/render.py @@ -7,7 +7,7 @@ from collections.abc import Callable from core.text import count_text as count_text from model.collection import manufacturer_slug -from model.systemnames import console_anchors, system_name +from sitegen.runsections import installed, system_name WIKI_SRC_DIR = "wiki" # manually maintained wiki sources @@ -80,8 +80,9 @@ 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 + run = installed() key = (manufacturer_slug(manufacturer), console) - return console_anchors.get(key) or toc_slug(console) + return (run.anchors.get(key) if run else None) or toc_slug(console) def board_slug(sys_id: str) -> str: diff --git a/scripts/sitegen/runlinks.py b/scripts/sitegen/runlinks.py index 916128aa5..c8f53e82b 100644 --- a/scripts/sitegen/runlinks.py +++ b/scripts/sitegen/runlinks.py @@ -9,13 +9,9 @@ from dataclasses import dataclass, field 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 model.systemnames import SYSTEM_PARENTS +from sitegen import runsections +from sitegen.runsections import section_without_boards, system_name from sitegen import markup from sitegen.arcadeboards import ArcadeBoards, read_arcade_boards from sitegen.pageprep import ICON_DIR @@ -33,9 +29,9 @@ class LinkTables: 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 + holds a copy. ``arcade``: the boards elected, with the runsections generation they were elected under. ``aliases``: page_aliases() built from the rest, - with the sections_generation it read, dropped whenever a table it reads + with the runsections generation it read, dropped whenever a table it reads changes. """ @@ -220,20 +216,20 @@ 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() + generation = runsections.current().generation tables = current() - tables.arcade = (sections_generation[0], boards) + tables.arcade = (generation, boards) tables.aliases = None def _boards() -> ArcadeBoards: - ensure_console_sections() + generation = runsections.current().generation tables = current() held = tables.arcade - if held is not None and held[0] == sections_generation[0]: + if held is not None and held[0] == generation: return held[1] boards = read_arcade_boards() - tables.arcade = (sections_generation[0], boards) + tables.arcade = (generation, boards) return boards @@ -343,8 +339,8 @@ def page_aliases(rel: str) -> list[str]: tables = current() if not tables.system_pages: return [] - ensure_console_sections() - if tables.aliases is None or tables.aliases[0] != sections_generation[0]: + generation = runsections.current().generation + if tables.aliases is None or tables.aliases[0] != generation: by_page: dict[str, set[str]] = {} for sys_id in list(tables.system_pages): section = system_section(sys_id) @@ -353,6 +349,6 @@ def page_aliases(rel: str) -> list[str]: continue target = console_href(*section).partition("#")[0] by_page.setdefault(urllib.parse.unquote(target), set()).update(names) - tables.aliases = (sections_generation[0], { + tables.aliases = (generation, { page: sorted(names, key=str.casefold) for page, names in by_page.items()}) return list(tables.aliases[1].get(rel, [])) diff --git a/scripts/sitegen/runsections.py b/scripts/sitegen/runsections.py new file mode 100644 index 000000000..66b4eb4fc --- /dev/null +++ b/scripts/sitegen/runsections.py @@ -0,0 +1,111 @@ +"""The console sections one site run names systems from, and their heading ids.""" + +from __future__ import annotations + +from dataclasses import dataclass + +from core.anchors import toc_slug, unique_anchor +from model import siteinputs +from model.collection import group_by_manufacturer, manufacturer_slug +from model.systemnames import ( + ConsoleSections, + console_sections, + own_section_in, + program_names, + section_without_boards_in, + system_name_in, +) + + +@dataclass(frozen=True) +class RunSections: + """The sections a run installed, under the site inputs it read. + + ``anchors``: (manufacturer slug, console) -> the id of the console's + heading. Two folders spelled alike (Sega's "Mega CD" and "Mega-CD") + share a slug, and the second heading took "mega-cd_1" while every link + said "mega-cd". ``generation`` counts the installs: what a page derives + from the sections (the arcade boards) is stale once it moves. + """ + + sections: ConsoleSections + anchors: dict[tuple[str, str], str] + inputs: siteinputs.SiteInputs + generation: int + + +_current: list[RunSections | None] = [None] +_installs = [0] + + +def install( + sections: dict[str, dict] | set[tuple[str, str]], + programs: set[str] | frozenset[str] = frozenset(), +) -> RunSections: + """Install the console sections the system pages carry, under the + current site inputs, the previous ones forgotten. + + ``sections`` maps each manufacturer to its consoles, as the system pages + group them, or is a set of (manufacturer, console) pairs. ``programs`` + are the emulator names, which never name a system. + """ + carried = console_sections(sections, programs) + by_maker: dict[str, list[str]] = {} + for mfr, console in carried.pairs: + by_maker.setdefault(mfr, []).append(console) + anchors: dict[tuple[str, str], str] = {} + # In the order the page lists them, after the page title's own id. + for mfr, consoles in by_maker.items(): + used = {toc_slug(mfr)} + for console in sorted(consoles): + anchors[(manufacturer_slug(mfr), console)] = unique_anchor(toc_slug(console), used) + _installs[0] += 1 + run = RunSections(carried, anchors, siteinputs.current(), _installs[0]) + _current[0] = run + return run + + +def reset() -> None: + """Forget the installed sections: the next name is read from the inputs.""" + _current[0] = None + + +def installed() -> RunSections | None: + """The sections installed under the current site inputs, None when + none were, without reading anything.""" + run = _current[0] + return run if run is not None and run.inputs == siteinputs.current() else None + + +def current() -> RunSections: + """The installed sections, read from the site inputs when none were + installed under them, so a page rendered on its own names systems as + the site does.""" + run = installed() + if run is not None: + return run + inputs = siteinputs.current() + from model.database import load_database + from model.profiles import load_emulator_profiles + + db = load_database(str(inputs.db)) + profiles = load_emulator_profiles(str(inputs.emulators), skip_aliases=False) + return install(group_by_manufacturer(db), program_names(profiles)) + + +def system_name(sys_id: str) -> str: + """The display name of a system id, the only one a page prints + (model.systemnames.system_name_in).""" + return system_name_in(sys_id, current().sections) + + +def own_section(sys_id: str) -> tuple[str, str] | None: + """The console section that is this id's own, or None + (model.systemnames.own_section_in).""" + return own_section_in(sys_id, current().sections) + + +def section_without_boards(sys_id: str) -> tuple[str, str] | None: + """The console section a system id leads to before arcade boards + (model.systemnames.section_without_boards_in).""" + return section_without_boards_in(sys_id, current().sections) diff --git a/scripts/sitegen/startwith.py b/scripts/sitegen/startwith.py index 21129dcaf..3013a1cd4 100644 --- a/scripts/sitegen/startwith.py +++ b/scripts/sitegen/startwith.py @@ -300,7 +300,8 @@ def _start_groups( the Mega CD BIOS for its Genesis), and one under Other is a single emulator's, its shaders and fonts. A file the emulator ships with is no file to fetch.""" - from model.systemnames import heading_name, system_name + from model.systemnames import heading_name + from sitegen.runsections import system_name from model.collection import manufacturer_slug here = (manufacturer_slug(section[0]), section[1]) if section else None diff --git a/scripts/sitegen/structured.py b/scripts/sitegen/structured.py index d29e8affe..ce1773fb9 100644 --- a/scripts/sitegen/structured.py +++ b/scripts/sitegen/structured.py @@ -9,7 +9,7 @@ from pathlib import Path from model import siteinputs from model.collection import collection_paths -from model.systemnames import system_name +from sitegen.runsections 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 diff --git a/tests/test_install_selection.py b/tests/test_install_selection.py index 8c3211e78..ad1e4578a 100644 --- a/tests/test_install_selection.py +++ b/tests/test_install_selection.py @@ -1389,11 +1389,11 @@ class ThePlatformsOwnSystemNamesAreAccepted(unittest.TestCase): # from the repository's collection, read inside the name lookup. from unittest import mock - from model import systemnames + from model import siteinputs, systemnames from packs.scope import system_titles sections = systemnames.console_sections({("Acme", "Widget")}) - with mock.patch.object(systemnames, "ensure_console_sections", + with mock.patch.object(siteinputs, "current", side_effect=AssertionError("site inputs read")): self.assertEqual( system_titles(sections, [{"dest": "a.bin", "systems": ["acme-widget"]}]), diff --git a/tests/test_site_arcade_boards.py b/tests/test_site_arcade_boards.py index 93593d67f..438e0d600 100644 --- a/tests/test_site_arcade_boards.py +++ b/tests/test_site_arcade_boards.py @@ -23,7 +23,7 @@ from pathlib import Path from sitegen import arcadeboards from sitegen import render as siterender from sitegen import runlinks -from model import systemnames +from sitegen import runsections from core.anchors import toc_slug REPO_ROOT = Path(__file__).resolve().parents[1] @@ -70,7 +70,7 @@ STAYS_PLAIN = { def _reset() -> None: """Back to the repository's sections and boards, none written.""" runlinks.current().arcade = None - systemnames._sections_installed[0] = False + runsections.reset() runlinks.reset_console_pages() @@ -102,7 +102,7 @@ class Boards(unittest.TestCase): names = set(boards.values()) for sys_id, name in NAMED_BOARDS.items(): with self.subTest(sys_id=sys_id): - self.assertEqual(systemnames.system_name(sys_id), name) + self.assertEqual(runsections.system_name(sys_id), name) self.assertIn(name, names) def test_every_copy_names_its_board(self) -> None: @@ -227,7 +227,7 @@ class BoardRules(unittest.TestCase): def setUp(self) -> None: self._tmp = tempfile.TemporaryDirectory() self.root = Path(self._tmp.name) - systemnames.set_console_sections({("Arcade", "MAME"), ("SNK", "Neo Geo")}) + runsections.install({("Arcade", "MAME"), ("SNK", "Neo Geo")}) def tearDown(self) -> None: self._tmp.cleanup() diff --git a/tests/test_site_emulators.py b/tests/test_site_emulators.py index dd8ba89e2..2ceeabe6a 100644 --- a/tests/test_site_emulators.py +++ b/tests/test_site_emulators.py @@ -45,7 +45,7 @@ from sitegen import emulatorsindex from sitegen import install as sitegen_install from sitegen import lookup from sitegen import runlinks -from model import systemnames +from sitegen import runsections from sitegen import validate from resolve import layout from sitegen.pageregistry import PageRegistry @@ -228,7 +228,7 @@ class TheIndexNamesEmulatorsAndSystems(unittest.TestCase): self.assertNotIn("| Engine |", page) self.assertNotIn(" -- ", page) row = next(line for line in page.splitlines() if line.startswith("| [DuckStation]")) - self.assertIn(f"[{systemnames.system_name('sony-playstation')}]", row) + self.assertIn(f"[{runsections.system_name('sony-playstation')}]", row) self.assertIn("(../systems/sony.md#playstation)", row) self.assertNotIn("sony-playstation |", row) diff --git a/tests/test_site_exports.py b/tests/test_site_exports.py index 8a2d77dc3..094b7fb87 100644 --- a/tests/test_site_exports.py +++ b/tests/test_site_exports.py @@ -1259,11 +1259,10 @@ class TheOneLinerIsWhereUsersLand(unittest.TestCase): def test_a_system_is_offered_only_where_the_manifest_records_it(self): from sitegen import cards from sitegen import runlinks + from sitegen import runsections - from model import systemnames - - systemnames.set_console_sections({("Sony", "PlayStation")}) - self.addCleanup(systemnames._sections_installed.__setitem__, 0, False) + runsections.install({("Sony", "PlayStation")}) + self.addCleanup(runsections.reset) runlinks.reset_console_pages() self.addCleanup(runlinks.reset_console_pages) # "playstation" leads to the same section, but the manifest records diff --git a/tests/test_site_inputs.py b/tests/test_site_inputs.py index f3a20bf79..35c5393e3 100644 --- a/tests/test_site_inputs.py +++ b/tests/test_site_inputs.py @@ -39,6 +39,28 @@ class _Inputs(unittest.TestCase): self.addCleanup(siteinputs.use, siteinputs.SiteInputs()) +class SectionsFollowTheInputs(_Inputs): + """Sections installed under one collection named systems after another + once the inputs moved: the old ones answered until a test reset a + private flag.""" + + def test_new_inputs_drop_the_installed_sections(self) -> None: + from sitegen import runsections + + self.addCleanup(runsections.reset) + runsections.install({("Sony", "PlayStation")}) + self.assertEqual(runsections.system_name("sony-playstation"), "Sony PlayStation") + tmp = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, tmp) + (tmp / "emulators").mkdir() + (tmp / "database.json").write_text(json.dumps({"files": {}}), encoding="utf-8") + self.use(db=tmp / "database.json", emulators=tmp / "emulators") + self.assertIsNone(runsections.installed()) + with self.assertRaises(KeyError): + runsections.system_name("sony-playstation") + self.assertEqual(runsections.current().anchors, {}) + + class TheGivenDatabase(_Inputs): def setUp(self) -> None: tmp = Path(tempfile.mkdtemp()) @@ -215,7 +237,7 @@ class NoPageModuleReadsTheRepositoryInputs(unittest.TestCase): MODULES = (*script_paths("generate_site.py"), SCRIPTS / "sitegen" / "render.py", SCRIPTS / "sitegen" / "diagrams.py", SCRIPTS / "model" / "collection.py", - SCRIPTS / "model" / "systemnames.py") + SCRIPTS / "model" / "systemnames.py", SCRIPTS / "sitegen" / "runsections.py") INPUTS = {"database.json", "emulators", "platforms"} def test_no_literal_input_path(self) -> None: diff --git a/tests/test_site_reference.py b/tests/test_site_reference.py index b218db816..bd0edcb9a 100644 --- a/tests/test_site_reference.py +++ b/tests/test_site_reference.py @@ -71,7 +71,7 @@ from sitegen import publish from sitegen import render from sitegen import runlinks from sitegen import wanted as sitewanted -from model import systemnames +from sitegen import runsections from model.registry import list_registered_platforms, list_release_pack_platforms from model.profiles import load_emulator_profiles from model.platforms import load_platform_config @@ -316,7 +316,7 @@ class PlatformReferenceInWords(unittest.TestCase): def test_systems_by_name_with_the_id_in_small_text(self): systems = {"sony-playstation": {"files": [{"name": "f.bin"}]}} page = self._page("md5", "md5", systems) - name = systemnames.system_name("sony-playstation") + name = runsections.system_name("sony-playstation") self.assertIn(f"| [{name}](#sony-playstation) sony-playstation |", page) heading = next(line for line in page.splitlines() if line.startswith("### ") and "sony-playstation" in line) @@ -837,7 +837,7 @@ class LookupUrlsResolve(unittest.TestCase): def test_each_record_names_its_system_as_the_pages_do(self): """Find a file opens on "a BIOS file for Sony PlayStation": the name comes from system_name, never built in the browser.""" - from model.systemnames import system_name + from sitegen.runsections import system_name db = {"files": {"ab" * 20: {"path": "bios/Sony/PlayStation/scph5501.bin", "name": "scph5501.bin", "md5": "490f666e1afb15b7362b406ed1cea246"}}} diff --git a/tests/test_site_system_links.py b/tests/test_site_system_links.py index bfbf7857a..af47678fc 100644 --- a/tests/test_site_system_links.py +++ b/tests/test_site_system_links.py @@ -25,6 +25,7 @@ from sitegen import systempages from sitegen import systemsindex from sitegen import whichpack from sitegen import runlinks +from sitegen import runsections from model import systemnames REPO_ROOT = Path(__file__).resolve().parents[1] @@ -279,7 +280,7 @@ class PagesFollowOwnSection(unittest.TestCase): db = load_database(str(REPO_ROOT / "database.json")) profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"), skip_aliases=False) manufacturers = collection.group_by_manufacturer(db) - systemnames.set_console_sections(manufacturers, systemnames.program_names(profiles)) + runsections.install(manufacturers, systemnames.program_names(profiles)) platforms = REPO_ROOT / "platforms" coverages = { name: {"config": load_platform_config(name, str(platforms))} @@ -293,7 +294,7 @@ class PagesFollowOwnSection(unittest.TestCase): def test_every_own_section_is_the_page(self): for sys_id in self.ids: - own = systemnames.own_section(sys_id) + own = runsections.own_section(sys_id) if own is None: continue with self.subTest(system=sys_id): @@ -304,7 +305,7 @@ class PagesFollowOwnSection(unittest.TestCase): self.assertEqual(self.pages.get("atari-lynx"), ("atari", "Lynx")) self.assertEqual(self.pages.get("atom"), ("acorn", "Atom")) # A program's folder places its page, though it is no system's own. - self.assertIsNone(systemnames.own_section("scummvm")) + self.assertIsNone(runsections.own_section("scummvm")) self.assertEqual(self.pages.get("scummvm"), ("scummvm", "ScummVM")) self.assertEqual(self.pages.get("solarus"), ("game-engines", "Solarus")) @@ -331,7 +332,7 @@ class EverySystemLinkLandsOnItsSection(unittest.TestCase): db = load_database(str(REPO_ROOT / "database.json")) profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"), skip_aliases=False) - systemnames.set_console_sections(collection.group_by_manufacturer(db), systemnames.program_names(profiles)) + runsections.install(collection.group_by_manufacturer(db), systemnames.program_names(profiles)) platforms = REPO_ROOT / "platforms" ids = {str(sid) for profile in profiles.values() for sid in profile.get("systems") or []} for name in list_registered_platforms(str(platforms)): diff --git a/tests/test_site_system_names.py b/tests/test_site_system_names.py index 3a463c04c..7511e4d08 100644 --- a/tests/test_site_system_names.py +++ b/tests/test_site_system_names.py @@ -17,6 +17,7 @@ import unittest from pathlib import Path from model import systemnames +from sitegen import runsections from model.registry import list_registered_platforms from model.profiles import load_emulator_profiles from model.platforms import load_platform_config @@ -47,7 +48,7 @@ class SystemNames(unittest.TestCase): cls.manufacturers = group_by_manufacturer(db) cls.profiles = load_emulator_profiles( str(REPO_ROOT / "emulators"), skip_aliases=False) - systemnames.set_console_sections( + runsections.install( cls.manufacturers, systemnames.program_names(cls.profiles)) platforms_dir = str(REPO_ROOT / "platforms") cls.platform_ids = { @@ -64,7 +65,7 @@ class SystemNames(unittest.TestCase): unnamed = [] for sys_id in sorted(self._all_ids()): try: - name = systemnames.system_name(sys_id) + name = runsections.system_name(sys_id) except KeyError: unnamed.append(sys_id) continue @@ -75,9 +76,9 @@ class SystemNames(unittest.TestCase): taken = {name.casefold() for name in self.manufacturers} taken |= {name.casefold() for name in systemnames.program_names(self.profiles)} clashes = sorted( - (sys_id, systemnames.system_name(sys_id)) + (sys_id, runsections.system_name(sys_id)) for sys_id in self._all_ids() - if systemnames.system_name(sys_id).casefold() in taken + if runsections.system_name(sys_id).casefold() in taken ) self.assertEqual(clashes, []) @@ -86,36 +87,36 @@ class SystemNames(unittest.TestCase): no platform or profile names is a leftover.""" shadowed = sorted( sys_id for sys_id in systemnames.SYSTEM_NAMES - if systemnames.own_section(sys_id) is not None + if runsections.own_section(sys_id) is not None ) self.assertEqual(shadowed, []) unused = sorted(set(systemnames.SYSTEM_NAMES) - self._all_ids()) self.assertEqual(unused, []) def test_names_that_read_a_folder_vote(self) -> None: - self.assertEqual(systemnames.system_name("nintendo-gba"), "Nintendo Game Boy Advance") - self.assertEqual(systemnames.system_name("camplynx"), "Camputers Lynx") - self.assertEqual(systemnames.system_name("atari-lynx"), "Atari Lynx") - self.assertEqual(systemnames.system_name("arcade"), "Arcade games") - self.assertEqual(systemnames.system_name("sega-naomi"), "Sega NAOMI") + self.assertEqual(runsections.system_name("nintendo-gba"), "Nintendo Game Boy Advance") + self.assertEqual(runsections.system_name("camplynx"), "Camputers Lynx") + self.assertEqual(runsections.system_name("atari-lynx"), "Atari Lynx") + self.assertEqual(runsections.system_name("arcade"), "Arcade games") + self.assertEqual(runsections.system_name("sega-naomi"), "Sega NAOMI") def test_own_section_names_from_its_heading(self) -> None: - self.assertEqual(systemnames.system_name("nintendo-snes"), "Nintendo SNES") - self.assertEqual(systemnames.system_name("sony-playstation"), "Sony PlayStation") + self.assertEqual(runsections.system_name("nintendo-snes"), "Nintendo SNES") + self.assertEqual(runsections.system_name("sony-playstation"), "Sony PlayStation") def test_an_unknown_id_raises(self) -> None: with self.assertRaises(KeyError): - systemnames.system_name("no-such-system-anywhere") + runsections.system_name("no-such-system-anywhere") def test_mame_names_systems_not_emulators(self) -> None: - names = {systemnames.system_name(s) for s in self.profiles["mame"].get("systems") or []} + names = {runsections.system_name(s) for s in self.profiles["mame"].get("systems") or []} self.assertNotIn("FBNeo", names) self.assertNotIn("Arcade", names) self.assertFalse(names & systemnames.program_names(self.profiles)) class SectionsComeBeforeThePlan(unittest.TestCase): - """plan_emulator_pages names systems. Run before set_console_sections, + """plan_emulator_pages names systems. Run before runsections.install, it made siterender read ./database.json and ./emulators whatever --db and --emulators-dir gave, so the parts were cut on another collection.""" @@ -128,9 +129,9 @@ class SectionsComeBeforeThePlan(unittest.TestCase): tree = ast.parse(inspect.getsource(build.generate_site)) lines = {} for node in ast.walk(tree): - if isinstance(node, ast.Call) and isinstance(node.func, ast.Name): - lines.setdefault(node.func.id, node.lineno) - self.assertLess(lines["set_console_sections"], lines["plan_emulator_pages"]) + if isinstance(node, ast.Call): + lines.setdefault(ast.unparse(node.func), node.lineno) + self.assertLess(lines["runsections.install"], lines["plan_emulator_pages"]) if __name__ == "__main__": diff --git a/tests/test_site_system_sections.py b/tests/test_site_system_sections.py index 0bc2143da..df1c221cf 100644 --- a/tests/test_site_system_sections.py +++ b/tests/test_site_system_sections.py @@ -25,6 +25,7 @@ from pathlib import Path from sitegen import render as siterender from sitegen import runlinks +from sitegen import runsections from model import siteinputs, systemnames REPO_ROOT = Path(__file__).resolve().parents[1] @@ -160,7 +161,7 @@ class SystemLinks(unittest.TestCase): db = json.load(handle) cls.manufacturers = group_by_manufacturer(db) profiles = load_emulator_profiles("emulators", skip_aliases=False) - systemnames.set_console_sections( + runsections.install( cls.manufacturers, systemnames.program_names(profiles)) # The system pages give every arcade board a section of its own # and record it. The built pages are checked by @@ -243,12 +244,12 @@ class SystemLinks(unittest.TestCase): by_heading.setdefault(name.casefold(), set()).add((mfr, console)) missed = [] for sys_id in sorted(self.ids): - places = by_heading.get(systemnames.system_name(sys_id).casefold(), set()) + places = by_heading.get(runsections.system_name(sys_id).casefold(), set()) if len(places) != 1: continue mfr, console = next(iter(places)) if mfr == "Other" or ( - mfr == "Arcade" and console.casefold() in systemnames.known_program_names + mfr == "Arcade" and console.casefold() in runsections.current().sections.programs ): continue if runlinks.system_section(sys_id) is None: @@ -268,12 +269,12 @@ class SystemLinks(unittest.TestCase): An entry its own section shadows is never read and is not judged.""" by_name: dict[str, set[tuple[str, str]]] = {} for sys_id, sections in self.held.items(): - by_name.setdefault(systemnames.system_name(sys_id), set()).update(sections) + by_name.setdefault(runsections.system_name(sys_id), set()).update(sections) wrong = [] for sys_id, parent in sorted(systemnames.SYSTEM_PARENTS.items()): - if systemnames.own_section(sys_id) is not None: + if runsections.own_section(sys_id) is not None: continue - held = by_name.get(systemnames.system_name(sys_id)) + held = by_name.get(runsections.system_name(sys_id)) if held is not None and parent not in held: wrong.append((sys_id, parent)) self.assertEqual(wrong, [])