refactor: write card anchors through one helper

This commit is contained in:
Abdessamad Derraz committed 2026-11-21 06:03:21 +01:00
1 parent 4e67868e11
commit 4585e3ffea
11 files changed
+50 -25

No files matched your search

+2 -2
View File
@@ -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 []):
+4 -5
View File
@@ -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:
+4 -4
View File
@@ -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
+4 -3
View File
@@ -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:])
+3 -2
View File
@@ -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'<span id="{anchor}"></span>'
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:
+3 -3
View File
@@ -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"])
+3 -2
View File
@@ -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]}`)"
+13
View File
@@ -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-<first 12 hex>."""
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'}"
+2 -2
View File
@@ -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"(?<!\[)(?<!\(as )`([^`]*)`(?!\]\()", link, line)
+2 -2
View File
@@ -17,7 +17,7 @@ from sitegen.descriptions import EMULATOR_SNIPPETS, NOTHING_TO_FETCH, PAGE_DATA,
from sitegen.emulatorcards import snippet_noun
from sitegen.install import comes_with_app
from sitegen.lookup import data_member_digests, sorted_hash_values
from sitegen.render import system_page_map
from sitegen.render import card_anchor, system_page_map
from sitegen.write import write_if_changed
@@ -142,7 +142,7 @@ def system_structured_data(slug: str, consoles: dict[str, list]) -> 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)
+10
View File
@@ -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