From c0d85cca0b0a597ce58dd074a95ffff291e9df77 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:17:50 +0100 Subject: [PATCH] refactor: grouping returns its labels and moves --- .github/workflows/deploy-site.yml | 1 + scripts/model/collection.py | 75 +++++++++++++++++++----------- scripts/model/manufacturers.py | 8 ++++ scripts/model/systemnames.py | 34 ++++++++------ scripts/resolve/ownership.py | 2 +- scripts/sitegen/apiitems.py | 5 +- scripts/sitegen/build.py | 8 ++-- scripts/sitegen/emulatorcards.py | 2 +- scripts/sitegen/imagefetch.py | 2 +- scripts/sitegen/lookup.py | 2 +- scripts/sitegen/nav.py | 2 +- scripts/sitegen/ogcards.py | 5 +- scripts/sitegen/places.py | 3 +- scripts/sitegen/render.py | 2 +- scripts/sitegen/runlinks.py | 23 +++++++-- scripts/sitegen/runsections.py | 32 ++++++++++--- scripts/sitegen/startwith.py | 8 ++-- scripts/sitegen/systempages.py | 11 ++--- scripts/sitegen/systemsindex.py | 12 +++-- tests/test_site_inputs.py | 4 +- tests/test_site_system_links.py | 18 +++---- tests/test_site_system_names.py | 11 +++-- tests/test_site_system_sections.py | 10 ++-- tests/test_site_systems.py | 28 ++++++++++- 24 files changed, 210 insertions(+), 98 deletions(-) create mode 100644 scripts/model/manufacturers.py diff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.yml index efb8e997f..28beb3135 100644 --- a/.github/workflows/deploy-site.yml +++ b/.github/workflows/deploy-site.yml @@ -58,6 +58,7 @@ on: - "scripts/model/largefiles.py" - "scripts/model/launcherrecords.py" - "scripts/model/mamerelease.py" + - "scripts/model/manufacturers.py" - "scripts/model/measurements.py" - "scripts/model/nodedup.py" - "scripts/model/platforms.py" diff --git a/scripts/model/collection.py b/scripts/model/collection.py index eaec9e2dd..945b46fc0 100644 --- a/scripts/model/collection.py +++ b/scripts/model/collection.py @@ -9,11 +9,13 @@ bios folder comes from siteinputs, never the working directory. from __future__ import annotations import functools +from collections.abc import Mapping from dataclasses import dataclass from pathlib import Path from model import siteinputs from model.composition import GAME_DATA_TOPS +from model.manufacturers import manufacturer_slug from model.profiles import is_emulator, load_emulator_profiles @@ -44,10 +46,6 @@ def copy_places( return places -def manufacturer_slug(manufacturer: str) -> str: - return manufacturer.lower().replace(" ", "-") - - def collection_paths(db: dict) -> dict[str, set[str]]: """Every path under bios/ that holds each file, by sha1. @@ -70,11 +68,32 @@ def collection_paths(db: dict) -> dict[str, set[str]]: return paths +# (manufacturer slug, folder, sha1) -> the (manufacturer slug, console) a +# copy's card goes to when its section is not its folder. +CardMoves = dict[tuple[str, str, str], tuple[str, str]] + + +@dataclass(frozen=True) +class Grouping: + """The sections a collection files, as manufacturer -> console -> files. + + ``labels``: (manufacturer, console) -> the heading a section shows in + place of its folder, SECTION_LABELS and the engine names. ``moves``: + (manufacturer slug, folder, sha1) -> the (manufacturer slug, console) + holding the card of a copy filed outside its folder: ScummVM's engine + data under Other/ScummVM. + """ + + sections: dict[str, dict[str, list]] + labels: Mapping[tuple[str, str], str] + moves: Mapping[tuple[str, str, str], tuple[str, str]] + + def group_by_manufacturer( db: dict, bios_dir: Path | None = None, profiles: dict[str, dict] | None = None, -) -> dict[str, dict[str, list]]: +) -> Grouping: """Group files by manufacturer -> console -> files. The database keeps one path per content, and a copy filed elsewhere was @@ -95,7 +114,7 @@ def group_by_manufacturer( def _engine_sections( manufacturers: dict[str, dict[str, list]], all_profiles: dict[str, dict] | None = None, -) -> dict[str, dict[str, list]]: +) -> Grouping: """A game engine's files in one section headed with the engine's name. The Systems index listed ".variants", "scummvm.zip" and "wildmidi.cfg" @@ -104,7 +123,7 @@ def _engine_sections( the section of the one engine that reads it (else of the engine the top is named after), the folder under Other named after a game-engine top joins that top, and a folder named by a profile key is headed with - the engine's name (SECTION_LABELS), its address unchanged. + the engine's name (Grouping.labels), its address unchanged. """ if all_profiles is None: @@ -112,19 +131,21 @@ def _engine_sections( profiles = {key: profile for key, profile in all_profiles.items() if is_emulator(profile)} engines = _Engines(profiles, _file_readers(profiles)) + moves: CardMoves = {} out: dict[str, dict[str, list]] = {} for mfr, consoles in manufacturers.items(): if mfr not in GAME_DATA_TOPS: out[mfr] = dict(consoles) continue - out[mfr] = _regroup_top(mfr, consoles, engines) - _join_other_folders(out) + out[mfr] = _regroup_top(mfr, consoles, engines, moves) + _join_other_folders(out, moves) + labels = dict(SECTION_LABELS) for mfr in GAME_DATA_TOPS: for console in out.get(mfr, {}): named = console if console in profiles else None if named and engines.engine(named) != console: - SECTION_LABELS[(mfr, console)] = engines.engine(named) - return {mfr: consoles for mfr, consoles in out.items() if consoles} + labels[(mfr, console)] = engines.engine(named) + return Grouping({mfr: consoles for mfr, consoles in out.items() if consoles}, labels, moves) @dataclass(frozen=True) @@ -152,7 +173,9 @@ def _file_readers(profiles: dict[str, dict]) -> dict[str, set[str]]: return readers -def _regroup_top(mfr: str, consoles: dict[str, list], engines: _Engines) -> dict[str, list]: +def _regroup_top( + mfr: str, consoles: dict[str, list], engines: _Engines, moves: CardMoves, +) -> dict[str, list]: own = engines.profile_of(mfr) regrouped: dict[str, list] = {} @@ -170,12 +193,12 @@ def _regroup_top(mfr: str, consoles: dict[str, list], engines: _Engines) -> dict target = found or (next((c for c in consoles if c == reader), None) or (engines.engine(reader) if reader else base)) if target != console: - record_card_move(mfr, console, str(f.get("sha1", "")), mfr, target) + _move_card(moves, (mfr, console, str(f.get("sha1", ""))), (mfr, target)) regrouped.setdefault(target, []).append(f) return regrouped -def _join_other_folders(out: dict[str, dict[str, list]]) -> None: +def _join_other_folders(out: dict[str, dict[str, list]], moves: CardMoves) -> None: """The folder under Other an engine top is named after: ScummVM's engine data under Other/ScummVM, its themes under ScummVM/.""" @@ -189,7 +212,7 @@ def _join_other_folders(out: dict[str, dict[str, list]]) -> None: target = next((c for c in sections if c.casefold() == folder.casefold()), folder) held = {str(f.get("sha1", "")) for f in sections.get(target, [])} for f in others[folder]: - record_card_move("Other", folder, str(f.get("sha1", "")), top, target) + _move_card(moves, ("Other", folder, str(f.get("sha1", ""))), (top, target)) sections[target] = [*sections.get(target, []), *(f for f in others.pop(folder) if str(f.get("sha1", "")) not in held)] @@ -203,18 +226,14 @@ def profiles_in(emulators_dir: str, skip_aliases: bool) -> dict[str, dict]: return load_emulator_profiles(emulators_dir, skip_aliases=skip_aliases) -# (manufacturer slug, folder, sha1) -> the (manufacturer slug, console) a -# copy's card went to when the system pages file it outside its folder: -# ScummVM's engine data under Other/ScummVM, neogeo.zip under Arcade. -card_moves: dict[tuple[str, str, str], tuple[str, str]] = {} - - -def record_card_move(manufacturer: str, folder: str, sha1: str, - to_manufacturer: str, to_console: str) -> None: - """Mark that the card of the copy under bios/// - sits in the section (to_manufacturer, to_console).""" - card_moves[(manufacturer_slug(manufacturer), folder, str(sha1))] = ( - manufacturer_slug(to_manufacturer), to_console) +def _move_card( + moves: CardMoves, copy: tuple[str, str, str], section: tuple[str, str], +) -> None: + """Mark that the card of the copy (manufacturer, folder, sha1) sits in + the section (manufacturer, console).""" + manufacturer, folder, sha1 = copy + moves[(manufacturer_slug(manufacturer), folder, sha1)] = ( + manufacturer_slug(section[0]), section[1]) # System display names. A system is named by the heading of the console @@ -232,6 +251,6 @@ PROGRAM_TOPS = frozenset({"Other", "Arcade"}) # A section whose folder is a short name the code reads, headed with the # program's name instead (bios/Arcade/fba2012 holds FB Alpha 2012's samples). -SECTION_LABELS: dict[tuple[str, str], str] = { +SECTION_LABELS: Mapping[tuple[str, str], str] = { ("Arcade", "fba2012"): "FB Alpha 2012", } diff --git a/scripts/model/manufacturers.py b/scripts/model/manufacturers.py new file mode 100644 index 000000000..30337b8fa --- /dev/null +++ b/scripts/model/manufacturers.py @@ -0,0 +1,8 @@ +"""The slug a manufacturer's name gives in an address.""" + +from __future__ import annotations + + +def manufacturer_slug(manufacturer: str) -> str: + """The manufacturer's name lowercased, spaces as hyphens: "Sega" gives "sega".""" + return manufacturer.lower().replace(" ", "-") diff --git a/scripts/model/systemnames.py b/scripts/model/systemnames.py index 4aa19f943..d2c6bfea6 100644 --- a/scripts/model/systemnames.py +++ b/scripts/model/systemnames.py @@ -11,39 +11,44 @@ from model.collection import ( SECTION_LABELS, PROGRAM_TOPS, group_by_manufacturer, - manufacturer_slug, ) +from model.manufacturers import manufacturer_slug @dataclass(frozen=True) class ConsoleSections: """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.""" + console) pair, by normalized id and by the name its heading reads, the + program names (casefolded) whose headings name no system, and the + heading each labelled section shows in place of its folder.""" index: Mapping[str, set[tuple[str, str]]] programs: AbstractSet[str] pairs: AbstractSet[tuple[str, str]] by_name: Mapping[str, set[tuple[str, str]]] + labels: Mapping[tuple[str, str], str] def console_sections( sections: dict[str, dict] | set[tuple[str, str]], programs: Iterable[str] = (), + labels: Mapping[tuple[str, str], str] = SECTION_LABELS, ) -> ConsoleSections: """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.""" + system. ``labels`` are the headings the grouping gave + (model.collection.Grouping.labels).""" 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()}: + for name in {heading_name(mfr, console, labels).casefold(), console.casefold()}: by_name.setdefault(name, set()).add((mfr, console)) return ConsoleSections( console_index(pairs), frozenset(name.casefold() for name in programs), frozenset(pairs), by_name, + labels, ) @@ -52,10 +57,8 @@ def collection_sections( ) -> ConsoleSections: """The console sections of a collection: its database, the bios folder it describes and every emulator profile, aliases included.""" - return console_sections( - group_by_manufacturer(db, bios_dir=bios_dir, profiles=profiles), - program_names(profiles), - ) + grouping = group_by_manufacturer(db, bios_dir=bios_dir, profiles=profiles) + return console_sections(grouping.sections, program_names(profiles), grouping.labels) def program_names(profiles: dict[str, dict]) -> set[str]: @@ -139,19 +142,22 @@ def own_section_in(sys_id: str, sections: ConsoleSections) -> tuple[str, str] | if ( mfr in PROGRAM_TOPS or console.casefold() == mfr.casefold() - or heading_name(mfr, console).casefold() in sections.programs + or heading_name(mfr, console, sections.labels).casefold() in sections.programs ): return None return mfr, console -def heading_name(mfr: str, console: str) -> str: +def heading_name( + mfr: str, console: str, labels: Mapping[tuple[str, str], str] = SECTION_LABELS, +) -> str: """A console heading read out of its page: the maker in front, unless - the heading already starts with it or the page is a game publisher's.""" + the heading already starts with it or the page is a game publisher's, + headed with its label (``labels``) or its folder.""" from model.composition import GAME_DATA_TOPS if mfr in GAME_DATA_TOPS: - return SECTION_LABELS.get((mfr, console), console) + return labels.get((mfr, console), console) if console.casefold().startswith(mfr.split()[0].casefold()): return console return f"{mfr} {console}" @@ -194,7 +200,7 @@ def system_name_in(sys_id: str, sections: ConsoleSections) -> str: sys_id = str(sys_id) section = own_section_in(sys_id, sections) if section is not None: - return heading_name(*section) + return heading_name(*section, sections.labels) name = SYSTEM_NAMES.get(sys_id) if name is None: raise KeyError( diff --git a/scripts/resolve/ownership.py b/scripts/resolve/ownership.py index 6c8d8712f..800ecc0a6 100644 --- a/scripts/resolve/ownership.py +++ b/scripts/resolve/ownership.py @@ -5,7 +5,7 @@ from __future__ import annotations import re from core.memo import DerivedView -from model.collection import manufacturer_slug +from model.manufacturers import manufacturer_slug # bios/Other/ and bios/Arcade/ file a copy by diff --git a/scripts/sitegen/apiitems.py b/scripts/sitegen/apiitems.py index 85809567e..4d6063388 100644 --- a/scripts/sitegen/apiitems.py +++ b/scripts/sitegen/apiitems.py @@ -5,7 +5,8 @@ from __future__ import annotations import urllib.parse from collections.abc import Callable -from model.collection import group_by_manufacturer, manufacturer_slug +from model.collection import group_by_manufacturer +from model.manufacturers import manufacturer_slug from model.database import declared_records, sha1_at from sitegen.runsections import system_name from model.profiles import is_emulator @@ -52,7 +53,7 @@ def system_index_items(db: dict, coverages: dict, profiles: dict) -> list[dict]: for sha1 in named} for sys_id in ids: held.setdefault(sys_id, set()).update(found) - manufacturers = {manufacturer_slug(mfr): mfr for mfr in group_by_manufacturer(db)} + manufacturers = {manufacturer_slug(mfr): mfr for mfr in group_by_manufacturer(db).sections} base = urllib.parse.urlsplit(SITE_URL).path items = [] for sys_id in sorted(system_ids(profiles, [c["config"] for c in coverages.values()])): diff --git a/scripts/sitegen/build.py b/scripts/sitegen/build.py index 33573858a..5f66ae110 100644 --- a/scripts/sitegen/build.py +++ b/scripts/sitegen/build.py @@ -15,7 +15,8 @@ from core.artifacts import build_timestamp from romrecipes import ledger from model import releaserecord from model import siteinputs -from model.collection import group_by_manufacturer, manufacturer_slug +from model.collection import group_by_manufacturer +from model.manufacturers import manufacturer_slug from model.composition import compute_composition from model.database import load_database from model.dumpcatalog import load_provenance_snapshots @@ -683,8 +684,9 @@ def generate_site(args: argparse.Namespace) -> None: # cut into weigh the status its rows show. 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) - runsections.install(run.manufacturers, program_names(profiles)) + grouping = group_by_manufacturer(db) + run.manufacturers = grouping.sections + runsections.install_grouping(grouping, 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/emulatorcards.py b/scripts/sitegen/emulatorcards.py index 2321689de..fe01ac260 100644 --- a/scripts/sitegen/emulatorcards.py +++ b/scripts/sitegen/emulatorcards.py @@ -12,7 +12,7 @@ from dataclasses import dataclass from pathlib import Path from core.sizes import size_text -from model.collection import manufacturer_slug +from model.manufacturers import manufacturer_slug from sitegen.runsections import system_name from model.profiles import reads_own_files from packs.consumers import FileConsumers, entry_target, held_copy diff --git a/scripts/sitegen/imagefetch.py b/scripts/sitegen/imagefetch.py index 583ff5651..0c277c82a 100644 --- a/scripts/sitegen/imagefetch.py +++ b/scripts/sitegen/imagefetch.py @@ -97,7 +97,7 @@ def fetch_icons() -> Iterator[str]: db = load_database(str(REPO_ROOT / DB_FILE)) names = sorted({ console_icon_name(manufacturer, console) - for manufacturer, consoles in group_by_manufacturer(db).items() + for manufacturer, consoles in group_by_manufacturer(db).sections.items() for console in consoles }) ICON_DIR.mkdir(parents=True, exist_ok=True) diff --git a/scripts/sitegen/lookup.py b/scripts/sitegen/lookup.py index e8ba48ba3..ab5049e7b 100644 --- a/scripts/sitegen/lookup.py +++ b/scripts/sitegen/lookup.py @@ -11,7 +11,7 @@ from pathlib import Path from core.hashing import declared_hash_lists from model import siteinputs -from model.collection import manufacturer_slug +from model.manufacturers import manufacturer_slug from model.database import declared_records from model.registry import load_versions, versions_file_for from sitegen.runsections import system_name diff --git a/scripts/sitegen/nav.py b/scripts/sitegen/nav.py index 7e555dcae..acb551be1 100644 --- a/scripts/sitegen/nav.py +++ b/scripts/sitegen/nav.py @@ -6,7 +6,7 @@ import re from collections.abc import Iterator from pathlib import Path -from model.collection import manufacturer_slug +from model.manufacturers import manufacturer_slug from model.composition import GAME_DATA_TOPS from sitegen.guidedata import device_groups, group_tiles, handheld_guide from model.profiles import unique_emulator_profiles diff --git a/scripts/sitegen/ogcards.py b/scripts/sitegen/ogcards.py index 49e016b0d..f29812660 100644 --- a/scripts/sitegen/ogcards.py +++ b/scripts/sitegen/ogcards.py @@ -9,7 +9,8 @@ from xml.sax.saxutils import escape from core.paths import DB_FILE, PLATFORMS_DIR, REPO_ROOT from core.text import series -from model.collection import group_by_manufacturer, manufacturer_slug +from model.collection import group_by_manufacturer +from model.manufacturers import manufacturer_slug from model.composition import GAME_DATA_TOPS from model.database import load_database from model.platforms import load_platform_config @@ -99,7 +100,7 @@ def system_cards() -> dict[str, tuple[str, str]]: """Each manufacturer page's card under og/systems/, titled with the manufacturer and listing its consoles. Read from the same grouping the system pages are written from.""" - manufacturers = group_by_manufacturer(load_database(str(REPO_ROOT / DB_FILE))) + manufacturers = group_by_manufacturer(load_database(str(REPO_ROOT / DB_FILE))).sections return { f"systems/{manufacturer_slug(manufacturer)}": ( manufacturer, consoles_tagline(list(consoles), _manufacturer_lead(manufacturer))) diff --git a/scripts/sitegen/places.py b/scripts/sitegen/places.py index 6cee5755d..f765a31eb 100644 --- a/scripts/sitegen/places.py +++ b/scripts/sitegen/places.py @@ -4,7 +4,8 @@ from __future__ import annotations from dataclasses import dataclass -from model.collection import copy_places, manufacturer_slug +from model.collection import copy_places +from model.manufacturers import manufacturer_slug from model.systemnames import console_index, section_pairs_of, spelled_section from resolve.localfile import resolution_is_hash_exact, resolve_local_file from resolve.ownership import BUCKET_FOLDERS, names_manufacturer diff --git a/scripts/sitegen/render.py b/scripts/sitegen/render.py index 7d6fc9a92..f1575755b 100644 --- a/scripts/sitegen/render.py +++ b/scripts/sitegen/render.py @@ -6,7 +6,7 @@ import re from collections.abc import Callable from core.text import count_text as count_text -from model.collection import manufacturer_slug +from model.manufacturers import manufacturer_slug from sitegen import runsections from sitegen.runsections import system_name diff --git a/scripts/sitegen/runlinks.py b/scripts/sitegen/runlinks.py index c8f53e82b..c2e094aa3 100644 --- a/scripts/sitegen/runlinks.py +++ b/scripts/sitegen/runlinks.py @@ -8,7 +8,7 @@ from collections.abc import Mapping from dataclasses import dataclass, field from model import siteinputs -from model.collection import card_moves +from model.manufacturers import manufacturer_slug from model.systemnames import SYSTEM_PARENTS from sitegen import runsections from sitegen.runsections import section_without_boards, system_name @@ -26,7 +26,9 @@ class LinkTables: (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 + stem holding that card. ``card_moves``: (slug, folder, sha1) -> the + (slug, console) section a system page filed that copy's card in, outside + its folder: neogeo.zip under Arcade. ``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 runsections generation @@ -38,6 +40,7 @@ class LinkTables: 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) + card_moves: dict[tuple[str, str, str], tuple[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) @@ -96,10 +99,19 @@ def reset_console_pages() -> None: tables = current() tables.console_pages.clear() tables.card_pages.clear() + tables.card_moves.clear() tables.board_sections.clear() tables.aliases = None +def record_card_move(manufacturer: str, folder: str, sha1: str, + to_manufacturer: str, to_console: str) -> None: + """Mark that the card of the copy under bios/// + sits in the section (to_manufacturer, to_console).""" + current().card_moves[(manufacturer_slug(manufacturer), folder, str(sha1))] = ( + manufacturer_slug(to_manufacturer), to_console) + + def record_console_pages( slug: str, console: str, stems: list[str], sha1s: list[list[str]] ) -> None: @@ -137,7 +149,8 @@ def console_href(slug: str, console: str, prefix: str = "") -> str: def card_page(path: str, sha1: str) -> str: """The systems/ page stem holding the card of the copy at ``path`` (bios///...). A board's set is on the board's - page whatever folder holds the copy.""" + page whatever folder holds the copy, and a copy a system page or the + grouping filed outside its folder is on that section's page.""" tables = current() parts = path.split("/") slug = parts[1].lower().replace(" ", "-") @@ -146,7 +159,9 @@ def card_page(path: str, sha1: str) -> str: 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)) + key = (slug, console, str(sha1)) + slug, console = (tables.card_moves.get(key) or runsections.current().moves.get(key) + or (slug, console)) return tables.card_pages.get((slug, console, sha1), slug) diff --git a/scripts/sitegen/runsections.py b/scripts/sitegen/runsections.py index 66b4eb4fc..0f669bd14 100644 --- a/scripts/sitegen/runsections.py +++ b/scripts/sitegen/runsections.py @@ -2,11 +2,13 @@ from __future__ import annotations -from dataclasses import dataclass +from collections.abc import Mapping +from dataclasses import dataclass, field from core.anchors import toc_slug, unique_anchor from model import siteinputs -from model.collection import group_by_manufacturer, manufacturer_slug +from model.collection import SECTION_LABELS, Grouping, group_by_manufacturer +from model.manufacturers import manufacturer_slug from model.systemnames import ( ConsoleSections, console_sections, @@ -26,12 +28,15 @@ class RunSections: 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. + ``moves``: the cards the grouping filed outside their folder + (model.collection.Grouping.moves). """ sections: ConsoleSections anchors: dict[tuple[str, str], str] inputs: siteinputs.SiteInputs generation: int + moves: Mapping[tuple[str, str, str], tuple[str, str]] = field(default_factory=dict) _current: list[RunSections | None] = [None] @@ -41,15 +46,19 @@ _installs = [0] def install( sections: dict[str, dict] | set[tuple[str, str]], programs: set[str] | frozenset[str] = frozenset(), + labels: Mapping[tuple[str, str], str] = SECTION_LABELS, + moves: Mapping[tuple[str, str, str], tuple[str, str]] | None = None, ) -> 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. + are the emulator names, which never name a system. ``labels`` and + ``moves`` are the headings and card moves of the grouping + (install_grouping). """ - carried = console_sections(sections, programs) + carried = console_sections(sections, programs, labels) by_maker: dict[str, list[str]] = {} for mfr, console in carried.pairs: by_maker.setdefault(mfr, []).append(console) @@ -60,11 +69,17 @@ def install( 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]) + run = RunSections(carried, anchors, siteinputs.current(), _installs[0], dict(moves or {})) _current[0] = run return run +def install_grouping(grouping: Grouping, programs: set[str] | frozenset[str]) -> RunSections: + """Install the sections of a collection's grouping, with its headings + and card moves.""" + return install(grouping.sections, programs, grouping.labels, grouping.moves) + + def reset() -> None: """Forget the installed sections: the next name is read from the inputs.""" _current[0] = None @@ -90,7 +105,12 @@ def current() -> RunSections: 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)) + return install_grouping(group_by_manufacturer(db), program_names(profiles)) + + +def section_labels() -> Mapping[tuple[str, str], str]: + """The heading each labelled section shows in place of its folder.""" + return current().sections.labels def system_name(sys_id: str) -> str: diff --git a/scripts/sitegen/startwith.py b/scripts/sitegen/startwith.py index 3013a1cd4..4b9f62f52 100644 --- a/scripts/sitegen/startwith.py +++ b/scripts/sitegen/startwith.py @@ -6,7 +6,7 @@ import re from collections.abc import Iterator from dataclasses import dataclass -from model.collection import SECTION_LABELS +from model.manufacturers import manufacturer_slug from packs.consumers import FileConsumers from sitegen import markup from sitegen.cards import ROMSET_FAQ, emulator_display, romset_releases @@ -28,6 +28,7 @@ from core.text import series from sitegen.emulatorcards import region_words from sitegen.install import comes_with_app from sitegen.render import card_anchor, code_span, count_text, console_anchor +from sitegen.runsections import section_labels class _StartGroup: @@ -302,7 +303,6 @@ def _start_groups( no file to fetch.""" 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 kept, candidates = _section_reads(files, consumers, here) @@ -327,7 +327,7 @@ def _start_groups( named_keys = [key for key in groups if key is not None] if None in groups and named_keys: # An entry that names no system reads the section's own console. - heading = heading_name(*section) if section else None + heading = heading_name(*section, section_labels()) if section else None groups[heading if heading in groups else named_keys[0]].absorb(groups.pop(None)) return groups @@ -721,4 +721,4 @@ def section_label(manufacturer: str, console: str) -> str: """The heading a section shows.""" if (manufacturer, console) == OTHER_ARCADE: return OTHER_ARCADE_LABEL - return SECTION_LABELS.get((manufacturer, console), console) + return section_labels().get((manufacturer, console), console) diff --git a/scripts/sitegen/systempages.py b/scripts/sitegen/systempages.py index 7487cc47d..d2c7117f4 100644 --- a/scripts/sitegen/systempages.py +++ b/scripts/sitegen/systempages.py @@ -9,7 +9,7 @@ import re import urllib.parse from dataclasses import dataclass -from model.collection import SECTION_LABELS, manufacturer_slug +from model.manufacturers import manufacturer_slug from model.composition import GAME_DATA_TOPS from packs.consumers import FileConsumers from sitegen import markup @@ -31,6 +31,7 @@ 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 +from sitegen.runsections import section_labels from sitegen.runlinks import console_href, record_console_pages from sitegen.startwith import ( OTHER_ARCADE, @@ -84,8 +85,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.runlinks import arcade_board, archive_machine - from model.collection import record_card_move + from sitegen.runlinks import arcade_board, archive_machine, record_card_move for console in sorted(arcade): joined = by_name.get(console.casefold()) @@ -105,8 +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.runlinks import arcade_board, archive_machine - from model.collection import record_card_move + from sitegen.runlinks import arcade_board, archive_machine, record_card_move for mfr, consoles in manufacturers.items(): if mfr == "Arcade": @@ -194,7 +193,7 @@ def _part_name(manufacturer: str, console: str) -> str: """What a part's title calls the files: "Arcade files a to b".""" if (manufacturer, console) == OTHER_ARCADE: return "Arcade" - return SECTION_LABELS.get((manufacturer, console), console) + return section_labels().get((manufacturer, console), console) def _system_front_matter( diff --git a/scripts/sitegen/systemsindex.py b/scripts/sitegen/systemsindex.py index 042ece9b9..f0cec80a9 100644 --- a/scripts/sitegen/systemsindex.py +++ b/scripts/sitegen/systemsindex.py @@ -2,12 +2,14 @@ from __future__ import annotations -from model.collection import SECTION_LABELS, profiles_on_disk, manufacturer_slug +from model.collection import profiles_on_disk +from model.manufacturers import 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 from sitegen.runlinks import console_href +from sitegen.runsections import section_labels from sitegen.startwith import section_label @@ -18,7 +20,9 @@ def _console_display(manufacturer: str, console: str) -> str: from model.collection import PROGRAM_TOPS from model.systemnames import heading_name - return console if manufacturer in PROGRAM_TOPS else heading_name(manufacturer, console) + if manufacturer in PROGRAM_TOPS: + return console + return heading_name(manufacturer, console, section_labels()) def generate_systems_index(manufacturers: dict) -> str: @@ -49,6 +53,8 @@ def generate_systems_index(manufacturers: dict) -> str: "", ] + labels = section_labels() + # Other holds one folder per emulator: a7800 or altirra in the console # table named no console. Arcade boards are neither consoles nor # computers, and the crumb of their page says Arcade too. @@ -72,7 +78,7 @@ def generate_systems_index(manufacturers: dict) -> str: rows = sorted( ((folder_emulator(console)[0] if group == "programs" else section_label(mfr, console) if mfr == "Arcade" - or (mfr, console) in SECTION_LABELS + or (mfr, console) in labels else _console_display(mfr, console), mfr, console, len(files)) for mfr, consoles in manufacturers.items() if kind(mfr) == group for console, files in consoles.items()), diff --git a/tests/test_site_inputs.py b/tests/test_site_inputs.py index 79f4288f2..fca7aff8e 100644 --- a/tests/test_site_inputs.py +++ b/tests/test_site_inputs.py @@ -74,7 +74,9 @@ class SectionsFollowTheInputs(_Inputs): (tmp / "emulators").mkdir() (tmp / "database.json").write_text(json.dumps({"files": {}}), encoding="utf-8") self.use(db=tmp / "database.json", emulators=tmp / "emulators") - folders = {"Sega": {"Mega CD": [], "Mega-CD": []}} + from model.collection import SECTION_LABELS, Grouping + + folders = Grouping({"Sega": {"Mega CD": [], "Mega-CD": []}}, SECTION_LABELS, {}) with mock.patch.object(runsections, "group_by_manufacturer", return_value=folders): self.assertEqual(render.console_anchor("Sega", "Mega CD"), "mega-cd") self.assertEqual(render.console_anchor("Sega", "Mega-CD"), "mega-cd_1") diff --git a/tests/test_site_system_links.py b/tests/test_site_system_links.py index af47678fc..4088ed83d 100644 --- a/tests/test_site_system_links.py +++ b/tests/test_site_system_links.py @@ -18,6 +18,7 @@ import unittest from pathlib import Path from model import collection +from model.manufacturers import manufacturer_slug from sitegen import places from sitegen import platformfiles from sitegen import startwith @@ -55,7 +56,7 @@ class LinksFollowContent(unittest.TestCase): db = load_database("database.json") config = load_platform_config("misterfpga") names: dict = {} - for mfr, consoles in collection.group_by_manufacturer(db).items(): + for mfr, consoles in collection.group_by_manufacturer(db).sections.items(): for console, entries in consoles.items(): for entry in entries: names.setdefault(entry["name"], set()).add((mfr, console)) @@ -122,7 +123,7 @@ class ACopyIsOnItsOwnFoldersPage(unittest.TestCase): "Fairchild/Channel F/sl31253.bin": ["s"], "Channel F/sl31253.bin": ["s"], }}, } - groups = collection.group_by_manufacturer(db) + groups = collection.group_by_manufacturer(db).sections self.assertEqual(sorted(groups), ["Arcade", "Fairchild"]) self.assertEqual(list(groups["Fairchild"]), ["Channel F"]) # The copy is listed twice and counted once. @@ -198,7 +199,7 @@ class ACopyFiledByEmulatorDoesNotMoveAMachine(unittest.TestCase): with tempfile.TemporaryDirectory() as tmp: db = self._db(tmp) - manufacturers = collection.group_by_manufacturer(db) + manufacturers = collection.group_by_manufacturer(db).sections config = {"systems": {"nintendo-nes": {"files": [ {"name": "FDS_disksys-nintendo.rom", "sha1": "d" * 40}]}}} pages = places.system_pages_from_data( @@ -215,7 +216,7 @@ class ACopyFiledByEmulatorDoesNotMoveAMachine(unittest.TestCase): from model.profiles import load_emulator_profiles db = load_database("database.json") - manufacturers = collection.group_by_manufacturer(db) + manufacturers = collection.group_by_manufacturer(db).sections pages = places.system_pages_from_data( manufacturers, {}, db, load_emulator_profiles("emulators", skip_aliases=False)) expected = { @@ -279,8 +280,9 @@ 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) - runsections.install(manufacturers, systemnames.program_names(profiles)) + grouping = collection.group_by_manufacturer(db) + manufacturers = grouping.sections + runsections.install_grouping(grouping, systemnames.program_names(profiles)) platforms = REPO_ROOT / "platforms" coverages = { name: {"config": load_platform_config(name, str(platforms))} @@ -299,7 +301,7 @@ class PagesFollowOwnSection(unittest.TestCase): continue with self.subTest(system=sys_id): self.assertEqual( - self.pages.get(sys_id), (collection.manufacturer_slug(own[0]), own[1])) + self.pages.get(sys_id), (manufacturer_slug(own[0]), own[1])) def test_named_cases(self): self.assertEqual(self.pages.get("atari-lynx"), ("atari", "Lynx")) @@ -332,7 +334,7 @@ class EverySystemLinkLandsOnItsSection(unittest.TestCase): db = load_database(str(REPO_ROOT / "database.json")) profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"), skip_aliases=False) - runsections.install(collection.group_by_manufacturer(db), systemnames.program_names(profiles)) + runsections.install_grouping(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 7511e4d08..d3b52b5e1 100644 --- a/tests/test_site_system_names.py +++ b/tests/test_site_system_names.py @@ -45,11 +45,12 @@ class SystemNames(unittest.TestCase): def setUpClass(cls) -> None: with open(REPO_ROOT / "database.json", encoding="utf-8") as handle: db = json.load(handle) - cls.manufacturers = group_by_manufacturer(db) + grouping = group_by_manufacturer(db) + cls.manufacturers = grouping.sections cls.profiles = load_emulator_profiles( str(REPO_ROOT / "emulators"), skip_aliases=False) - runsections.install( - cls.manufacturers, systemnames.program_names(cls.profiles)) + runsections.install_grouping( + grouping, systemnames.program_names(cls.profiles)) platforms_dir = str(REPO_ROOT / "platforms") cls.platform_ids = { sys_id @@ -116,7 +117,7 @@ class SystemNames(unittest.TestCase): class SectionsComeBeforeThePlan(unittest.TestCase): - """plan_emulator_pages names systems. Run before runsections.install, + """plan_emulator_pages names systems. Run before runsections.install_grouping, it made siterender read ./database.json and ./emulators whatever --db and --emulators-dir gave, so the parts were cut on another collection.""" @@ -131,7 +132,7 @@ class SectionsComeBeforeThePlan(unittest.TestCase): for node in ast.walk(tree): if isinstance(node, ast.Call): lines.setdefault(ast.unparse(node.func), node.lineno) - self.assertLess(lines["runsections.install"], lines["plan_emulator_pages"]) + self.assertLess(lines["runsections.install_grouping"], lines["plan_emulator_pages"]) if __name__ == "__main__": diff --git a/tests/test_site_system_sections.py b/tests/test_site_system_sections.py index df1c221cf..83926e89f 100644 --- a/tests/test_site_system_sections.py +++ b/tests/test_site_system_sections.py @@ -159,10 +159,11 @@ class SystemLinks(unittest.TestCase): with open("database.json", encoding="utf-8") as handle: db = json.load(handle) - cls.manufacturers = group_by_manufacturer(db) + grouping = group_by_manufacturer(db) + cls.manufacturers = grouping.sections profiles = load_emulator_profiles("emulators", skip_aliases=False) - runsections.install( - cls.manufacturers, systemnames.program_names(profiles)) + runsections.install_grouping( + grouping, 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 # test_site_built_gate. @@ -238,9 +239,10 @@ class SystemLinks(unittest.TestCase): def test_a_matching_heading_is_linked(self) -> None: """An id whose name reads one heading, outside Other, leads there.""" by_heading: dict[str, set[tuple[str, str]]] = {} + labels = runsections.section_labels() for mfr, consoles in self.manufacturers.items(): for console in consoles: - for name in {systemnames.heading_name(mfr, console), console}: + for name in {systemnames.heading_name(mfr, console, labels), console}: by_heading.setdefault(name.casefold(), set()).add((mfr, console)) missed = [] for sys_id in sorted(self.ids): diff --git a/tests/test_site_systems.py b/tests/test_site_systems.py index 742de18fe..5b9ea5c73 100644 --- a/tests/test_site_systems.py +++ b/tests/test_site_systems.py @@ -42,6 +42,7 @@ import zipfile import json from model import collection +from model.manufacturers import manufacturer_slug import sitegen from sitegen import cards as sitegen_cards from sitegen import consolecards @@ -932,7 +933,7 @@ class ConsolesFieldNamesMachinesOnce(unittest.TestCase): def test_no_emulator_folder_is_a_console(self) -> None: for maker in ("Other", "Game Engines"): page = systempages.system_pages(maker, {"dolphin": [_game_boy_file("a.bin", "a")]}, _consumers_by_system({})) - self.assertEqual(_consoles(page[collection.manufacturer_slug(maker)][0]), [], maker) + self.assertEqual(_consoles(page[manufacturer_slug(maker)][0]), [], maker) def test_a_console_with_its_own_page_is_left_to_it(self) -> None: big = [_game_boy_file(f"r{i:02}.bin", "0123456789"[i], f"bios/Sega/Saturn/r{i:02}.bin") @@ -1242,6 +1243,31 @@ class EnginesGoByEngine(unittest.TestCase): self.assertEqual(table.get("/systems/oric/"), "/systems/tangerine/#oric") +class TheGroupingCarriesItsLabelsAndMoves(unittest.TestCase): + """The grouping wrote engine headings into SECTION_LABELS and card moves + into a module dict nothing reset: a heading one collection left named a + section of the next, and a manifest build wrote site state.""" + + def test_the_labels_come_back_with_the_sections(self) -> None: + before = dict(collection.SECTION_LABELS) + copy = {"sha1": "s", "name": "a.bin", "path": "bios/3D Realms/eng/a.bin"} + named = collection._engine_sections( + {"3D Realms": {"eng": [copy]}}, {"eng": {"emulator": "Engine One"}}) + self.assertEqual(named.labels[("3D Realms", "eng")], "Engine One") + self.assertEqual(named.labels[("Arcade", "fba2012")], "FB Alpha 2012") + self.assertEqual(dict(collection.SECTION_LABELS), before) + plain = collection._engine_sections({"3D Realms": {"eng": [copy]}}, {}) + self.assertNotIn(("3D Realms", "eng"), plain.labels) + + def test_the_moves_come_back_with_the_sections(self) -> None: + copy = {"sha1": "s", "name": "a.dat", "path": "bios/Other/ScummVM/a.dat"} + grouping = collection._engine_sections( + {"ScummVM": {}, "Other": {"ScummVM": [copy]}}, {}) + self.assertEqual(grouping.sections, {"ScummVM": {"ScummVM": [copy]}}) + self.assertEqual(dict(grouping.moves), {("other", "ScummVM", "s"): ("scummvm", "ScummVM")}) + self.assertEqual(collection._engine_sections({"Sony": {"PS": [copy]}}, {}).moves, {}) + + class OneLabelOnceOnABoardPage(unittest.TestCase): """6.7, 6.8, 6.9, 6.10: the words a board or part page repeats."""