"""A platform's file reference: each system's rows, roles and checks.""" from __future__ import annotations import functools import html import json import re import urllib.parse 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 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 from sitegen.fields import hash_spans, search_excluded from sitegen.parts import ( PAGE_BYTES, PAGE_ELEMENTS, PLATFORM_PART_BUDGET, PLATFORM_REFERENCE_BUDGET, PLATFORM_SECTION_BUDGET, blocks_in_runs, character_count, parent_front_matter, ) from sitegen.render import ( code_span, count_text, emulator_link, escape_tags, card_page, console_href, ) def _collection_sha1(path: str) -> str: """The sha1 of the file the collection holds at a path.""" return sha1_at(_collection_db(str(siteinputs.current().db)), path) or "" @functools.cache def _collection_db(db_path: str) -> dict: return load_database(db_path) def _system_heading_link(sys_id: str, prefix: str = "") -> str: """A system's name, linked to its own console section when it has one. The id stays beside it in small text: it is what the platform's list writes. A system with no section of its own is named, never sent to the page a storage folder chose. """ return f"{_system_named_link(sys_id, prefix)} {escape_tags(sys_id)}" def _system_named_link(sys_id: str, prefix: str = "") -> str: """A system's name, linked to the section system_section gives.""" from sitegen.render import system_section name = escape_tags(system_name(sys_id)) section = system_section(sys_id) if section is not None: slug, console = section name = f"[{name}]({console_href(slug, console, prefix)})" return name def emulator_named_link(key: str, prefix: str = "") -> str: """An emulator by the name its page carries, linked to that page. A profile with no page (an alias, a test) is named only.""" profile = profiles_on_disk().get(key, {}) label = escape_tags(str(profile.get("emulator") or key)) if not is_emulator(profile): return label return f"[{label}]({prefix}emulators/{key}.md)" def _served_line(f: dict, declared_sha1: str = "") -> str: """Which collection file answers the entry, from the resolver's result. "OK" with no path gave an expert nothing to check: Batocera's scph1001.bin is served by bios/Sony/PlayStation/scph1001_v20.bin. The copy's sha1 is named only when it is not one the row already declares (Recalbox joins several with commas). """ path = str(f.get("path") or "") if f.get("status") == "missing": return "Not held" if not path: # A slot the pack fills from a release asset or leaves to the user. return "" sha1 = _collection_sha1(path) label = "Served by" if f.get("status") == "ok" else "Held, not the declared hash" parts = path.split("/") if not sha1 or len(parts) < 3 or parts[0] != "bios": 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]})" declared = {value.strip().lower() for value in declared_sha1.split(",")} return link if sha1 in declared else f"{link} (sha1 `{sha1[:8]}`)" def _launcher_refs(config: dict) -> dict[str, list[str]]: """Entry name, casefolded -> each launcher record that opens it, rendered.""" from resolve.launchers import record_names as launcher_names from resolve.launchers import bound_launchers from sitegen.sources import launcher_ref_markdown, list_source # Every scraper reads its launchers in the repository and at the revision # of the list it scrapes, so `source` pins each source_ref. A record a # config file does not prove opens nothing: it is listed apart. source = list_source(str(config.get("source") or "")) found: dict[str, list[str]] = {} for record in bound_launchers(config): if not isinstance(record, dict) or not record.get("source_ref"): continue text = (f"{escape_tags(str(record.get('emulator', '')))} at " f"{launcher_ref_markdown(source, str(record['source_ref']))}") for name in launcher_names(record): names = found.setdefault(name.rsplit("/", 1)[-1].casefold(), []) if text not in names: names.append(text) return found UNPROVEN_TITLE = "Launcher records a config does not prove" def launcher_unproven_section(config: dict) -> list[str]: """The platform's launcher records resting on a config the code does not prove. A config file is proof only when the code installing it and the code reading it are shown: these records place no file. """ from resolve.launchers import launcher_unproven from sitegen.sources import launcher_ref_markdown, list_source rows = launcher_unproven({str(config.get("_key") or ""): config}) if not rows: return [] source = list_source(str(config.get("source") or "")) body = [ f"- {escape_tags(row['emulator'])}, `{escape_tags(row['passes_to'] or row['kind'])}` " f"at {launcher_ref_markdown(source, row['source_ref'])}: " f"{escape_tags('; '.join(row['missing']))}" for row in rows ] return ["", *markup.details("note", f"{UNPROVEN_TITLE} ({len(rows)})", body)] # The hash a row shows first, when the list does not say which it checks. _ROW_HASHES = ("sha1", "md5", "sha256", "crc32") # An untested entry whose reason is a hash the bytes do not match. _OTHER_HASH = re.compile(r"hash|mismatch|expected|must match", re.IGNORECASE) # A list this long gets a filter box above it, as a table of RECORD_ROWS # rows does (website/src/plugins/rehype-stack-tables.mjs). FILTER_ROWS = 20 def _status_chip(f: dict) -> str: """The row's status as a chip, its word and its colour saying the same. A declared hash the held copy does not have is "Other hash": the two differ, which says nothing of whose is right (a platform may pin its own bundle).""" status = f.get("status") if status == "ok": word, tone = "OK", "success" elif status == "missing": word, tone = "Missing", "danger" elif status == "untested": word = "Other hash" if _OTHER_HASH.search(str(f.get("reason") or "")) else "Untested" tone = "warning" else: word, tone = str(status), "muted" return f'{html.escape(word)}' def _copy_hash(algorithm: str, value: str | list) -> str: """A declared hash cut to SHORT_HASH characters on a button that copies it whole. A list of accepted values (Recalbox) copies its first. Outside a form a button submits nothing, so it carries no type.""" from core.hashing import parse_hash_list values = parse_hash_list(value) if not values: return "" first = html.escape(values[0]) more = f" +{len(values) - 1}" if len(values) > 1 else "" return (f'') # Characters Markdown or MDX would read inside the raw HTML of a row: an # MDX page parses the text of its HTML as Markdown, a .md page does not. _INERT = str.maketrans({"*": "*", "_": "_", "`": "`", "[": "[", "]": "]"}) _INLINE_MD = re.compile( r"\[(?P