From 4585e3ffea5d3d4ad7a9f78a7ace7a2a9518442d Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 04:35:26 +0100 Subject: [PATCH] refactor: write card anchors through one helper --- scripts/sitegen/apiitems.py | 4 ++-- scripts/sitegen/cards.py | 9 ++++----- scripts/sitegen/decorate.py | 8 ++++---- scripts/sitegen/emulatorcards.py | 7 ++++--- scripts/sitegen/emulatorpage.py | 5 +++-- scripts/sitegen/lookup.py | 6 +++--- scripts/sitegen/platformfiles.py | 5 +++-- scripts/sitegen/render.py | 13 +++++++++++++ scripts/sitegen/startwith.py | 4 ++-- scripts/sitegen/structured.py | 4 ++-- tests/test_site_render.py | 10 ++++++++++ 11 files changed, 50 insertions(+), 25 deletions(-) diff --git a/scripts/sitegen/apiitems.py b/scripts/sitegen/apiitems.py index 24c1a5a61..9c91f296a 100644 --- a/scripts/sitegen/apiitems.py +++ b/scripts/sitegen/apiitems.py @@ -11,7 +11,7 @@ from model.systemnames import system_name from model.profiles import is_emulator from sitegen.config import SITE_URL from sitegen.lookup import sorted_hash_values, site_path -from sitegen.render import console_href +from sitegen.render import card_anchor, console_href def system_index_items(db: dict, coverages: dict, profiles: dict) -> list[dict]: @@ -84,7 +84,7 @@ def _first_file_place( parts = str(files[sha1].get("path", "")).split("/") if len(parts) >= 3 and parts[0] == "bios": page = card_page("/".join(parts), sha1) - return parts[1], site_path(f"systems/{page}.md#sha1-{sha1[:12]}") + return parts[1], site_path(f"systems/{page}.md#{card_anchor(sha1)}") for key in sorted(profiles): profile = profiles[key] if is_emulator(profile) and sys_id in (profile.get("systems") or []): diff --git a/scripts/sitegen/cards.py b/scripts/sitegen/cards.py index c35e2e257..e7c3e5ed4 100644 --- a/scripts/sitegen/cards.py +++ b/scripts/sitegen/cards.py @@ -18,7 +18,9 @@ from sitegen import markup, wanted as sitewanted from core.paths import REPO_ROOT from sitegen.fields import search_excluded from sitegen.install import manifest_systems, platform_display -from sitegen.render import code_span, count_text, system_page_map, emulator_card_page +from sitegen.render import ( + SHORT_HASH, card_anchor, code_span, count_text, emulator_card_page, system_page_map, +) def emulator_file_anchors(files: list[dict]) -> list[str]: @@ -452,7 +454,7 @@ def system_file_card( emus = sorted(consumers.emulators.get(sha1_full, ())) installed = _installed_places(sha1_full, consumers, set(plats)) - anchor = f"sha1-{sha1_full[:12]}" if sha1_full != "unknown" else "" + anchor = card_anchor(sha1_full) if sha1_full != "unknown" else "" # A copy filed under two consoles of one maker is listed twice on its # page: the first card holds the anchor, as an id names one element. if anchored is not None: @@ -559,9 +561,6 @@ _CARD_HASHES = ("SHA1", "MD5", "CRC32", "SHA256") # The words a card's fold names its other facts by. _CARD_MORE_WORDS = {"Romset": "romset", "Collection path": "collection path", "Catalogued": "catalogues"} -# A hash shown short, in a card, a platform row or an emulator table: as long -# as the card's own address (sha1-<12 hex>), one length across the site. -SHORT_HASH = 12 def listed_words(words: list[str]) -> str: diff --git a/scripts/sitegen/decorate.py b/scripts/sitegen/decorate.py index 52498fa62..c1551feda 100644 --- a/scripts/sitegen/decorate.py +++ b/scripts/sitegen/decorate.py @@ -16,7 +16,7 @@ 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.diagrams import prepare_page, unresolved_images -from sitegen.render import WIKI_SRC_DIR +from sitegen.render import CARD_ANCHOR, WIKI_SRC_DIR, card_anchor from sitegen.write import undecorated, write_decorated @@ -113,20 +113,20 @@ def front_matter(markdown: str) -> dict: @functools.cache def _sha1_by_prefix(db_path: str) -> dict[str, str]: - return {sha1[:12]: sha1 for sha1 in load_database(db_path)["files"]} + return {card_anchor(sha1): sha1 for sha1 in load_database(db_path)["files"]} def _cards_elsewhere(markdown: str) -> str: """A start line links each file to its card. A console split over part pages keeps its cards on the parts, so a card this page does not hold is reached by its permanent link instead.""" - links = set(re.findall(r"\]\(#(sha1-[0-9a-f]{12})\)", markdown)) + links = set(re.findall(rf"\]\(#({CARD_ANCHOR.pattern})\)", markdown)) away = {ident for ident in links if f'id="{ident}"' not in markdown} if not away: return markdown by_prefix = _sha1_by_prefix(str(siteinputs.current().db)) for ident in away: - full = by_prefix[ident.removeprefix("sha1-")] + full = by_prefix[ident] markdown = markdown.replace(f"](#{ident})", f"]({markup.site_href(f'files/?sha1={full}')})") return markdown diff --git a/scripts/sitegen/emulatorcards.py b/scripts/sitegen/emulatorcards.py index bbe470a11..3e3b345fa 100644 --- a/scripts/sitegen/emulatorcards.py +++ b/scripts/sitegen/emulatorcards.py @@ -20,7 +20,6 @@ from sitegen import markup from sitegen.cards import ( ROMSET_FAQ, SEARCH_SKIPPED, - SHORT_HASH, card_title, listed_words, places_markdown, @@ -41,7 +40,9 @@ from sitegen.install import ( standalone_place, ) from sitegen.render import ( + SHORT_HASH, WIKI_SRC_DIR, + card_anchor, code_span, count_text, escape_tags, @@ -513,7 +514,7 @@ def _card_copy_line( page = card_page(held, sha1) return [ f"Collection copy: [{code_span(held)}]" - f"(../systems/{urllib.parse.quote(page)}.md#sha1-{sha1[:12]})" + f"(../systems/{urllib.parse.quote(page)}.md#{card_anchor(sha1)})" ] if in_repo and not any(d.startswith("Collection copies:") for d in details): copy = held_copy(f) @@ -798,7 +799,7 @@ def _held_copy_line(copy: tuple[str, str], consumers: FileConsumers) -> str: zsha1 = consumers.sha1_at(path) if zsha1 and len(parts) >= 3 and parts[0] == "bios": page = urllib.parse.quote(card_page(path, zsha1)) - archive = f"[{archive}](../systems/{page}.md#sha1-{zsha1[:12]})" + archive = f"[{archive}](../systems/{page}.md#{card_anchor(zsha1)})" return f"Collection copy: member {code_span(member)} of {archive}" if parts[0] == "data" and len(parts) >= 2: ref, inside = parts[1], "/".join(parts[2:]) diff --git a/scripts/sitegen/emulatorpage.py b/scripts/sitegen/emulatorpage.py index e4bbda314..91af04636 100644 --- a/scripts/sitegen/emulatorpage.py +++ b/scripts/sitegen/emulatorpage.py @@ -47,6 +47,7 @@ from sitegen.install import ( from sitegen.lookup import data_directory_origin, data_tree_pages from sitegen.render import ( admonition_body, + card_anchor, code_span, count_text, escape_tags, @@ -238,7 +239,7 @@ def _data_member_table(members: dict[str, dict], names: list[str], anchors: set[ sha1 = str(info.get("sha1", "")) # One id per page: two members can hold the same bytes (every empty # file), and Dolphin's trees share Sys. - anchor = f"sha1-{sha1[:12]}" + anchor = card_anchor(sha1) span = "" if anchor in anchors else f'' anchors.add(anchor) table.append(f"| {span}{code_span(member)} | {size_text(int(info.get('size', 0)))} | {code_span(sha1)} |") @@ -518,7 +519,7 @@ def _collection_card_href(entry: dict, consumers: FileConsumers | None, owner: s held = consumers.path_of(sha1) if sha1 else "" if not held.startswith("bios/"): return "" - return f"../systems/{urllib.parse.quote(card_page(held, sha1))}.md#sha1-{sha1[:12]}" + return f"../systems/{urllib.parse.quote(card_page(held, sha1))}.md#{card_anchor(sha1)}" def _any_name_folder(profile: dict, entry: dict) -> str: diff --git a/scripts/sitegen/lookup.py b/scripts/sitegen/lookup.py index ae941d5d0..9e5607202 100644 --- a/scripts/sitegen/lookup.py +++ b/scripts/sitegen/lookup.py @@ -19,7 +19,7 @@ from packs.crossref import FileConsumers from sitegen.cards import PROVENANCE_LABELS, emulator_card_anchor, emulator_file_anchors from sitegen.config import SITE_URL from core.paths import REPO_ROOT -from sitegen.render import code_span, slugify_anchor, card_page, emulator_card_page +from sitegen.render import card_anchor, code_span, slugify_anchor, card_page, emulator_card_page from sitegen.write import write_if_changed @@ -206,7 +206,7 @@ def file_location_items( if len(parts) < 3 or parts[0] != "bios": continue page = card_page(entry.get("path", ""), sha1) - items.append({"sha1": sha1, "url": site_path(f"systems/{page}.md#sha1-{sha1[:12]}")}) + items.append({"sha1": sha1, "url": site_path(f"systems/{page}.md#{card_anchor(sha1)}")}) # A data directory's files are listed on the page of an emulator reading # the tree: 2,534 hashes the packs ship were found nowhere on the site. owners = _data_member_owners(profiles or {}) @@ -223,7 +223,7 @@ def file_location_items( known.add(sha1) page = page_of.get(member, owners[ref]) items.append({"sha1": sha1, - "url": site_path(f"emulators/{page}.md#sha1-{sha1[:12]}")}) + "url": site_path(f"emulators/{page}.md#{card_anchor(sha1)}")}) return sorted(items, key=lambda item: item["sha1"]) diff --git a/scripts/sitegen/platformfiles.py b/scripts/sitegen/platformfiles.py index d91d94851..972ba1632 100644 --- a/scripts/sitegen/platformfiles.py +++ b/scripts/sitegen/platformfiles.py @@ -14,7 +14,6 @@ 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 import entries as siteentries, markup -from sitegen.cards import SHORT_HASH from sitegen.config import REPO_URL, date_line from core.paths import REPO_ROOT from core.sizes import size_text @@ -32,6 +31,8 @@ from sitegen.parts import ( part_stems, ) from sitegen.render import ( + SHORT_HASH, + card_anchor, code_span, count_text, emulator_link, @@ -104,7 +105,7 @@ def _served_line(f: dict, declared_sha1: str = "") -> str: return f"{label}: {code_span(path)}" # The card of that copy: every hash, provenance and the download. page = urllib.parse.quote(card_page(path, sha1)) - link = f"{label}: [{code_span(path)}](../systems/{page}.md#sha1-{sha1[:12]})" + link = f"{label}: [{code_span(path)}](../systems/{page}.md#{card_anchor(sha1)})" declared = {value.strip().lower() for value in declared_sha1.split(",")} return link if sha1 in declared else f"{link} (sha1 `{sha1[:8]}`)" diff --git a/scripts/sitegen/render.py b/scripts/sitegen/render.py index 588a5dd14..bdb3aea75 100644 --- a/scripts/sitegen/render.py +++ b/scripts/sitegen/render.py @@ -46,6 +46,19 @@ def code_span(value: object) -> str: return "`" + str(value).replace("`", "'") + "`" +# A hash shown short, in a card, a platform row or an emulator table: as long +# as the card's own address (sha1-<12 hex>), one length across the site. +SHORT_HASH = 12 +# A file card's permanent id: published, linked from outside, and read back +# by the site's lookup (model/retired.py keeps a retired one answering). +CARD_ANCHOR = re.compile(rf"sha1-[0-9a-f]{{{SHORT_HASH}}}") + + +def card_anchor(sha1: str) -> str: + """The id of the card a file's sha1 heads: sha1-.""" + return f"sha1-{sha1[:SHORT_HASH]}" + + def count_text(number: int, noun: str, plural: str = "") -> str: """A count and its noun, singular for one: the site printed "1 files" 234 times.""" return f"{number:,} {noun if number == 1 else plural or noun + 's'}" diff --git a/scripts/sitegen/startwith.py b/scripts/sitegen/startwith.py index fd426a8bd..db8cc7ab1 100644 --- a/scripts/sitegen/startwith.py +++ b/scripts/sitegen/startwith.py @@ -27,7 +27,7 @@ from sitegen.consolecards import ( from sitegen.descriptions import said_as_list from sitegen.emulatorcards import region_words from sitegen.install import comes_with_app -from sitegen.render import code_span, count_text, console_anchor +from sitegen.render import card_anchor, code_span, count_text, console_anchor class _StartGroup: @@ -386,7 +386,7 @@ def _link_held_names(line: str, sha1s: dict[str, str], held: set[str]) -> str: the Apple II line named eight files and none was a way to get one.""" def link(match: re.Match) -> str: sha1 = sha1s.get(match[1], "") - return f"[{match[0]}](#sha1-{sha1[:12]})" if sha1 in held else match[0] + return f"[{match[0]}](#{card_anchor(sha1)})" if sha1 in held else match[0] # A name inside a link already (a "Keep it zipped" archive) stays as # is, and so does the name a file is read under, "(as `d2fdc.zip`)". return re.sub(r"(? dict: sha1 = str(entry.get("sha1") or "") part: dict = {"@type": "CreativeWork", "name": str(entry.get("name", ""))} if sha1: - part["url"] = urllib.parse.urljoin(SITE_URL, f"systems/{slug}/#sha1-{sha1[:12]}") + part["url"] = urllib.parse.urljoin(SITE_URL, f"systems/{slug}/#{card_anchor(sha1)}") identifiers = [ f"{field}:{str(entry[field]).lower()}" for field in ("sha1", "md5", "crc32", "sha256") if entry.get(field) diff --git a/tests/test_site_render.py b/tests/test_site_render.py index dbbe31b00..18ad9eec0 100644 --- a/tests/test_site_render.py +++ b/tests/test_site_render.py @@ -169,6 +169,16 @@ class StructuredBlocks(unittest.TestCase): self.assertIn("end.", page) +class CardAnchorsKeepTheirPublishedForm(unittest.TestCase): + """files/?sha1= and #sha1-<12> addresses are published: the id written + and the pattern that reads it back are one format.""" + + def test_the_anchor_reads_back(self): + sha1 = "0123456789abcdef0123456789abcdef01234567" + self.assertEqual(siterender.card_anchor(sha1), "sha1-0123456789ab") + self.assertTrue(siterender.CARD_ANCHOR.fullmatch(siterender.card_anchor(sha1))) + + class FileCardsLinkTheReadingEntry(unittest.TestCase): def test_an_emulator_link_lands_on_its_entry(self): """The platform links landed on their section, the emulator links on