refactor: site commands keep only their options

This commit is contained in:
Abdessamad Derraz committed 2026-11-18 19:31:27 +01:00
1 parent 206dae3163
commit 231002a7c0
49 files changed
+4354 -4290

No files matched your search

+7 -7
View File
@@ -1521,20 +1521,20 @@ def check_source_paths(profiles: dict) -> Finding:
or a pinned tree the record lacks, means a pin moved or a profile was
added and `sitesources.py --fetch` was not run after it. Every tree a run
tries is recorded, read or not, so a lacking one was never tried."""
import sitesources
from sitegen import sources as sitegen_sources
pinned = {
sitesources.tree_key(repo, pin)
for profile in profiles.values() if sitesources.cited_paths(profile)
for repo, pin in sitesources.profile_trees(profile)
sitegen_sources.tree_key(repo, pin)
for profile in profiles.values() if sitegen_sources.cited_paths(profile)
for repo, pin in sitegen_sources.profile_trees(profile)
} | {
# The platform build files pin_build names, linked from a page too.
sitesources.tree_key(repo, pin)
sitegen_sources.tree_key(repo, pin)
for profile in profiles.values()
for repo, pin, _path in sitesources.build_files(profile)
for repo, pin, _path in sitegen_sources.build_files(profile)
}
try:
recorded = set(json.loads(sitesources.SOURCE_PATHS.read_text(encoding="utf-8")))
recorded = set(json.loads(sitegen_sources.SOURCE_PATHS.read_text(encoding="utf-8")))
except (OSError, ValueError) as exc:
return Finding("profiles", "source-paths.json", ERROR, detail=str(exc))
orphaned = sorted(recorded - pinned)
+2 -970
View File
@@ -11,968 +11,13 @@ Usage:
from __future__ import annotations
import argparse
import json
import os
import re
import sys
from collections.abc import Callable
from datetime import datetime, timezone
from pathlib import Path
from types import ModuleType
sys.path.insert(0, os.path.dirname(__file__))
from core.cli import InputMissing
from model.composition import compute_composition, count_catalog_matched
from model.declarations import declared_root
from core.github import github_token
from model.registry import list_registered_platforms, load_platform_registry
from model.database import load_database
from model.profiles import load_emulator_profiles, unique_emulator_profiles
from model.platforms import load_platform_config
from core.artifacts import repository_output_lock, write_if_changed
from resolve.cores import resolve_platform_cores
from model.systems import system_index
import archive_build
import release_record
from model.guides import PACKAGE_COMMAND, install_command
from resolve.review import LARGE_FILE_ISSUE_URL
from model.largefiles import LARGE_FILES_CACHE, load_registered_paths
import pr_checks
from packs.coverage import verify_platform
from core.paths import REPO_ROOT
def _installer_words() -> ModuleType:
"""install.py read as a module, for the words its screen shows: the
README named a line menu the one-liner never opens."""
import importlib.util
path = REPO_ROOT / "install.py"
spec = importlib.util.spec_from_file_location("install", path)
if spec is None or spec.loader is None:
raise ImportError(f"cannot load {path}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
# The repository's profiles wherever the script is run from: a bare
# "emulators" read the working directory, and a run elsewhere counted 0 cores.
_EMULATORS_DIR = str(REPO_ROOT / "emulators")
def compute_coverage(
platform_name: str,
platforms_dir: str,
db: dict,
data_registry: dict | None = None,
emulators_dir: str = _EMULATORS_DIR,
) -> dict:
config = load_platform_config(platform_name, platforms_dir)
result = verify_platform(
config,
db,
emulators_dir,
data_dir_registry=data_registry,
)
sc = result.get("status_counts", {})
ok = sc.get("ok", 0)
untested = sc.get("untested", 0)
missing = sc.get("missing", 0)
total = result["total_files"]
# An UNTESTED file the builder refuses (its declared hash contradicted on
# a hash platform) is held, not packed.
present = ok + untested - len(result.get("excluded_files", []))
pct = (present / total * 100) if total > 0 else 0
undeclared = result.get("undeclared_files", [])
# Held is not packed: a file the platform has no folder for, or one below
# a folder it lists flat, stays out of the pack the fraction describes.
core_present = sum(
1 for u in undeclared if u.get("in_repo") and u.get("in_pack", True)
)
core_missing = len(undeclared) - core_present
# Files a profile marks unsourceable never reach the undeclared list, so
# the gap they represent has to be counted back in.
profiles = load_emulator_profiles(emulators_dir)
unsourceable_names = {
f.get("name", "")
for emu in resolve_platform_cores(config, profiles)
for f in (profiles.get(emu) or {}).get("files", []) or []
if f.get("unsourceable")
}
core_unsourceable = len(unsourceable_names)
missing_names = unsourceable_names | {
u.get("name", "") for u in undeclared if not u.get("in_repo")
}
return {
"platform": config.get("platform", platform_name),
"total": total,
"verified": ok,
"untested": untested,
"missing": missing,
"missing_not_firmware": {
category: len(dests)
for category, dests in (result.get("missing_not_firmware") or {}).items()
},
"present": present,
"percentage": pct,
"core_present": core_present,
"core_missing": core_missing,
"core_unsourceable": core_unsourceable,
"missing_names": missing_names,
"unsourceable_names": unsourceable_names,
"pack_files": present + core_present,
"total_missing": missing + core_missing,
"mode": config.get("verification_mode", "existence"),
"details": result["details"],
"config": config,
"ground_truth": result.get(
"ground_truth_coverage",
{"with_validation": 0, "platform_only": total, "total": total},
),
}
_REPO = REPO_ROOT
# The site and the README read the same coverage: the first generator to run
# stores it here and the second reads it back, instead of verifying every
# platform twice (about a minute of the site build).
COVERAGE_CACHE_DIR = _REPO / "tmp" / "coverage-cache"
_COVERAGE_CACHE_FORMAT = "3"
def _coverage_inputs(db_path: Path, platforms_dir: str, emulators_dir: str) -> str:
"""A digest of everything coverage is computed from.
The database, the platform and emulator files, the code, the install
manifests, the data directory revisions, the state of bios/ on disk, and
what a release asset resolves to: the large-file cache and whether this
run may download. A test run is offline with its own cache, and its
result was read back by the next normal run (Lakka 534/535 for 535/535).
A change to any of them computes the coverage again.
"""
import hashlib
digest = hashlib.sha256(_COVERAGE_CACHE_FORMAT.encode())
def add_file(path: Path) -> None:
digest.update(str(path).encode() + b"\0")
digest.update(path.read_bytes() if path.is_file() else b"<absent>")
add_file(db_path.resolve())
for root, pattern in ((Path(platforms_dir), "*"), (Path(emulators_dir), "*.yml"),
(_REPO / "scripts", "*.py"), (_REPO / "install", "*.json"),
(_REPO / "recipes", "*.json")):
for path in sorted(p for p in root.resolve().rglob(pattern) if p.is_file()):
add_file(path)
for path in (_REPO / ".gitignore", _REPO / "_mame_clones.json",
_REPO / "data" / ".versions.json"):
add_file(path)
digest.update(b"offline\0" + (b"1" if os.environ.get("RETROBIOS_OFFLINE") else b"0") + b"\n")
large = Path(LARGE_FILES_CACHE).resolve()
digest.update(str(large).encode() + b"\0")
for path in sorted(large.glob("*")) if large.is_dir() else ():
if path.is_file():
stat = path.stat()
digest.update(f"{path.name}\0{stat.st_size}\0{stat.st_mtime_ns}\n".encode())
bios = _REPO / "bios"
for path in sorted(bios.rglob("*")):
if path.is_file():
stat = path.stat()
digest.update(f"{path.relative_to(bios)}\0{stat.st_size}\0{stat.st_mtime_ns}\n".encode())
return digest.hexdigest()
def platform_coverages(
platform_names: list[str],
platforms_dir: str,
db: dict,
data_registry: dict | None = None,
emulators_dir: str = _EMULATORS_DIR,
db_path: str = "database.json",
report: Callable[[str, dict], None] | None = None,
) -> dict[str, dict]:
"""compute_coverage for each platform, read from the cache when its
inputs have not changed since a generator last stored it.
A platform with no YAML is left out, as compute_coverage raises for it.
``report`` is called with each platform and its coverage.
"""
# pickle, not JSON: the coverage holds sets and enums that JSON would
# turn into lists and strings. The file is written by this function into
# the repository's own tmp/, never downloaded.
import pickle
key = _coverage_inputs(Path(db_path), platforms_dir, emulators_dir)
names = sorted(platform_names)
cache = COVERAGE_CACHE_DIR / f"{key}.pickle"
coverages: dict[str, dict] | None = None
if cache.is_file():
try:
with cache.open("rb") as handle:
stored = pickle.load(handle)
except (OSError, EOFError, pickle.UnpicklingError) as exc:
print(f" coverage cache unreadable, computing again: {exc}", file=sys.stderr)
else:
if stored.get("platforms") == names:
coverages = stored["coverages"]
print(f" coverage read from {cache.relative_to(_REPO)}")
if coverages is None:
coverages = {}
for name in names:
try:
coverages[name] = compute_coverage(
name, platforms_dir, db, data_registry, emulators_dir=emulators_dir,
)
except InputMissing:
# A missing profile or platform directory is no platform
# left out: it emptied every one and cached the result.
raise
except FileNotFoundError as exc:
print(f" {name}: skipped ({exc})", file=sys.stderr)
COVERAGE_CACHE_DIR.mkdir(parents=True, exist_ok=True)
scratch = cache.with_suffix(f".{os.getpid()}.tmp")
with scratch.open("wb") as handle:
pickle.dump({"platforms": names, "coverages": coverages}, handle,
protocol=pickle.HIGHEST_PROTOCOL)
scratch.replace(cache)
# generate_site and generate_readme both purge here. One unlinking
# what the other had just listed ended it on FileNotFoundError.
for stale in COVERAGE_CACHE_DIR.glob("*.pickle"):
if stale != cache:
stale.unlink(missing_ok=True)
ordered = {name: coverages[name] for name in platform_names if name in coverages}
if report:
for name in names:
if name in ordered:
report(name, ordered[name])
return ordered
def release_totals(platform_name: str, record: dict) -> tuple[int | None, int | None]:
"""Files and bytes of the pack the latest release serves for a platform.
The Download link gives that release, so these are the figures a reader
can check against an extraction. The install manifests describe what
main would build today, which is a different pack as soon as a commit
lands after the release. Returns (None, None) for a platform the release
carries no pack for.
"""
pack = release_record.pack_for(platform_name, record)
if not pack:
return None, None
return pack["files"], pack["extracted_size"]
NO_PACK = "Use the command"
def asset_links(
platform_name: str, record: dict, repo: str, label: str, attrs: str = "",
button: Callable[[str, str], str] | None = None,
) -> str:
"""Markdown links to the files of a platform's pack in the recorded release.
Written on the platform's get/ page only: every other surface links that
page, whose address does not change with the release. A pack published
whole gets one link labelled *label*. A pack in parts gets one link per
part, since every part is needed, after the number of files to download:
a reader who took one link for the pack extracted half of it. *repo* is
the repository URL, *attrs* an attribute list put after each link, or
*button* the function that draws each link as a button. Without a
recorded release the link is the latest release page.
"""
pack = release_record.pack_for(platform_name, record)
tag = record.get("tag")
assets = pack.get("assets") if pack else None
def link(text: str, url: str) -> str:
return button(text, url) if button else f"[{text}]({url}){attrs}"
if not tag or not assets:
return link(label, f"{repo}/releases/latest")
urls = [f"{repo}/releases/download/{tag}/{asset}" for asset in assets]
if len(urls) == 1:
return link(label, urls[0])
styled = bool(attrs or button)
parts = [
link(f"{'P' if styled else 'p'}art {number} of {len(urls)}", url)
for number, url in enumerate(urls, 1)
]
if styled:
return f"{len(urls)} files to download, all needed: " + " ".join(parts)
return f"{label}, {len(urls)} files, all needed: " + ", ".join(parts)
def download_links(
platform_name: str, record: dict, label: str, attrs: str = "",
button: Callable[[str, str], str] | None = None,
site: str = "", platforms_dir: str = "platforms", page: str | None = None,
) -> str:
"""The download cell of a platform: its permanent get/ page.
*record* is the release record reduced to the release_pack platforms
(release_record.advertised). A platform with a pack in it gets *label*
linked to its page, which lists the files of the current release. A
platform marked release_pack but missing from the release, added since,
gets "No ZIP yet". Any other platform is served by the installer, and
the cell says so instead of staying empty. *site* is the site root the
get/ address hangs from, or *page* the address itself as the site links
it, and *attrs* and *button* style the link.
"""
page = page or release_record.get_page(platform_name, site)
def link(text: str) -> str:
return button(text, page) if button else f"[{text}]({page}){attrs}"
if (load_platform_registry(platforms_dir).get(platform_name) or {}).get("release_pack") is not True:
return link(NO_PACK)
pack = release_record.pack_for(platform_name, record)
if record.get("tag") and not (pack and pack.get("assets")):
return f"No ZIP yet: {link(NO_PACK.lower())}"
return link(label)
def extract_targets(platforms_dir: str) -> list[tuple[str, str]]:
"""(display name, folder) per registered platform, where its pack extracts.
Read from the registry so the README, the site and the pack guide answer
from one place. Sorted by display name.
"""
rows = [
(load_platform_config(key, platforms_dir).get("platform", key), entry["extract_to"])
for key, entry in load_platform_registry(platforms_dir).items()
if entry.get("extract_to")
]
return sorted(rows, key=lambda row: row[0].casefold())
def own_root(config: dict) -> str:
"""The folder a pack written from an empty base_destination starts with.
RetroDECK writes bios/ in front of its files, the MinUI family hands its
cores folders below Bios/.
"""
root = declared_root(config)
if root:
return root
tops = {directory.split("/", 1)[0] for directory in config.get("core_system_dirs") or {}}
return tops.pop() if len(tops) == 1 else "bios"
def extract_notes(platforms_dir: str, released_only: bool = False) -> list[str]:
"""A pack whose entries carry their own root extracts above the BIOS folder.
*released_only* keeps the platforms a release publishes a pack for.
"""
folders = dict(extract_targets(platforms_dir))
registry = load_platform_registry(platforms_dir)
notes = []
for key in sorted(registry):
if released_only and registry[key].get("release_pack") is not True:
continue
config = load_platform_config(key, platforms_dir)
display = config.get("platform", key)
if config.get("base_destination") == "" and display in folders:
notes.append(
f"The {display} pack holds its own `{own_root(config)}/` folder."
f" Unzip it into `{folders[display]}`."
)
return notes
def _extract_cells(platforms_dir: str) -> dict[str, str]:
"""The download table's "Extract to" cell, by display name."""
return {display: f"`{folder}`" for display, folder in extract_targets(platforms_dir)}
def _paragraphs(texts: list[str]) -> list[str]:
return [line for text in texts for line in ("", text)]
def download_table(
coverages: dict,
extract_paths: dict[str, str],
record: dict,
) -> list[str]:
"""One row per platform: what its released pack holds and where it extracts."""
lines = [
"| Platform | Files | Extracted size | Extract to | Download |",
"|----------|------:|---------------:|-----------|----------|",
]
for name, cov in sorted(coverages.items(), key=lambda x: x[1]["platform"]):
files, size = release_totals(name, record)
lines.append(
f"| {cov['platform']} | {f'{files:,}' if files else '-'} |"
f" {format_size(size) if size else '-'} |"
f" {extract_paths.get(cov['platform'], '')} |"
f" {download_links(name, record, 'Download', site=SITE_URL)} |"
)
return lines
def no_pack_line() -> str:
"""Why some rows read "Use the command", in one sentence."""
return (
"ZIPs are made for the setups most people download. The others read"
f" \"{NO_PACK}\": the installer above installs every file for them and"
" checks each one, and `--dry-run` shows what it would install"
f" ([why no ZIP]({SITE_URL}wiki/faq/#why-is-there-no-zip-for-my-setup))."
)
def _names_list(coverages: dict) -> str:
"""The platforms' names in reading order, the last after "and"."""
names = sorted(c["platform"] for c in coverages.values())
return ", ".join(names[:-1]) + f", and {names[-1]}" if len(names) > 1 else "".join(names)
def collection_line(total_files: int, comp: dict) -> str:
"""The size of the whole collection, said as such.
Printed bare beside the download links it read as the content of one
pack, and a complete extraction looked like a broken one.
"""
return (
f"- **{total_files:,} files in the collection**, each with its SHA1,"
" MD5, SHA256, CRC32 and Adler-32 fingerprints:"
f" {comp['systems']['files']:,} system files,"
f" {comp['arcade']['files']:,} arcade ROM sets,"
f" {comp['game_data']['files']:,} game and engine data files."
" That is every platform and emulator together, so no pack holds"
" them all: each carries what its own emulators load, counted in"
" the download table"
)
def format_size(size: int) -> str:
"""Human-readable pack size."""
if size >= 1024**3:
return f"{size / 1024**3:.1f} GB"
return f"{size / 1024**2:.0f} MB"
SITE_URL = "https://abdess.github.io/retrobios/"
# The installer demo (scripts/make_demo.py): the recording and what it shows.
DEMO_DIR = REPO_ROOT / "docs_assets" / "demo"
DEMO_GIF = "docs_assets/demo/install.gif"
REPO_PATH = "../.."
REPO = "Abdess/retrobios"
# GitHub's "Add file > Upload files" page for bios/: a browser upload by
# someone without write access lands on a fork and opens a pull request.
UPLOAD_URL = f"https://github.com/{REPO}/upload/main/bios"
def clone_line(db: dict) -> str:
"""How to get the clone the commands below run in, and its size.
Said bare, "clone the repo" started a multi-gigabyte transfer for a user
after a 20 MB --required-only pack. The size counts the collection files
the repository commits, a floor: release assets are fetched only when a
pack needs them.
"""
assets = set(load_registered_paths())
committed = sum(
entry.get("size", 0) for entry in db.get("files", {}).values()
if entry.get("path") not in assets
)
return (
"Packs are built from a clone, and the clone carries the collection:"
f" its checkout alone is over {format_size(committed)}."
f" `git clone --depth 1 https://github.com/{REPO}.git` leaves the"
" history out. Files kept as release assets are downloaded when a"
" pack needs them. Then generate packs for any platform, emulator,"
" or system:"
)
def demo_facts(variant: str = "default") -> dict:
"""What an installer demo shows, as make_demo.py measured it: one entry
per variant (default, handheld)."""
facts = json.loads((DEMO_DIR / "demo.json").read_text(encoding="utf-8"))
return facts[variant]
def demo_description(facts: dict | None = None) -> str:
"""The demo in words, for a reader who cannot see it: the alt text
make_demo.py wrote from what it measured."""
return str((facts or demo_facts())["alt"])
def _existing_contributor_block(readme_path: str = "README.md") -> list[str]:
"""The contributors already published, read back from the file.
The section is the one part of this document that comes from the network.
A refused or rate-limited request used to leave the list empty, which
silently deleted the section from a published README and put the local
result permanently at odds with what the freshness check regenerates.
Keeping what is already there makes an offline run additive-only.
"""
try:
with open(readme_path, encoding="utf-8") as handle:
text = handle.read()
except OSError:
return []
start = text.find("## Contributors")
if start == -1:
return []
rest = text[start:].splitlines()
block = []
for line in rest[1:]:
if line.startswith("## "):
break
block.append(line)
while block and not block[-1].strip():
block.pop()
return ["## Contributors"] + block if block else []
def fetch_contributors() -> list[dict]:
"""Fetch contributors from GitHub API, exclude bots."""
import urllib.error
import urllib.request
url = f"https://api.github.com/repos/{REPO}/contributors"
headers = {"User-Agent": "retrobios-readme/1.0"}
token = github_token()
if token:
headers["Authorization"] = f"token {token}"
try:
req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req, timeout=10) as resp:
data = json.loads(resp.read().decode())
owner = REPO.split("/")[0]
return [
c
for c in data
if not c.get("login", "").endswith("[bot]")
and c.get("type") == "User"
and c.get("login") != owner
]
except (urllib.error.URLError, urllib.error.HTTPError):
return []
_CATALOG_LABELS = {"redump": "Redump", "no-intro": "No-Intro", "tosec": "TOSEC"}
def _catalog_matched_line(db: dict) -> list[str]:
"""Bullet line for files matched to dump-preservation catalogs."""
matched = count_catalog_matched(db)
if not matched:
return []
sources: set[str] = set()
for entry in db.get("files", {}).values():
sources.update(entry.get("provenance") or ())
system_files = compute_composition(db)["systems"]["files"]
labels = ", ".join(_CATALOG_LABELS.get(s, s) for s in sorted(sources))
return [
f"- **{matched:,} of {system_files:,} system files** matched to"
f" dump-preservation catalogs ({labels}). Arcade sets and engine data"
f" fall outside what those catalogs index"
]
# The badge row under the links: (alt text, image, link). A badge earns its
# place by saying what the page does not: the Python floor is in the install
# text, and GitHub cannot name the license of LICENSE, which opens on its scope.
BADGES = (
("PyPI version", "https://img.shields.io/pypi/v/retrobios", "https://pypi.org/project/retrobios/"),
("Validation",
"https://github.com/Abdess/retrobios/actions/workflows/validate.yml/badge.svg?branch=main",
"https://github.com/Abdess/retrobios/actions/workflows/validate.yml"),
)
def badge_row() -> str:
badges = " ".join(f'<a href="{link}"><img src="{image}" alt="{alt}"></a>'
for alt, image, link in BADGES)
return f'<p align="center">{badges}</p>'
def archive_line(counts: dict[str, int]) -> str:
"""The README's line on archive recipes, counted from recipes/archives.json."""
return (f"- **{counts['total']:,} archives**, each with a recipe that rebuilds it from the"
f" ROMs the collection holds: {counts['exact']:,} byte for byte,"
f" {counts['canonical']:,} with the same files inside"
f" ([rebuilding an archive]({SITE_URL}wiki/archive-recipes/))")
def generate_readme(db: dict, platforms_dir: str, db_path: str = "database.json") -> str:
total_files = db.get("total_files", 0)
ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
platform_names = list_registered_platforms(platforms_dir)
from model.registry import load_data_dir_registry
data_registry = load_data_dir_registry(platforms_dir)
coverages = platform_coverages(platform_names, platforms_dir, db, data_registry,
db_path=db_path)
profiles = unique_emulator_profiles(
load_emulator_profiles("emulators", skip_aliases=False)
)
emulator_count = len(profiles)
profile_files = [f for prof in profiles.values() for f in prof.get("files") or []
if isinstance(f, dict)]
# A citation counts when it names a line, `file.c:120`: a bare file name
# or a binary offset does not point at the code that reads the file.
cited_share = (round(100 * sum(1 for f in profile_files
if re.search(r"\.\w+:\d", str(f.get("source_ref") or "")))
/ len(profile_files)) if profile_files else 0)
closed_count = sum(1 for prof in profiles.values()
if str(prof.get("upstream") or "").startswith("closed"))
system_ids = system_index(profiles)
# The README is the repository's front page and its most read page: a
# visitor from a search lands here, often new to terminals. It says what
# the project does, gives the one line that installs, shows it, and leads
# on to the site, where every detail lives. The figures and the lists it
# once carried (coverage, collection, build commands) are the site's.
record = release_record.load_advertised(platforms_dir=platforms_dir)
extract_paths = _extract_cells(platforms_dir)
released = [name for name in sorted(coverages, key=lambda n: coverages[n]["platform"])
if release_totals(name, record)[0]]
lines = [
'<p align="center">',
" <picture>",
' <source media="(prefers-color-scheme: dark)" srcset=".github/assets/banner-dark.svg">',
' <img src=".github/assets/banner-light.svg" alt="RetroBIOS" width="400">',
" </picture>",
"</p>",
"",
'<p align="center"><strong>The BIOS files emulators need, put in the right folder and checked.</strong></p>',
"",
'<p align="center">'
f'<a href="{SITE_URL}">Website</a> · '
f'<a href="{SITE_URL}which-pack/">Get the files</a> · '
f'<a href="{SITE_URL}wiki/troubleshooting/">A game does not start</a> · '
f'<a href="{SITE_URL}wiki/faq/">Questions</a>'
"</p>",
"",
badge_row(),
"",
"Some consoles need a small program, the **BIOS**, to start their games: PlayStation 1"
" and 2, Saturn, Neo Geo, Dreamcast and more. RetroBIOS installs the BIOS and firmware"
f" files for {_names_list(coverages)}, checked the way each one checks them.",
"",
"## Install in one line",
"",
"**Windows**: open the Start menu, type **PowerShell** and open it. Paste this line"
" (Ctrl+V or right-click in the window) and press Enter.",
"",
"```powershell",
install_command("powershell"),
"```",
"",
"**Linux, macOS, Steam Deck, Android (Termux)**: open a terminal, paste this line"
" and press Enter.",
"",
"```bash",
install_command("sh"),
"```",
"",
f"**With Python 3.8 or newer**: `{PACKAGE_COMMAND}` runs the same installer, and so"
" does `pipx run retrobios`.",
"",
f"**A handheld, an SD card, or not sure?** [Pick the device]({SITE_URL}which-pack/):"
" its page gives the folder and the command. A muOS, Onion, spruceOS, MinUI, KNULLI,"
" ROCKNIX, Lakka or MiSTer SD card plugged into the computer is found by itself.",
"",
f"![{demo_description()}]({DEMO_GIF})",
"",
"The installer finds the setup and its BIOS folder, installs the files it needs (only"
" what the games need when it finds them on the card) and checks each one. Its screen"
" installs everything, or fewer under **" + _installer_words().TUI_SYSTEMS_ROW + "**."
" Arrow keys and Enter drive it, or a controller on a handheld. It sends no report of"
f" its own ([what is counted]({SITE_URL}wiki/privacy/)). Options go after the line in the"
f" form the [installer page]({SITE_URL}wiki/installer/#passing-options) gives.",
"",
f"First time? [The first install, step by step]({SITE_URL}wiki/first-install/)."
f" A game does not start: [what to check]({SITE_URL}wiki/troubleshooting/)."
f" Other questions: [FAQ]({SITE_URL}wiki/faq/).",
"",
"## Or download a ZIP",
"",
"The Files column counts what a pack holds once unzipped.",
"",
"| Setup | Files | Size | Unzip into | Download |",
"|-------|------:|-----:|------------|----------|",
]
for name in released:
files, size = release_totals(name, record)
display = coverages[name]["platform"]
lines.append(
f"| {display} | {files:,} | {format_size(size) if size else '-'} |"
f" {extract_paths.get(display, '')} |"
f" {download_links(name, record, 'Download', site=SITE_URL)} |"
)
others = [name for name in sorted(coverages, key=lambda n: coverages[n]["platform"])
if name not in released]
lines.extend([
"",
"ZIPs are made for the setups most people download. The others install with the line"
" above, and each page gives the command: "
+ ", ".join(f"[{coverages[name]['platform']}]({SITE_URL}get/{name}/)" for name in others)
+ ".",
"",
"Unzip into the BIOS folder, files straight in it. A big pack comes in parts"
" (`Pack.part1of2.zip`): download every part"
f" ([why some setups have no ZIP]({SITE_URL}wiki/faq/#why-is-there-no-zip-for-my-setup))."
" Each release lists its files' SHA-256 with a signature"
f" ([verifying a release]({SITE_URL}wiki/release-process/#verifying-a-release)).",
"",
"## Help",
"",
f"- \"BIOS missing\" or a game does not start: [what to check]({SITE_URL}wiki/troubleshooting/)",
f"- Have a file? [Check it by its hash]({SITE_URL}files/)",
f"- Every console and the files it needs: [systems]({SITE_URL}systems/)",
f"- Asking an AI assistant: it reads the site best from [llms.txt]({SITE_URL}llms.txt)",
"",
"## How it is built",
"",
f"- **{emulator_count} emulators profiled**, {emulator_count - closed_count} from their"
f" source code and {closed_count} closed-source builds from their binaries:"
f" {cited_share}% of the files they load cite the file and line that reads them",
f"- **{len(coverages)} setups**, each checked its own way: MD5 for Batocera and Recalbox,"
" the file name for RetroArch, as their own code does",
f"- **{len(system_ids)} systems**, {total_files:,} files in the collection,"
f" [what is still missing]({SITE_URL}gaps/) named file by file",
archive_line(archive_build.rebuild_counts()),
f"- Public data: [JSON, CSV and SQLite]({SITE_URL}data/), the metadata under MIT",
"",
"<details>",
"<summary><strong>For developers: build a pack</strong></summary>",
"",
clone_line(db),
"",
"```bash",
"python scripts/generate_pack.py --platform retroarch --output-dir dist/",
"python scripts/generate_pack.py --emulator dolphin",
"python scripts/generate_pack.py --platform batocera --required-only",
"python scripts/verify.py --platform batocera",
"```",
"",
"Requires Python 3.9 or newer and `pyyaml`. The one-line installer alone runs on Python 3.8."
f" Every tool and option: [tools]({SITE_URL}wiki/tools/). How the lists are built:"
f" [architecture]({SITE_URL}wiki/architecture/).",
"",
"</details>",
"",
])
contributors = fetch_contributors()
if not contributors:
# The request failed. Republish what is already there rather than
# dropping the section: losing it is a worse answer than a stale list.
kept = _existing_contributor_block("README.md")
if kept:
print("contributors: request failed, keeping the published list")
lines.extend(kept + [""])
if contributors:
lines.extend(
[
"## Contributors",
"",
]
)
for c in contributors:
login = c["login"]
avatar = c.get("avatar_url", "")
url = c.get("html_url", f"https://github.com/{login}")
lines.append(
f'<a href="{url}"><img src="{avatar}" width="50" alt="{login}"'
f' title="{login}"></a>'
)
lines.append("")
lines.extend(
[
"",
"## Community tools",
"",
"- [BIOS Preservation Tool](https://github.com/monster-penguin/BIOS-Preservation-Tool)"
" by [monster-penguin](https://github.com/monster-penguin)"
" - scans, verifies and stages a BIOS collection"
" using RetroBIOS hash metadata",
"",
"## Contributing",
"",
"See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.",
"",
"## License",
"",
"The scripts and tooling are released under the [MIT License](LICENSE).",
"The BIOS and firmware files are not covered by that license: they are"
" third-party system software, preserved and provided for personal"
" backup, archival, and interoperability with emulation software."
" [NOTICE](NOTICE) sets out their status and how to ask for a file"
" to be removed.",
f"The reasoning, and where it is weakest, is in"
f" [the project's legal position]({SITE_URL}wiki/legal/).",
"",
f"*Auto-generated on {ts}*",
]
)
return "\n".join(lines) + "\n"
def ci_install_lines() -> tuple[str, str]:
"""The pip lines the test job of validate.yml runs, verbatim.
The guide listed the packages without their versions, so a local run
could pass on releases CI never installs. Read from the workflow, the
two cannot disagree. The second line is the Python 3.8 one.
"""
text = (_REPO / ".github" / "workflows" / "validate.yml").read_text(encoding="utf-8")
main = re.search(r'^\s*run: (pip install pyyaml "jsonschema.*markdown.*)$', text, re.M)
floor = re.search(r"^\s*run: (python3\.8 -m pip install .*)$", text, re.M)
if main is None or floor is None:
raise RuntimeError("validate.yml no longer installs the packages CONTRIBUTING quotes")
return main.group(1), floor.group(1)
def contributing_text(
link: Callable[[str], str], title: str, site_words: str
) -> str:
"""The contribution guide, one text for the repository and the site.
Two copies drifted apart: four steps to add a platform here, five on the
site. *link* renders a site page (absolute URL for the README, relative
.md for the site); *site_words* names the site from where the text is read.
"""
pip_line, floor_line = ci_install_lines()
width = max(len(pr_checks.shown(step)) for step in pr_checks.STEPS)
steps = "\n".join(f"{pr_checks.shown(step):<{width}} # {step.why}" for step in pr_checks.STEPS)
return f"""{title}
## Add a BIOS file
Have a file the collection lacks? Add it from the browser. It is checked on arrival.
Not sure? Drop it on [the wanted page]({link("wanted")}). It reads the file on
the device, says if it is wanted, and opens the upload in the right folder.
[Upload it into `bios/`]({UPLOAD_URL}), 25 MB at most per file. GitHub
writes it to a fork and opens the pull request.
The files most wanted are on [what the packs do not hold]({link("gaps")}). The
[dump provenance]({link("provenance")}) page lists catalogued dumps still
missing from the collection, with their hashes. A file matching one of those is
the most useful contribution.
## What happens next
1. CI hashes the file and looks it up in every platform list and emulator
profile. For a file it recognises, it names the folder holding the other
files of its system. The report is in the summary of the pull request's
Validation run.
2. The file can be moved to that folder in the same pull request. A file whose
hash differs from the one already held under its name goes to that folder's
`.variants/`.
A ZIP that no list declares as a whole is read file by file, and the report
says which of them the collection already holds: upload the files
themselves, unzipped.
From a clone, the file goes to `bios/Manufacturer/Console/filename`, and
`python scripts/validate_pr.py path/to/file` names that folder for a file still
outside `bios/`, and `--place` copies it there under its declared name. Given a
folder, such as an old card's BIOS folder, it checks every file under it. A
file over the browser's 25 MB limit goes in that way, up to the 100 MB GitHub
accepts in a push. A larger file stays out of the pull request: [open an
issue]({LARGE_FILE_ISSUE_URL}) with the hashes `validate_pr.py` prints, and a
maintainer adds it to the `large-files` release.
## Add a platform
1. Write a scraper in `scripts/scraper/` (inherit `BaseScraper`)
2. Read the platform's upstream source to determine how it checks BIOS files
3. Register it in `platforms/_registry.yml`
4. Generate the platform YAML and test: `python scripts/verify.py --platform <name>`
Full walkthrough: [adding a platform]({link("wiki/adding-a-platform")}).
## Add an emulator profile
1. Clone the emulator's source code, upstream and libretro port
2. Trace the file loading from the entry point, not from a keyword grep
3. Document every file the code loads, with a `source_ref` line reference
4. Write the YAML to `emulators/<name>.yml`
5. Test: `python scripts/cross_reference.py --emulator <name>`
Full walkthrough: [profiling guide]({link("wiki/profiling")}).
## Change the installer
`install.py` is built from the `installer/` package, one module per concern:
edit the module, then run `python scripts/build_installer.py` and
`python scripts/pin_installer.py`. CI fails when `install.py` is not the file
the package builds. [Changing the installer]({link("wiki/installer")}#changing-the-installer)
lists what else a change rewrites.
## File conventions
- `bios/Manufacturer/Console/filename` for canonical files
- `bios/Manufacturer/Console/.variants/filename.sha1prefix` for alternate versions
- A file too large for git goes to the `large-files` GitHub release and its
path into `.gitignore`, the list that decides what is served from the release
- Trees addressed by path are kept out of deduplication (`NODEDUP_DIRS` in
`scripts/model/nodedup.py`)
- Two paths differing only by case break clones on Windows and macOS,
and `tests/test_no_case_collisions.py` enforces this
## Before opening a PR
A pull request that only adds files under `bios/` needs none of this: the
validation above is its check. For code, profiles or platform files, these are
the checks CI runs on a pull request (Python 3.12 or newer):
```bash
{pip_line}
python scripts/pr_checks.py
```
`pr_checks.py` runs these, in CI's order, carries on past a failure as CI
does, and names at the end each check that failed or could not run:
```bash
{steps}
```
The versions are the ones CI pins. Three tools come from the system, not from
that line, and the tests that need them skip without them: `shellcheck` for the
handheld launchers, `bwrap` (bubblewrap) for the probe sandbox, and a Python 3.8
with pyte (`{floor_line}`) for the full screen. CI has all three.
`profile_sync.py` compares the branch with this repository's `main`, and
fetches it in a fork's clone. An edited profile is not held to
`--strict`: its older refs are reviewed by hand.
The full pipeline is not needed for a contribution: it rebuilds every pack
in `dist/`, which is why maintainers run it before a release.
## PR validation
CI computes SHA1/MD5/CRC32 for every new file, checks them against the platform
configs, validates the YAML against the schemas, confronts each added profile
with its upstream source and runs the test suite. The BIOS report goes to the
summary of the Validation run, and also to a comment when the branch lives in
this repository: a fork's pull request runs with a read-only token.
Contributors who add platform support are credited in the README,
{site_words}, and in the BIOS packs.
"""
def generate_contributing() -> str:
return contributing_text(
lambda page: f"{SITE_URL}{page}/",
"# Contributing to RetroBIOS",
"on the documentation site",
)
from core.artifacts import repository_output_lock
from sitegen.readme import _write, generate_readme
def main() -> None:
@@ -1002,19 +47,6 @@ def main() -> None:
_write(readme)
def _write(readme: str) -> None:
status = "Generated" if write_if_changed("README.md", readme) else "Unchanged"
print(f"{status} ./README.md")
contributing = generate_contributing()
status = (
"Generated"
if write_if_changed("CONTRIBUTING.md", contributing)
else "Unchanged"
)
print(f"{status} ./CONTRIBUTING.md")
if __name__ == "__main__":
from core.cli import run_cli
+11 -11
View File
@@ -78,7 +78,7 @@ from core.artifacts import json_text as _json_text
from packs.crossref import FileConsumers, entry_target, held_copy
from resolve.nativemode import check_label, digest_algorithm, reads_file_contents
from generate_readme import (
from sitegen.readme import (
platform_coverages,
NO_PACK,
asset_links,
@@ -95,7 +95,7 @@ from sitegen import entries as siteentries
from model import siteinputs
from model import retired as model_retired
from sitegen import agents as siteagents
import sitediagrams
from sitegen import diagrams
from sitegen import starlight as sitestarlight
from sitegen import steps as sitesteps
from sitegen.exports import generate_exports_page, load_export_reports
@@ -126,7 +126,7 @@ from sitegen import handheld as sitehandheld
from sitegen import measurements as sitemeasurements
from sitegen import wanted as sitewanted
from resolve.review import load_platform_hashes, load_profile_hashes
from sitediagrams import local_images, prepare_page, unresolved_images
from sitegen.diagrams import local_images, prepare_page, unresolved_images
from sitegen.write import (
_record,
_undecorated,
@@ -135,7 +135,7 @@ from sitegen.write import (
_sweep_generated,
_sweep_top_pages,
)
from sitesources import (
from sitegen.sources import (
link_prose_citations,
requested_by,
revision_markdown,
@@ -3725,7 +3725,7 @@ def _launcher_refs(config: dict) -> dict[str, list[str]]:
"""Entry name, casefolded -> each launcher record that opens it, rendered."""
from resolve.launchers import _names as launcher_names
from resolve.launchers import bound_launchers
from sitesources import launcher_ref_markdown, list_source
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
@@ -3754,7 +3754,7 @@ def _launcher_unproven_section(config: dict) -> list[str]:
reading it are shown: these records place no file.
"""
from resolve.launchers import launcher_unproven
from sitesources import launcher_ref_markdown, list_source
from sitegen.sources import launcher_ref_markdown, list_source
rows = launcher_unproven({str(config.get("_key") or ""): config})
if not rows:
@@ -4126,7 +4126,7 @@ ROLE_LEGEND = (
def _refs_by_role(profile: dict, value: str | dict | None) -> str:
"""A source_ref's parts grouped by whose code they cite, each role named
once by its ROLE_WORDS word: `glue a.c:1, b.c:2 and port c.c:3`."""
from sitesources import source_ref_items
from sitegen.sources import source_ref_items
texts = []
for label, items in source_ref_items(profile, value):
@@ -4723,7 +4723,7 @@ _HASH_WORDS = {"md5": "MD5", "sha1": "SHA-1", "sha256": "SHA-256", "crc32": "CRC
def _transcribed_row(config: dict) -> list[str]:
"""The file every declaration on this page was read from: without it
a hash could not be traced to the revision that states it."""
from sitesources import list_source
from sitegen.sources import list_source
transcribed = str(config.get("source") or "")
if not transcribed:
@@ -8596,7 +8596,7 @@ def _build_file_links(pin_build: list[dict]) -> list[str]:
"""Each platform build file that holds the revision, linked at the
commit it was read at when the source record holds it. The prose of
pin_frozen named the file as plain text."""
from sitesources import _browse_repo, tree_holds
from sitegen.sources import _browse_repo, tree_holds
links = []
for build in pin_build:
@@ -13091,8 +13091,8 @@ def _write_public_assets(docs: Path, public: Path) -> None:
if source.is_dir():
shutil.copytree(source, public / "assets" / dest, dirs_exist_ok=True)
# The diagrams and the drawn install steps, one SVG per layout and theme.
sitediagrams.write_diagram_files(public / sitediagrams.DIAGRAM_DIR,
{**sitediagrams.figure_files(), **sitesteps.steps_files()})
diagrams.write_diagram_files(public / diagrams.DIAGRAM_DIR,
{**diagrams.figure_files(), **sitesteps.steps_files()})
demo_dest = public / "assets" / "demo"
demo_dest.mkdir(parents=True, exist_ok=True)
for name in DEMO_ASSETS:
+1 -1
View File
@@ -27,7 +27,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
from model.registry import list_registered_platforms
from model.platforms import load_platform_config
from sitediagrams import OG_SECTIONS, og_card_svg, wrap
from sitegen.diagrams import OG_SECTIONS, og_card_svg, wrap
ROOT = Path(__file__).resolve().parent.parent
+8 -8
View File
@@ -654,7 +654,7 @@ def _refresh_source_paths(args: argparse.Namespace) -> None:
if not _WRITTEN or args.dry_run or args.offline or os.environ.get("RETROBIOS_OFFLINE"):
return
from model.profiles import _emulator_profiles_cache
import sitesources
from sitegen import sources
from core.artifacts import write_if_changed
# The run loaded the profiles before writing them, and the loader caches
@@ -662,19 +662,19 @@ def _refresh_source_paths(args: argparse.Namespace) -> None:
# (linapple, then ten profiles in one advance).
_emulator_profiles_cache.clear()
profiles = load_emulator_profiles(args.emulators_dir, skip_aliases=False)
held, unread = sitesources.build_source_paths(
profiles, [sitesources.TREE_CACHE], fetch=True
held, unread = sources.build_source_paths(
profiles, [sources.TREE_CACHE], fetch=True
)
held = sitesources.keep_unread(
held, unread, sitesources.read_record(sitesources.SOURCE_PATHS)
held = sources.keep_unread(
held, unread, sources.read_record(sources.SOURCE_PATHS)
)
sitesources.SOURCE_PATHS.parent.mkdir(parents=True, exist_ok=True)
sources.SOURCE_PATHS.parent.mkdir(parents=True, exist_ok=True)
write_if_changed(
str(sitesources.SOURCE_PATHS), json.dumps(held, indent=1, sort_keys=True) + "\n"
str(sources.SOURCE_PATHS), json.dumps(held, indent=1, sort_keys=True) + "\n"
)
print(
f"source paths: {sum(map(len, held.values()))} in {len(held)} trees, "
f"{len(unread)} trees not cached: {sitesources.SOURCE_PATHS}",
f"{len(unread)} trees not cached: {sources.SOURCE_PATHS}",
file=sys.stderr,
)
+8 -257
View File
@@ -27,273 +27,24 @@ Usage:
from __future__ import annotations
import argparse
import base64
import datetime as dt
import json
import os
import re
import subprocess
import sys
import tempfile
import time
import urllib.parse
import urllib.request
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
from core.github import github_token
from model.database import load_database
from model.profiles import load_emulator_profiles
from core.cli import run_cli
from core.paths import REPO_ROOT
CONFIG = Path(os.environ.get("RETROBIOS_CONFIG", Path.home() / ".config" / "retrobios"))
SITE_PROPERTY = "https://abdess.github.io/retrobios/"
GOATCOUNTER = "https://retrobios.goatcounter.com/api/v0"
REPOSITORY = "Abdess/retrobios"
SOURCES = ("gsc", "goatcounter", "github")
# A word of a search that names a file: "scph5501.bin", "prod.keys".
FILE_TOKEN = re.compile(r"\b[\w.+-]+\.(?:bin|rom|zip|pup|keys|img|dat|bios|ic\d+|u\d+|sys|nvm|mec|"
r"rom1|j64|pce|col|sms|gb|gbc|gba|nds|cfg|chd|iso|txt|fw|dll|xml|yaml)\b", re.I)
@dataclass(frozen=True)
class Query:
text: str
page: str
clicks: int
impressions: int
position: float
@property
def ctr(self) -> float:
return self.clicks / self.impressions if self.impressions else 0.0
# Reading the sources
def _get_json(url: str, headers: dict[str, str] | None = None, body: dict | None = None) -> dict | list:
data = json.dumps(body).encode() if body is not None else None
request = urllib.request.Request(url, data=data, headers={
"User-Agent": "retrobios-site-insights", **({"Content-Type": "application/json"} if data else {}),
**(headers or {})})
with urllib.request.urlopen(request, timeout=60) as response:
return json.load(response)
def _google_token(key_file: Path) -> str:
"""An access token for a service account, signed by openssl: the JWT
grant needs RS256 and the standard library has no RSA."""
key = json.loads(key_file.read_text(encoding="utf-8"))
now = int(time.time())
def b64(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
claims = {"iss": key["client_email"], "scope": "https://www.googleapis.com/auth/webmasters.readonly",
"aud": key["token_uri"], "iat": now, "exp": now + 3600}
unsigned = f"{b64(json.dumps({'alg': 'RS256', 'typ': 'JWT'}).encode())}.{b64(json.dumps(claims).encode())}"
with tempfile.TemporaryDirectory() as scratch:
pem = Path(scratch) / "key.pem"
pem.touch(mode=0o600)
pem.write_text(key["private_key"], encoding="utf-8")
signature = subprocess.run(["openssl", "dgst", "-sha256", "-sign", str(pem)],
input=unsigned.encode(), capture_output=True, check=True).stdout
body = urllib.parse.urlencode({"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": f"{unsigned}.{b64(signature)}"}).encode()
request = urllib.request.Request(key["token_uri"], data=body)
with urllib.request.urlopen(request, timeout=60) as response:
return json.load(response)["access_token"]
def fetch_queries(start: dt.date, end: dt.date) -> list[Query]:
token = _google_token(CONFIG / "gsc-service-account.json")
url = ("https://www.googleapis.com/webmasters/v3/sites/"
f"{urllib.parse.quote(SITE_PROPERTY, safe='')}/searchAnalytics/query")
rows: list[Query] = []
while True:
answer = _get_json(url, {"Authorization": f"Bearer {token}"}, {
"startDate": start.isoformat(), "endDate": end.isoformat(),
"dimensions": ["query", "page"], "rowLimit": 25000, "startRow": len(rows)})
if not isinstance(answer, dict):
raise SystemExit("Search Console answered with something other than an object")
batch = answer.get("rows", [])
rows += [Query(r["keys"][0], r["keys"][1], int(r["clicks"]), int(r["impressions"]),
float(r["position"])) for r in batch]
if len(batch) < 25000:
return rows
def fetch_goatcounter(start: dt.date, end: dt.date) -> dict:
"""Paths and events with their visit counts, and the referring domains."""
token = (CONFIG / "goatcounter-api-token.txt").read_text(encoding="utf-8").strip()
auth = {"Authorization": f"Bearer {token}"}
span = {"start": f"{start.isoformat()}T00:00:00Z", "end": f"{end.isoformat()}T23:59:59Z"}
hits: list[tuple[str, int]] = []
exclude: list[str] = []
while True:
params = urllib.parse.urlencode({**span, "limit": 100, "exclude_paths": ",".join(exclude)})
answer = _get_json(f"{GOATCOUNTER}/stats/hits?{params}", auth)
if not isinstance(answer, dict):
raise SystemExit("GoatCounter answered with something other than an object")
for hit in answer.get("hits", []):
hits.append((hit["path"] + (" [404]" if hit.get("title") == "404" else ""), int(hit["count"])))
exclude.append(str(hit["path_id"]))
if not answer.get("more"):
break
refs = _get_json(f"{GOATCOUNTER}/stats/toprefs?{urllib.parse.urlencode({**span, 'limit': 50})}", auth)
total = _get_json(f"{GOATCOUNTER}/stats/total?{urllib.parse.urlencode(span)}", auth)
if not isinstance(refs, dict) or not isinstance(total, dict):
raise SystemExit("GoatCounter answered with something other than an object")
# An action carries no referrer, and GoatCounter files it as a direct
# visit: 592 of the first day's 1,145 "direct" were clicks.
events = int(total.get("total_events", 0))
referrers = [("(direct)", max(int(r["count"]) - events, 0)) if not r.get("name") else (r["name"], int(r["count"]))
for r in refs.get("stats", [])]
return {"hits": hits, "referrers": sorted(referrers, key=lambda row: -row[1]),
"visits": int(total.get("total", 0)) - events, "actions": events}
def fetch_github() -> dict:
token = github_token()
if not token:
raise SystemExit("GitHub traffic needs a token: GITHUB_TOKEN, or gh auth login")
auth = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json"}
api = f"https://api.github.com/repos/{REPOSITORY}"
releases = _get_json(f"{api}/releases?per_page=10", auth)
return {
"views": _get_json(f"{api}/traffic/views", auth),
"clones": _get_json(f"{api}/traffic/clones", auth),
"referrers": _get_json(f"{api}/traffic/popular/referrers", auth),
"paths": _get_json(f"{api}/traffic/popular/paths", auth),
"downloads": [(release["tag_name"], asset["name"], asset["download_count"])
for release in releases for asset in release.get("assets", [])],
}
# Reading the figures
def searched_files(queries: list[Query], held: set[str], declared: set[str]) -> list[tuple[str, int, str]]:
"""File names typed in searches, by impressions, with what the project
knows of each: held in the collection, declared by a profile only, or
unknown."""
seen: dict[str, int] = defaultdict(int)
shown: dict[str, str] = {}
for query in queries:
for token in FILE_TOKEN.findall(query.text):
key = token.casefold()
seen[key] += query.impressions
shown.setdefault(key, token)
state = {key: "held" if key in held else "declared, not held" if key in declared else "unknown"
for key in seen}
return sorted(((shown[key], seen[key], state[key]) for key in seen), key=lambda row: -row[1])
def missed_clicks(queries: list[Query], least: int = 100) -> list[Query]:
"""On the first page but rarely clicked: what the result says loses
the reader."""
return sorted((q for q in queries if q.position <= 10 and q.impressions >= least and q.ctr < 0.03),
key=lambda q: -q.impressions)
def near_first_page(queries: list[Query], least: int = 50) -> list[Query]:
return sorted((q for q in queries if 10 < q.position <= 20 and q.impressions >= least),
key=lambda q: -q.impressions)
def site_actions(hits: list[tuple[str, int]]) -> dict[str, list[tuple[str, int]]]:
"""Events by kind ("search-none", "helpful", "download"...), pages apart."""
groups: dict[str, list[tuple[str, int]]] = defaultdict(list)
for path, count in hits:
if path.endswith(" [404]"):
groups["404"].append((path.removesuffix(" [404]"), count))
elif not path.startswith("/") and "/" in path:
kind, _, name = path.partition("/")
groups[kind].append((name, count))
else:
groups["pages"].append((path, count))
return {kind: sorted(rows, key=lambda row: -row[1]) for kind, rows in groups.items()}
# The report
def _table(header: tuple[str, ...], rows: list[tuple], limit: int = 25) -> list[str]:
if not rows:
return ["None.", ""]
lines = ["| " + " | ".join(header) + " |", "|" + "---|" * len(header)]
lines += ["| " + " | ".join(str(cell) for cell in row) + " |" for row in rows[:limit]]
return [*lines, ""]
def _page(url: str) -> str:
return url.removeprefix(SITE_PROPERTY.rstrip("/")) or "/"
def report(start: dt.date, end: dt.date, queries: list[Query] | None, goat: dict | None,
github: dict | None, held: set[str], declared: set[str]) -> str:
out = [f"# Site insights, {start.isoformat()} to {end.isoformat()}", ""]
if queries is not None:
clicks = sum(q.clicks for q in queries)
shown = sum(q.impressions for q in queries)
out += ["## Google searches", "",
f"{clicks:,} clicks, {shown:,} impressions, {len({q.text for q in queries}):,} searches.", "",
"### On the first page, rarely clicked", "",
*_table(("Search", "Page", "Impressions", "CTR", "Position"),
[(q.text, _page(q.page), f"{q.impressions:,}", f"{q.ctr:.1%}", f"{q.position:.1f}")
for q in missed_clicks(queries)]),
"### Just past the first page", "",
*_table(("Search", "Page", "Impressions", "Position"),
[(q.text, _page(q.page), f"{q.impressions:,}", f"{q.position:.1f}")
for q in near_first_page(queries)]),
"### File names searched", "",
*_table(("File", "Impressions", "In the project"),
[(f"`{name}`", f"{seen:,}", state)
for name, seen, state in searched_files(queries, held, declared)], limit=40)]
if goat is not None:
actions = site_actions(goat["hits"])
named = {"search-none": "Site searches that found nothing", "404": "Broken addresses",
"helpful": "Did this page help?", "get": "Pack pages opened",
"download": "Release downloads", "file": "File downloads", "copy": "Copy buttons",
"out": "Links leaving the site", "pages": "Pages"}
out += ["## On the site", "",
f"{goat.get('visits', 0):,} page views, {goat.get('actions', 0):,} actions.", ""]
for kind, title in named.items():
if kind in actions:
out += [f"### {title}", "", *_table(("Name", "Visits"), [(n, f"{c:,}") for n, c in actions[kind]])]
out += ["### Came from", "", *_table(("Site", "Visits"), [(n, f"{c:,}") for n, c in goat["referrers"]])]
if github is not None:
views, clones = github["views"], github["clones"]
out += ["## GitHub", "",
f"Last 14 days: {views.get('count', 0):,} views by {views.get('uniques', 0):,} visitors, "
f"{clones.get('count', 0):,} clones.", "",
"### Came from", "",
*_table(("Site", "Views", "Visitors"),
[(r["referrer"], r["count"], r["uniques"]) for r in github["referrers"]]),
"### Most viewed", "",
*_table(("Path", "Views"), [(p["path"], p["count"]) for p in github["paths"]]),
"### Release downloads", "",
*_table(("Release", "File", "Downloads"),
sorted(github["downloads"], key=lambda row: -row[2]), limit=40)]
return "\n".join(out).rstrip() + "\n"
def collection_names(db: dict, profiles: dict[str, dict]) -> tuple[set[str], set[str]]:
"""File names the collection holds, and those a profile declares."""
held = {name.casefold() for name in db.get("indexes", {}).get("by_name", {})}
declared: set[str] = set()
for profile in profiles.values():
for entry in profile.get("files") or []:
if isinstance(entry, dict):
for name in [entry.get("name"), *(entry.get("aliases") or [])]:
if name:
declared.add(Path(str(name)).name.casefold())
return held, declared
from sitegen.insights import (
SOURCES,
collection_names,
fetch_github,
fetch_goatcounter,
fetch_queries,
report,
)
def main() -> int:
+1 -450
View File
@@ -27,462 +27,13 @@ on the built site:
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import subprocess
import sys
from collections.abc import Callable
from html.parser import HTMLParser
from pathlib import Path
from typing import ClassVar
sys.path.insert(0, os.path.dirname(__file__))
from core.cli import run_cli
from core.paths import REPO_ROOT
SITE = "https://abdess.github.io"
BASE = "/retrobios/"
# Elements whose content is never words a reader needs.
SKIPPED = frozenset({"script", "style", "svg", "button", "nav", "template", "noscript", "video"})
HEADINGS = {f"h{n}": n for n in range(1, 7)}
# The pages llms-full.txt joins, by path under the site, in reading order.
FULL_PAGES = ("", "which-pack/", "wiki/what-are-bios-files/", "wiki/first-install/",
"wiki/troubleshooting/", "wiki/faq/", "wiki/installer/", "wiki/legal/",
"wiki/privacy/")
class _Converter(HTMLParser):
"""The Markdown of a page's article: its title and its content."""
def __init__(self, page_url: str) -> None:
super().__init__(convert_charrefs=True)
self.page_url = page_url
self.out: list[str] = []
self.skip = 0
self.inside = 0
self.depth_stack: list[str] = []
self.lists: list[list[int]] = []
self.pre = 0
self.links: list[str | None] = []
self.row: list[str] | None = None
self.cell: list[str] | None = None
self.table: list[list[str]] | None = None
self.header_rows = 0
self.title = ""
self._in_title = False
# A tab's name by its id, read from the tab list, said above its
# panel: a command under the wrong OS is the answer an assistant
# gets wrong.
self.tab_names: dict[str, str] = {}
self._tab: str | None = None
self._card = False
# Output
def _emit(self, text: str) -> None:
if self.cell is not None:
self.cell.append(text)
else:
self.out.append(text)
def _block(self) -> None:
if self.cell is not None:
self.cell.append(" ")
return
joined = "".join(self.out)
if joined and not joined.endswith("\n\n"):
self.out.append("\n" if joined.endswith("\n") else "\n\n")
# Parsing
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
attr = {key: value or "" for key, value in attrs}
classes = set(attr.get("class", "").split())
if tag == "h1" and attr.get("id") == "_top":
self._in_title = True
if not self.inside:
if "sl-markdown-content" in classes:
self.inside = 1
self.depth_stack = [tag]
return
if tag not in ("br", "img", "hr", "input", "meta", "link", "source", "wbr"):
self.depth_stack.append(tag)
if self._open_tabs(tag, attr) or self._open_skipped(tag, attr, classes):
return
if self.pre:
# Inside a code block a line is a div, never a paragraph.
if tag == "div" and "ec-line" in classes and not "".join(self.out[-1:]).endswith("```\n"):
self._emit("\n")
return
opener = self._OPENERS.get(tag)
if opener is not None:
opener(self, tag, attr, classes)
def _open_tabs(self, tag: str, attr: dict[str, str]) -> bool:
"""A tab list, a tab's name or a tab panel: True when handled."""
if attr.get("role") == "tablist":
self.skip += 1
return True
if self.skip and attr.get("role") == "tab" and attr.get("id"):
self._tab = attr["id"]
self.tab_names[self._tab] = ""
self.skip += 1
return True
if attr.get("role") == "tabpanel" and not self.skip:
self._block()
name = self.tab_names.get(attr.get("aria-labelledby", ""), "").strip()
if name:
self._emit(f"**{' '.join(name.split())}:**")
self._block()
return True
return False
def _open_skipped(self, tag: str, attr: dict[str, str], classes: set[str]) -> bool:
# A `hidden` element is chrome the page's script shows (a filter
# box, the file picker, a setup's install chooser): a tab panel,
# hidden too, was read above.
if self.skip or tag in SKIPPED or attr.get("aria-hidden") == "true" or "hidden" in attr \
or classes & {"sr-only", "sl-anchor-link", "copy", "rb-anchor"}:
if tag not in ("br", "img", "hr", "input", "wbr"):
self.skip += 1
return True
return False
def _open_heading(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._block()
self._emit("#" * HEADINGS[tag] + " ")
def _open_block(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._block()
def _open_bold_block(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._block()
self._emit("**")
def _open_list(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._block()
self.lists.append([0 if tag == "ol" else -1])
def _open_item(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
if self.out and not "".join(self.out[-1:]).endswith("\n"):
self._emit("\n")
level = len(self.lists) - 1
marker = "-"
if self.lists and self.lists[-1][0] >= 0:
self.lists[-1][0] += 1
marker = f"{self.lists[-1][0]}."
self._emit(" " * max(level, 0) + marker + " ")
def _open_pre(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._block()
self.pre += 1
self._emit("```\n")
def _open_code(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
if not self.pre:
self._emit("`")
def _open_strong(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._emit("**")
def _open_em(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._emit("*")
def _open_link(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
href = attr.get("href", "")
if "rb-card" in classes:
# A card of a grid: one list line each, its name then what it
# says, instead of one run-on line of links.
href = SITE + href if href.startswith("/") else href
self._block()
self._emit("- [")
self.links.append(href or None)
self._card = True
return
if href.startswith("#"):
href = self.page_url + href
elif href.startswith("/"):
href = SITE + href
self.links.append(href or None)
if href:
self._emit("[")
def _open_span(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
if self._card and self.links:
self._emit(": ")
def _open_img(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
alt = attr.get("alt", "").strip()
if alt:
self._emit(alt)
def _open_table(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._block()
self.table, self.header_rows = [], 0
def _open_row(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
if self.table is not None:
self.row = []
def _open_cell(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
if self.row is not None:
self.cell = []
if tag == "th" and not self.row:
self.header_rows = max(self.header_rows, len(self.table or []) + 1)
def _open_definition(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._emit(": ")
_OPENERS: ClassVar[dict[str, Callable[[_Converter, str, dict[str, str], set[str]], None]]] = {
**dict.fromkeys(HEADINGS, _open_heading),
**dict.fromkeys(("p", "div", "section", "figure", "details", "blockquote", "dl"), _open_block),
"summary": _open_bold_block,
"dt": _open_bold_block,
"ul": _open_list,
"ol": _open_list,
"li": _open_item,
"pre": _open_pre,
"code": _open_code,
"strong": _open_strong,
"b": _open_strong,
"em": _open_em,
"i": _open_em,
"a": _open_link,
"span": _open_span,
"img": _open_img,
"table": _open_table,
"tr": _open_row,
"td": _open_cell,
"th": _open_cell,
"dd": _open_definition,
}
def handle_endtag(self, tag: str) -> None:
if tag == "h1" and self._in_title:
self._in_title = False
if not self.inside:
return
if self.depth_stack:
self.depth_stack.pop()
if not self.depth_stack:
self.inside = 0
return
if self.skip:
if tag not in ("br", "img", "hr", "input", "wbr"):
self.skip -= 1
if tag == "a" and self._tab:
self._tab = None
return
if self.pre and tag != "pre":
return
closer = self._CLOSERS.get(tag)
if closer is not None:
closer(self, tag)
def _close_block(self, tag: str) -> None:
self._block()
def _close_summary(self, tag: str) -> None:
self._emit("**")
self._block()
def _close_list(self, tag: str) -> None:
if self.lists:
self.lists.pop()
self._block()
def _close_pre(self, tag: str) -> None:
self.pre -= 1
self._emit("\n```")
self._block()
def _close_code(self, tag: str) -> None:
if not self.pre:
self._emit("`")
def _close_strong(self, tag: str) -> None:
self._emit("**")
def _close_em(self, tag: str) -> None:
self._emit("*")
def _close_link(self, tag: str) -> None:
href = self.links.pop() if self.links else None
if href:
self._emit(f"]({href})")
if self._card:
self._card = False
self._emit("\n")
def _close_cell(self, tag: str) -> None:
if self.cell is not None and self.row is not None:
self.row.append(" ".join("".join(self.cell).split()).replace("|", "\\|"))
self.cell = None
def _close_row(self, tag: str) -> None:
if self.row is not None and self.table is not None:
self.table.append(self.row)
self.row = None
def _close_table(self, tag: str) -> None:
if self.table is None:
return
rows, self.table = self.table, None
if rows:
width = max(len(r) for r in rows)
rows = [r + [""] * (width - len(r)) for r in rows]
head = rows[0] if self.header_rows else [""] * width
body = rows[1:] if self.header_rows else rows
lines = ["| " + " | ".join(head) + " |", "|" + "---|" * width]
lines += ["| " + " | ".join(r) + " |" for r in body]
self.out.append("\n".join(lines))
self._block()
def _close_break(self, tag: str) -> None:
self._emit("\n" if self.pre else " \n")
_CLOSERS: ClassVar[dict[str, Callable[[_Converter, str], None]]] = {
**dict.fromkeys(HEADINGS, _close_block),
**dict.fromkeys(("p", "section", "figure", "details", "blockquote", "dl"), _close_block),
"summary": _close_summary,
"ul": _close_list,
"ol": _close_list,
"pre": _close_pre,
"code": _close_code,
"strong": _close_strong,
"b": _close_strong,
"dt": _close_strong,
"em": _close_em,
"i": _close_em,
"a": _close_link,
"td": _close_cell,
"th": _close_cell,
"tr": _close_row,
"table": _close_table,
"br": _close_break,
}
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
self.handle_starttag(tag, attrs)
if tag not in ("img", "br", "hr", "input", "wbr", "meta", "link", "source"):
self.handle_endtag(tag)
def handle_data(self, data: str) -> None:
if self._in_title and not self.inside:
self.title += data
return
if self._tab is not None:
self.tab_names[self._tab] += data
if not self.inside or self.skip:
return
if self.pre:
# The whitespace between <pre> and its first line is no line.
if data.strip() or not "".join(self.out[-1:]).endswith("```\n"):
self._emit(data)
return
text = re.sub(r"\s+", " ", data)
if text.strip() or (text and self.out and not "".join(self.out[-1:]).endswith((" ", "\n"))):
self._emit(text)
def markdown(self) -> str:
body = "".join(self.out)
body = re.sub(r"[ \t]+\n", "\n", body)
body = re.sub(r"\n{3,}", "\n\n", body).strip()
title = " ".join(self.title.split())
return (f"# {title}\n\n" if title else "") + f"Source: {self.page_url}\n\n{body}\n"
def page_markdown(html: str, page_url: str) -> str:
converter = _Converter(page_url)
converter.feed(html)
converter.close()
return converter.markdown()
ROOT = REPO_ROOT
def build_stamp() -> dict[str, str]:
"""The commit the site is built from and its date. CI names the commit
in GITHUB_SHA. The date is the commit's, so two builds of one commit
write the same bytes."""
commit = os.environ.get("GITHUB_SHA") or subprocess.run(
["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, text=True,
check=True).stdout.strip()
date = subprocess.run(["git", "log", "-1", "--format=%cI", commit], cwd=ROOT,
capture_output=True, text=True, check=True).stdout.strip()
return {"commit": commit, "date": date}
def stamp_line(stamp: dict[str, str]) -> str:
return (f"> Built from commit {stamp['commit'][:12]} on {stamp['date'][:10]}. "
f"The current build: {SITE}{BASE}version.json")
def stamped(text: str, stamp: dict[str, str]) -> str:
"""*text* with the build line under its first line, the title."""
first, _, rest = text.partition("\n")
return f"{first}\n\n{stamp_line(stamp)}\n{rest}"
def convert_site(dist: Path, stamp: dict[str, str] | None = None) -> int:
"""Write index.md beside every page's index.html, then llms-full.txt,
version.json and digests.json, and stamp llms.txt."""
stamp = stamp or build_stamp()
written = 0
digests: dict[str, str] = {}
for html_path in sorted(dist.rglob("index.html")):
relative = html_path.parent.relative_to(dist).as_posix()
page = "" if relative == "." else f"{relative}/"
url = f"{SITE}{BASE}{page}"
text = page_markdown(html_path.read_text(encoding="utf-8"), url)
digests[url] = hashlib.sha256(text.encode("utf-8")).hexdigest()
(html_path.parent / "index.md").write_text(stamped(text, stamp), encoding="utf-8")
written += 1
write_full(dist, stamp)
llms = dist / "llms.txt"
if llms.is_file():
text = llms.read_text(encoding="utf-8")
digests[f"{SITE}{BASE}llms.txt"] = hashlib.sha256(text.encode("utf-8")).hexdigest()
# Under the summary, which llms.txt keeps as the quote after its title.
title, summary, rest = text.split("\n\n", 2)
line = stamp_line(stamp).removeprefix("> ")
llms.write_text(f"{title}\n\n{summary}\n\n{line}\n\n{rest}", encoding="utf-8")
(dist / "version.json").write_text(json.dumps(stamp, indent=1) + "\n", encoding="utf-8")
(dist / "digests.json").write_text(
json.dumps(dict(sorted(digests.items())), indent=0) + "\n", encoding="utf-8")
return written
def _unstamped(text: str, stamp: dict[str, str]) -> str:
"""A page's copy without its build line: llms-full.txt says it once."""
return text.replace(f"\n\n{stamp_line(stamp)}\n", "\n", 1)
def write_full(dist: Path, stamp: dict[str, str]) -> None:
"""llms-full.txt from the pages' Markdown copies."""
parts = ["# RetroBIOS: the guides in one file", "", stamp_line(stamp), "",
"> The pages a setup is done with, in reading order. Every page of the site also has "
"its own Markdown copy at `<page>/index.md`.", ""]
for page in FULL_PAGES:
md = dist / page / "index.md"
if md.is_file():
parts += [_unstamped(md.read_text(encoding="utf-8"), stamp).rstrip(), "", "---", ""]
# Each setup's own page (the setups the picker lists, not the parts a
# long page is cut into), up to its reference of every file: what to
# do and where, not the full lists, which its own copy keeps. All of
# them was 6.9 MB, past what an assistant reads at once.
index = dist / "data" / "picker" / "index.json"
setups = [str(item["platform"]) for item in json.loads(index.read_text(encoding="utf-8"))] \
if index.is_file() else []
for setup in [*setups, "linux-handhelds"]:
md = dist / "platforms" / setup / "index.md"
if md.is_file():
text = _unstamped(md.read_text(encoding="utf-8"), stamp)
parts += [text.split("\n## Reference", 1)[0].rstrip(), "", "---", ""]
(dist / "llms-full.txt").write_text("\n".join(parts).rstrip() + "\n", encoding="utf-8")
from sitegen.pagemarkdown import convert_site
def main() -> int:
+1 -1119
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+265
View File
@@ -0,0 +1,265 @@
"""What readers look for and do not find, from totals only."""
from __future__ import annotations
import base64
import datetime as dt
import json
import os
import re
import subprocess
import tempfile
import time
import urllib.request
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
from core.github import github_token
CONFIG = Path(os.environ.get("RETROBIOS_CONFIG", Path.home() / ".config" / "retrobios"))
SITE_PROPERTY = "https://abdess.github.io/retrobios/"
GOATCOUNTER = "https://retrobios.goatcounter.com/api/v0"
REPOSITORY = "Abdess/retrobios"
SOURCES = ("gsc", "goatcounter", "github")
# A word of a search that names a file: "scph5501.bin", "prod.keys".
FILE_TOKEN = re.compile(r"\b[\w.+-]+\.(?:bin|rom|zip|pup|keys|img|dat|bios|ic\d+|u\d+|sys|nvm|mec|"
r"rom1|j64|pce|col|sms|gb|gbc|gba|nds|cfg|chd|iso|txt|fw|dll|xml|yaml)\b", re.I)
@dataclass(frozen=True)
class Query:
text: str
page: str
clicks: int
impressions: int
position: float
@property
def ctr(self) -> float:
return self.clicks / self.impressions if self.impressions else 0.0
# Reading the sources
def _get_json(url: str, headers: dict[str, str] | None = None, body: dict | None = None) -> dict | list:
data = json.dumps(body).encode() if body is not None else None
request = urllib.request.Request(url, data=data, headers={
"User-Agent": "retrobios-site-insights", **({"Content-Type": "application/json"} if data else {}),
**(headers or {})})
with urllib.request.urlopen(request, timeout=60) as response:
return json.load(response)
def _google_token(key_file: Path) -> str:
"""An access token for a service account, signed by openssl: the JWT
grant needs RS256 and the standard library has no RSA."""
key = json.loads(key_file.read_text(encoding="utf-8"))
now = int(time.time())
def b64(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
claims = {"iss": key["client_email"], "scope": "https://www.googleapis.com/auth/webmasters.readonly",
"aud": key["token_uri"], "iat": now, "exp": now + 3600}
unsigned = f"{b64(json.dumps({'alg': 'RS256', 'typ': 'JWT'}).encode())}.{b64(json.dumps(claims).encode())}"
with tempfile.TemporaryDirectory() as scratch:
pem = Path(scratch) / "key.pem"
pem.touch(mode=0o600)
pem.write_text(key["private_key"], encoding="utf-8")
signature = subprocess.run(["openssl", "dgst", "-sha256", "-sign", str(pem)],
input=unsigned.encode(), capture_output=True, check=True).stdout
body = urllib.parse.urlencode({"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": f"{unsigned}.{b64(signature)}"}).encode()
request = urllib.request.Request(key["token_uri"], data=body)
with urllib.request.urlopen(request, timeout=60) as response:
return json.load(response)["access_token"]
def fetch_queries(start: dt.date, end: dt.date) -> list[Query]:
token = _google_token(CONFIG / "gsc-service-account.json")
url = ("https://www.googleapis.com/webmasters/v3/sites/"
f"{urllib.parse.quote(SITE_PROPERTY, safe='')}/searchAnalytics/query")
rows: list[Query] = []
while True:
answer = _get_json(url, {"Authorization": f"Bearer {token}"}, {
"startDate": start.isoformat(), "endDate": end.isoformat(),
"dimensions": ["query", "page"], "rowLimit": 25000, "startRow": len(rows)})
if not isinstance(answer, dict):
raise SystemExit("Search Console answered with something other than an object")
batch = answer.get("rows", [])
rows += [Query(r["keys"][0], r["keys"][1], int(r["clicks"]), int(r["impressions"]),
float(r["position"])) for r in batch]
if len(batch) < 25000:
return rows
def fetch_goatcounter(start: dt.date, end: dt.date) -> dict:
"""Paths and events with their visit counts, and the referring domains."""
token = (CONFIG / "goatcounter-api-token.txt").read_text(encoding="utf-8").strip()
auth = {"Authorization": f"Bearer {token}"}
span = {"start": f"{start.isoformat()}T00:00:00Z", "end": f"{end.isoformat()}T23:59:59Z"}
hits: list[tuple[str, int]] = []
exclude: list[str] = []
while True:
params = urllib.parse.urlencode({**span, "limit": 100, "exclude_paths": ",".join(exclude)})
answer = _get_json(f"{GOATCOUNTER}/stats/hits?{params}", auth)
if not isinstance(answer, dict):
raise SystemExit("GoatCounter answered with something other than an object")
for hit in answer.get("hits", []):
hits.append((hit["path"] + (" [404]" if hit.get("title") == "404" else ""), int(hit["count"])))
exclude.append(str(hit["path_id"]))
if not answer.get("more"):
break
refs = _get_json(f"{GOATCOUNTER}/stats/toprefs?{urllib.parse.urlencode({**span, 'limit': 50})}", auth)
total = _get_json(f"{GOATCOUNTER}/stats/total?{urllib.parse.urlencode(span)}", auth)
if not isinstance(refs, dict) or not isinstance(total, dict):
raise SystemExit("GoatCounter answered with something other than an object")
# An action carries no referrer, and GoatCounter files it as a direct
# visit: 592 of the first day's 1,145 "direct" were clicks.
events = int(total.get("total_events", 0))
referrers = [("(direct)", max(int(r["count"]) - events, 0)) if not r.get("name") else (r["name"], int(r["count"]))
for r in refs.get("stats", [])]
return {"hits": hits, "referrers": sorted(referrers, key=lambda row: -row[1]),
"visits": int(total.get("total", 0)) - events, "actions": events}
def fetch_github() -> dict:
token = github_token()
if not token:
raise SystemExit("GitHub traffic needs a token: GITHUB_TOKEN, or gh auth login")
auth = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json"}
api = f"https://api.github.com/repos/{REPOSITORY}"
releases = _get_json(f"{api}/releases?per_page=10", auth)
return {
"views": _get_json(f"{api}/traffic/views", auth),
"clones": _get_json(f"{api}/traffic/clones", auth),
"referrers": _get_json(f"{api}/traffic/popular/referrers", auth),
"paths": _get_json(f"{api}/traffic/popular/paths", auth),
"downloads": [(release["tag_name"], asset["name"], asset["download_count"])
for release in releases for asset in release.get("assets", [])],
}
# Reading the figures
def searched_files(queries: list[Query], held: set[str], declared: set[str]) -> list[tuple[str, int, str]]:
"""File names typed in searches, by impressions, with what the project
knows of each: held in the collection, declared by a profile only, or
unknown."""
seen: dict[str, int] = defaultdict(int)
shown: dict[str, str] = {}
for query in queries:
for token in FILE_TOKEN.findall(query.text):
key = token.casefold()
seen[key] += query.impressions
shown.setdefault(key, token)
state = {key: "held" if key in held else "declared, not held" if key in declared else "unknown"
for key in seen}
return sorted(((shown[key], seen[key], state[key]) for key in seen), key=lambda row: -row[1])
def missed_clicks(queries: list[Query], least: int = 100) -> list[Query]:
"""On the first page but rarely clicked: what the result says loses
the reader."""
return sorted((q for q in queries if q.position <= 10 and q.impressions >= least and q.ctr < 0.03),
key=lambda q: -q.impressions)
def near_first_page(queries: list[Query], least: int = 50) -> list[Query]:
return sorted((q for q in queries if 10 < q.position <= 20 and q.impressions >= least),
key=lambda q: -q.impressions)
def site_actions(hits: list[tuple[str, int]]) -> dict[str, list[tuple[str, int]]]:
"""Events by kind ("search-none", "helpful", "download"...), pages apart."""
groups: dict[str, list[tuple[str, int]]] = defaultdict(list)
for path, count in hits:
if path.endswith(" [404]"):
groups["404"].append((path.removesuffix(" [404]"), count))
elif not path.startswith("/") and "/" in path:
kind, _, name = path.partition("/")
groups[kind].append((name, count))
else:
groups["pages"].append((path, count))
return {kind: sorted(rows, key=lambda row: -row[1]) for kind, rows in groups.items()}
# The report
def _table(header: tuple[str, ...], rows: list[tuple], limit: int = 25) -> list[str]:
if not rows:
return ["None.", ""]
lines = ["| " + " | ".join(header) + " |", "|" + "---|" * len(header)]
lines += ["| " + " | ".join(str(cell) for cell in row) + " |" for row in rows[:limit]]
return [*lines, ""]
def _page(url: str) -> str:
return url.removeprefix(SITE_PROPERTY.rstrip("/")) or "/"
def report(start: dt.date, end: dt.date, queries: list[Query] | None, goat: dict | None,
github: dict | None, held: set[str], declared: set[str]) -> str:
out = [f"# Site insights, {start.isoformat()} to {end.isoformat()}", ""]
if queries is not None:
clicks = sum(q.clicks for q in queries)
shown = sum(q.impressions for q in queries)
out += ["## Google searches", "",
f"{clicks:,} clicks, {shown:,} impressions, {len({q.text for q in queries}):,} searches.", "",
"### On the first page, rarely clicked", "",
*_table(("Search", "Page", "Impressions", "CTR", "Position"),
[(q.text, _page(q.page), f"{q.impressions:,}", f"{q.ctr:.1%}", f"{q.position:.1f}")
for q in missed_clicks(queries)]),
"### Just past the first page", "",
*_table(("Search", "Page", "Impressions", "Position"),
[(q.text, _page(q.page), f"{q.impressions:,}", f"{q.position:.1f}")
for q in near_first_page(queries)]),
"### File names searched", "",
*_table(("File", "Impressions", "In the project"),
[(f"`{name}`", f"{seen:,}", state)
for name, seen, state in searched_files(queries, held, declared)], limit=40)]
if goat is not None:
actions = site_actions(goat["hits"])
named = {"search-none": "Site searches that found nothing", "404": "Broken addresses",
"helpful": "Did this page help?", "get": "Pack pages opened",
"download": "Release downloads", "file": "File downloads", "copy": "Copy buttons",
"out": "Links leaving the site", "pages": "Pages"}
out += ["## On the site", "",
f"{goat.get('visits', 0):,} page views, {goat.get('actions', 0):,} actions.", ""]
for kind, title in named.items():
if kind in actions:
out += [f"### {title}", "", *_table(("Name", "Visits"), [(n, f"{c:,}") for n, c in actions[kind]])]
out += ["### Came from", "", *_table(("Site", "Visits"), [(n, f"{c:,}") for n, c in goat["referrers"]])]
if github is not None:
views, clones = github["views"], github["clones"]
out += ["## GitHub", "",
f"Last 14 days: {views.get('count', 0):,} views by {views.get('uniques', 0):,} visitors, "
f"{clones.get('count', 0):,} clones.", "",
"### Came from", "",
*_table(("Site", "Views", "Visitors"),
[(r["referrer"], r["count"], r["uniques"]) for r in github["referrers"]]),
"### Most viewed", "",
*_table(("Path", "Views"), [(p["path"], p["count"]) for p in github["paths"]]),
"### Release downloads", "",
*_table(("Release", "File", "Downloads"),
sorted(github["downloads"], key=lambda row: -row[2]), limit=40)]
return "\n".join(out).rstrip() + "\n"
def collection_names(db: dict, profiles: dict[str, dict]) -> tuple[set[str], set[str]]:
"""File names the collection holds, and those a profile declares."""
held = {name.casefold() for name in db.get("indexes", {}).get("by_name", {})}
declared: set[str] = set()
for profile in profiles.values():
for entry in profile.get("files") or []:
if isinstance(entry, dict):
for name in [entry.get("name"), *(entry.get("aliases") or [])]:
if name:
declared.add(Path(str(name)).name.casefold())
return held, declared
+458
View File
@@ -0,0 +1,458 @@
"""Each built page as Markdown, for the assistants that read the site."""
from __future__ import annotations
import hashlib
import json
import os
import re
import subprocess
from collections.abc import Callable
from html.parser import HTMLParser
from pathlib import Path
from typing import ClassVar
from core.paths import REPO_ROOT
SITE = "https://abdess.github.io"
BASE = "/retrobios/"
# Elements whose content is never words a reader needs.
SKIPPED = frozenset({"script", "style", "svg", "button", "nav", "template", "noscript", "video"})
HEADINGS = {f"h{n}": n for n in range(1, 7)}
# The pages llms-full.txt joins, by path under the site, in reading order.
FULL_PAGES = ("", "which-pack/", "wiki/what-are-bios-files/", "wiki/first-install/",
"wiki/troubleshooting/", "wiki/faq/", "wiki/installer/", "wiki/legal/",
"wiki/privacy/")
class _Converter(HTMLParser):
"""The Markdown of a page's article: its title and its content."""
def __init__(self, page_url: str) -> None:
super().__init__(convert_charrefs=True)
self.page_url = page_url
self.out: list[str] = []
self.skip = 0
self.inside = 0
self.depth_stack: list[str] = []
self.lists: list[list[int]] = []
self.pre = 0
self.links: list[str | None] = []
self.row: list[str] | None = None
self.cell: list[str] | None = None
self.table: list[list[str]] | None = None
self.header_rows = 0
self.title = ""
self._in_title = False
# A tab's name by its id, read from the tab list, said above its
# panel: a command under the wrong OS is the answer an assistant
# gets wrong.
self.tab_names: dict[str, str] = {}
self._tab: str | None = None
self._card = False
# Output
def _emit(self, text: str) -> None:
if self.cell is not None:
self.cell.append(text)
else:
self.out.append(text)
def _block(self) -> None:
if self.cell is not None:
self.cell.append(" ")
return
joined = "".join(self.out)
if joined and not joined.endswith("\n\n"):
self.out.append("\n" if joined.endswith("\n") else "\n\n")
# Parsing
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
attr = {key: value or "" for key, value in attrs}
classes = set(attr.get("class", "").split())
if tag == "h1" and attr.get("id") == "_top":
self._in_title = True
if not self.inside:
if "sl-markdown-content" in classes:
self.inside = 1
self.depth_stack = [tag]
return
if tag not in ("br", "img", "hr", "input", "meta", "link", "source", "wbr"):
self.depth_stack.append(tag)
if self._open_tabs(tag, attr) or self._open_skipped(tag, attr, classes):
return
if self.pre:
# Inside a code block a line is a div, never a paragraph.
if tag == "div" and "ec-line" in classes and not "".join(self.out[-1:]).endswith("```\n"):
self._emit("\n")
return
opener = self._OPENERS.get(tag)
if opener is not None:
opener(self, tag, attr, classes)
def _open_tabs(self, tag: str, attr: dict[str, str]) -> bool:
"""A tab list, a tab's name or a tab panel: True when handled."""
if attr.get("role") == "tablist":
self.skip += 1
return True
if self.skip and attr.get("role") == "tab" and attr.get("id"):
self._tab = attr["id"]
self.tab_names[self._tab] = ""
self.skip += 1
return True
if attr.get("role") == "tabpanel" and not self.skip:
self._block()
name = self.tab_names.get(attr.get("aria-labelledby", ""), "").strip()
if name:
self._emit(f"**{' '.join(name.split())}:**")
self._block()
return True
return False
def _open_skipped(self, tag: str, attr: dict[str, str], classes: set[str]) -> bool:
# A `hidden` element is chrome the page's script shows (a filter
# box, the file picker, a setup's install chooser): a tab panel,
# hidden too, was read above.
if self.skip or tag in SKIPPED or attr.get("aria-hidden") == "true" or "hidden" in attr \
or classes & {"sr-only", "sl-anchor-link", "copy", "rb-anchor"}:
if tag not in ("br", "img", "hr", "input", "wbr"):
self.skip += 1
return True
return False
def _open_heading(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._block()
self._emit("#" * HEADINGS[tag] + " ")
def _open_block(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._block()
def _open_bold_block(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._block()
self._emit("**")
def _open_list(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._block()
self.lists.append([0 if tag == "ol" else -1])
def _open_item(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
if self.out and not "".join(self.out[-1:]).endswith("\n"):
self._emit("\n")
level = len(self.lists) - 1
marker = "-"
if self.lists and self.lists[-1][0] >= 0:
self.lists[-1][0] += 1
marker = f"{self.lists[-1][0]}."
self._emit(" " * max(level, 0) + marker + " ")
def _open_pre(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._block()
self.pre += 1
self._emit("```\n")
def _open_code(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
if not self.pre:
self._emit("`")
def _open_strong(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._emit("**")
def _open_em(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._emit("*")
def _open_link(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
href = attr.get("href", "")
if "rb-card" in classes:
# A card of a grid: one list line each, its name then what it
# says, instead of one run-on line of links.
href = SITE + href if href.startswith("/") else href
self._block()
self._emit("- [")
self.links.append(href or None)
self._card = True
return
if href.startswith("#"):
href = self.page_url + href
elif href.startswith("/"):
href = SITE + href
self.links.append(href or None)
if href:
self._emit("[")
def _open_span(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
if self._card and self.links:
self._emit(": ")
def _open_img(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
alt = attr.get("alt", "").strip()
if alt:
self._emit(alt)
def _open_table(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._block()
self.table, self.header_rows = [], 0
def _open_row(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
if self.table is not None:
self.row = []
def _open_cell(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
if self.row is not None:
self.cell = []
if tag == "th" and not self.row:
self.header_rows = max(self.header_rows, len(self.table or []) + 1)
def _open_definition(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._emit(": ")
_OPENERS: ClassVar[dict[str, Callable[[_Converter, str, dict[str, str], set[str]], None]]] = {
**dict.fromkeys(HEADINGS, _open_heading),
**dict.fromkeys(("p", "div", "section", "figure", "details", "blockquote", "dl"), _open_block),
"summary": _open_bold_block,
"dt": _open_bold_block,
"ul": _open_list,
"ol": _open_list,
"li": _open_item,
"pre": _open_pre,
"code": _open_code,
"strong": _open_strong,
"b": _open_strong,
"em": _open_em,
"i": _open_em,
"a": _open_link,
"span": _open_span,
"img": _open_img,
"table": _open_table,
"tr": _open_row,
"td": _open_cell,
"th": _open_cell,
"dd": _open_definition,
}
def handle_endtag(self, tag: str) -> None:
if tag == "h1" and self._in_title:
self._in_title = False
if not self.inside:
return
if self.depth_stack:
self.depth_stack.pop()
if not self.depth_stack:
self.inside = 0
return
if self.skip:
if tag not in ("br", "img", "hr", "input", "wbr"):
self.skip -= 1
if tag == "a" and self._tab:
self._tab = None
return
if self.pre and tag != "pre":
return
closer = self._CLOSERS.get(tag)
if closer is not None:
closer(self, tag)
def _close_block(self, tag: str) -> None:
self._block()
def _close_summary(self, tag: str) -> None:
self._emit("**")
self._block()
def _close_list(self, tag: str) -> None:
if self.lists:
self.lists.pop()
self._block()
def _close_pre(self, tag: str) -> None:
self.pre -= 1
self._emit("\n```")
self._block()
def _close_code(self, tag: str) -> None:
if not self.pre:
self._emit("`")
def _close_strong(self, tag: str) -> None:
self._emit("**")
def _close_em(self, tag: str) -> None:
self._emit("*")
def _close_link(self, tag: str) -> None:
href = self.links.pop() if self.links else None
if href:
self._emit(f"]({href})")
if self._card:
self._card = False
self._emit("\n")
def _close_cell(self, tag: str) -> None:
if self.cell is not None and self.row is not None:
self.row.append(" ".join("".join(self.cell).split()).replace("|", "\\|"))
self.cell = None
def _close_row(self, tag: str) -> None:
if self.row is not None and self.table is not None:
self.table.append(self.row)
self.row = None
def _close_table(self, tag: str) -> None:
if self.table is None:
return
rows, self.table = self.table, None
if rows:
width = max(len(r) for r in rows)
rows = [r + [""] * (width - len(r)) for r in rows]
head = rows[0] if self.header_rows else [""] * width
body = rows[1:] if self.header_rows else rows
lines = ["| " + " | ".join(head) + " |", "|" + "---|" * width]
lines += ["| " + " | ".join(r) + " |" for r in body]
self.out.append("\n".join(lines))
self._block()
def _close_break(self, tag: str) -> None:
self._emit("\n" if self.pre else " \n")
_CLOSERS: ClassVar[dict[str, Callable[[_Converter, str], None]]] = {
**dict.fromkeys(HEADINGS, _close_block),
**dict.fromkeys(("p", "section", "figure", "details", "blockquote", "dl"), _close_block),
"summary": _close_summary,
"ul": _close_list,
"ol": _close_list,
"pre": _close_pre,
"code": _close_code,
"strong": _close_strong,
"b": _close_strong,
"dt": _close_strong,
"em": _close_em,
"i": _close_em,
"a": _close_link,
"td": _close_cell,
"th": _close_cell,
"tr": _close_row,
"table": _close_table,
"br": _close_break,
}
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
self.handle_starttag(tag, attrs)
if tag not in ("img", "br", "hr", "input", "wbr", "meta", "link", "source"):
self.handle_endtag(tag)
def handle_data(self, data: str) -> None:
if self._in_title and not self.inside:
self.title += data
return
if self._tab is not None:
self.tab_names[self._tab] += data
if not self.inside or self.skip:
return
if self.pre:
# The whitespace between <pre> and its first line is no line.
if data.strip() or not "".join(self.out[-1:]).endswith("```\n"):
self._emit(data)
return
text = re.sub(r"\s+", " ", data)
if text.strip() or (text and self.out and not "".join(self.out[-1:]).endswith((" ", "\n"))):
self._emit(text)
def markdown(self) -> str:
body = "".join(self.out)
body = re.sub(r"[ \t]+\n", "\n", body)
body = re.sub(r"\n{3,}", "\n\n", body).strip()
title = " ".join(self.title.split())
return (f"# {title}\n\n" if title else "") + f"Source: {self.page_url}\n\n{body}\n"
def page_markdown(html: str, page_url: str) -> str:
converter = _Converter(page_url)
converter.feed(html)
converter.close()
return converter.markdown()
ROOT = REPO_ROOT
def build_stamp() -> dict[str, str]:
"""The commit the site is built from and its date. CI names the commit
in GITHUB_SHA. The date is the commit's, so two builds of one commit
write the same bytes."""
commit = os.environ.get("GITHUB_SHA") or subprocess.run(
["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, text=True,
check=True).stdout.strip()
date = subprocess.run(["git", "log", "-1", "--format=%cI", commit], cwd=ROOT,
capture_output=True, text=True, check=True).stdout.strip()
return {"commit": commit, "date": date}
def stamp_line(stamp: dict[str, str]) -> str:
return (f"> Built from commit {stamp['commit'][:12]} on {stamp['date'][:10]}. "
f"The current build: {SITE}{BASE}version.json")
def stamped(text: str, stamp: dict[str, str]) -> str:
"""*text* with the build line under its first line, the title."""
first, _, rest = text.partition("\n")
return f"{first}\n\n{stamp_line(stamp)}\n{rest}"
def convert_site(dist: Path, stamp: dict[str, str] | None = None) -> int:
"""Write index.md beside every page's index.html, then llms-full.txt,
version.json and digests.json, and stamp llms.txt."""
stamp = stamp or build_stamp()
written = 0
digests: dict[str, str] = {}
for html_path in sorted(dist.rglob("index.html")):
relative = html_path.parent.relative_to(dist).as_posix()
page = "" if relative == "." else f"{relative}/"
url = f"{SITE}{BASE}{page}"
text = page_markdown(html_path.read_text(encoding="utf-8"), url)
digests[url] = hashlib.sha256(text.encode("utf-8")).hexdigest()
(html_path.parent / "index.md").write_text(stamped(text, stamp), encoding="utf-8")
written += 1
write_full(dist, stamp)
llms = dist / "llms.txt"
if llms.is_file():
text = llms.read_text(encoding="utf-8")
digests[f"{SITE}{BASE}llms.txt"] = hashlib.sha256(text.encode("utf-8")).hexdigest()
# Under the summary, which llms.txt keeps as the quote after its title.
title, summary, rest = text.split("\n\n", 2)
line = stamp_line(stamp).removeprefix("> ")
llms.write_text(f"{title}\n\n{summary}\n\n{line}\n\n{rest}", encoding="utf-8")
(dist / "version.json").write_text(json.dumps(stamp, indent=1) + "\n", encoding="utf-8")
(dist / "digests.json").write_text(
json.dumps(dict(sorted(digests.items())), indent=0) + "\n", encoding="utf-8")
return written
def _unstamped(text: str, stamp: dict[str, str]) -> str:
"""A page's copy without its build line: llms-full.txt says it once."""
return text.replace(f"\n\n{stamp_line(stamp)}\n", "\n", 1)
def write_full(dist: Path, stamp: dict[str, str]) -> None:
"""llms-full.txt from the pages' Markdown copies."""
parts = ["# RetroBIOS: the guides in one file", "", stamp_line(stamp), "",
"> The pages a setup is done with, in reading order. Every page of the site also has "
"its own Markdown copy at `<page>/index.md`.", ""]
for page in FULL_PAGES:
md = dist / page / "index.md"
if md.is_file():
parts += [_unstamped(md.read_text(encoding="utf-8"), stamp).rstrip(), "", "---", ""]
# Each setup's own page (the setups the picker lists, not the parts a
# long page is cut into), up to its reference of every file: what to
# do and where, not the full lists, which its own copy keeps. All of
# them was 6.9 MB, past what an assistant reads at once.
index = dist / "data" / "picker" / "index.json"
setups = [str(item["platform"]) for item in json.loads(index.read_text(encoding="utf-8"))] \
if index.is_file() else []
for setup in [*setups, "linux-handhelds"]:
md = dist / "platforms" / setup / "index.md"
if md.is_file():
text = _unstamped(md.read_text(encoding="utf-8"), stamp)
parts += [text.split("\n## Reference", 1)[0].rstrip(), "", "---", ""]
(dist / "llms-full.txt").write_text("\n".join(parts).rstrip() + "\n", encoding="utf-8")
+977
View File
@@ -0,0 +1,977 @@
"""The README and CONTRIBUTING texts, from the database, the platforms and the release."""
from __future__ import annotations
import json
import os
import re
import sys
from collections.abc import Callable
from datetime import datetime, timezone
from pathlib import Path
from types import ModuleType
import archive_build
import pr_checks
import release_record
from core.artifacts import write_if_changed
from core.cli import InputMissing
from core.github import github_token
from core.paths import REPO_ROOT
from model.composition import compute_composition, count_catalog_matched
from model.declarations import declared_root
from model.guides import PACKAGE_COMMAND, install_command
from model.largefiles import LARGE_FILES_CACHE, load_registered_paths
from model.platforms import load_platform_config
from model.profiles import load_emulator_profiles, unique_emulator_profiles
from model.registry import list_registered_platforms, load_platform_registry
from model.systems import system_index
from packs.coverage import verify_platform
from resolve.cores import resolve_platform_cores
from resolve.review import LARGE_FILE_ISSUE_URL
def _installer_words() -> ModuleType:
"""install.py read as a module, for the words its screen shows: the
README named a line menu the one-liner never opens."""
import importlib.util
path = REPO_ROOT / "install.py"
spec = importlib.util.spec_from_file_location("install", path)
if spec is None or spec.loader is None:
raise ImportError(f"cannot load {path}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
# The repository's profiles wherever the script is run from: a bare
# "emulators" read the working directory, and a run elsewhere counted 0 cores.
_EMULATORS_DIR = str(REPO_ROOT / "emulators")
def compute_coverage(
platform_name: str,
platforms_dir: str,
db: dict,
data_registry: dict | None = None,
emulators_dir: str = _EMULATORS_DIR,
) -> dict:
config = load_platform_config(platform_name, platforms_dir)
result = verify_platform(
config,
db,
emulators_dir,
data_dir_registry=data_registry,
)
sc = result.get("status_counts", {})
ok = sc.get("ok", 0)
untested = sc.get("untested", 0)
missing = sc.get("missing", 0)
total = result["total_files"]
# An UNTESTED file the builder refuses (its declared hash contradicted on
# a hash platform) is held, not packed.
present = ok + untested - len(result.get("excluded_files", []))
pct = (present / total * 100) if total > 0 else 0
undeclared = result.get("undeclared_files", [])
# Held is not packed: a file the platform has no folder for, or one below
# a folder it lists flat, stays out of the pack the fraction describes.
core_present = sum(
1 for u in undeclared if u.get("in_repo") and u.get("in_pack", True)
)
core_missing = len(undeclared) - core_present
# Files a profile marks unsourceable never reach the undeclared list, so
# the gap they represent has to be counted back in.
profiles = load_emulator_profiles(emulators_dir)
unsourceable_names = {
f.get("name", "")
for emu in resolve_platform_cores(config, profiles)
for f in (profiles.get(emu) or {}).get("files", []) or []
if f.get("unsourceable")
}
core_unsourceable = len(unsourceable_names)
missing_names = unsourceable_names | {
u.get("name", "") for u in undeclared if not u.get("in_repo")
}
return {
"platform": config.get("platform", platform_name),
"total": total,
"verified": ok,
"untested": untested,
"missing": missing,
"missing_not_firmware": {
category: len(dests)
for category, dests in (result.get("missing_not_firmware") or {}).items()
},
"present": present,
"percentage": pct,
"core_present": core_present,
"core_missing": core_missing,
"core_unsourceable": core_unsourceable,
"missing_names": missing_names,
"unsourceable_names": unsourceable_names,
"pack_files": present + core_present,
"total_missing": missing + core_missing,
"mode": config.get("verification_mode", "existence"),
"details": result["details"],
"config": config,
"ground_truth": result.get(
"ground_truth_coverage",
{"with_validation": 0, "platform_only": total, "total": total},
),
}
_REPO = REPO_ROOT
# The site and the README read the same coverage: the first generator to run
# stores it here and the second reads it back, instead of verifying every
# platform twice (about a minute of the site build).
COVERAGE_CACHE_DIR = _REPO / "tmp" / "coverage-cache"
_COVERAGE_CACHE_FORMAT = "3"
def _coverage_inputs(db_path: Path, platforms_dir: str, emulators_dir: str) -> str:
"""A digest of everything coverage is computed from.
The database, the platform and emulator files, the code, the install
manifests, the data directory revisions, the state of bios/ on disk, and
what a release asset resolves to: the large-file cache and whether this
run may download. A test run is offline with its own cache, and its
result was read back by the next normal run (Lakka 534/535 for 535/535).
A change to any of them computes the coverage again.
"""
import hashlib
digest = hashlib.sha256(_COVERAGE_CACHE_FORMAT.encode())
def add_file(path: Path) -> None:
digest.update(str(path).encode() + b"\0")
digest.update(path.read_bytes() if path.is_file() else b"<absent>")
add_file(db_path.resolve())
for root, pattern in ((Path(platforms_dir), "*"), (Path(emulators_dir), "*.yml"),
(_REPO / "scripts", "*.py"), (_REPO / "install", "*.json"),
(_REPO / "recipes", "*.json")):
for path in sorted(p for p in root.resolve().rglob(pattern) if p.is_file()):
add_file(path)
for path in (_REPO / ".gitignore", _REPO / "_mame_clones.json",
_REPO / "data" / ".versions.json"):
add_file(path)
digest.update(b"offline\0" + (b"1" if os.environ.get("RETROBIOS_OFFLINE") else b"0") + b"\n")
large = Path(LARGE_FILES_CACHE).resolve()
digest.update(str(large).encode() + b"\0")
for path in sorted(large.glob("*")) if large.is_dir() else ():
if path.is_file():
stat = path.stat()
digest.update(f"{path.name}\0{stat.st_size}\0{stat.st_mtime_ns}\n".encode())
bios = _REPO / "bios"
for path in sorted(bios.rglob("*")):
if path.is_file():
stat = path.stat()
digest.update(f"{path.relative_to(bios)}\0{stat.st_size}\0{stat.st_mtime_ns}\n".encode())
return digest.hexdigest()
def platform_coverages(
platform_names: list[str],
platforms_dir: str,
db: dict,
data_registry: dict | None = None,
emulators_dir: str = _EMULATORS_DIR,
db_path: str = "database.json",
report: Callable[[str, dict], None] | None = None,
) -> dict[str, dict]:
"""compute_coverage for each platform, read from the cache when its
inputs have not changed since a generator last stored it.
A platform with no YAML is left out, as compute_coverage raises for it.
``report`` is called with each platform and its coverage.
"""
# pickle, not JSON: the coverage holds sets and enums that JSON would
# turn into lists and strings. The file is written by this function into
# the repository's own tmp/, never downloaded.
import pickle
key = _coverage_inputs(Path(db_path), platforms_dir, emulators_dir)
names = sorted(platform_names)
cache = COVERAGE_CACHE_DIR / f"{key}.pickle"
coverages: dict[str, dict] | None = None
if cache.is_file():
try:
with cache.open("rb") as handle:
stored = pickle.load(handle)
except (OSError, EOFError, pickle.UnpicklingError) as exc:
print(f" coverage cache unreadable, computing again: {exc}", file=sys.stderr)
else:
if stored.get("platforms") == names:
coverages = stored["coverages"]
print(f" coverage read from {cache.relative_to(_REPO)}")
if coverages is None:
coverages = {}
for name in names:
try:
coverages[name] = compute_coverage(
name, platforms_dir, db, data_registry, emulators_dir=emulators_dir,
)
except InputMissing:
# A missing profile or platform directory is no platform
# left out: it emptied every one and cached the result.
raise
except FileNotFoundError as exc:
print(f" {name}: skipped ({exc})", file=sys.stderr)
COVERAGE_CACHE_DIR.mkdir(parents=True, exist_ok=True)
scratch = cache.with_suffix(f".{os.getpid()}.tmp")
with scratch.open("wb") as handle:
pickle.dump({"platforms": names, "coverages": coverages}, handle,
protocol=pickle.HIGHEST_PROTOCOL)
scratch.replace(cache)
# generate_site and generate_readme both purge here. One unlinking
# what the other had just listed ended it on FileNotFoundError.
for stale in COVERAGE_CACHE_DIR.glob("*.pickle"):
if stale != cache:
stale.unlink(missing_ok=True)
ordered = {name: coverages[name] for name in platform_names if name in coverages}
if report:
for name in names:
if name in ordered:
report(name, ordered[name])
return ordered
def release_totals(platform_name: str, record: dict) -> tuple[int | None, int | None]:
"""Files and bytes of the pack the latest release serves for a platform.
The Download link gives that release, so these are the figures a reader
can check against an extraction. The install manifests describe what
main would build today, which is a different pack as soon as a commit
lands after the release. Returns (None, None) for a platform the release
carries no pack for.
"""
pack = release_record.pack_for(platform_name, record)
if not pack:
return None, None
return pack["files"], pack["extracted_size"]
NO_PACK = "Use the command"
def asset_links(
platform_name: str, record: dict, repo: str, label: str, attrs: str = "",
button: Callable[[str, str], str] | None = None,
) -> str:
"""Markdown links to the files of a platform's pack in the recorded release.
Written on the platform's get/ page only: every other surface links that
page, whose address does not change with the release. A pack published
whole gets one link labelled *label*. A pack in parts gets one link per
part, since every part is needed, after the number of files to download:
a reader who took one link for the pack extracted half of it. *repo* is
the repository URL, *attrs* an attribute list put after each link, or
*button* the function that draws each link as a button. Without a
recorded release the link is the latest release page.
"""
pack = release_record.pack_for(platform_name, record)
tag = record.get("tag")
assets = pack.get("assets") if pack else None
def link(text: str, url: str) -> str:
return button(text, url) if button else f"[{text}]({url}){attrs}"
if not tag or not assets:
return link(label, f"{repo}/releases/latest")
urls = [f"{repo}/releases/download/{tag}/{asset}" for asset in assets]
if len(urls) == 1:
return link(label, urls[0])
styled = bool(attrs or button)
parts = [
link(f"{'P' if styled else 'p'}art {number} of {len(urls)}", url)
for number, url in enumerate(urls, 1)
]
if styled:
return f"{len(urls)} files to download, all needed: " + " ".join(parts)
return f"{label}, {len(urls)} files, all needed: " + ", ".join(parts)
def download_links(
platform_name: str, record: dict, label: str, attrs: str = "",
button: Callable[[str, str], str] | None = None,
site: str = "", platforms_dir: str = "platforms", page: str | None = None,
) -> str:
"""The download cell of a platform: its permanent get/ page.
*record* is the release record reduced to the release_pack platforms
(release_record.advertised). A platform with a pack in it gets *label*
linked to its page, which lists the files of the current release. A
platform marked release_pack but missing from the release, added since,
gets "No ZIP yet". Any other platform is served by the installer, and
the cell says so instead of staying empty. *site* is the site root the
get/ address hangs from, or *page* the address itself as the site links
it, and *attrs* and *button* style the link.
"""
page = page or release_record.get_page(platform_name, site)
def link(text: str) -> str:
return button(text, page) if button else f"[{text}]({page}){attrs}"
if (load_platform_registry(platforms_dir).get(platform_name) or {}).get("release_pack") is not True:
return link(NO_PACK)
pack = release_record.pack_for(platform_name, record)
if record.get("tag") and not (pack and pack.get("assets")):
return f"No ZIP yet: {link(NO_PACK.lower())}"
return link(label)
def extract_targets(platforms_dir: str) -> list[tuple[str, str]]:
"""(display name, folder) per registered platform, where its pack extracts.
Read from the registry so the README, the site and the pack guide answer
from one place. Sorted by display name.
"""
rows = [
(load_platform_config(key, platforms_dir).get("platform", key), entry["extract_to"])
for key, entry in load_platform_registry(platforms_dir).items()
if entry.get("extract_to")
]
return sorted(rows, key=lambda row: row[0].casefold())
def own_root(config: dict) -> str:
"""The folder a pack written from an empty base_destination starts with.
RetroDECK writes bios/ in front of its files, the MinUI family hands its
cores folders below Bios/.
"""
root = declared_root(config)
if root:
return root
tops = {directory.split("/", 1)[0] for directory in config.get("core_system_dirs") or {}}
return tops.pop() if len(tops) == 1 else "bios"
def extract_notes(platforms_dir: str, released_only: bool = False) -> list[str]:
"""A pack whose entries carry their own root extracts above the BIOS folder.
*released_only* keeps the platforms a release publishes a pack for.
"""
folders = dict(extract_targets(platforms_dir))
registry = load_platform_registry(platforms_dir)
notes = []
for key in sorted(registry):
if released_only and registry[key].get("release_pack") is not True:
continue
config = load_platform_config(key, platforms_dir)
display = config.get("platform", key)
if config.get("base_destination") == "" and display in folders:
notes.append(
f"The {display} pack holds its own `{own_root(config)}/` folder."
f" Unzip it into `{folders[display]}`."
)
return notes
def _extract_cells(platforms_dir: str) -> dict[str, str]:
"""The download table's "Extract to" cell, by display name."""
return {display: f"`{folder}`" for display, folder in extract_targets(platforms_dir)}
def _paragraphs(texts: list[str]) -> list[str]:
return [line for text in texts for line in ("", text)]
def download_table(
coverages: dict,
extract_paths: dict[str, str],
record: dict,
) -> list[str]:
"""One row per platform: what its released pack holds and where it extracts."""
lines = [
"| Platform | Files | Extracted size | Extract to | Download |",
"|----------|------:|---------------:|-----------|----------|",
]
for name, cov in sorted(coverages.items(), key=lambda x: x[1]["platform"]):
files, size = release_totals(name, record)
lines.append(
f"| {cov['platform']} | {f'{files:,}' if files else '-'} |"
f" {format_size(size) if size else '-'} |"
f" {extract_paths.get(cov['platform'], '')} |"
f" {download_links(name, record, 'Download', site=SITE_URL)} |"
)
return lines
def no_pack_line() -> str:
"""Why some rows read "Use the command", in one sentence."""
return (
"ZIPs are made for the setups most people download. The others read"
f" \"{NO_PACK}\": the installer above installs every file for them and"
" checks each one, and `--dry-run` shows what it would install"
f" ([why no ZIP]({SITE_URL}wiki/faq/#why-is-there-no-zip-for-my-setup))."
)
def _names_list(coverages: dict) -> str:
"""The platforms' names in reading order, the last after "and"."""
names = sorted(c["platform"] for c in coverages.values())
return ", ".join(names[:-1]) + f", and {names[-1]}" if len(names) > 1 else "".join(names)
def collection_line(total_files: int, comp: dict) -> str:
"""The size of the whole collection, said as such.
Printed bare beside the download links it read as the content of one
pack, and a complete extraction looked like a broken one.
"""
return (
f"- **{total_files:,} files in the collection**, each with its SHA1,"
" MD5, SHA256, CRC32 and Adler-32 fingerprints:"
f" {comp['systems']['files']:,} system files,"
f" {comp['arcade']['files']:,} arcade ROM sets,"
f" {comp['game_data']['files']:,} game and engine data files."
" That is every platform and emulator together, so no pack holds"
" them all: each carries what its own emulators load, counted in"
" the download table"
)
def format_size(size: int) -> str:
"""Human-readable pack size."""
if size >= 1024**3:
return f"{size / 1024**3:.1f} GB"
return f"{size / 1024**2:.0f} MB"
SITE_URL = "https://abdess.github.io/retrobios/"
# The installer demo (scripts/make_demo.py): the recording and what it shows.
DEMO_DIR = REPO_ROOT / "docs_assets" / "demo"
DEMO_GIF = "docs_assets/demo/install.gif"
REPO_PATH = "../.."
REPO = "Abdess/retrobios"
# GitHub's "Add file > Upload files" page for bios/: a browser upload by
# someone without write access lands on a fork and opens a pull request.
UPLOAD_URL = f"https://github.com/{REPO}/upload/main/bios"
def clone_line(db: dict) -> str:
"""How to get the clone the commands below run in, and its size.
Said bare, "clone the repo" started a multi-gigabyte transfer for a user
after a 20 MB --required-only pack. The size counts the collection files
the repository commits, a floor: release assets are fetched only when a
pack needs them.
"""
assets = set(load_registered_paths())
committed = sum(
entry.get("size", 0) for entry in db.get("files", {}).values()
if entry.get("path") not in assets
)
return (
"Packs are built from a clone, and the clone carries the collection:"
f" its checkout alone is over {format_size(committed)}."
f" `git clone --depth 1 https://github.com/{REPO}.git` leaves the"
" history out. Files kept as release assets are downloaded when a"
" pack needs them. Then generate packs for any platform, emulator,"
" or system:"
)
def demo_facts(variant: str = "default") -> dict:
"""What an installer demo shows, as make_demo.py measured it: one entry
per variant (default, handheld)."""
facts = json.loads((DEMO_DIR / "demo.json").read_text(encoding="utf-8"))
return facts[variant]
def demo_description(facts: dict | None = None) -> str:
"""The demo in words, for a reader who cannot see it: the alt text
make_demo.py wrote from what it measured."""
return str((facts or demo_facts())["alt"])
def _existing_contributor_block(readme_path: str = "README.md") -> list[str]:
"""The contributors already published, read back from the file.
The section is the one part of this document that comes from the network.
A refused or rate-limited request used to leave the list empty, which
silently deleted the section from a published README and put the local
result permanently at odds with what the freshness check regenerates.
Keeping what is already there makes an offline run additive-only.
"""
try:
with open(readme_path, encoding="utf-8") as handle:
text = handle.read()
except OSError:
return []
start = text.find("## Contributors")
if start == -1:
return []
rest = text[start:].splitlines()
block = []
for line in rest[1:]:
if line.startswith("## "):
break
block.append(line)
while block and not block[-1].strip():
block.pop()
return ["## Contributors"] + block if block else []
def fetch_contributors() -> list[dict]:
"""Fetch contributors from GitHub API, exclude bots."""
import urllib.error
import urllib.request
url = f"https://api.github.com/repos/{REPO}/contributors"
headers = {"User-Agent": "retrobios-readme/1.0"}
token = github_token()
if token:
headers["Authorization"] = f"token {token}"
try:
req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req, timeout=10) as resp:
data = json.loads(resp.read().decode())
owner = REPO.split("/")[0]
return [
c
for c in data
if not c.get("login", "").endswith("[bot]")
and c.get("type") == "User"
and c.get("login") != owner
]
except (urllib.error.URLError, urllib.error.HTTPError):
return []
_CATALOG_LABELS = {"redump": "Redump", "no-intro": "No-Intro", "tosec": "TOSEC"}
def _catalog_matched_line(db: dict) -> list[str]:
"""Bullet line for files matched to dump-preservation catalogs."""
matched = count_catalog_matched(db)
if not matched:
return []
sources: set[str] = set()
for entry in db.get("files", {}).values():
sources.update(entry.get("provenance") or ())
system_files = compute_composition(db)["systems"]["files"]
labels = ", ".join(_CATALOG_LABELS.get(s, s) for s in sorted(sources))
return [
f"- **{matched:,} of {system_files:,} system files** matched to"
f" dump-preservation catalogs ({labels}). Arcade sets and engine data"
f" fall outside what those catalogs index"
]
# The badge row under the links: (alt text, image, link). A badge earns its
# place by saying what the page does not: the Python floor is in the install
# text, and GitHub cannot name the license of LICENSE, which opens on its scope.
BADGES = (
("PyPI version", "https://img.shields.io/pypi/v/retrobios", "https://pypi.org/project/retrobios/"),
("Validation",
"https://github.com/Abdess/retrobios/actions/workflows/validate.yml/badge.svg?branch=main",
"https://github.com/Abdess/retrobios/actions/workflows/validate.yml"),
)
def badge_row() -> str:
badges = " ".join(f'<a href="{link}"><img src="{image}" alt="{alt}"></a>'
for alt, image, link in BADGES)
return f'<p align="center">{badges}</p>'
def archive_line(counts: dict[str, int]) -> str:
"""The README's line on archive recipes, counted from recipes/archives.json."""
return (f"- **{counts['total']:,} archives**, each with a recipe that rebuilds it from the"
f" ROMs the collection holds: {counts['exact']:,} byte for byte,"
f" {counts['canonical']:,} with the same files inside"
f" ([rebuilding an archive]({SITE_URL}wiki/archive-recipes/))")
def generate_readme(db: dict, platforms_dir: str, db_path: str = "database.json") -> str:
total_files = db.get("total_files", 0)
ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
platform_names = list_registered_platforms(platforms_dir)
from model.registry import load_data_dir_registry
data_registry = load_data_dir_registry(platforms_dir)
coverages = platform_coverages(platform_names, platforms_dir, db, data_registry,
db_path=db_path)
profiles = unique_emulator_profiles(
load_emulator_profiles("emulators", skip_aliases=False)
)
emulator_count = len(profiles)
profile_files = [f for prof in profiles.values() for f in prof.get("files") or []
if isinstance(f, dict)]
# A citation counts when it names a line, `file.c:120`: a bare file name
# or a binary offset does not point at the code that reads the file.
cited_share = (round(100 * sum(1 for f in profile_files
if re.search(r"\.\w+:\d", str(f.get("source_ref") or "")))
/ len(profile_files)) if profile_files else 0)
closed_count = sum(1 for prof in profiles.values()
if str(prof.get("upstream") or "").startswith("closed"))
system_ids = system_index(profiles)
# The README is the repository's front page and its most read page: a
# visitor from a search lands here, often new to terminals. It says what
# the project does, gives the one line that installs, shows it, and leads
# on to the site, where every detail lives. The figures and the lists it
# once carried (coverage, collection, build commands) are the site's.
record = release_record.load_advertised(platforms_dir=platforms_dir)
extract_paths = _extract_cells(platforms_dir)
released = [name for name in sorted(coverages, key=lambda n: coverages[n]["platform"])
if release_totals(name, record)[0]]
lines = [
'<p align="center">',
" <picture>",
' <source media="(prefers-color-scheme: dark)" srcset=".github/assets/banner-dark.svg">',
' <img src=".github/assets/banner-light.svg" alt="RetroBIOS" width="400">',
" </picture>",
"</p>",
"",
'<p align="center"><strong>The BIOS files emulators need, put in the right folder and checked.</strong></p>',
"",
'<p align="center">'
f'<a href="{SITE_URL}">Website</a> · '
f'<a href="{SITE_URL}which-pack/">Get the files</a> · '
f'<a href="{SITE_URL}wiki/troubleshooting/">A game does not start</a> · '
f'<a href="{SITE_URL}wiki/faq/">Questions</a>'
"</p>",
"",
badge_row(),
"",
"Some consoles need a small program, the **BIOS**, to start their games: PlayStation 1"
" and 2, Saturn, Neo Geo, Dreamcast and more. RetroBIOS installs the BIOS and firmware"
f" files for {_names_list(coverages)}, checked the way each one checks them.",
"",
"## Install in one line",
"",
"**Windows**: open the Start menu, type **PowerShell** and open it. Paste this line"
" (Ctrl+V or right-click in the window) and press Enter.",
"",
"```powershell",
install_command("powershell"),
"```",
"",
"**Linux, macOS, Steam Deck, Android (Termux)**: open a terminal, paste this line"
" and press Enter.",
"",
"```bash",
install_command("sh"),
"```",
"",
f"**With Python 3.8 or newer**: `{PACKAGE_COMMAND}` runs the same installer, and so"
" does `pipx run retrobios`.",
"",
f"**A handheld, an SD card, or not sure?** [Pick the device]({SITE_URL}which-pack/):"
" its page gives the folder and the command. A muOS, Onion, spruceOS, MinUI, KNULLI,"
" ROCKNIX, Lakka or MiSTer SD card plugged into the computer is found by itself.",
"",
f"![{demo_description()}]({DEMO_GIF})",
"",
"The installer finds the setup and its BIOS folder, installs the files it needs (only"
" what the games need when it finds them on the card) and checks each one. Its screen"
" installs everything, or fewer under **" + _installer_words().TUI_SYSTEMS_ROW + "**."
" Arrow keys and Enter drive it, or a controller on a handheld. It sends no report of"
f" its own ([what is counted]({SITE_URL}wiki/privacy/)). Options go after the line in the"
f" form the [installer page]({SITE_URL}wiki/installer/#passing-options) gives.",
"",
f"First time? [The first install, step by step]({SITE_URL}wiki/first-install/)."
f" A game does not start: [what to check]({SITE_URL}wiki/troubleshooting/)."
f" Other questions: [FAQ]({SITE_URL}wiki/faq/).",
"",
"## Or download a ZIP",
"",
"The Files column counts what a pack holds once unzipped.",
"",
"| Setup | Files | Size | Unzip into | Download |",
"|-------|------:|-----:|------------|----------|",
]
for name in released:
files, size = release_totals(name, record)
display = coverages[name]["platform"]
lines.append(
f"| {display} | {files:,} | {format_size(size) if size else '-'} |"
f" {extract_paths.get(display, '')} |"
f" {download_links(name, record, 'Download', site=SITE_URL)} |"
)
others = [name for name in sorted(coverages, key=lambda n: coverages[n]["platform"])
if name not in released]
lines.extend([
"",
"ZIPs are made for the setups most people download. The others install with the line"
" above, and each page gives the command: "
+ ", ".join(f"[{coverages[name]['platform']}]({SITE_URL}get/{name}/)" for name in others)
+ ".",
"",
"Unzip into the BIOS folder, files straight in it. A big pack comes in parts"
" (`Pack.part1of2.zip`): download every part"
f" ([why some setups have no ZIP]({SITE_URL}wiki/faq/#why-is-there-no-zip-for-my-setup))."
" Each release lists its files' SHA-256 with a signature"
f" ([verifying a release]({SITE_URL}wiki/release-process/#verifying-a-release)).",
"",
"## Help",
"",
f"- \"BIOS missing\" or a game does not start: [what to check]({SITE_URL}wiki/troubleshooting/)",
f"- Have a file? [Check it by its hash]({SITE_URL}files/)",
f"- Every console and the files it needs: [systems]({SITE_URL}systems/)",
f"- Asking an AI assistant: it reads the site best from [llms.txt]({SITE_URL}llms.txt)",
"",
"## How it is built",
"",
f"- **{emulator_count} emulators profiled**, {emulator_count - closed_count} from their"
f" source code and {closed_count} closed-source builds from their binaries:"
f" {cited_share}% of the files they load cite the file and line that reads them",
f"- **{len(coverages)} setups**, each checked its own way: MD5 for Batocera and Recalbox,"
" the file name for RetroArch, as their own code does",
f"- **{len(system_ids)} systems**, {total_files:,} files in the collection,"
f" [what is still missing]({SITE_URL}gaps/) named file by file",
archive_line(archive_build.rebuild_counts()),
f"- Public data: [JSON, CSV and SQLite]({SITE_URL}data/), the metadata under MIT",
"",
"<details>",
"<summary><strong>For developers: build a pack</strong></summary>",
"",
clone_line(db),
"",
"```bash",
"python scripts/generate_pack.py --platform retroarch --output-dir dist/",
"python scripts/generate_pack.py --emulator dolphin",
"python scripts/generate_pack.py --platform batocera --required-only",
"python scripts/verify.py --platform batocera",
"```",
"",
"Requires Python 3.9 or newer and `pyyaml`. The one-line installer alone runs on Python 3.8."
f" Every tool and option: [tools]({SITE_URL}wiki/tools/). How the lists are built:"
f" [architecture]({SITE_URL}wiki/architecture/).",
"",
"</details>",
"",
])
contributors = fetch_contributors()
if not contributors:
# The request failed. Republish what is already there rather than
# dropping the section: losing it is a worse answer than a stale list.
kept = _existing_contributor_block("README.md")
if kept:
print("contributors: request failed, keeping the published list")
lines.extend(kept + [""])
if contributors:
lines.extend(
[
"## Contributors",
"",
]
)
for c in contributors:
login = c["login"]
avatar = c.get("avatar_url", "")
url = c.get("html_url", f"https://github.com/{login}")
lines.append(
f'<a href="{url}"><img src="{avatar}" width="50" alt="{login}"'
f' title="{login}"></a>'
)
lines.append("")
lines.extend(
[
"",
"## Community tools",
"",
"- [BIOS Preservation Tool](https://github.com/monster-penguin/BIOS-Preservation-Tool)"
" by [monster-penguin](https://github.com/monster-penguin)"
" - scans, verifies and stages a BIOS collection"
" using RetroBIOS hash metadata",
"",
"## Contributing",
"",
"See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.",
"",
"## License",
"",
"The scripts and tooling are released under the [MIT License](LICENSE).",
"The BIOS and firmware files are not covered by that license: they are"
" third-party system software, preserved and provided for personal"
" backup, archival, and interoperability with emulation software."
" [NOTICE](NOTICE) sets out their status and how to ask for a file"
" to be removed.",
f"The reasoning, and where it is weakest, is in"
f" [the project's legal position]({SITE_URL}wiki/legal/).",
"",
f"*Auto-generated on {ts}*",
]
)
return "\n".join(lines) + "\n"
def ci_install_lines() -> tuple[str, str]:
"""The pip lines the test job of validate.yml runs, verbatim.
The guide listed the packages without their versions, so a local run
could pass on releases CI never installs. Read from the workflow, the
two cannot disagree. The second line is the Python 3.8 one.
"""
text = (_REPO / ".github" / "workflows" / "validate.yml").read_text(encoding="utf-8")
main = re.search(r'^\s*run: (pip install pyyaml "jsonschema.*markdown.*)$', text, re.M)
floor = re.search(r"^\s*run: (python3\.8 -m pip install .*)$", text, re.M)
if main is None or floor is None:
raise RuntimeError("validate.yml no longer installs the packages CONTRIBUTING quotes")
return main.group(1), floor.group(1)
def contributing_text(
link: Callable[[str], str], title: str, site_words: str
) -> str:
"""The contribution guide, one text for the repository and the site.
Two copies drifted apart: four steps to add a platform here, five on the
site. *link* renders a site page (absolute URL for the README, relative
.md for the site); *site_words* names the site from where the text is read.
"""
pip_line, floor_line = ci_install_lines()
width = max(len(pr_checks.shown(step)) for step in pr_checks.STEPS)
steps = "\n".join(f"{pr_checks.shown(step):<{width}} # {step.why}" for step in pr_checks.STEPS)
return f"""{title}
## Add a BIOS file
Have a file the collection lacks? Add it from the browser. It is checked on arrival.
Not sure? Drop it on [the wanted page]({link("wanted")}). It reads the file on
the device, says if it is wanted, and opens the upload in the right folder.
[Upload it into `bios/`]({UPLOAD_URL}), 25 MB at most per file. GitHub
writes it to a fork and opens the pull request.
The files most wanted are on [what the packs do not hold]({link("gaps")}). The
[dump provenance]({link("provenance")}) page lists catalogued dumps still
missing from the collection, with their hashes. A file matching one of those is
the most useful contribution.
## What happens next
1. CI hashes the file and looks it up in every platform list and emulator
profile. For a file it recognises, it names the folder holding the other
files of its system. The report is in the summary of the pull request's
Validation run.
2. The file can be moved to that folder in the same pull request. A file whose
hash differs from the one already held under its name goes to that folder's
`.variants/`.
A ZIP that no list declares as a whole is read file by file, and the report
says which of them the collection already holds: upload the files
themselves, unzipped.
From a clone, the file goes to `bios/Manufacturer/Console/filename`, and
`python scripts/validate_pr.py path/to/file` names that folder for a file still
outside `bios/`, and `--place` copies it there under its declared name. Given a
folder, such as an old card's BIOS folder, it checks every file under it. A
file over the browser's 25 MB limit goes in that way, up to the 100 MB GitHub
accepts in a push. A larger file stays out of the pull request: [open an
issue]({LARGE_FILE_ISSUE_URL}) with the hashes `validate_pr.py` prints, and a
maintainer adds it to the `large-files` release.
## Add a platform
1. Write a scraper in `scripts/scraper/` (inherit `BaseScraper`)
2. Read the platform's upstream source to determine how it checks BIOS files
3. Register it in `platforms/_registry.yml`
4. Generate the platform YAML and test: `python scripts/verify.py --platform <name>`
Full walkthrough: [adding a platform]({link("wiki/adding-a-platform")}).
## Add an emulator profile
1. Clone the emulator's source code, upstream and libretro port
2. Trace the file loading from the entry point, not from a keyword grep
3. Document every file the code loads, with a `source_ref` line reference
4. Write the YAML to `emulators/<name>.yml`
5. Test: `python scripts/cross_reference.py --emulator <name>`
Full walkthrough: [profiling guide]({link("wiki/profiling")}).
## Change the installer
`install.py` is built from the `installer/` package, one module per concern:
edit the module, then run `python scripts/build_installer.py` and
`python scripts/pin_installer.py`. CI fails when `install.py` is not the file
the package builds. [Changing the installer]({link("wiki/installer")}#changing-the-installer)
lists what else a change rewrites.
## File conventions
- `bios/Manufacturer/Console/filename` for canonical files
- `bios/Manufacturer/Console/.variants/filename.sha1prefix` for alternate versions
- A file too large for git goes to the `large-files` GitHub release and its
path into `.gitignore`, the list that decides what is served from the release
- Trees addressed by path are kept out of deduplication (`NODEDUP_DIRS` in
`scripts/model/nodedup.py`)
- Two paths differing only by case break clones on Windows and macOS,
and `tests/test_no_case_collisions.py` enforces this
## Before opening a PR
A pull request that only adds files under `bios/` needs none of this: the
validation above is its check. For code, profiles or platform files, these are
the checks CI runs on a pull request (Python 3.12 or newer):
```bash
{pip_line}
python scripts/pr_checks.py
```
`pr_checks.py` runs these, in CI's order, carries on past a failure as CI
does, and names at the end each check that failed or could not run:
```bash
{steps}
```
The versions are the ones CI pins. Three tools come from the system, not from
that line, and the tests that need them skip without them: `shellcheck` for the
handheld launchers, `bwrap` (bubblewrap) for the probe sandbox, and a Python 3.8
with pyte (`{floor_line}`) for the full screen. CI has all three.
`profile_sync.py` compares the branch with this repository's `main`, and
fetches it in a fork's clone. An edited profile is not held to
`--strict`: its older refs are reviewed by hand.
The full pipeline is not needed for a contribution: it rebuilds every pack
in `dist/`, which is why maintainers run it before a release.
## PR validation
CI computes SHA1/MD5/CRC32 for every new file, checks them against the platform
configs, validates the YAML against the schemas, confronts each added profile
with its upstream source and runs the test suite. The BIOS report goes to the
summary of the Validation run, and also to a comment when the branch lives in
this repository: a fork's pull request runs with a read-only token.
Contributors who add platform support are credited in the README,
{site_words}, and in the BIOS packs.
"""
def generate_contributing() -> str:
return contributing_text(
lambda page: f"{SITE_URL}{page}/",
"# Contributing to RetroBIOS",
"on the documentation site",
)
def _write(readme: str) -> None:
status = "Generated" if write_if_changed("README.md", readme) else "Unchanged"
print(f"{status} ./README.md")
contributing = generate_contributing()
status = (
"Generated"
if write_if_changed("CONTRIBUTING.md", contributing)
else "Unchanged"
)
print(f"{status} ./CONTRIBUTING.md")
+742
View File
@@ -0,0 +1,742 @@
"""Permalinks into the sources a profile cites, and the paths each cached tree holds."""
from __future__ import annotations
import functools
import json
import re
import sys
import urllib.parse
from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path
from core import upstream
from core.paths import REPO_ROOT
from model.sourceref import (
_HEX_ADDRESS_RE,
_prose_runs,
is_binary_citation,
ref_annotation,
ref_role,
source_ref_values,
split_source_ref,
)
from sitegen.render import _by_mode, _escape_tags
def _repo_pins(profile: dict, field: str, label: str) -> list[tuple[str, str, str]]:
"""Pair each declared repository URL with its own revision.
A profile whose builds live in separate repositories keys both the URL
and the revision by build mode. Reading them apart would pin a libretro
fork to the standalone revision and produce a permalink into a tree that
never held the cited line. Each tuple is (url, pin, source_commit
fallback for that same mode).
"""
raw = profile.get(field, "")
pin_field = profile.get(f"{field}_commit") or ""
source_field = profile.get("source_commit") or ""
if not isinstance(raw, dict):
if not raw:
return []
return [
(
str(raw),
_by_mode(pin_field, label),
_by_mode(source_field, label),
)
]
# The requested build mode first, so it wins when several repositories
# would otherwise be equally good candidates.
ordered = ([label] if label and label in raw else []) + [
key for key in raw if key != label
]
return [
(str(raw[key]), _by_mode(pin_field, key), _by_mode(source_field, key))
for key in ordered
if raw.get(key)
]
# Forges the pages link into but upstream.py does not read from. Each is
# reached by browser only, so the Repo carries no API or raw base.
_BROWSE_ONLY = {
"voidpoint.io": "gitlab",
"bitbucket.org": "bitbucket",
"sourceforge.net": "sourceforge",
"archive.softwareheritage.org": "swh",
}
def _browse_repo(url: str) -> upstream.Repo | None:
"""The repository a profile URL names, on any forge the pages can link.
Profiles pinned on SourceForge, voidpoint.io, Bitbucket or Software
Heritage showed no revision and no linked citation: parse_repo knows
only the forges profile_sync fetches from.
"""
repo = upstream.parse_repo(url)
if repo is not None or not url:
return repo
parts = urllib.parse.urlsplit(url.strip())
family = _BROWSE_ONLY.get(parts.netloc)
segments = [seg for seg in parts.path.split("/") if seg]
if family == "gitlab":
if "-" in segments:
segments = segments[: segments.index("-")]
if len(segments) < 2:
return None
owner, name = "/".join(segments[:-1]), segments[-1]
elif family == "bitbucket" and len(segments) >= 2:
owner, name = segments[0], segments[1]
elif family == "sourceforge" and len(segments) >= 3 and segments[0] == "p":
owner, name = segments[1], segments[2]
elif family == "swh":
# A revision URL names no project: the pin alone addresses the tree.
owner, name = "softwareheritage", "revision"
else:
return None
return upstream.Repo(parts.netloc, family, "", "", owner, name.removesuffix(".git"))
def _forge_sources(profile: dict, label: str = "") -> list[tuple[upstream.Repo, str]]:
"""Supported source repositories and immutable revisions for a profile."""
candidates: list[tuple[upstream.Repo, str]] = []
seen: set[tuple[str, str, str]] = set()
source_repos: set[tuple[str, str]] = set()
for field in ("source", "upstream"):
for value, pin, fallback in _repo_pins(profile, field, label):
repo = _browse_repo(value)
if repo is None:
continue
repo_key = (repo.host, repo.slug)
if field == "upstream" and not pin and repo_key in source_repos:
pin = fallback
if not pin:
continue
key = (repo.host, repo.slug, pin)
if key not in seen:
candidates.append((repo, pin))
seen.add(key)
if field == "source":
source_repos.add(repo_key)
return candidates
def _source_permalink(repo: upstream.Repo, pin: str, path: str,
start: int | None, end: int | None) -> str:
"""Forge-specific browser URL for one file at one immutable revision."""
quoted_path = urllib.parse.quote(path, safe="/@:+-._~")
base = f"https://{repo.host}/{repo.owner}/{repo.name}"
if repo.family == "bitbucket":
url = f"{base}/src/{pin}/{quoted_path}"
if start is not None:
url += f"#lines-{start}" + (f":{end}" if end is not None and end != start else "")
return url
if repo.family == "sourceforge":
# The Allura code browser takes no line range: the file at the pin.
return f"https://{repo.host}/p/{repo.owner}/{repo.name}/ci/{pin}/tree/{quoted_path}"
if repo.family == "swh":
url = f"https://{repo.host}/browse/revision/{pin}/?path={quoted_path}"
if start is not None:
url += f"#L{start}" + (f"-L{end}" if end is not None and end != start else "")
return url
if repo.family == "github":
url = f"{base}/blob/{pin}/{quoted_path}"
elif repo.family == "gitlab":
url = f"{base}/-/blob/{pin}/{quoted_path}"
else:
url = f"{base}/src/commit/{pin}/{quoted_path}"
if start is not None:
if repo.family == "gitlab":
url += f"#L{start}"
if end is not None and end != start:
url += f"-{end}"
else:
url += f"#L{start}"
if end is not None and end != start:
url += f"-L{end}"
return url
# The tree listings profile_sync caches, read only by the command that
# writes SOURCE_PATHS. The pages read that file: the deploy has no tree
# cache, and a citation it could not check was linked into whichever
# repository the profile declared, 30 of them to a 404.
TREE_CACHE = REPO_ROOT / upstream.CACHE_DIR
SOURCE_PATHS = (REPO_ROOT
/ "website" / "src" / "data" / "source-paths.json")
def tree_key(repo: upstream.Repo, pin: str) -> str:
"""How SOURCE_PATHS names one repository at one revision."""
return f"{repo.host}/{repo.slug}@{pin}"
@functools.cache
def _verified() -> dict[str, frozenset[str]]:
"""The committed record, empty when it has not been written."""
try:
data = json.loads(SOURCE_PATHS.read_text(encoding="utf-8"))
except FileNotFoundError:
return {}
return {key: frozenset(paths) for key, paths in data.items()}
@functools.cache
def _tree_paths(repo: upstream.Repo, pin: str) -> frozenset[str]:
"""The cited paths of a repository at a revision that its tree holds."""
return _verified().get(tree_key(repo, pin), frozenset())
def tree_holds(repo: upstream.Repo, pin: str, path: str) -> bool:
"""Whether ``path`` was found in the repository's tree at ``pin``.
trident cites src/core/loader/ncch.cpp, a Panda3DS file, and the page
linked it into 3dsTrident, where it is a 404. A path no tree confirmed,
on a forge whose tree cannot be read or a revision not cached when the
record was written, is not linked: no link beats a link to nothing.
"""
return path in _tree_paths(repo, pin)
def _holder(
candidates: list[tuple[upstream.Repo, str]], path: str,
) -> tuple[upstream.Repo, str] | None:
"""The pinned repository that holds ``path``, source before upstream as
profile_sync.select_views orders them."""
return next((cand for cand in candidates if tree_holds(*cand, path)), None)
def _cached_tree(
repo: upstream.Repo, pin: str, cache_dirs: list[Path], fetch: bool = False,
) -> frozenset[str] | None:
"""Every file of a repository at a revision, None when not cached or
truncated (a missing path would then prove nothing). Each cache is read
in turn. With *fetch*, a tree none holds is fetched into the last one."""
if not repo.api_base:
return None # a browse-only forge: no listing to read
for index, cache_dir in enumerate(cache_dirs):
online = fetch and index == len(cache_dirs) - 1
try:
paths, truncated = upstream.list_tree(repo, pin, str(cache_dir), offline=not online)
except upstream.UpstreamError as exc:
print(f" {tree_key(repo, pin)}: {exc}", file=sys.stderr)
return None
if paths and not truncated:
return frozenset(paths)
return None
def _walk(value: object) -> Iterator[tuple[str, object]]:
"""Every (key, value) of a profile, nested lists and mappings included."""
if isinstance(value, dict):
for key, item in value.items():
yield str(key), item
yield from _walk(item)
elif isinstance(value, list):
for item in value:
yield from _walk(item)
def cited_paths(profile: dict) -> set[str]:
"""Every path a page of the profile could link: the parts of each
source_ref, the file:line citations of its prose and the file its
version is read from."""
basis = profile.get("version_basis")
bases = ([basis] if isinstance(basis, dict) and "kind" in basis
else list(basis.values()) if isinstance(basis, dict) else [])
paths: set[str] = {
str(b["path"]) for b in bases
if isinstance(b, dict) and b.get("kind") == "file" and b.get("path")
}
for key, value in _walk(profile):
if key == "source_ref" and isinstance(value, (str, dict)):
for _label, refs in source_ref_values(value):
paths.update(ref_role(part.path)[1] for part in split_source_ref(refs))
elif isinstance(value, str) and ":" in value:
for _n, _span, _spans, parts, _run, _wrapped in _prose_runs(value):
paths.update(part.path for part in parts)
return {path for path in paths
if _PATH_RE.fullmatch(path) and not is_binary_citation(path)}
def profile_trees(profile: dict) -> list[tuple[upstream.Repo, str]]:
"""Every repository and revision a page of the profile can link into."""
found: list[tuple[upstream.Repo, str]] = []
labels = {""} | {
str(mode) for field in ("source", "upstream", "source_commit", "upstream_commit")
if isinstance(profile.get(field), dict) for mode in profile[field]}
for label in sorted(labels):
for pair in _forge_sources(profile, label) + list(role_sources(profile, label).values()):
if pair not in found:
found.append(pair)
return found
def _listed_directories(
repo: upstream.Repo, pin: str, paths: set[str], cache_dirs: list[Path], fetch: bool,
) -> frozenset[str] | None:
"""The cited paths found by listing their directories one by one, for a
tree the forge truncates (aps3e vendors RPCS3 whole). A directory that
cannot be listed confirms none of its paths. None off GitHub, the one
forge with that call, and None when no directory could be listed: the
tree was not read, so its record is kept (TeknoParrotUI answers 404, and
each fetch without its cached tree dropped its four paths)."""
if repo.family != "github":
return None
found: set[str] = set()
listed = False
for folder in sorted({path.rpartition("/")[0] for path in paths} - {""}):
names = None
for index, cache_dir in enumerate(cache_dirs):
online = fetch and index == len(cache_dirs) - 1
try:
names = upstream.list_directory(repo, pin, folder, str(cache_dir), offline=not online)
except upstream.UpstreamError:
names = None
if names is not None:
break
listed = listed or names is not None
found.update(f"{folder}/{name}" for name in names or ())
return frozenset(found) if listed else None
def build_source_paths(
profiles: dict, cache_dirs: list[Path], fetch: bool = False,
) -> tuple[dict[str, list[str]], list[str]]:
"""The cited paths each cached tree holds, and the trees not cached."""
held: dict[str, set[str]] = {}
unread: set[str] = set()
for _name, profile in sorted(profiles.items()):
paths = cited_paths(profile)
if not paths:
continue
for repo, pin in profile_trees(profile):
tree = _cached_tree(repo, pin, cache_dirs, fetch)
if tree is None:
tree = _listed_directories(repo, pin, paths, cache_dirs, fetch)
if tree is None:
unread.add(tree_key(repo, pin))
continue
# Recorded even when it holds no cited path, so a pinned tree
# missing from the record is one no run has read.
held.setdefault(tree_key(repo, pin), set()).update(paths & tree)
for repo, pin, path in build_files(profile):
tree = (_cached_tree(repo, pin, cache_dirs, fetch)
or _listed_directories(repo, pin, {path}, cache_dirs, fetch))
if tree is None:
unread.add(tree_key(repo, pin))
continue
held.setdefault(tree_key(repo, pin), set()).update({path} & tree)
return {key: sorted(paths) for key, paths in sorted(held.items())}, sorted(unread)
def build_files(profile: dict) -> list[tuple[upstream.Repo, str, str]]:
"""The platform build files `pin_build` names at a commit, as (repo,
revision, path). A tag can move, so a build read at a tag is not linked."""
found = []
for build in profile.get("pin_build") or []:
repo = _browse_repo(str(build.get("repo", "")))
revision = str(build.get("revision", ""))
if repo is not None and re.fullmatch(r"[0-9a-f]{40}", revision):
found.append((repo, revision, str(build.get("path", ""))))
return found
def keep_unread(
held: dict[str, list[str]], unread: list[str], previous: dict[str, list[str]]
) -> dict[str, list[str]]:
"""Carry over what the last record held for the trees this run could not read.
A tree key names a pinned sha, so what it held then it holds now. A run
that GitLab rate-limited dropped about twenty trees it never read. A tree
no run could read is recorded empty: confirming no path, it links none,
and check_freshness tells it from a pin no run has tried.
"""
kept = dict(held)
for key in unread:
kept.setdefault(key, previous.get(key, []))
return dict(sorted(kept.items()))
def read_record(path: Path) -> dict[str, list[str]]:
"""The record a previous run wrote, empty when there is none."""
try:
return json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError:
return {}
def _commit_url(repo: upstream.Repo, pin: str) -> str:
"""Forge-specific browser URL for one commit."""
base = f"https://{repo.host}/{repo.owner}/{repo.name}"
if repo.family == "gitlab":
return f"{base}/-/commit/{pin}"
if repo.family == "bitbucket":
return f"{base}/commits/{pin}"
if repo.family == "sourceforge":
return f"https://{repo.host}/p/{repo.owner}/{repo.name}/ci/{pin}/"
if repo.family == "swh":
return f"https://{repo.host}/browse/revision/{pin}/"
return f"{base}/commit/{pin}"
def version_basis_url(profile: dict, basis: dict, mode: str = "") -> str:
"""Where a reader checks a version: the file stating it at the pin, or
the tag it counts from. "" when neither can be linked.
The Version cell printed `libretro/handy.h` as bare text beside a
pinned Revision link, so the #define it reads was one search away.
"""
field = "upstream" if basis.get("repo") == "upstream" else "source"
declared = next(iter(_repo_pins(profile, field, mode)), None)
repo = _browse_repo(declared[0]) if declared else None
if repo is None:
return ""
kind, path, tag = basis.get("kind"), str(basis.get("path") or ""), str(basis.get("tag") or "")
if kind == "file" and path:
pin = next((p for r, p in _forge_sources(profile, mode)
if (r.host, r.slug) == (repo.host, repo.slug)), "")
return _source_permalink(repo, pin, path, None, None) if pin and tree_holds(
repo, pin, path) else ""
if kind == "tag" and tag and repo.family in ("github", "gitlab"):
tree = "/-/tree/" if repo.family == "gitlab" else "/tree/"
return f"https://{repo.host}/{repo.owner}/{repo.name}{tree}{urllib.parse.quote(tag)}"
return ""
def revision_markdown(profile: dict) -> str:
"""Each repository the profile reads, linked at the commit it was read at.
The page linked the repositories unpinned: the revision every citation
refers to sat in the YAML alone, for 178 profiles.
"""
links = [
f"[{'Software Heritage' if repo.family == 'swh' else repo.slug}@{pin[:12]}]"
f"({_commit_url(repo, pin)})"
for repo, pin in _forge_sources(profile)
]
branch = profile.get("source_branch")
if branch and not isinstance(branch, dict):
links.append(f"branch `{branch}`")
elif isinstance(branch, dict):
links += [f"{mode} branch `{name}`" for mode, name in branch.items()]
return ", ".join(links)
_GLUE_RE = re.compile(r"(^|/)(libretro|retro_)[^/]*$|(^|/)libretro[^/]*/", re.IGNORECASE)
def role_label(profile: dict, role: str, path: str = "") -> str:
"""Whose code a cited path is, said the way a reader asks it.
A libretro port carries the emulator's own sources beside its glue: pcem
cites src/mem.c in the port, which is PCem's code, not the core's.
"""
if role == "upstream":
return "upstream emulator"
if "libretro" not in str(profile.get("type", "")):
return "this build"
if _GLUE_RE.search(path):
return "libretro glue"
return "emulator code, libretro port"
def role_sources(profile: dict, label: str = "") -> dict[str, tuple[upstream.Repo, str]]:
"""The forge repository and pin behind each role a citation can name."""
found: dict[str, tuple[upstream.Repo, str]] = {}
for field in ("source", "upstream"):
for value, pin, _fallback in _repo_pins(profile, field, label):
repo = _browse_repo(value)
if repo is not None and pin and field not in found:
found[field] = (repo, pin)
return found
def requested_by(profile: dict, value: str | dict | None) -> str:
"""Whose code the citations of an entry are in, said in words."""
labels = []
for _label, refs in source_ref_values(value):
for part in split_source_ref(refs):
role, bare = ref_role(part.path)
if role:
label = role_label(profile, role, bare)
if label not in labels:
labels.append(label)
if not labels or not _two_repositories(profile):
return ""
return labels[0] if len(labels) == 1 else ", ".join(labels[:-1]) + f" and {labels[-1]}"
def _two_repositories(profile: dict) -> bool:
source, upstream_url = profile.get("source"), profile.get("upstream")
return bool(source and upstream_url and source != upstream_url)
def _source_ref_markdown(profile: dict, value: str | dict | None) -> str:
"""Render source_ref values as pinned links when their forge is known.
Each part is followed by whose code it cites, in words, when the profile
reads two repositories. source_ref_items() gives the same parts with
that role apart, for a page that names the roles once in a legend.
"""
rendered_groups = []
for label, items in source_ref_items(profile, value):
text = ", ".join(f"{part} ({role})" if role else part for part, role in items)
if label:
text = f"**{label}:** {text}"
rendered_groups.append(text)
return ", ".join(rendered_groups)
def source_ref_items(profile: dict, value: str | dict | None) -> list[tuple[str, list[tuple[str, str]]]]:
"""Each group of source_ref values: its label and its parts, each part
as Markdown with the role_label() of the code it cites ("" when the
profile reads one repository).
A profile can declare two repositories: the libretro port in ``source`` and
the original emulator in ``upstream``. A path links into the one whose
tree SOURCE_PATHS says holds it. Any other path is rendered as plain
code: a citation with no link still names the file and the lines, while a
link to the wrong repository is a false citation. An address inside a
shipped binary reads as one (offset 0x8094-0x80ac in libnes.so).
"""
groups: list[tuple[str, list[tuple[str, str]]]] = []
path_re = re.compile(r"^[A-Za-z0-9_.@/+~-]+$")
for label, refs in source_ref_values(value):
candidates = _forge_sources(profile, label)
by_role = role_sources(profile, label)
rendered: list[tuple[str, str]] = []
current_role = ""
binary = ""
for part in split_source_ref(refs):
if is_binary_citation(part.path):
text, binary = _binary_citation(part.path, binary)
rendered.append((text + _annotation_markdown(ref_annotation(part.raw)), ""))
continue
binary = ""
role, bare = ref_role(part.path)
if bare != part.path or role:
current_role = role
elif part.raw and not part.raw[:1].isdigit():
current_role = ""
part = type(part)(bare, part.start, part.end, part.raw)
display = part.path
if part.start is not None:
display += f":{part.start}"
if part.end is not None and part.end != part.start:
display += f"-{part.end}"
# The path is linked as written. A first segment equal to a
# repository's name proves nothing: PCSX2 keeps its sources in
# pcsx2/, hatariB vendors Hatari in hatari/, and stripping it
# broke 470 links. Two repositories and no tree to read: no link.
selected: tuple[upstream.Repo, str] | None = None
real_path = part.path
if path_re.fullmatch(part.path):
if current_role:
# Only the repository the part names, or no link at all.
selected = by_role.get(current_role)
if selected is not None and not tree_holds(*selected, part.path):
selected = None
else:
selected = _holder(candidates, part.path)
role = (role_label(profile, current_role, part.path)
if current_role and _two_repositories(profile) else "")
note = _annotation_markdown(ref_annotation(part.raw))
if selected is None:
rendered.append((f"`{display}`{note}", role))
else:
repo, pin = selected
url = _source_permalink(
repo, pin, real_path, part.start, part.end
)
rendered.append((f"[`{display}`]({url}){note}", role))
groups.append((label, rendered or [(f"`{refs}`", "")]))
return groups
def _annotation_markdown(text: str) -> str:
"""A part's annotation after its citation, as written: `(lsf default)`.
Profile prose, so placeholders keep their brackets and nothing in it
opens emphasis or a table cell.
"""
if not text:
return ""
return " " + _escape_tags(re.sub(r"([*|\\])", r"\\\1", text))
def _binary_citation(path: str, previous: str) -> tuple[str, str]:
"""A part citing code inside a shipped binary, and the binary it names.
`Nesoid 2.5.0 libnes.so 0x455a4-0x45694, 0x8094-0x80ac` cites two
ranges of one library: the bare address continues the binary before it.
No revision of a repository holds those bytes, so nothing is linked.
"""
found = _HEX_ADDRESS_RE.search(path)
if found is None:
return f"`{path}`", path
binary = path[:found.start()].rstrip(" :") or previous
if not binary:
return f"`{path}`", ""
return f"offset `{path[found.start():]}` in `{binary}`", binary
def link_prose_citations(profile: dict, text: str) -> str:
"""Prose file:line citations as pinned links, where the target is certain.
profile_sync keeps these citations on their pin, and the page printed
4,328 of them as plain text. A citation links only when the path is
rooted (it holds a directory) or is one a structured source_ref of the
profile already uses: a bare name could be anywhere in the tree, and a
link to the wrong file is a false citation. Of the repositories a profile
reads, the one its role word names is taken, else the one tree holding
the path: held by both, the citation does not say which it means.
Text already in backticks or in a link is left alone.
"""
candidates = _forge_sources(profile)
if not candidates or ":" not in text:
return text
by_role = role_sources(profile)
structured = {
part.path
for entry in profile.get("files") or []
if isinstance(entry, dict)
for _label, refs in source_ref_values(entry.get("source_ref"))
for part in split_source_ref(refs)
}
out = []
for line in text.split("\n"):
guarded = _guarded_spans(line)
edits = []
for _n, path_span, spans, parts, _run, wrapped in _prose_runs(line):
path = parts[0].path
if wrapped or " " in path or not _PATH_RE.fullmatch(path):
continue
if "/" not in path and path not in structured:
continue
if any(lo <= path_span[0] < hi for lo, hi in guarded):
continue
role = parts[0].role
# `upstream a.c:5` names its repository: none other is linked.
named = [by_role[role]] if role in by_role else [] if role else candidates
holders = [tree for tree in named if tree_holds(*tree, path)]
if len(holders) != 1:
continue
repo, pin = holders[0]
for index, ((lo, hi), part) in enumerate(zip(spans, parts)):
start = path_span[0] if index == 0 else lo
url = _source_permalink(repo, pin, part.path, part.start, part.end)
edits.append((start, hi, f"[`{line[start:hi]}`]({url})"))
for start, end, link in sorted(edits, reverse=True):
line = line[:start] + link + line[end:]
out.append(line)
return "\n".join(out)
_PATH_RE = re.compile(r"^[A-Za-z0-9_.@/+~-]+$")
def _guarded_spans(line: str) -> list[tuple[int, int]]:
"""Code spans and links of a markdown line."""
return [m.span() for m in re.finditer(r"`[^`]*`|\[[^\]]*\]\([^)]*\)", line)]
# Where a platform's list was read: the forge, the repository, the revision
# and the path inside it, out of the URL its scraper pinned.
_LIST_URL_RES = (
re.compile(r"^https://raw\.githubusercontent\.com/(?P<owner>[^/]+)/(?P<repo>[^/]+)/"
r"(?P<rev>[^/]+)/(?P<path>.+)$"),
re.compile(r"^https://github\.com/(?P<owner>[^/]+)/(?P<repo>[^/]+)/(?:blob|tree)/"
r"(?P<rev>[^/]+)(?:/(?P<path>.+))?$"),
re.compile(r"^https://codeload\.github\.com/(?P<owner>[^/]+)/(?P<repo>[^/]+)/"
r"tar\.gz/(?P<rev>[^/]+)$"),
re.compile(r"^https://(?P<host>gitlab\.com)/(?P<owner>[^/]+)/(?P<repo>[^/]+)/-/"
r"(?:raw|blob)/(?P<rev>[^/]+)/(?P<path>.+)$"),
)
_BRANCHES = frozenset({"master", "main", "db"})
@dataclass(frozen=True)
class ListSource:
"""A platform's list as its scraper read it."""
host: str
owner: str
repo: str
rev: str
path: str
@property
def moving(self) -> bool:
"""The revision is a branch: what was read is not recorded."""
return not self.rev or self.rev in _BRANCHES
@property
def label(self) -> str:
"""`batocera-systems at tag batocera-43.1`, said in words."""
name = self.path.rsplit("/", 1)[-1] if self.path else f"{self.repo} repository"
if not self.rev:
return f"{name}, default branch"
if re.fullmatch(r"[0-9a-f]{40}", self.rev):
return f"{name} at commit {self.rev[:12]}"
if self.moving:
return f"{name} on branch {self.rev}"
return f"{name} at tag {self.rev}"
def browse(self, path: str = "", start: int | None = None,
end: int | None = None) -> str:
"""The page a reader opens: the file, or the tree, at the revision."""
path = path or self.path
if self.host == "gitlab.com":
url = f"https://gitlab.com/{self.owner}/{self.repo}/-/blob/{self.rev}/{path}"
anchor = f"#L{start}" + (f"-{end}" if end and end != start else "")
else:
base = f"https://github.com/{self.owner}/{self.repo}"
if not self.rev:
return base
kind = "blob" if path else "tree"
url = f"{base}/{kind}/{self.rev}" + (f"/{path}" if path else "")
anchor = f"#L{start}" + (f"-L{end}" if end and end != start else "")
return url + (anchor if start else "")
def list_source(url: str) -> ListSource | None:
"""The forge, repository, revision and path of a platform's `source:`."""
url = str(url or "").strip()
for pattern in _LIST_URL_RES:
found = pattern.match(url)
if found:
parts = found.groupdict()
return ListSource(parts.get("host") or "github.com", parts["owner"],
parts["repo"], parts["rev"], parts.get("path") or "")
bare = re.match(r"^https://github\.com/([^/]+)/([^/]+?)/?$", url)
if bare:
return ListSource("github.com", bare[1], bare[2], "", "")
return None
def launcher_ref_markdown(source: ListSource | None, ref: str) -> str:
"""A launcher record's source_ref, each part a pinned link.
Linked only where the caller knows the launcher code sits in the
repository and revision of the platform's list. Otherwise each part is
plain code: a link to another repository is a false citation.
"""
rendered: list[str] = []
for part in split_source_ref(ref):
display = part.path.rsplit("/", 1)[-1]
if part.start is not None:
display += f":{part.start}"
if part.end is not None and part.end != part.start:
display += f"-{part.end}"
if source is None or not source.rev or not _PATH_RE.fullmatch(part.path):
rendered.append(f"`{display}`")
else:
rendered.append(f"[`{display}`]({source.browse(part.path, part.start, part.end)})")
return ", ".join(rendered)
+1 -1
View File
@@ -24,7 +24,7 @@ from dataclasses import dataclass
from xml.sax.saxutils import escape
from sitegen import markup
from sitediagrams import (
from sitegen.diagrams import (
MONO_STYLE,
NARROW,
STROKE,
+488
View File
@@ -0,0 +1,488 @@
"""Checks of the built site as a navigable, accessible data product."""
from __future__ import annotations
import json
import re
import sys
from collections import Counter, defaultdict
from dataclasses import dataclass, field
from html.parser import HTMLParser
from pathlib import Path
from urllib.parse import unquote, urlsplit
@dataclass
class Page:
path: Path
title: str = ""
h1: str = ""
lang: str = ""
descriptions: list[str] = field(default_factory=list)
canonical: list[str] = field(default_factory=list)
h1_count: int = 0
main_count: int = 0
ids: list[str] = field(default_factory=list)
links: list[str] = field(default_factory=list)
missing_alt: list[str] = field(default_factory=list)
jsonld: list[str] = field(default_factory=list)
unrendered: list[str] = field(default_factory=list)
remote_images: list[str] = field(default_factory=list)
remote_scripts: list[str] = field(default_factory=list)
placeholders: list[str] = field(default_factory=list)
headings: list[int] = field(default_factory=list)
empty_headers: int = 0
runtime_diagrams: int = 0
size: int = 0
elements: int = 0
# A moved page's old address: a meta refresh to the new one, no content.
redirect: str = ""
# Budgets the site was brought under on 2026-10-22, with room to grow. A
# change that passes one is a regression of what a visitor downloads, not a
# matter of taste: raise the number in the same change that explains why.
#
# The largest page was 10.5 MB (systems/game-engines/) and took 21 s of
# main-thread work on a throttled phone. Split pages now top out at 0.9 MB.
MAX_PAGE_BYTES = 1_000_000
# Elements outside scripts and styles: the browser lays out and styles each.
# emulators/mame held 13,300 and blocked the main thread for 235 ms. Its
# index now carries each card's id on the link itself.
MAX_PAGE_ELEMENTS = 10_000
# Pages allowed past it, each with the reason, removed when it comes under.
OVER_ELEMENT_BUDGET: dict[str, str] = {}
# Pagefind loads its index in pieces: the metadata, then the chunks the words
# typed fall in (stored compressed). 59 KB for the largest chunk and 7.5 KB of
# metadata on 2026-10-22, 5.2 MB for the whole index on disk.
MAX_PAGEFIND_CHUNK_BYTES = 150_000
MAX_PAGEFIND_META_BYTES = 50_000
MAX_PAGEFIND_TOTAL_BYTES = 12_000_000
# Pages whose description is one text once the page's own name is taken
# out. 707 pages shared five templates ("X: source-pinned emulator
# firmware profile with paths, hashes..."), and a search engine showed the
# same line under every result.
MAX_SHARED_DESCRIPTION = 10
# Text inside these is shown as written, so markup there is not a leftover.
_LITERAL_TAGS = frozenset({"pre", "code", "script", "style", "textarea"})
class _PageParser(HTMLParser):
def __init__(self, path: Path) -> None:
super().__init__(convert_charrefs=True)
self.page = Page(path)
self._title_depth = 0
self._title_parts: list[str] = []
self._h1_depth = 0
self._h1_parts: list[str] = []
self._jsonld_depth = 0
self._jsonld_parts: list[str] = []
self._literal_depth = 0
self._header_parts: list[str] | None = None
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
data = {key: value or "" for key, value in attrs}
self._count(tag, data)
self._open(tag, data)
self._references(tag, data)
def _count(self, tag: str, data: dict[str, str]) -> None:
if tag not in ("script", "style"):
self.page.elements += 1
if tag in _LITERAL_TAGS:
self._literal_depth += 1
if re.fullmatch(r"h[1-6]", tag):
self.page.headings.append(int(tag[1]))
if tag == "th":
self._header_parts = []
if "mermaid" in data.get("class", "").split():
# Material renders it in the browser with a script from a CDN.
self.page.runtime_diagrams += 1
if tag == "script" and re.match(r"\s*(?:https?:)?//", data.get("src", "")):
self.page.remote_scripts.append(data["src"])
def _open(self, tag: str, data: dict[str, str]) -> None:
if tag == "html":
self.page.lang = data.get("lang", "")
elif tag == "title":
self._title_depth += 1
elif tag == "meta" and data.get("http-equiv", "").lower() == "refresh":
self.page.redirect = data.get("content", "").partition("url=")[2]
elif tag == "meta" and data.get("name", "").lower() == "description":
self.page.descriptions.append(data.get("content", "").strip())
elif tag == "h1":
self.page.h1_count += 1
self._h1_depth += 1
elif tag == "main":
self.page.main_count += 1
elif tag == "img" and "alt" not in data:
self.page.missing_alt.append(data.get("src", "?"))
elif tag == "script" and data.get("type") == "application/ld+json":
self._jsonld_depth += 1
self._jsonld_parts = []
def _references(self, tag: str, data: dict[str, str]) -> None:
element_id = data.get("id")
if element_id is not None:
self.page.ids.append(element_id)
if tag in ("a", "link") and data.get("href"):
self.page.links.append(data["href"])
if tag in ("img", "script", "source") and data.get("src"):
self.page.links.append(data["src"])
# An image from another host breaks when that host renames it, and
# tells it about every visit: the site serves its own copies.
sources = [data.get("src") or ""] + (data.get("srcset") or "").split(",")
if tag in ("img", "source", "image") and any(
re.match(r"\s*(?:https?:)?//", value) for value in sources if value
):
self.page.remote_images.append(data.get("src") or data.get("srcset") or "?")
if tag == "link" and "canonical" in data.get("rel", "").split():
self.page.canonical.append(data.get("href", ""))
def handle_comment(self, data: str) -> None:
match = re.match(r"\s*image:\s*(\S+)", data)
if match:
self.page.placeholders.append(match.group(1))
def handle_endtag(self, tag: str) -> None:
if tag in _LITERAL_TAGS and self._literal_depth:
self._literal_depth -= 1
if tag == "th" and self._header_parts is not None:
if not "".join(self._header_parts).strip():
self.page.empty_headers += 1
self._header_parts = None
if tag == "title":
self._title_depth -= 1
elif tag == "h1" and self._h1_depth:
self._h1_depth -= 1
elif tag == "script" and self._jsonld_depth:
self.page.jsonld.append("".join(self._jsonld_parts).strip())
self._jsonld_depth -= 1
self._jsonld_parts = []
def handle_data(self, data: str) -> None:
if self._header_parts is not None:
self._header_parts.append(data)
if self._title_depth:
self._title_parts.append(data)
if self._h1_depth:
self._h1_parts.append(data)
if self._jsonld_depth:
self._jsonld_parts.append(data)
if not self._literal_depth and "**" in data:
self.page.unrendered.append(data.strip()[:60])
def close(self) -> None:
super().close()
self.page.title = "".join(self._title_parts).strip()
self.page.h1 = re.sub(r"\s+", " ", "".join(self._h1_parts)).strip()
def _parse_page(path: Path) -> Page:
parser = _PageParser(path)
text = path.read_text(encoding="utf-8", errors="replace")
parser.feed(text)
parser.close()
parser.page.size = len(text.encode("utf-8"))
return parser.page
def _heading_jumps(levels: list[int]) -> list[str]:
"""Each heading more than one level below the one before it: a screen
reader user moving by level finds nothing at the level skipped."""
return [f"h{before} to h{after}" for before, after in zip(levels, levels[1:])
if after > before + 1]
def _check_pagefind(site: Path) -> list[str]:
"""Pagefind's index pieces, each against its budget."""
root = site / "pagefind"
files = [path for path in root.rglob("*") if path.is_file()]
issues = []
for path in files:
size = path.stat().st_size
rel = path.relative_to(site).as_posix()
if path.suffix == ".pf_index" and size > MAX_PAGEFIND_CHUNK_BYTES:
issues.append(f"{rel}: {size:,} bytes, over the {MAX_PAGEFIND_CHUNK_BYTES:,} budget of a chunk")
if path.suffix == ".pf_meta" and size > MAX_PAGEFIND_META_BYTES:
issues.append(f"{rel}: {size:,} bytes, over the {MAX_PAGEFIND_META_BYTES:,} budget")
total = sum(path.stat().st_size for path in files)
if total > MAX_PAGEFIND_TOTAL_BYTES:
issues.append(f"pagefind/: {total:,} bytes, over the {MAX_PAGEFIND_TOTAL_BYTES:,} budget")
return issues
def _local_target(
href: str, page_path: Path, site: Path, base_path: str
) -> tuple[list[Path], str] | None:
parsed = urlsplit(href)
if parsed.scheme or parsed.netloc or href.startswith(
("mailto:", "tel:", "data:", "javascript:")
):
return None
raw_path = unquote(parsed.path)
if not raw_path:
return [page_path], unquote(parsed.fragment)
if base_path != "/" and (
raw_path == base_path.rstrip("/") or raw_path.startswith(base_path)
):
suffix = raw_path[len(base_path.rstrip("/")) :]
raw_path = "/" + suffix.lstrip("/")
target = (
site / raw_path.lstrip("/")
if raw_path.startswith("/")
else page_path.parent / raw_path
).resolve()
try:
target.relative_to(site)
except ValueError:
return [], unquote(parsed.fragment)
candidates = [target]
if raw_path.endswith("/"):
candidates = [target / "index.html"]
elif not target.suffix:
candidates.extend([target / "index.html", target.with_suffix(".html")])
return candidates, unquote(parsed.fragment)
def _check_pages(
pages: dict, site: Path, titles: dict, descriptions: dict
) -> list[str]:
"""Every per-page check: title, description, links, JSON-LD.
Split out of validate_site, which reached complexity 43. The
cross-page duplicate check stays with the caller, since it can only
run once every page has been seen. *titles* and *descriptions* are
filled here for it.
"""
issues: list[str] = []
for path, page in pages.items():
rel = path.relative_to(site)
is_404 = rel == Path("404.html")
messages = [
*_document_issues(path, page, is_404, titles, descriptions),
*_content_issues(page, rel.as_posix()),
*_jsonld_issues(page, is_404),
]
issues.extend(f"{rel}: {message}" for message in messages)
return issues
def _document_issues(path: Path, page: Page, is_404: bool, titles: dict, descriptions: dict) -> list[str]:
"""The head and landmarks: title, language, description, H1, main, canonical."""
messages = []
if not page.title:
messages.append("missing document title")
elif not is_404:
titles[page.title].append(path)
if page.lang != "en":
messages.append(f"expected lang='en', got {page.lang!r}")
if len(page.descriptions) != 1 or not page.descriptions[0]:
messages.append(f"expected one non-empty description, got {len(page.descriptions)}")
elif not is_404:
descriptions[page.descriptions[0]].append(path)
if not is_404 and page.h1_count != 1:
messages.append(f"expected one H1, got {page.h1_count}")
if page.main_count != 1:
messages.append(f"expected one main landmark, got {page.main_count}")
if not is_404 and (
len(page.canonical) != 1
or not page.canonical[0].startswith("https://")
):
messages.append(f"expected one HTTPS canonical URL, got {page.canonical!r}")
return messages
def _content_issues(page: Page, rel: str) -> list[str]:
messages = []
duplicate_ids = [
value
for value, count in Counter(page.ids).items()
if value and count > 1
]
if duplicate_ids:
messages.append(f"duplicate IDs: {duplicate_ids[:5]}")
if page.missing_alt:
messages.append(f"images missing alt: {page.missing_alt[:5]}")
if page.remote_images:
messages.append(f"images loaded from another host: {page.remote_images[:3]}")
if page.remote_scripts:
messages.append(f"scripts loaded from another host: {page.remote_scripts[:3]}")
if page.runtime_diagrams:
messages.append(f"{page.runtime_diagrams} diagram(s) drawn by a script at runtime")
if page.size > MAX_PAGE_BYTES:
messages.append(f"{page.size:,} bytes of HTML, over the {MAX_PAGE_BYTES:,} budget")
if page.elements > MAX_PAGE_ELEMENTS and rel not in OVER_ELEMENT_BUDGET:
messages.append(f"{page.elements:,} elements, over the {MAX_PAGE_ELEMENTS:,} budget")
jumps = _heading_jumps(page.headings)
if jumps:
messages.append(f"heading levels skipped: {sorted(set(jumps))}")
if page.empty_headers:
messages.append(f"{page.empty_headers} table header cell(s) without text")
if page.placeholders:
# scripts/sitediagrams.py knows no diagram of this name.
messages.append(f"image placeholders left unresolved: {page.placeholders[:3]}")
if page.unrendered:
# Bold that reached the reader as asterisks: a block indented
# one level too deep is read as code (the clownmdemu analysis).
messages.append(f"markdown left unrendered: {page.unrendered[:3]}")
return messages
def _jsonld_issues(page: Page, is_404: bool) -> list[str]:
messages = []
if not is_404 and len(page.jsonld) != 1:
messages.append(f"expected one JSON-LD block, got {len(page.jsonld)}")
for document in page.jsonld:
try:
payload = json.loads(document)
except json.JSONDecodeError as exc:
messages.append(f"invalid JSON-LD: {exc}")
continue
if not isinstance(payload, dict) or payload.get("@context") != "https://schema.org":
messages.append("JSON-LD is not a schema.org object")
return messages
def description_template(page: Page, site_name: str = "RetroBIOS") -> str:
"""A page's description with its own names taken out: its h1 and its
window title. What is left is the text it shares with its template."""
text = page.descriptions[0] if page.descriptions else ""
names = {page.h1, page.title.removesuffix(f" - {site_name}").strip()}
for name in sorted(filter(None, names), key=len, reverse=True):
text = text.replace(name, "")
return re.sub(r"\s+", " ", text).strip()
def _check_description_templates(pages: dict, site: Path) -> list[str]:
"""No more than MAX_SHARED_DESCRIPTION pages share one description
once their names are taken out."""
shared: dict[str, list[Path]] = defaultdict(list)
for path, page in pages.items():
if path.relative_to(site) != Path("404.html") and page.descriptions:
shared[description_template(page)].append(path)
return [
f"{len(paths)} pages share the description {text!r} after their name: "
+ ", ".join(str(path.relative_to(site)) for path in paths[:3])
for text, paths in shared.items()
if len(paths) > MAX_SHARED_DESCRIPTION
]
def _check_links(pages: dict, site: Path, base_path: str) -> list[str]:
"""Every local link and fragment resolves to something on disk."""
issues: list[str] = []
def report(path: Path, message: str) -> None:
issues.append(f"{path.relative_to(site)}: {message}")
for path, page in pages.items():
for href in page.links:
resolved = _local_target(href, path, site, base_path)
if resolved is None:
continue
candidates, fragment = resolved
if not candidates:
report(path, f"link escapes site root: {href}")
continue
existing = next((candidate for candidate in candidates if candidate.is_file()), None)
if existing is None:
report(path, f"broken local link or resource: {href}")
continue
if fragment and existing.suffix.lower() == ".html":
target_page = pages.get(existing.resolve())
if target_page is not None and fragment not in target_page.ids:
report(path, f"missing fragment in {href}")
return issues
RELEASE_DOWNLOAD = "https://github.com/Abdess/retrobios/releases/download/"
def _check_get_pages(
pages: dict, site: Path, platforms_dir: Path, record_path: Path,
) -> list[str]:
"""get/<platform>/ resolves for every registered platform, as a page.
Links outside the site keep these addresses across releases, so a
missing one is a dead download link for whoever followed it. A platform
with a pack in the release record links every one of its assets at the
recorded tag, and one without links none and gives the command.
"""
sys.path.insert(0, str(Path(__file__).resolve().parent))
import release_record
from model.guides import INSTALL_SH
from model.registry import list_registered_platforms, list_release_pack_platforms
if not (platforms_dir / "_registry.yml").is_file():
return [f"no platform registry in {platforms_dir}"]
record = release_record.load_advertised(record_path, str(platforms_dir))
released = set(list_release_pack_platforms(str(platforms_dir)))
issues: list[str] = []
for platform in list_registered_platforms(str(platforms_dir)):
rel = f"{release_record.GET_DIR}/{platform}/index.html"
page = pages.get((site / rel).resolve())
if page is None or page.redirect:
issues.append(f"{rel}: no download page for {platform}")
continue
assets = [link for link in page.links if link.startswith(RELEASE_DOWNLOAD)]
pack = release_record.pack_for(platform, record)
if platform in released and pack:
expected = {f"{RELEASE_DOWNLOAD}{record['tag']}/{a}" for a in pack["assets"]}
missing = sorted(expected - set(assets))
if missing:
issues.append(f"{rel}: does not link {', '.join(missing)}")
elif platform not in released:
packs = [a for a in assets if "_BIOS_Pack" in a]
if packs:
issues.append(f"{rel}: links a pack for a setup without one: {packs[0]}")
if f"{INSTALL_SH} | sh" not in (site / rel).read_text(encoding="utf-8"):
issues.append(f"{rel}: gives no install command")
return issues
def validate_site(
site: Path, base_path: str = "/retrobios/", platforms_dir: Path | None = None,
record_path: Path | None = None,
) -> list[str]:
site = site.resolve()
if not site.is_dir():
return [f"site directory does not exist: {site}"]
html_paths = sorted(site.rglob("*.html"))
if not html_paths:
return [f"no HTML pages found in {site}"]
pages = {path.resolve(): _parse_page(path) for path in html_paths}
issues: list[str] = []
titles: dict[str, list[Path]] = defaultdict(list)
descriptions: dict[str, list[Path]] = defaultdict(list)
# A redirect has no page to judge, only a target. The link check below
# still follows its link, so a redirect to nowhere is reported.
content = {path: page for path, page in pages.items() if not page.redirect}
issues.extend(_check_pages(content, site, titles, descriptions))
for label, values in (("title", titles), ("description", descriptions)):
for value, paths in values.items():
if len(paths) > 1:
rendered = ", ".join(str(path.relative_to(site)) for path in paths[:5])
issues.append(f"duplicate {label} {value!r}: {rendered}")
issues.extend(_check_description_templates(content, site))
issues.extend(_check_links(pages, site, base_path))
issues.extend(_check_pagefind(site))
if platforms_dir is not None:
issues.extend(_check_get_pages(
pages, site, platforms_dir, record_path or platforms_dir.parent / "release.json"))
return issues
+1 -734
View File
@@ -6,744 +6,11 @@ was written against, so a permalink is pinned, never guessed."""
from __future__ import annotations
import argparse
import functools
import json
import re
import sys
import urllib.parse
from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path
from core import upstream
from sitegen.render import _by_mode, _escape_tags
from model.sourceref import (
_HEX_ADDRESS_RE,
_prose_runs,
is_binary_citation,
ref_annotation,
ref_role,
source_ref_values,
split_source_ref,
)
from core.paths import REPO_ROOT
def _repo_pins(profile: dict, field: str, label: str) -> list[tuple[str, str, str]]:
"""Pair each declared repository URL with its own revision.
A profile whose builds live in separate repositories keys both the URL
and the revision by build mode. Reading them apart would pin a libretro
fork to the standalone revision and produce a permalink into a tree that
never held the cited line. Each tuple is (url, pin, source_commit
fallback for that same mode).
"""
raw = profile.get(field, "")
pin_field = profile.get(f"{field}_commit") or ""
source_field = profile.get("source_commit") or ""
if not isinstance(raw, dict):
if not raw:
return []
return [
(
str(raw),
_by_mode(pin_field, label),
_by_mode(source_field, label),
)
]
# The requested build mode first, so it wins when several repositories
# would otherwise be equally good candidates.
ordered = ([label] if label and label in raw else []) + [
key for key in raw if key != label
]
return [
(str(raw[key]), _by_mode(pin_field, key), _by_mode(source_field, key))
for key in ordered
if raw.get(key)
]
# Forges the pages link into but upstream.py does not read from. Each is
# reached by browser only, so the Repo carries no API or raw base.
_BROWSE_ONLY = {
"voidpoint.io": "gitlab",
"bitbucket.org": "bitbucket",
"sourceforge.net": "sourceforge",
"archive.softwareheritage.org": "swh",
}
def _browse_repo(url: str) -> upstream.Repo | None:
"""The repository a profile URL names, on any forge the pages can link.
Profiles pinned on SourceForge, voidpoint.io, Bitbucket or Software
Heritage showed no revision and no linked citation: parse_repo knows
only the forges profile_sync fetches from.
"""
repo = upstream.parse_repo(url)
if repo is not None or not url:
return repo
parts = urllib.parse.urlsplit(url.strip())
family = _BROWSE_ONLY.get(parts.netloc)
segments = [seg for seg in parts.path.split("/") if seg]
if family == "gitlab":
if "-" in segments:
segments = segments[: segments.index("-")]
if len(segments) < 2:
return None
owner, name = "/".join(segments[:-1]), segments[-1]
elif family == "bitbucket" and len(segments) >= 2:
owner, name = segments[0], segments[1]
elif family == "sourceforge" and len(segments) >= 3 and segments[0] == "p":
owner, name = segments[1], segments[2]
elif family == "swh":
# A revision URL names no project: the pin alone addresses the tree.
owner, name = "softwareheritage", "revision"
else:
return None
return upstream.Repo(parts.netloc, family, "", "", owner, name.removesuffix(".git"))
def _forge_sources(profile: dict, label: str = "") -> list[tuple[upstream.Repo, str]]:
"""Supported source repositories and immutable revisions for a profile."""
candidates: list[tuple[upstream.Repo, str]] = []
seen: set[tuple[str, str, str]] = set()
source_repos: set[tuple[str, str]] = set()
for field in ("source", "upstream"):
for value, pin, fallback in _repo_pins(profile, field, label):
repo = _browse_repo(value)
if repo is None:
continue
repo_key = (repo.host, repo.slug)
if field == "upstream" and not pin and repo_key in source_repos:
pin = fallback
if not pin:
continue
key = (repo.host, repo.slug, pin)
if key not in seen:
candidates.append((repo, pin))
seen.add(key)
if field == "source":
source_repos.add(repo_key)
return candidates
def _source_permalink(repo: upstream.Repo, pin: str, path: str,
start: int | None, end: int | None) -> str:
"""Forge-specific browser URL for one file at one immutable revision."""
quoted_path = urllib.parse.quote(path, safe="/@:+-._~")
base = f"https://{repo.host}/{repo.owner}/{repo.name}"
if repo.family == "bitbucket":
url = f"{base}/src/{pin}/{quoted_path}"
if start is not None:
url += f"#lines-{start}" + (f":{end}" if end is not None and end != start else "")
return url
if repo.family == "sourceforge":
# The Allura code browser takes no line range: the file at the pin.
return f"https://{repo.host}/p/{repo.owner}/{repo.name}/ci/{pin}/tree/{quoted_path}"
if repo.family == "swh":
url = f"https://{repo.host}/browse/revision/{pin}/?path={quoted_path}"
if start is not None:
url += f"#L{start}" + (f"-L{end}" if end is not None and end != start else "")
return url
if repo.family == "github":
url = f"{base}/blob/{pin}/{quoted_path}"
elif repo.family == "gitlab":
url = f"{base}/-/blob/{pin}/{quoted_path}"
else:
url = f"{base}/src/commit/{pin}/{quoted_path}"
if start is not None:
if repo.family == "gitlab":
url += f"#L{start}"
if end is not None and end != start:
url += f"-{end}"
else:
url += f"#L{start}"
if end is not None and end != start:
url += f"-L{end}"
return url
# The tree listings profile_sync caches, read only by the command that
# writes SOURCE_PATHS. The pages read that file: the deploy has no tree
# cache, and a citation it could not check was linked into whichever
# repository the profile declared, 30 of them to a 404.
TREE_CACHE = REPO_ROOT / upstream.CACHE_DIR
SOURCE_PATHS = (REPO_ROOT
/ "website" / "src" / "data" / "source-paths.json")
def tree_key(repo: upstream.Repo, pin: str) -> str:
"""How SOURCE_PATHS names one repository at one revision."""
return f"{repo.host}/{repo.slug}@{pin}"
@functools.cache
def _verified() -> dict[str, frozenset[str]]:
"""The committed record, empty when it has not been written."""
try:
data = json.loads(SOURCE_PATHS.read_text(encoding="utf-8"))
except FileNotFoundError:
return {}
return {key: frozenset(paths) for key, paths in data.items()}
@functools.cache
def _tree_paths(repo: upstream.Repo, pin: str) -> frozenset[str]:
"""The cited paths of a repository at a revision that its tree holds."""
return _verified().get(tree_key(repo, pin), frozenset())
def tree_holds(repo: upstream.Repo, pin: str, path: str) -> bool:
"""Whether ``path`` was found in the repository's tree at ``pin``.
trident cites src/core/loader/ncch.cpp, a Panda3DS file, and the page
linked it into 3dsTrident, where it is a 404. A path no tree confirmed,
on a forge whose tree cannot be read or a revision not cached when the
record was written, is not linked: no link beats a link to nothing.
"""
return path in _tree_paths(repo, pin)
def _holder(
candidates: list[tuple[upstream.Repo, str]], path: str,
) -> tuple[upstream.Repo, str] | None:
"""The pinned repository that holds ``path``, source before upstream as
profile_sync.select_views orders them."""
return next((cand for cand in candidates if tree_holds(*cand, path)), None)
def _cached_tree(
repo: upstream.Repo, pin: str, cache_dirs: list[Path], fetch: bool = False,
) -> frozenset[str] | None:
"""Every file of a repository at a revision, None when not cached or
truncated (a missing path would then prove nothing). Each cache is read
in turn. With *fetch*, a tree none holds is fetched into the last one."""
if not repo.api_base:
return None # a browse-only forge: no listing to read
for index, cache_dir in enumerate(cache_dirs):
online = fetch and index == len(cache_dirs) - 1
try:
paths, truncated = upstream.list_tree(repo, pin, str(cache_dir), offline=not online)
except upstream.UpstreamError as exc:
print(f" {tree_key(repo, pin)}: {exc}", file=sys.stderr)
return None
if paths and not truncated:
return frozenset(paths)
return None
def _walk(value: object) -> Iterator[tuple[str, object]]:
"""Every (key, value) of a profile, nested lists and mappings included."""
if isinstance(value, dict):
for key, item in value.items():
yield str(key), item
yield from _walk(item)
elif isinstance(value, list):
for item in value:
yield from _walk(item)
def cited_paths(profile: dict) -> set[str]:
"""Every path a page of the profile could link: the parts of each
source_ref, the file:line citations of its prose and the file its
version is read from."""
basis = profile.get("version_basis")
bases = ([basis] if isinstance(basis, dict) and "kind" in basis
else list(basis.values()) if isinstance(basis, dict) else [])
paths: set[str] = {
str(b["path"]) for b in bases
if isinstance(b, dict) and b.get("kind") == "file" and b.get("path")
}
for key, value in _walk(profile):
if key == "source_ref" and isinstance(value, (str, dict)):
for _label, refs in source_ref_values(value):
paths.update(ref_role(part.path)[1] for part in split_source_ref(refs))
elif isinstance(value, str) and ":" in value:
for _n, _span, _spans, parts, _run, _wrapped in _prose_runs(value):
paths.update(part.path for part in parts)
return {path for path in paths
if _PATH_RE.fullmatch(path) and not is_binary_citation(path)}
def profile_trees(profile: dict) -> list[tuple[upstream.Repo, str]]:
"""Every repository and revision a page of the profile can link into."""
found: list[tuple[upstream.Repo, str]] = []
labels = {""} | {
str(mode) for field in ("source", "upstream", "source_commit", "upstream_commit")
if isinstance(profile.get(field), dict) for mode in profile[field]}
for label in sorted(labels):
for pair in _forge_sources(profile, label) + list(role_sources(profile, label).values()):
if pair not in found:
found.append(pair)
return found
def _listed_directories(
repo: upstream.Repo, pin: str, paths: set[str], cache_dirs: list[Path], fetch: bool,
) -> frozenset[str] | None:
"""The cited paths found by listing their directories one by one, for a
tree the forge truncates (aps3e vendors RPCS3 whole). A directory that
cannot be listed confirms none of its paths. None off GitHub, the one
forge with that call, and None when no directory could be listed: the
tree was not read, so its record is kept (TeknoParrotUI answers 404, and
each fetch without its cached tree dropped its four paths)."""
if repo.family != "github":
return None
found: set[str] = set()
listed = False
for folder in sorted({path.rpartition("/")[0] for path in paths} - {""}):
names = None
for index, cache_dir in enumerate(cache_dirs):
online = fetch and index == len(cache_dirs) - 1
try:
names = upstream.list_directory(repo, pin, folder, str(cache_dir), offline=not online)
except upstream.UpstreamError:
names = None
if names is not None:
break
listed = listed or names is not None
found.update(f"{folder}/{name}" for name in names or ())
return frozenset(found) if listed else None
def build_source_paths(
profiles: dict, cache_dirs: list[Path], fetch: bool = False,
) -> tuple[dict[str, list[str]], list[str]]:
"""The cited paths each cached tree holds, and the trees not cached."""
held: dict[str, set[str]] = {}
unread: set[str] = set()
for _name, profile in sorted(profiles.items()):
paths = cited_paths(profile)
if not paths:
continue
for repo, pin in profile_trees(profile):
tree = _cached_tree(repo, pin, cache_dirs, fetch)
if tree is None:
tree = _listed_directories(repo, pin, paths, cache_dirs, fetch)
if tree is None:
unread.add(tree_key(repo, pin))
continue
# Recorded even when it holds no cited path, so a pinned tree
# missing from the record is one no run has read.
held.setdefault(tree_key(repo, pin), set()).update(paths & tree)
for repo, pin, path in build_files(profile):
tree = (_cached_tree(repo, pin, cache_dirs, fetch)
or _listed_directories(repo, pin, {path}, cache_dirs, fetch))
if tree is None:
unread.add(tree_key(repo, pin))
continue
held.setdefault(tree_key(repo, pin), set()).update({path} & tree)
return {key: sorted(paths) for key, paths in sorted(held.items())}, sorted(unread)
def build_files(profile: dict) -> list[tuple[upstream.Repo, str, str]]:
"""The platform build files `pin_build` names at a commit, as (repo,
revision, path). A tag can move, so a build read at a tag is not linked."""
found = []
for build in profile.get("pin_build") or []:
repo = _browse_repo(str(build.get("repo", "")))
revision = str(build.get("revision", ""))
if repo is not None and re.fullmatch(r"[0-9a-f]{40}", revision):
found.append((repo, revision, str(build.get("path", ""))))
return found
def keep_unread(
held: dict[str, list[str]], unread: list[str], previous: dict[str, list[str]]
) -> dict[str, list[str]]:
"""Carry over what the last record held for the trees this run could not read.
A tree key names a pinned sha, so what it held then it holds now. A run
that GitLab rate-limited dropped about twenty trees it never read. A tree
no run could read is recorded empty: confirming no path, it links none,
and check_freshness tells it from a pin no run has tried.
"""
kept = dict(held)
for key in unread:
kept.setdefault(key, previous.get(key, []))
return dict(sorted(kept.items()))
def read_record(path: Path) -> dict[str, list[str]]:
"""The record a previous run wrote, empty when there is none."""
try:
return json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError:
return {}
def _commit_url(repo: upstream.Repo, pin: str) -> str:
"""Forge-specific browser URL for one commit."""
base = f"https://{repo.host}/{repo.owner}/{repo.name}"
if repo.family == "gitlab":
return f"{base}/-/commit/{pin}"
if repo.family == "bitbucket":
return f"{base}/commits/{pin}"
if repo.family == "sourceforge":
return f"https://{repo.host}/p/{repo.owner}/{repo.name}/ci/{pin}/"
if repo.family == "swh":
return f"https://{repo.host}/browse/revision/{pin}/"
return f"{base}/commit/{pin}"
def version_basis_url(profile: dict, basis: dict, mode: str = "") -> str:
"""Where a reader checks a version: the file stating it at the pin, or
the tag it counts from. "" when neither can be linked.
The Version cell printed `libretro/handy.h` as bare text beside a
pinned Revision link, so the #define it reads was one search away.
"""
field = "upstream" if basis.get("repo") == "upstream" else "source"
declared = next(iter(_repo_pins(profile, field, mode)), None)
repo = _browse_repo(declared[0]) if declared else None
if repo is None:
return ""
kind, path, tag = basis.get("kind"), str(basis.get("path") or ""), str(basis.get("tag") or "")
if kind == "file" and path:
pin = next((p for r, p in _forge_sources(profile, mode)
if (r.host, r.slug) == (repo.host, repo.slug)), "")
return _source_permalink(repo, pin, path, None, None) if pin and tree_holds(
repo, pin, path) else ""
if kind == "tag" and tag and repo.family in ("github", "gitlab"):
tree = "/-/tree/" if repo.family == "gitlab" else "/tree/"
return f"https://{repo.host}/{repo.owner}/{repo.name}{tree}{urllib.parse.quote(tag)}"
return ""
def revision_markdown(profile: dict) -> str:
"""Each repository the profile reads, linked at the commit it was read at.
The page linked the repositories unpinned: the revision every citation
refers to sat in the YAML alone, for 178 profiles.
"""
links = [
f"[{'Software Heritage' if repo.family == 'swh' else repo.slug}@{pin[:12]}]"
f"({_commit_url(repo, pin)})"
for repo, pin in _forge_sources(profile)
]
branch = profile.get("source_branch")
if branch and not isinstance(branch, dict):
links.append(f"branch `{branch}`")
elif isinstance(branch, dict):
links += [f"{mode} branch `{name}`" for mode, name in branch.items()]
return ", ".join(links)
_GLUE_RE = re.compile(r"(^|/)(libretro|retro_)[^/]*$|(^|/)libretro[^/]*/", re.IGNORECASE)
def role_label(profile: dict, role: str, path: str = "") -> str:
"""Whose code a cited path is, said the way a reader asks it.
A libretro port carries the emulator's own sources beside its glue: pcem
cites src/mem.c in the port, which is PCem's code, not the core's.
"""
if role == "upstream":
return "upstream emulator"
if "libretro" not in str(profile.get("type", "")):
return "this build"
if _GLUE_RE.search(path):
return "libretro glue"
return "emulator code, libretro port"
def role_sources(profile: dict, label: str = "") -> dict[str, tuple[upstream.Repo, str]]:
"""The forge repository and pin behind each role a citation can name."""
found: dict[str, tuple[upstream.Repo, str]] = {}
for field in ("source", "upstream"):
for value, pin, _fallback in _repo_pins(profile, field, label):
repo = _browse_repo(value)
if repo is not None and pin and field not in found:
found[field] = (repo, pin)
return found
def requested_by(profile: dict, value: str | dict | None) -> str:
"""Whose code the citations of an entry are in, said in words."""
labels = []
for _label, refs in source_ref_values(value):
for part in split_source_ref(refs):
role, bare = ref_role(part.path)
if role:
label = role_label(profile, role, bare)
if label not in labels:
labels.append(label)
if not labels or not _two_repositories(profile):
return ""
return labels[0] if len(labels) == 1 else ", ".join(labels[:-1]) + f" and {labels[-1]}"
def _two_repositories(profile: dict) -> bool:
source, upstream_url = profile.get("source"), profile.get("upstream")
return bool(source and upstream_url and source != upstream_url)
def _source_ref_markdown(profile: dict, value: str | dict | None) -> str:
"""Render source_ref values as pinned links when their forge is known.
Each part is followed by whose code it cites, in words, when the profile
reads two repositories. source_ref_items() gives the same parts with
that role apart, for a page that names the roles once in a legend.
"""
rendered_groups = []
for label, items in source_ref_items(profile, value):
text = ", ".join(f"{part} ({role})" if role else part for part, role in items)
if label:
text = f"**{label}:** {text}"
rendered_groups.append(text)
return ", ".join(rendered_groups)
def source_ref_items(profile: dict, value: str | dict | None) -> list[tuple[str, list[tuple[str, str]]]]:
"""Each group of source_ref values: its label and its parts, each part
as Markdown with the role_label() of the code it cites ("" when the
profile reads one repository).
A profile can declare two repositories: the libretro port in ``source`` and
the original emulator in ``upstream``. A path links into the one whose
tree SOURCE_PATHS says holds it. Any other path is rendered as plain
code: a citation with no link still names the file and the lines, while a
link to the wrong repository is a false citation. An address inside a
shipped binary reads as one (offset 0x8094-0x80ac in libnes.so).
"""
groups: list[tuple[str, list[tuple[str, str]]]] = []
path_re = re.compile(r"^[A-Za-z0-9_.@/+~-]+$")
for label, refs in source_ref_values(value):
candidates = _forge_sources(profile, label)
by_role = role_sources(profile, label)
rendered: list[tuple[str, str]] = []
current_role = ""
binary = ""
for part in split_source_ref(refs):
if is_binary_citation(part.path):
text, binary = _binary_citation(part.path, binary)
rendered.append((text + _annotation_markdown(ref_annotation(part.raw)), ""))
continue
binary = ""
role, bare = ref_role(part.path)
if bare != part.path or role:
current_role = role
elif part.raw and not part.raw[:1].isdigit():
current_role = ""
part = type(part)(bare, part.start, part.end, part.raw)
display = part.path
if part.start is not None:
display += f":{part.start}"
if part.end is not None and part.end != part.start:
display += f"-{part.end}"
# The path is linked as written. A first segment equal to a
# repository's name proves nothing: PCSX2 keeps its sources in
# pcsx2/, hatariB vendors Hatari in hatari/, and stripping it
# broke 470 links. Two repositories and no tree to read: no link.
selected: tuple[upstream.Repo, str] | None = None
real_path = part.path
if path_re.fullmatch(part.path):
if current_role:
# Only the repository the part names, or no link at all.
selected = by_role.get(current_role)
if selected is not None and not tree_holds(*selected, part.path):
selected = None
else:
selected = _holder(candidates, part.path)
role = (role_label(profile, current_role, part.path)
if current_role and _two_repositories(profile) else "")
note = _annotation_markdown(ref_annotation(part.raw))
if selected is None:
rendered.append((f"`{display}`{note}", role))
else:
repo, pin = selected
url = _source_permalink(
repo, pin, real_path, part.start, part.end
)
rendered.append((f"[`{display}`]({url}){note}", role))
groups.append((label, rendered or [(f"`{refs}`", "")]))
return groups
def _annotation_markdown(text: str) -> str:
"""A part's annotation after its citation, as written: `(lsf default)`.
Profile prose, so placeholders keep their brackets and nothing in it
opens emphasis or a table cell.
"""
if not text:
return ""
return " " + _escape_tags(re.sub(r"([*|\\])", r"\\\1", text))
def _binary_citation(path: str, previous: str) -> tuple[str, str]:
"""A part citing code inside a shipped binary, and the binary it names.
`Nesoid 2.5.0 libnes.so 0x455a4-0x45694, 0x8094-0x80ac` cites two
ranges of one library: the bare address continues the binary before it.
No revision of a repository holds those bytes, so nothing is linked.
"""
found = _HEX_ADDRESS_RE.search(path)
if found is None:
return f"`{path}`", path
binary = path[:found.start()].rstrip(" :") or previous
if not binary:
return f"`{path}`", ""
return f"offset `{path[found.start():]}` in `{binary}`", binary
def link_prose_citations(profile: dict, text: str) -> str:
"""Prose file:line citations as pinned links, where the target is certain.
profile_sync keeps these citations on their pin, and the page printed
4,328 of them as plain text. A citation links only when the path is
rooted (it holds a directory) or is one a structured source_ref of the
profile already uses: a bare name could be anywhere in the tree, and a
link to the wrong file is a false citation. Of the repositories a profile
reads, the one its role word names is taken, else the one tree holding
the path: held by both, the citation does not say which it means.
Text already in backticks or in a link is left alone.
"""
candidates = _forge_sources(profile)
if not candidates or ":" not in text:
return text
by_role = role_sources(profile)
structured = {
part.path
for entry in profile.get("files") or []
if isinstance(entry, dict)
for _label, refs in source_ref_values(entry.get("source_ref"))
for part in split_source_ref(refs)
}
out = []
for line in text.split("\n"):
guarded = _guarded_spans(line)
edits = []
for _n, path_span, spans, parts, _run, wrapped in _prose_runs(line):
path = parts[0].path
if wrapped or " " in path or not _PATH_RE.fullmatch(path):
continue
if "/" not in path and path not in structured:
continue
if any(lo <= path_span[0] < hi for lo, hi in guarded):
continue
role = parts[0].role
# `upstream a.c:5` names its repository: none other is linked.
named = [by_role[role]] if role in by_role else [] if role else candidates
holders = [tree for tree in named if tree_holds(*tree, path)]
if len(holders) != 1:
continue
repo, pin = holders[0]
for index, ((lo, hi), part) in enumerate(zip(spans, parts)):
start = path_span[0] if index == 0 else lo
url = _source_permalink(repo, pin, part.path, part.start, part.end)
edits.append((start, hi, f"[`{line[start:hi]}`]({url})"))
for start, end, link in sorted(edits, reverse=True):
line = line[:start] + link + line[end:]
out.append(line)
return "\n".join(out)
_PATH_RE = re.compile(r"^[A-Za-z0-9_.@/+~-]+$")
def _guarded_spans(line: str) -> list[tuple[int, int]]:
"""Code spans and links of a markdown line."""
return [m.span() for m in re.finditer(r"`[^`]*`|\[[^\]]*\]\([^)]*\)", line)]
# Where a platform's list was read: the forge, the repository, the revision
# and the path inside it, out of the URL its scraper pinned.
_LIST_URL_RES = (
re.compile(r"^https://raw\.githubusercontent\.com/(?P<owner>[^/]+)/(?P<repo>[^/]+)/"
r"(?P<rev>[^/]+)/(?P<path>.+)$"),
re.compile(r"^https://github\.com/(?P<owner>[^/]+)/(?P<repo>[^/]+)/(?:blob|tree)/"
r"(?P<rev>[^/]+)(?:/(?P<path>.+))?$"),
re.compile(r"^https://codeload\.github\.com/(?P<owner>[^/]+)/(?P<repo>[^/]+)/"
r"tar\.gz/(?P<rev>[^/]+)$"),
re.compile(r"^https://(?P<host>gitlab\.com)/(?P<owner>[^/]+)/(?P<repo>[^/]+)/-/"
r"(?:raw|blob)/(?P<rev>[^/]+)/(?P<path>.+)$"),
)
_BRANCHES = frozenset({"master", "main", "db"})
@dataclass(frozen=True)
class ListSource:
"""A platform's list as its scraper read it."""
host: str
owner: str
repo: str
rev: str
path: str
@property
def moving(self) -> bool:
"""The revision is a branch: what was read is not recorded."""
return not self.rev or self.rev in _BRANCHES
@property
def label(self) -> str:
"""`batocera-systems at tag batocera-43.1`, said in words."""
name = self.path.rsplit("/", 1)[-1] if self.path else f"{self.repo} repository"
if not self.rev:
return f"{name}, default branch"
if re.fullmatch(r"[0-9a-f]{40}", self.rev):
return f"{name} at commit {self.rev[:12]}"
if self.moving:
return f"{name} on branch {self.rev}"
return f"{name} at tag {self.rev}"
def browse(self, path: str = "", start: int | None = None,
end: int | None = None) -> str:
"""The page a reader opens: the file, or the tree, at the revision."""
path = path or self.path
if self.host == "gitlab.com":
url = f"https://gitlab.com/{self.owner}/{self.repo}/-/blob/{self.rev}/{path}"
anchor = f"#L{start}" + (f"-{end}" if end and end != start else "")
else:
base = f"https://github.com/{self.owner}/{self.repo}"
if not self.rev:
return base
kind = "blob" if path else "tree"
url = f"{base}/{kind}/{self.rev}" + (f"/{path}" if path else "")
anchor = f"#L{start}" + (f"-L{end}" if end and end != start else "")
return url + (anchor if start else "")
def list_source(url: str) -> ListSource | None:
"""The forge, repository, revision and path of a platform's `source:`."""
url = str(url or "").strip()
for pattern in _LIST_URL_RES:
found = pattern.match(url)
if found:
parts = found.groupdict()
return ListSource(parts.get("host") or "github.com", parts["owner"],
parts["repo"], parts["rev"], parts.get("path") or "")
bare = re.match(r"^https://github\.com/([^/]+)/([^/]+?)/?$", url)
if bare:
return ListSource("github.com", bare[1], bare[2], "", "")
return None
def launcher_ref_markdown(source: ListSource | None, ref: str) -> str:
"""A launcher record's source_ref, each part a pinned link.
Linked only where the caller knows the launcher code sits in the
repository and revision of the platform's list. Otherwise each part is
plain code: a link to another repository is a false citation.
"""
rendered: list[str] = []
for part in split_source_ref(ref):
display = part.path.rsplit("/", 1)[-1]
if part.start is not None:
display += f":{part.start}"
if part.end is not None and part.end != part.start:
display += f"-{part.end}"
if source is None or not source.rev or not _PATH_RE.fullmatch(part.path):
rendered.append(f"`{display}`")
else:
rendered.append(f"[`{display}`]({source.browse(part.path, part.start, part.end)})")
return ", ".join(rendered)
from sitegen.sources import SOURCE_PATHS, TREE_CACHE, build_source_paths, keep_unread, read_record
def main() -> int:
+1 -480
View File
@@ -11,489 +11,10 @@ a get/ download page for every registered platform.
from __future__ import annotations
import argparse
import json
import re
import sys
from collections import Counter, defaultdict
from dataclasses import dataclass, field
from html.parser import HTMLParser
from pathlib import Path
from urllib.parse import unquote, urlsplit
@dataclass
class Page:
path: Path
title: str = ""
h1: str = ""
lang: str = ""
descriptions: list[str] = field(default_factory=list)
canonical: list[str] = field(default_factory=list)
h1_count: int = 0
main_count: int = 0
ids: list[str] = field(default_factory=list)
links: list[str] = field(default_factory=list)
missing_alt: list[str] = field(default_factory=list)
jsonld: list[str] = field(default_factory=list)
unrendered: list[str] = field(default_factory=list)
remote_images: list[str] = field(default_factory=list)
remote_scripts: list[str] = field(default_factory=list)
placeholders: list[str] = field(default_factory=list)
headings: list[int] = field(default_factory=list)
empty_headers: int = 0
runtime_diagrams: int = 0
size: int = 0
elements: int = 0
# A moved page's old address: a meta refresh to the new one, no content.
redirect: str = ""
# Budgets the site was brought under on 2026-10-22, with room to grow. A
# change that passes one is a regression of what a visitor downloads, not a
# matter of taste: raise the number in the same change that explains why.
#
# The largest page was 10.5 MB (systems/game-engines/) and took 21 s of
# main-thread work on a throttled phone. Split pages now top out at 0.9 MB.
MAX_PAGE_BYTES = 1_000_000
# Elements outside scripts and styles: the browser lays out and styles each.
# emulators/mame held 13,300 and blocked the main thread for 235 ms. Its
# index now carries each card's id on the link itself.
MAX_PAGE_ELEMENTS = 10_000
# Pages allowed past it, each with the reason, removed when it comes under.
OVER_ELEMENT_BUDGET: dict[str, str] = {}
# Pagefind loads its index in pieces: the metadata, then the chunks the words
# typed fall in (stored compressed). 59 KB for the largest chunk and 7.5 KB of
# metadata on 2026-10-22, 5.2 MB for the whole index on disk.
MAX_PAGEFIND_CHUNK_BYTES = 150_000
MAX_PAGEFIND_META_BYTES = 50_000
MAX_PAGEFIND_TOTAL_BYTES = 12_000_000
# Pages whose description is one text once the page's own name is taken
# out. 707 pages shared five templates ("X: source-pinned emulator
# firmware profile with paths, hashes..."), and a search engine showed the
# same line under every result.
MAX_SHARED_DESCRIPTION = 10
# Text inside these is shown as written, so markup there is not a leftover.
_LITERAL_TAGS = frozenset({"pre", "code", "script", "style", "textarea"})
class _PageParser(HTMLParser):
def __init__(self, path: Path) -> None:
super().__init__(convert_charrefs=True)
self.page = Page(path)
self._title_depth = 0
self._title_parts: list[str] = []
self._h1_depth = 0
self._h1_parts: list[str] = []
self._jsonld_depth = 0
self._jsonld_parts: list[str] = []
self._literal_depth = 0
self._header_parts: list[str] | None = None
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
data = {key: value or "" for key, value in attrs}
self._count(tag, data)
self._open(tag, data)
self._references(tag, data)
def _count(self, tag: str, data: dict[str, str]) -> None:
if tag not in ("script", "style"):
self.page.elements += 1
if tag in _LITERAL_TAGS:
self._literal_depth += 1
if re.fullmatch(r"h[1-6]", tag):
self.page.headings.append(int(tag[1]))
if tag == "th":
self._header_parts = []
if "mermaid" in data.get("class", "").split():
# Material renders it in the browser with a script from a CDN.
self.page.runtime_diagrams += 1
if tag == "script" and re.match(r"\s*(?:https?:)?//", data.get("src", "")):
self.page.remote_scripts.append(data["src"])
def _open(self, tag: str, data: dict[str, str]) -> None:
if tag == "html":
self.page.lang = data.get("lang", "")
elif tag == "title":
self._title_depth += 1
elif tag == "meta" and data.get("http-equiv", "").lower() == "refresh":
self.page.redirect = data.get("content", "").partition("url=")[2]
elif tag == "meta" and data.get("name", "").lower() == "description":
self.page.descriptions.append(data.get("content", "").strip())
elif tag == "h1":
self.page.h1_count += 1
self._h1_depth += 1
elif tag == "main":
self.page.main_count += 1
elif tag == "img" and "alt" not in data:
self.page.missing_alt.append(data.get("src", "?"))
elif tag == "script" and data.get("type") == "application/ld+json":
self._jsonld_depth += 1
self._jsonld_parts = []
def _references(self, tag: str, data: dict[str, str]) -> None:
element_id = data.get("id")
if element_id is not None:
self.page.ids.append(element_id)
if tag in ("a", "link") and data.get("href"):
self.page.links.append(data["href"])
if tag in ("img", "script", "source") and data.get("src"):
self.page.links.append(data["src"])
# An image from another host breaks when that host renames it, and
# tells it about every visit: the site serves its own copies.
sources = [data.get("src") or ""] + (data.get("srcset") or "").split(",")
if tag in ("img", "source", "image") and any(
re.match(r"\s*(?:https?:)?//", value) for value in sources if value
):
self.page.remote_images.append(data.get("src") or data.get("srcset") or "?")
if tag == "link" and "canonical" in data.get("rel", "").split():
self.page.canonical.append(data.get("href", ""))
def handle_comment(self, data: str) -> None:
match = re.match(r"\s*image:\s*(\S+)", data)
if match:
self.page.placeholders.append(match.group(1))
def handle_endtag(self, tag: str) -> None:
if tag in _LITERAL_TAGS and self._literal_depth:
self._literal_depth -= 1
if tag == "th" and self._header_parts is not None:
if not "".join(self._header_parts).strip():
self.page.empty_headers += 1
self._header_parts = None
if tag == "title":
self._title_depth -= 1
elif tag == "h1" and self._h1_depth:
self._h1_depth -= 1
elif tag == "script" and self._jsonld_depth:
self.page.jsonld.append("".join(self._jsonld_parts).strip())
self._jsonld_depth -= 1
self._jsonld_parts = []
def handle_data(self, data: str) -> None:
if self._header_parts is not None:
self._header_parts.append(data)
if self._title_depth:
self._title_parts.append(data)
if self._h1_depth:
self._h1_parts.append(data)
if self._jsonld_depth:
self._jsonld_parts.append(data)
if not self._literal_depth and "**" in data:
self.page.unrendered.append(data.strip()[:60])
def close(self) -> None:
super().close()
self.page.title = "".join(self._title_parts).strip()
self.page.h1 = re.sub(r"\s+", " ", "".join(self._h1_parts)).strip()
def _parse_page(path: Path) -> Page:
parser = _PageParser(path)
text = path.read_text(encoding="utf-8", errors="replace")
parser.feed(text)
parser.close()
parser.page.size = len(text.encode("utf-8"))
return parser.page
def _heading_jumps(levels: list[int]) -> list[str]:
"""Each heading more than one level below the one before it: a screen
reader user moving by level finds nothing at the level skipped."""
return [f"h{before} to h{after}" for before, after in zip(levels, levels[1:])
if after > before + 1]
def _check_pagefind(site: Path) -> list[str]:
"""Pagefind's index pieces, each against its budget."""
root = site / "pagefind"
files = [path for path in root.rglob("*") if path.is_file()]
issues = []
for path in files:
size = path.stat().st_size
rel = path.relative_to(site).as_posix()
if path.suffix == ".pf_index" and size > MAX_PAGEFIND_CHUNK_BYTES:
issues.append(f"{rel}: {size:,} bytes, over the {MAX_PAGEFIND_CHUNK_BYTES:,} budget of a chunk")
if path.suffix == ".pf_meta" and size > MAX_PAGEFIND_META_BYTES:
issues.append(f"{rel}: {size:,} bytes, over the {MAX_PAGEFIND_META_BYTES:,} budget")
total = sum(path.stat().st_size for path in files)
if total > MAX_PAGEFIND_TOTAL_BYTES:
issues.append(f"pagefind/: {total:,} bytes, over the {MAX_PAGEFIND_TOTAL_BYTES:,} budget")
return issues
def _local_target(
href: str, page_path: Path, site: Path, base_path: str
) -> tuple[list[Path], str] | None:
parsed = urlsplit(href)
if parsed.scheme or parsed.netloc or href.startswith(
("mailto:", "tel:", "data:", "javascript:")
):
return None
raw_path = unquote(parsed.path)
if not raw_path:
return [page_path], unquote(parsed.fragment)
if base_path != "/" and (
raw_path == base_path.rstrip("/") or raw_path.startswith(base_path)
):
suffix = raw_path[len(base_path.rstrip("/")) :]
raw_path = "/" + suffix.lstrip("/")
target = (
site / raw_path.lstrip("/")
if raw_path.startswith("/")
else page_path.parent / raw_path
).resolve()
try:
target.relative_to(site)
except ValueError:
return [], unquote(parsed.fragment)
candidates = [target]
if raw_path.endswith("/"):
candidates = [target / "index.html"]
elif not target.suffix:
candidates.extend([target / "index.html", target.with_suffix(".html")])
return candidates, unquote(parsed.fragment)
def _check_pages(
pages: dict, site: Path, titles: dict, descriptions: dict
) -> list[str]:
"""Every per-page check: title, description, links, JSON-LD.
Split out of validate_site, which reached complexity 43. The
cross-page duplicate check stays with the caller, since it can only
run once every page has been seen. *titles* and *descriptions* are
filled here for it.
"""
issues: list[str] = []
for path, page in pages.items():
rel = path.relative_to(site)
is_404 = rel == Path("404.html")
messages = [
*_document_issues(path, page, is_404, titles, descriptions),
*_content_issues(page, rel.as_posix()),
*_jsonld_issues(page, is_404),
]
issues.extend(f"{rel}: {message}" for message in messages)
return issues
def _document_issues(path: Path, page: Page, is_404: bool, titles: dict, descriptions: dict) -> list[str]:
"""The head and landmarks: title, language, description, H1, main, canonical."""
messages = []
if not page.title:
messages.append("missing document title")
elif not is_404:
titles[page.title].append(path)
if page.lang != "en":
messages.append(f"expected lang='en', got {page.lang!r}")
if len(page.descriptions) != 1 or not page.descriptions[0]:
messages.append(f"expected one non-empty description, got {len(page.descriptions)}")
elif not is_404:
descriptions[page.descriptions[0]].append(path)
if not is_404 and page.h1_count != 1:
messages.append(f"expected one H1, got {page.h1_count}")
if page.main_count != 1:
messages.append(f"expected one main landmark, got {page.main_count}")
if not is_404 and (
len(page.canonical) != 1
or not page.canonical[0].startswith("https://")
):
messages.append(f"expected one HTTPS canonical URL, got {page.canonical!r}")
return messages
def _content_issues(page: Page, rel: str) -> list[str]:
messages = []
duplicate_ids = [
value
for value, count in Counter(page.ids).items()
if value and count > 1
]
if duplicate_ids:
messages.append(f"duplicate IDs: {duplicate_ids[:5]}")
if page.missing_alt:
messages.append(f"images missing alt: {page.missing_alt[:5]}")
if page.remote_images:
messages.append(f"images loaded from another host: {page.remote_images[:3]}")
if page.remote_scripts:
messages.append(f"scripts loaded from another host: {page.remote_scripts[:3]}")
if page.runtime_diagrams:
messages.append(f"{page.runtime_diagrams} diagram(s) drawn by a script at runtime")
if page.size > MAX_PAGE_BYTES:
messages.append(f"{page.size:,} bytes of HTML, over the {MAX_PAGE_BYTES:,} budget")
if page.elements > MAX_PAGE_ELEMENTS and rel not in OVER_ELEMENT_BUDGET:
messages.append(f"{page.elements:,} elements, over the {MAX_PAGE_ELEMENTS:,} budget")
jumps = _heading_jumps(page.headings)
if jumps:
messages.append(f"heading levels skipped: {sorted(set(jumps))}")
if page.empty_headers:
messages.append(f"{page.empty_headers} table header cell(s) without text")
if page.placeholders:
# scripts/sitediagrams.py knows no diagram of this name.
messages.append(f"image placeholders left unresolved: {page.placeholders[:3]}")
if page.unrendered:
# Bold that reached the reader as asterisks: a block indented
# one level too deep is read as code (the clownmdemu analysis).
messages.append(f"markdown left unrendered: {page.unrendered[:3]}")
return messages
def _jsonld_issues(page: Page, is_404: bool) -> list[str]:
messages = []
if not is_404 and len(page.jsonld) != 1:
messages.append(f"expected one JSON-LD block, got {len(page.jsonld)}")
for document in page.jsonld:
try:
payload = json.loads(document)
except json.JSONDecodeError as exc:
messages.append(f"invalid JSON-LD: {exc}")
continue
if not isinstance(payload, dict) or payload.get("@context") != "https://schema.org":
messages.append("JSON-LD is not a schema.org object")
return messages
def description_template(page: Page, site_name: str = "RetroBIOS") -> str:
"""A page's description with its own names taken out: its h1 and its
window title. What is left is the text it shares with its template."""
text = page.descriptions[0] if page.descriptions else ""
names = {page.h1, page.title.removesuffix(f" - {site_name}").strip()}
for name in sorted(filter(None, names), key=len, reverse=True):
text = text.replace(name, "")
return re.sub(r"\s+", " ", text).strip()
def _check_description_templates(pages: dict, site: Path) -> list[str]:
"""No more than MAX_SHARED_DESCRIPTION pages share one description
once their names are taken out."""
shared: dict[str, list[Path]] = defaultdict(list)
for path, page in pages.items():
if path.relative_to(site) != Path("404.html") and page.descriptions:
shared[description_template(page)].append(path)
return [
f"{len(paths)} pages share the description {text!r} after their name: "
+ ", ".join(str(path.relative_to(site)) for path in paths[:3])
for text, paths in shared.items()
if len(paths) > MAX_SHARED_DESCRIPTION
]
def _check_links(pages: dict, site: Path, base_path: str) -> list[str]:
"""Every local link and fragment resolves to something on disk."""
issues: list[str] = []
def report(path: Path, message: str) -> None:
issues.append(f"{path.relative_to(site)}: {message}")
for path, page in pages.items():
for href in page.links:
resolved = _local_target(href, path, site, base_path)
if resolved is None:
continue
candidates, fragment = resolved
if not candidates:
report(path, f"link escapes site root: {href}")
continue
existing = next((candidate for candidate in candidates if candidate.is_file()), None)
if existing is None:
report(path, f"broken local link or resource: {href}")
continue
if fragment and existing.suffix.lower() == ".html":
target_page = pages.get(existing.resolve())
if target_page is not None and fragment not in target_page.ids:
report(path, f"missing fragment in {href}")
return issues
RELEASE_DOWNLOAD = "https://github.com/Abdess/retrobios/releases/download/"
def _check_get_pages(
pages: dict, site: Path, platforms_dir: Path, record_path: Path,
) -> list[str]:
"""get/<platform>/ resolves for every registered platform, as a page.
Links outside the site keep these addresses across releases, so a
missing one is a dead download link for whoever followed it. A platform
with a pack in the release record links every one of its assets at the
recorded tag, and one without links none and gives the command.
"""
sys.path.insert(0, str(Path(__file__).resolve().parent))
import release_record
from model.guides import INSTALL_SH
from model.registry import list_registered_platforms, list_release_pack_platforms
if not (platforms_dir / "_registry.yml").is_file():
return [f"no platform registry in {platforms_dir}"]
record = release_record.load_advertised(record_path, str(platforms_dir))
released = set(list_release_pack_platforms(str(platforms_dir)))
issues: list[str] = []
for platform in list_registered_platforms(str(platforms_dir)):
rel = f"{release_record.GET_DIR}/{platform}/index.html"
page = pages.get((site / rel).resolve())
if page is None or page.redirect:
issues.append(f"{rel}: no download page for {platform}")
continue
assets = [link for link in page.links if link.startswith(RELEASE_DOWNLOAD)]
pack = release_record.pack_for(platform, record)
if platform in released and pack:
expected = {f"{RELEASE_DOWNLOAD}{record['tag']}/{a}" for a in pack["assets"]}
missing = sorted(expected - set(assets))
if missing:
issues.append(f"{rel}: does not link {', '.join(missing)}")
elif platform not in released:
packs = [a for a in assets if "_BIOS_Pack" in a]
if packs:
issues.append(f"{rel}: links a pack for a setup without one: {packs[0]}")
if f"{INSTALL_SH} | sh" not in (site / rel).read_text(encoding="utf-8"):
issues.append(f"{rel}: gives no install command")
return issues
def validate_site(
site: Path, base_path: str = "/retrobios/", platforms_dir: Path | None = None,
record_path: Path | None = None,
) -> list[str]:
site = site.resolve()
if not site.is_dir():
return [f"site directory does not exist: {site}"]
html_paths = sorted(site.rglob("*.html"))
if not html_paths:
return [f"no HTML pages found in {site}"]
pages = {path.resolve(): _parse_page(path) for path in html_paths}
issues: list[str] = []
titles: dict[str, list[Path]] = defaultdict(list)
descriptions: dict[str, list[Path]] = defaultdict(list)
# A redirect has no page to judge, only a target. The link check below
# still follows its link, so a redirect to nowhere is reported.
content = {path: page for path, page in pages.items() if not page.redirect}
issues.extend(_check_pages(content, site, titles, descriptions))
for label, values in (("title", titles), ("description", descriptions)):
for value, paths in values.items():
if len(paths) > 1:
rendered = ", ".join(str(path.relative_to(site)) for path in paths[:5])
issues.append(f"duplicate {label} {value!r}: {rendered}")
issues.extend(_check_description_templates(content, site))
issues.extend(_check_links(pages, site, base_path))
issues.extend(_check_pagefind(site))
if platforms_dir is not None:
issues.extend(_check_get_pages(
pages, site, platforms_dir, record_path or platforms_dir.parent / "release.json"))
return issues
from sitegen.validate import validate_site
def main() -> None:
+4 -4
View File
@@ -3302,7 +3302,7 @@ class ContributorsSurviveAFailedRequest(unittest.TestCase):
def _block(self, text: str):
import tempfile
from generate_readme import _existing_contributor_block
from sitegen.readme import _existing_contributor_block
with tempfile.NamedTemporaryFile("w", suffix=".md", delete=False) as handle:
handle.write(text)
@@ -3330,7 +3330,7 @@ class ContributorsSurviveAFailedRequest(unittest.TestCase):
self.assertEqual(self._block("# Title\n\n## Other\n\ntext\n"), [])
def test_an_unreadable_file_yields_nothing(self):
from generate_readme import _existing_contributor_block
from sitegen.readme import _existing_contributor_block
self.assertEqual(_existing_contributor_block("/nonexistent/README.md"), [])
@@ -5653,9 +5653,9 @@ class AHeldRevisionLinksItsBuildFile(unittest.TestCase):
f"RetroPie-Setup/blob/{pin}/scriptmodules/emulators/advmame-1.4.sh)", rows[0])
def test_the_record_holds_the_build_files(self):
import sitesources
from sitegen import sources as sitegen_sources
files = sitesources.build_files({"pin_build": [
files = sitegen_sources.build_files({"pin_build": [
{"repo": "https://github.com/o/r", "revision": "a" * 40, "path": "p.mk"},
{"repo": "https://github.com/o/r", "revision": "v1", "path": "q.mk"}]})
self.assertEqual([(f[1], f[2]) for f in files], [("a" * 40, "p.mk")])
+13 -12
View File
@@ -14,6 +14,7 @@ from pathlib import Path
from unittest import mock
import generate_readme
from sitegen import readme
import generate_site
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -30,7 +31,7 @@ def _normalized(text: str) -> str:
class OneContributingText(unittest.TestCase):
def test_repository_and_site_pages_match(self):
self.assertEqual(
_normalized(generate_readme.generate_contributing()),
_normalized(readme.generate_contributing()),
_normalized(generate_site.generate_contributing()),
)
@@ -48,7 +49,7 @@ class CoverageReadsTheGivenProfiles(unittest.TestCase):
with mock.patch.object(generate_readme, "verify_platform", fake_verify), \
mock.patch.object(generate_readme, "load_emulator_profiles", return_value={}):
generate_readme.compute_coverage(
readme.compute_coverage(
"retroarch", str(REPO_ROOT / "platforms"), {"files": {}}, emulators_dir="elsewhere"
)
self.assertEqual(seen, ["elsewhere"])
@@ -81,7 +82,7 @@ class BeforeOpeningAPullRequest(unittest.TestCase):
def test_it_names_the_site_build_and_the_packages_ci_runs(self):
"""A wiki-only change passed every listed check and failed CI on
validate_site.py, which the list did not name."""
text = generate_readme.generate_contributing()
text = readme.generate_contributing()
section = text.split("## Before opening a PR", 1)[1].split("\n## ", 1)[0]
workflow = (REPO_ROOT / ".github" / "workflows" / "validate.yml").read_text(encoding="utf-8")
for command in ("npm ci --prefix website", "npm run build --prefix website",
@@ -102,7 +103,7 @@ class BeforeOpeningAPullRequest(unittest.TestCase):
refuses past 100 MB, and only a maintainer can write to the release."""
from resolve import review
text = generate_readme.generate_contributing()
text = readme.generate_contributing()
section = text.split("## What happens next", 1)[1].split("\n## ", 1)[0]
self.assertEqual(review.MAX_FILE_SIZE, 100 * 1024 * 1024)
self.assertIn("100 MB", section)
@@ -111,7 +112,7 @@ class BeforeOpeningAPullRequest(unittest.TestCase):
def test_it_installs_what_the_checks_need_and_no_site_package(self):
"""The site is built by Node from website/package-lock.json: a pip
line naming the old theme installed packages nothing reads."""
text = generate_readme.generate_contributing()
text = readme.generate_contributing()
section = text.split("## Before opening a PR", 1)[1].split("\n## ", 1)[0]
self.assertIn('pip install pyyaml "jsonschema[format-nongpl]==', section)
self.assertNotIn("mkdocs", section)
@@ -125,7 +126,7 @@ class TheChecklistInstallsWhatCiInstalls(unittest.TestCase):
def test_the_pip_lines_are_the_workflow_lines(self):
workflow = (REPO_ROOT / ".github" / "workflows" / "validate.yml").read_text(encoding="utf-8")
text = generate_readme.generate_contributing()
text = readme.generate_contributing()
section = text.split("## Before opening a PR", 1)[1].split("\n## ", 1)[0]
pinned = [line.split("run: ", 1)[1] for line in workflow.splitlines()
if re.match(r"\s*run: (python3\.8 -m )?pip install .*==", line)
@@ -137,7 +138,7 @@ class TheChecklistInstallsWhatCiInstalls(unittest.TestCase):
def test_it_names_the_system_tools_ci_installs(self):
workflow = (REPO_ROOT / ".github" / "workflows" / "validate.yml").read_text(encoding="utf-8")
text = generate_readme.generate_contributing()
text = readme.generate_contributing()
section = text.split("## Before opening a PR", 1)[1].split("\n## ", 1)[0]
for tool, step in (("shellcheck", "shellcheck --version"),
("bwrap", "bwrap --ro-bind"),
@@ -157,21 +158,21 @@ class OneFileThroughTheBrowser(unittest.TestCase):
def test_the_guide_and_the_issue_chooser_offer_the_upload(self):
import yaml
text = generate_readme.generate_contributing()
text = readme.generate_contributing()
section = text.split("## Add a BIOS file", 1)[1].split("\n## ", 1)[0]
self.assertIn(generate_readme.UPLOAD_URL, section)
self.assertIn(readme.UPLOAD_URL, section)
self.assertNotIn("Fork this repository", section)
self.assertNotIn("reported in a comment", text)
chooser = yaml.safe_load(
(REPO_ROOT / ".github" / "ISSUE_TEMPLATE" / "config.yml").read_text(encoding="utf-8")
)
self.assertIn(generate_readme.UPLOAD_URL, [link["url"] for link in chooser["contact_links"]])
self.assertIn(readme.UPLOAD_URL, [link["url"] for link in chooser["contact_links"]])
def test_ci_comments_only_on_branches_of_this_repository(self):
workflow = (REPO_ROOT / ".github" / "workflows" / "validate.yml").read_text(encoding="utf-8")
self.assertIn("github.event.pull_request.head.repo.full_name == github.repository", workflow)
self.assertIn('>> "$GITHUB_STEP_SUMMARY"', workflow)
self.assertIn("summary of the Validation run", generate_readme.generate_contributing())
self.assertIn("summary of the Validation run", readme.generate_contributing())
def test_an_upload_at_the_bios_root_is_told_its_folder(self):
import os
@@ -278,7 +279,7 @@ class OneCommandRunsTheChecks(unittest.TestCase):
def test_the_guide_gives_the_runner_and_what_it_runs(self):
import pr_checks
text = generate_readme.generate_contributing()
text = readme.generate_contributing()
section = text.split("## Before opening a PR", 1)[1].split("\n## ", 1)[0]
self.assertIn("python scripts/pr_checks.py\n", section)
for step in pr_checks.STEPS:
+6 -5
View File
@@ -17,6 +17,7 @@ from pathlib import Path
from unittest import mock
import generate_readme
from sitegen import readme
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -33,8 +34,8 @@ class CoverageCache(unittest.TestCase):
self.db.write_text("{}")
self.calls: list[str] = []
patches = [
mock.patch.object(generate_readme, "COVERAGE_CACHE_DIR", self.work / "cache"),
mock.patch.object(generate_readme, "compute_coverage", self._compute),
mock.patch.object(readme, "COVERAGE_CACHE_DIR", self.work / "cache"),
mock.patch.object(readme, "compute_coverage", self._compute),
]
for patch in patches:
patch.start()
@@ -52,7 +53,7 @@ class CoverageCache(unittest.TestCase):
return {"platform": name.title(), "missing_names": {"a.bin"}}
def _run(self, names=("beta", "alpha")) -> dict:
return generate_readme.platform_coverages(
return readme.platform_coverages(
list(names), str(self.platforms), {}, {},
emulators_dir=str(self.emulators), db_path=str(self.db),
)
@@ -121,8 +122,8 @@ class CoverageCache(unittest.TestCase):
def missing(*_args, **_kwargs):
raise generate_readme.InputMissing("no emulator profile directory at nosuch")
with mock.patch.object(generate_readme, "compute_coverage", missing), \
mock.patch.object(generate_readme, "_coverage_inputs", return_value="other"), \
with mock.patch.object(readme, "compute_coverage", missing), \
mock.patch.object(readme, "_coverage_inputs", return_value="other"), \
self.assertRaises(generate_readme.InputMissing):
self._run()
self.assertEqual(sorted((self.work / "cache").glob("*.pickle")), kept)
+7 -7
View File
@@ -779,9 +779,9 @@ class ReadmeInstallerOptions(unittest.TestCase):
README never linked."""
def test_quick_install_gives_the_powershell_form_and_the_page(self):
import generate_readme
from sitegen import readme as sitegen_readme
source = inspect.getsource(generate_readme.generate_readme)
source = inspect.getsource(sitegen_readme.generate_readme)
self.assertIn("wiki/installer/#passing-options", source)
self.assertIn("## Passing options", _page("installer.md"))
readme = (ROOT / "README.md").read_text(encoding="utf-8")
@@ -797,13 +797,13 @@ class PublishedNumbersShareOneFormat(unittest.TestCase):
the site home as 15.6 GB, and the emulators page `10095 files`."""
def test_generators_format_counts_and_sizes_alike(self):
import generate_readme
from sitegen import readme as sitegen_readme
readme_source = inspect.getsource(generate_readme.generate_readme)
readme_source = inspect.getsource(sitegen_readme.generate_readme)
self.assertNotIn("size_mb", readme_source)
self.assertIn("format_size(size)", readme_source)
self.assertIn("{total_files:,}", script_source("generate_site.py"))
self.assertEqual(generate_readme.format_size(16011 * 1024 * 1024), "15.6 GB")
self.assertEqual(sitegen_readme.format_size(16011 * 1024 * 1024), "15.6 GB")
def test_the_readme_has_no_bare_large_count(self):
readme = (ROOT / "README.md").read_text(encoding="utf-8")
@@ -2051,10 +2051,10 @@ class BuildYourOwnPackSaysWhatTheCloneCosts(unittest.TestCase):
command and no size, and the clone runs to several gigabytes."""
def test_readme_gives_the_clone_command_and_its_size(self):
import generate_readme
from sitegen import readme as sitegen_readme
db = json.loads((ROOT / "database.json").read_text(encoding="utf-8"))
line = generate_readme.clone_line(db)
line = sitegen_readme.clone_line(db)
self.assertIn("git clone --depth 1", line)
self.assertRegex(line, r"over \d+(\.\d)? GB")
readme = (ROOT / "README.md").read_text(encoding="utf-8")
+2 -2
View File
@@ -20,7 +20,7 @@ from functools import cache
from pathlib import Path
import release_record
from generate_readme import (
from sitegen.readme import (
SITE_URL,
asset_links,
contributing_text,
@@ -662,7 +662,7 @@ class ArchiveRecipesAreCountedFromTheRecipes(unittest.TestCase):
self.assertEqual(self.counts["exact"] + self.counts["canonical"], self.counts["total"])
def test_the_readme_line(self) -> None:
from generate_readme import archive_line
from sitegen.readme import archive_line
line = archive_line(self.counts)
self.assertIn(line, _read("README.md").splitlines())
+1 -1
View File
@@ -16,7 +16,7 @@ from pathlib import Path
from model.platforms import load_platform_config
from model.registry import load_platform_registry
from generate_readme import extract_notes, extract_targets
from sitegen.readme import extract_notes, extract_targets
REPO_ROOT = Path(__file__).resolve().parent.parent
+1 -1
View File
@@ -425,7 +425,7 @@ class TheSitePageOfACardPlatform(unittest.TestCase):
import generate_site
from model.database import load_database
from model.registry import load_platform_registry
from generate_readme import compute_coverage
from sitegen.readme import compute_coverage
if not (REPO_ROOT / "database.json").is_file():
self.skipTest("database.json absent")
+10 -10
View File
@@ -36,7 +36,7 @@ from packs import archive as packs_archive
from packs import datatrees
from packs import manifest as packs_manifest
from packs import platformpack
import generate_readme
from sitegen import readme as sitegen_readme
import generate_site
import release_notes
import release_record
@@ -368,21 +368,21 @@ class TheTableDescribesTheRelease(unittest.TestCase):
def test_a_platform_reads_the_pack_that_serves_it(self):
for platform in ("retroarch", "lakka"):
self.assertEqual(
generate_readme.release_totals(platform, RECORD),
sitegen_readme.release_totals(platform, RECORD),
(4525, 5882727352),
)
self.assertEqual(
generate_readme.release_totals("misterfpga", RECORD), (74, 17000000)
sitegen_readme.release_totals("misterfpga", RECORD), (74, 17000000)
)
def test_a_platform_the_release_does_not_carry_has_no_figure(self):
self.assertEqual(
generate_readme.release_totals("vita3k", RECORD), (None, None)
sitegen_readme.release_totals("vita3k", RECORD), (None, None)
)
self.assertEqual(generate_readme.release_totals("retroarch", {}), (None, None))
self.assertEqual(sitegen_readme.release_totals("retroarch", {}), (None, None))
def test_the_download_table_gives_the_file_count_of_each_pack(self):
rows = generate_readme.download_table(
rows = sitegen_readme.download_table(
{"retroarch": {"platform": "RetroArch"}, "vita3k": {"platform": "Vita3K"}},
{"RetroArch": "`system/`"},
RECORD,
@@ -397,7 +397,7 @@ class TheTableDescribesTheRelease(unittest.TestCase):
self.skipTest("no release.json")
record = json.loads(record_path.read_text(encoding="utf-8"))
readme = (REPO_ROOT / "README.md").read_text(encoding="utf-8")
files, _size = generate_readme.release_totals("retroarch", record)
files, _size = sitegen_readme.release_totals("retroarch", record)
self.assertTrue(f"| RetroArch | {files:,} |" in readme)
@@ -509,7 +509,7 @@ class TheCollectionTotalNamesTheCollection(unittest.TestCase):
}
def test_in_the_readme(self):
line = generate_readme.collection_line(10375, self.COMPOSITION)
line = sitegen_readme.collection_line(10375, self.COMPOSITION)
self.assertIn("**10,375 files in the collection**", line)
self.assertIn("no pack holds them all", line)
@@ -534,7 +534,7 @@ class RefusedFilesAreNotPresent(unittest.TestCase):
from model.platforms import _platform_config_cache
import generate_db
import generate_readme
from sitegen import readme as sitegen_readme
with tempfile.TemporaryDirectory() as tmp:
previous = os.getcwd()
@@ -567,7 +567,7 @@ class RefusedFilesAreNotPresent(unittest.TestCase):
)
_platform_config_cache.clear()
self.addCleanup(_platform_config_cache.clear)
coverage = generate_readme.compute_coverage(
coverage = sitegen_readme.compute_coverage(
"hashy", "platforms", db, emulators_dir="emulators"
)
self.assertEqual((coverage["present"], coverage["total"]), (1, 2))
+8 -8
View File
@@ -5153,9 +5153,9 @@ class AWriteRefreshesTheSourcePaths(unittest.TestCase):
def test_only_a_real_online_write_refreshes(self):
from unittest import mock
import sitesources
from sitegen import sources
with mock.patch.object(sitesources, "build_source_paths", return_value=({}, [])) as built, \
with mock.patch.object(sources, "build_source_paths", return_value=({}, [])) as built, \
mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), \
mock.patch.object(profile_sync, "load_emulator_profiles", return_value={}), \
mock.patch("core.artifacts.write_if_changed") as written, \
@@ -5178,7 +5178,7 @@ class AWriteRefreshesTheSourcePaths(unittest.TestCase):
from model import profiles as model_profiles
from model.profiles import _emulator_profiles_cache
import sitesources
from sitegen import sources
with tempfile.TemporaryDirectory() as tmp:
profile = Path(tmp) / "p.yml"
@@ -5187,7 +5187,7 @@ class AWriteRefreshesTheSourcePaths(unittest.TestCase):
self.addCleanup(_emulator_profiles_cache.clear)
model_profiles.load_emulator_profiles(tmp, skip_aliases=False)
profile.write_text('emulator: P\nsource_commit: "new"\n', encoding="utf-8")
with mock.patch.object(sitesources, "build_source_paths", return_value=({}, [])) as built, \
with mock.patch.object(sources, "build_source_paths", return_value=({}, [])) as built, \
mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), \
mock.patch("core.artifacts.write_if_changed"), \
contextlib.redirect_stderr(io.StringIO()), \
@@ -5202,9 +5202,9 @@ class AnUnreadTreeKeepsItsRecord(unittest.TestCase):
trees it never read from source-paths.json."""
def test_unread_trees_carry_over(self):
import sitesources
from sitegen import sources
kept = sitesources.keep_unread(
kept = sources.keep_unread(
{"a@1": ["x.c"]}, ["b@2", "c@3"], {"b@2": ["y.c"], "a@1": ["old.c"]}
)
# c@3 was never read: recorded empty, it confirms no path.
@@ -6287,9 +6287,9 @@ class TestBranchCheckIsWired(unittest.TestCase):
def test_contributing_and_ci_use_the_flags(self):
root = Path(__file__).resolve().parents[1]
import generate_readme
from sitegen import readme
text = generate_readme.generate_contributing()
text = readme.generate_contributing()
self.assertIn("profile_sync.py --added --strict", text)
# The default base is fetched by the tool: a documented upstream
# remote failed every clone that had origin alone.
+4 -4
View File
@@ -517,12 +517,12 @@ class TheSiteCheckResolvesEveryGetPage(unittest.TestCase):
return site
def test_missing_and_wrong_pages_are_reported(self):
import validate_site
from sitegen import validate
record = {"tag": "v1", "packs": {"RomM_BIOS_Pack.zip": {
"platforms": ["romm"], "assets": ["RomM_BIOS_Pack.zip"],
"files": 1, "extracted_size": 1, "download_size": 1}}}
download = validate_site.RELEASE_DOWNLOAD
download = validate.RELEASE_DOWNLOAD
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp:
root = Path(tmp)
record_path = root / "release.json"
@@ -535,8 +535,8 @@ class TheSiteCheckResolvesEveryGetPage(unittest.TestCase):
pages["get/knulli/index.html"] = f'<a href="{download}v1/K_BIOS_Pack.zip">x</a>'
del pages["get/lakka/index.html"]
site = self._site(root, pages)
parsed = {p.resolve(): validate_site._parse_page(p) for p in site.rglob("*.html")}
issues = validate_site._check_get_pages(parsed, site.resolve(), Path(PLATFORMS),
parsed = {p.resolve(): validate._parse_page(p) for p in site.rglob("*.html")}
issues = validate._check_get_pages(parsed, site.resolve(), Path(PLATFORMS),
record_path)
joined = "\n".join(issues)
self.assertIn("get/lakka/index.html: no download page", joined)
+2 -2
View File
@@ -145,7 +145,7 @@ class EveryPageHasAMarkdownCopy(unittest.TestCase):
self.assertIn("markdownCopies,", config)
def test_a_page_keeps_its_commands_under_their_system(self) -> None:
import site_markdown
from sitegen import pagemarkdown
html = ('<html><body><main><h1 id="_top">Demo</h1><div class="sl-markdown-content">'
'<p>Run it <a href="/retrobios/x/">here</a>.</p>'
@@ -157,7 +157,7 @@ class EveryPageHasAMarkdownCopy(unittest.TestCase):
'<div class="ec-line"><div class="code">curl x | sh</div></div></code></pre></div>'
'<table><tr><th>File</th><th>MD5</th></tr><tr><td>a.bin</td><td>ff</td></tr></table>'
'<button>Copy</button><span class="sr-only">hidden</span></div></main></body></html>')
text = site_markdown.page_markdown(html, "https://abdess.github.io/retrobios/demo/")
text = pagemarkdown.page_markdown(html, "https://abdess.github.io/retrobios/demo/")
self.assertTrue(text.startswith("# Demo\n\nSource: https://abdess.github.io/retrobios/demo/"))
self.assertIn("[here](https://abdess.github.io/retrobios/x/)", text)
self.assertIn("**Windows:**\n\n```\nirm x | iex\n```", text)
+5 -5
View File
@@ -19,7 +19,7 @@ import struct
import unittest
from pathlib import Path
import generate_readme
from sitegen import readme as sitegen_readme
import make_demo
from sitegen import starlight as sitestarlight
@@ -47,7 +47,7 @@ class TheFilesAreThereAndSmall(unittest.TestCase):
def test_only_the_readme_variant_has_a_gif(self):
gifs = sorted(p.name for p in DEMO.glob("*.gif"))
self.assertEqual(gifs, [Path(generate_readme.DEMO_GIF).name])
self.assertEqual(gifs, [Path(sitegen_readme.DEMO_GIF).name])
self.assertEqual([v.name for v in make_demo.VARIANTS.values() if v.gif], ["default"])
def test_the_gif_and_the_posters_have_the_recorded_size(self):
@@ -130,14 +130,14 @@ class TheTapeAndTheDriverAgree(unittest.TestCase):
class TheReadmeShowsTheGif(unittest.TestCase):
def test_the_gif_sits_under_the_commands_with_its_description(self):
readme = (ROOT / "README.md").read_text(encoding="utf-8")
line = f"![{generate_readme.demo_description()}]({generate_readme.DEMO_GIF})"
line = f"![{sitegen_readme.demo_description()}]({sitegen_readme.DEMO_GIF})"
self.assertIn(line, readme)
self.assertLess(readme.index("## Install in one line"), readme.index(line))
self.assertLess(readme.index(line), readme.index("## Or download a ZIP"))
def test_the_description_names_what_the_recording_measured(self):
facts = _facts()
words = generate_readme.demo_description(facts)
words = sitegen_readme.demo_description(facts)
for value in (facts["setup"], f"{facts['games']} games", f"{facts['files']} BIOS files",
facts["size"]):
self.assertIn(str(value), words)
@@ -195,7 +195,7 @@ class TheTwoPagesShowIt(unittest.TestCase):
import generate_site
tag = generate_site.install_demo()[0]
self.assertIn(f'description="{generate_readme.demo_description()}"', tag)
self.assertIn(f'description="{sitegen_readme.demo_description()}"', tag)
source = Path(generate_site.__file__).read_text(encoding="utf-8")
body = source[source.index("def generate_home("):]
body = body[:body.index("\ndef ", 1)]
+2 -2
View File
@@ -72,12 +72,12 @@ class WhoShipsTheBuildAndWhy(unittest.TestCase):
"""`0.97, stated in libretro/handy.h` was bare text beside a pinned
Revision link: the #define it reads was one search away."""
import generate_site as gs
import sitesources
from sitegen import sources
import yaml
handy = yaml.safe_load((REPO_ROOT / "emulators" / "handy.yml").read_text(encoding="utf-8"))
path = handy["version_basis"]["path"]
self.assertIn(path, sitesources.cited_paths(handy))
self.assertIn(path, sources.cited_paths(handy))
self.assertIn(f"stated in [`{path}`](https://github.com/libretro/libretro-handy/blob/"
f"{handy['source_commit']}/{path})", gs.version_markdown(handy))
tagged = {"source": "https://github.com/owner/emu", "source_commit": "a" * 40,
+5 -5
View File
@@ -40,7 +40,7 @@ import json
import generate_site as gs
from sitegen import render as siterender
from model import systemnames
import validate_site
from sitegen import validate
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -376,20 +376,20 @@ class DataDirectoryPagesStayOutOfSearch(unittest.TestCase):
class AnElementBudget(unittest.TestCase):
def test_validate_site_reports_a_crowded_page(self):
self.assertEqual(validate_site.MAX_PAGE_ELEMENTS, 10_000)
self.assertEqual(validate.MAX_PAGE_ELEMENTS, 10_000)
(REPO_ROOT / "tmp").mkdir(exist_ok=True)
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp:
page = Path(tmp) / "crowded" / "index.html"
page.parent.mkdir()
page.write_text("<html><body>" + "<i></i>" * 10_001
+ "<script>" + "<b>" * 5 + "</script></body></html>")
issues = validate_site.validate_site(Path(tmp))
issues = validate.validate_site(Path(tmp))
self.assertTrue(any("elements, over the 10,000 budget" in issue for issue in issues))
@unittest.skipUnless((DIST / "emulators" / "mame" / "index.html").is_file(), "site not built")
def test_mame_is_under_it(self):
page = validate_site._parse_page(DIST / "emulators" / "mame" / "index.html")
self.assertLess(page.elements, validate_site.MAX_PAGE_ELEMENTS)
page = validate._parse_page(DIST / "emulators" / "mame" / "index.html")
self.assertLess(page.elements, validate.MAX_PAGE_ELEMENTS)
def _pages(name: str, profile: dict | None = None) -> dict[str, str]:
+3 -3
View File
@@ -42,7 +42,7 @@ from pathlib import Path
import yaml
import generate_readme
from sitegen import readme as sitegen_readme
import generate_site
import release_record
from model import guides
@@ -325,10 +325,10 @@ class CommandBlocks(unittest.TestCase):
class ContributingOpensOnTheAction(unittest.TestCase):
def test_both_generators_open_on_the_upload(self):
for text in (generate_readme.generate_contributing(), generate_site.generate_contributing()):
for text in (sitegen_readme.generate_contributing(), generate_site.generate_contributing()):
body = text.split("## Add a BIOS file", 1)[1]
self.assertTrue(body.lstrip().startswith("Have a file the collection lacks?"))
self.assertLess(body.index(generate_readme.UPLOAD_URL), body.index("## What happens next"))
self.assertLess(body.index(sitegen_readme.UPLOAD_URL), body.index("## What happens next"))
self.assertLess(body.index("gaps"), body.index("## What happens next"))
self.assertLess(body.index("## What happens next"), body.index("CI hashes"))
+3 -3
View File
@@ -21,7 +21,7 @@ import yaml
import generate_site as gs
from sitegen import entries as siteentries
import validate_site
from sitegen import validate
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -330,9 +330,9 @@ class TheBuiltPagesStayShort(unittest.TestCase):
for pattern, _ceiling in VISIBLE_CEILINGS.values():
for page in self._pages(pattern):
with self.subTest(page=page):
parsed = validate_site._PageParser(DIST / page / "index.html")
parsed = validate._PageParser(DIST / page / "index.html")
parsed.feed((DIST / page / "index.html").read_text(encoding="utf-8"))
self.assertLessEqual(parsed.page.elements, validate_site.MAX_PAGE_ELEMENTS)
self.assertLessEqual(parsed.page.elements, validate.MAX_PAGE_ELEMENTS)
def test_every_mame_set_and_member_is_on_a_part(self):
profile = yaml.safe_load((REPO_ROOT / "emulators" / "mame.yml").read_text(encoding="utf-8"))
+11 -11
View File
@@ -142,7 +142,7 @@ class SiteReferenceContracts(unittest.TestCase):
}
return db, coverages, profiles, stats
@mock.patch("sitesources.tree_holds", lambda *_args: True) # a path the record confirms
@mock.patch("sitegen.sources.tree_holds", lambda *_args: True) # a path the record confirms
def test_source_references_are_revision_pinned_links(self):
_, _, profiles, _ = self._fixtures()
rendered = _source_ref_markdown(
@@ -173,7 +173,7 @@ class SiteReferenceContracts(unittest.TestCase):
prefixed = _source_ref_markdown(profile, "example/jg.c:213-214")
self.assertEqual(prefixed, "`example/jg.c:213-214`")
@mock.patch("sitesources.tree_holds", lambda *_args: True) # a path the record confirms
@mock.patch("sitegen.sources.tree_holds", lambda *_args: True) # a path the record confirms
def test_a_single_repository_links_the_path_as_written(self):
profile = {"source": "https://github.com/PCSX2/pcsx2", "source_commit": "c" * 40}
rendered = _source_ref_markdown(profile, "pcsx2/ImGui/FullscreenUI.cpp:755-759")
@@ -599,7 +599,7 @@ class OnlyAPinnedProfileClaimsAPin(unittest.TestCase):
class ADataDirectorySaysWhatItIs(unittest.TestCase):
"""The page said `dolphin-sys` > `Sys` and nothing of the tree it packs."""
@mock.patch("sitesources.tree_holds", lambda *_args: True) # a path the record confirms
@mock.patch("sitegen.sources.tree_holds", lambda *_args: True) # a path the record confirms
def test_description_origin_mode_and_source(self):
from generate_site import generate_emulator_page
@@ -952,9 +952,9 @@ class ProseCitationsLinkToThePin(unittest.TestCase):
"source_commit": "76c7a84f1f7e80f3e6f2bba96fe100cb24e99124",
"files": [{"name": "x", "source_ref": "libretro.c:10"}]}
@mock.patch("sitesources.tree_holds", lambda *_args: True) # a path the record confirms
@mock.patch("sitegen.sources.tree_holds", lambda *_args: True) # a path the record confirms
def test_a_rooted_or_structured_path_is_linked(self):
from sitesources import link_prose_citations
from sitegen.sources import link_prose_citations
text = link_prose_citations(
self.PROFILE, "BIOS loading is in src/libretro.c:186-208 and libretro.c:12.")
@@ -963,7 +963,7 @@ class ProseCitationsLinkToThePin(unittest.TestCase):
self.assertIn("[`libretro.c:12`](", text)
def test_what_cannot_be_placed_stays_text(self):
from sitesources import link_prose_citations
from sitegen.sources import link_prose_citations
self.assertEqual(link_prose_citations(self.PROFILE, "see memory.c:5"), "see memory.c:5")
self.assertEqual(link_prose_citations(self.PROFILE, "in `src/a.c:5`"), "in `src/a.c:5`")
@@ -973,14 +973,14 @@ class ProseCitationsLinkToThePin(unittest.TestCase):
def test_two_repositories_link_into_the_one_holding_the_path(self):
"""1,044 citations in 86 profiles that read two repositories stayed
text, the swanstation note on FindBIOSImageInDirectory among them."""
from sitesources import link_prose_citations
from sitegen.sources import link_prose_citations
two = {**self.PROFILE, "upstream": "https://github.com/x/y", "upstream_commit": "a" * 40}
def holds(repo, _pin, path):
return path == "src/both.c" or (path == "src/port.c") == (repo.owner == "libretro")
with mock.patch("sitesources.tree_holds", holds):
with mock.patch("sitegen.sources.tree_holds", holds):
text = link_prose_citations(two, "src/port.c:5, src/emu.c:7 and src/both.c:9")
upstream_only = link_prose_citations(two, "upstream src/port.c:5")
named = link_prose_citations(two, "upstream src/both.c:9")
@@ -1001,9 +1001,9 @@ class ACitationSaysWhoseCodeItIs(unittest.TestCase):
"upstream": "https://github.com/alekmaul/a5200",
"source_commit": "a" * 40, "upstream_commit": "b" * 40}
@mock.patch("sitesources.tree_holds", lambda *_args: True) # a path the record confirms
@mock.patch("sitegen.sources.tree_holds", lambda *_args: True) # a path the record confirms
def test_each_part_links_to_its_repository_with_its_label(self):
from sitesources import _source_ref_markdown, requested_by
from sitegen.sources import _source_ref_markdown, requested_by
ref = "source libretro.c:5, upstream emu/memory.c:46, 50-52"
text = _source_ref_markdown(self.PROFILE, ref)
@@ -1017,7 +1017,7 @@ class ACitationSaysWhoseCodeItIs(unittest.TestCase):
"upstream emulator")
def test_a_role_without_a_pin_links_nowhere_else(self):
from sitesources import _source_ref_markdown
from sitegen.sources import _source_ref_markdown
profile = {**self.PROFILE, "upstream_commit": ""}
self.assertEqual(_source_ref_markdown(profile, "upstream emu/memory.c:46"),
+3 -3
View File
@@ -15,7 +15,7 @@ from pathlib import Path
import indexnow
from sitegen import agents as siteagents
import site_markdown
from sitegen import pagemarkdown
ROOT = Path(__file__).resolve().parent.parent
@@ -39,7 +39,7 @@ class BuildStamp(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory(dir=ROOT / "tmp")
self.dist = _site(Path(self.tmp.name))
site_markdown.convert_site(self.dist, STAMP)
pagemarkdown.convert_site(self.dist, STAMP)
def tearDown(self):
self.tmp.cleanup()
@@ -65,7 +65,7 @@ class BuildStamp(unittest.TestCase):
first = json.loads((self.dist / "digests.json").read_text(encoding="utf-8"))
with tempfile.TemporaryDirectory(dir=ROOT / "tmp") as other:
dist = _site(Path(other))
site_markdown.convert_site(dist, {"commit": "f" * 40, "date": "2026-11-10T00:00:00Z"})
pagemarkdown.convert_site(dist, {"commit": "f" * 40, "date": "2026-11-10T00:00:00Z"})
second = json.loads((dist / "digests.json").read_text(encoding="utf-8"))
self.assertEqual(first, second)
self.assertIn("https://abdess.github.io/retrobios/llms.txt", first)
+29 -29
View File
@@ -17,7 +17,7 @@ import unittest
import xml.etree.ElementTree as ET
from pathlib import Path
import sitediagrams
from sitegen import diagrams
ROOT = Path(__file__).resolve().parent.parent
@@ -26,11 +26,11 @@ SVG = "{http://www.w3.org/2000/svg}"
class EveryDiagramIsAccessibleSvg(unittest.TestCase):
def test_each_layout_parses_and_is_named(self):
for image_id in sitediagrams.IMAGE_IDS:
figure = sitediagrams.figures()[image_id]
for image_id in diagrams.IMAGE_IDS:
figure = diagrams.figures()[image_id]
for layout in ("wide", "narrow"):
with self.subTest(image=image_id, layout=layout):
root = ET.fromstring(sitediagrams.svg(figure, layout, ""))
root = ET.fromstring(diagrams.svg(figure, layout, ""))
self.assertEqual(root.tag, f"{SVG}svg")
self.assertEqual(root.get("role"), "img")
title, desc = root.find(f"{SVG}title"), root.find(f"{SVG}desc")
@@ -42,19 +42,19 @@ class EveryDiagramIsAccessibleSvg(unittest.TestCase):
self.assertTrue(root.findall(f".//{SVG}text"))
def test_the_output_does_not_change_between_runs(self):
first = [sitediagrams.figure_html(i) for i in sitediagrams.IMAGE_IDS]
sitediagrams.figures.cache_clear()
self.assertEqual(first, [sitediagrams.figure_html(i) for i in sitediagrams.IMAGE_IDS])
first = [diagrams.figure_html(i) for i in diagrams.IMAGE_IDS]
diagrams.figures.cache_clear()
self.assertEqual(first, [diagrams.figure_html(i) for i in diagrams.IMAGE_IDS])
def test_text_carries_no_typographic_tics(self):
for image_id in sitediagrams.IMAGE_IDS:
html = sitediagrams.figure_html(image_id)
for image_id in diagrams.IMAGE_IDS:
html = diagrams.figure_html(image_id)
with self.subTest(image=image_id):
self.assertIsNone(re.search("[\u2013\u2014\u2190-\u21ff\u2500-\u257f\u2026]", html))
self.assertNotIn("; ", re.sub(r"<[^>]+>", " ", html))
def test_a_second_copy_on_one_page_gets_its_own_ids(self):
page = sitediagrams.resolve_images(
page = diagrams.resolve_images(
"<!-- image: install-flow -->\n\ntext\n\n<!-- image: install-flow -->\n"
)
ids = re.findall(r'\bid="([^"]+)"', page)
@@ -70,19 +70,19 @@ class PlaceholdersResolve(unittest.TestCase):
found = 0
for path in sources:
text = path.read_text(encoding="utf-8")
for image_id in sitediagrams.PLACEHOLDER_ANYWHERE.findall(text):
for image_id in diagrams.PLACEHOLDER_ANYWHERE.findall(text):
found += 1
with self.subTest(page=path.name, image=image_id):
self.assertIn(image_id, sitediagrams.IMAGE_IDS)
self.assertIn(image_id, diagrams.IMAGE_IDS)
self.assertGreater(found, 0)
def test_a_block_placeholder_becomes_a_figure(self):
page = sitediagrams.resolve_images("Intro\n\n<!-- image: bios-chain -->\n\nMore\n")
page = diagrams.resolve_images("Intro\n\n<!-- image: bios-chain -->\n\nMore\n")
self.assertIn('<figure class="rb-figure"', page)
self.assertNotIn("<!-- image:", page)
def test_an_indented_placeholder_keeps_its_indent_and_escapes_markdown(self):
page = sitediagrams.resolve_images("1. Step\n\n <!-- image: data-layers -->\n")
page = diagrams.resolve_images("1. Step\n\n <!-- image: data-layers -->\n")
line = page.splitlines()[2]
self.assertTrue(line.startswith(" <span class=\"rb-figure"))
self.assertNotIn("_shared", line)
@@ -90,16 +90,16 @@ class PlaceholdersResolve(unittest.TestCase):
def test_an_unknown_name_is_left_for_the_validator(self):
page = "<!-- image: no-such-diagram -->\n"
self.assertEqual(sitediagrams.resolve_images(page), page)
self.assertEqual(sitediagrams.unresolved_images(page), ["no-such-diagram"])
self.assertEqual(diagrams.resolve_images(page), page)
self.assertEqual(diagrams.unresolved_images(page), ["no-such-diagram"])
class DiagramsMatchTheData(unittest.TestCase):
def test_every_platform_appears_under_its_mode(self):
text = sitediagrams.figures()["verification-modes"].caption
for display, mode, _ in sitediagrams.platform_modes().values():
text = diagrams.figures()["verification-modes"].caption
for display, mode, _ in diagrams.platform_modes().values():
with self.subTest(platform=display):
self.assertIn(mode, sitediagrams.MODE_TEXT)
self.assertIn(mode, diagrams.MODE_TEXT)
self.assertIn(display, text)
def test_each_example_platform_runs_its_emulator(self):
@@ -108,7 +108,7 @@ class DiagramsMatchTheData(unittest.TestCase):
from resolve.cores import resolve_platform_cores
profiles = load_emulator_profiles(str(ROOT / "emulators"), skip_aliases=False)
for platform, emulator in sitediagrams.CHAIN_EXAMPLES:
for platform, emulator in diagrams.CHAIN_EXAMPLES:
with self.subTest(platform=platform, emulator=emulator):
config = load_platform_config(platform, str(ROOT / "platforms"))
self.assertIn(emulator, resolve_platform_cores(config, profiles))
@@ -118,15 +118,15 @@ class DiagramsMatchTheData(unittest.TestCase):
config = yaml.safe_load((ROOT / "platforms" / "minui.yml").read_text(encoding="utf-8"))
folders = set(config["core_system_dirs"])
for _, tag in sitediagrams.MINUI_EXAMPLES:
for _, tag in diagrams.MINUI_EXAMPLES:
with self.subTest(tag=tag):
self.assertIn(f"Bios/{tag}", folders)
self.assertTrue(sitediagrams.minui_files().get(tag))
self.assertTrue(diagrams.minui_files().get(tag))
def test_the_pipeline_drawing_is_the_step_list(self):
from pipeline import STEP_LABELS
numbers = [box.number for box in sitediagrams._pipeline_boxes()]
numbers = [box.number for box in diagrams._pipeline_boxes()]
self.assertEqual(numbers, [label.split(" ", 1)[0] for label in STEP_LABELS.values()])
@@ -166,17 +166,17 @@ class ImagesAreServedFromTheSite(unittest.TestCase):
def test_remote_links_with_a_copy_are_rewritten(self):
logo = self._manifest("logos")[0]
page = f"| ![X]({logo['source']}){{ width=20 }} | <img src=\"{logo['source']}\"> |"
local = sitediagrams.localize_images(page, Path("platforms/x.md"))
local = diagrams.localize_images(page, Path("platforms/x.md"))
self.assertNotIn(logo["source"], local)
self.assertEqual(local.count(f"../assets/logos/{logo['file']}"), 2)
def test_icon_paths_are_link_safe(self):
icon = self._manifest("system-icons")[0]
local = sitediagrams.localize_images(f"![a]({icon['source']})", Path("systems/x.md"))
local = diagrams.localize_images(f"![a]({icon['source']})", Path("systems/x.md"))
self.assertNotIn(" ", local)
def test_the_validator_refuses_a_remote_image(self):
from validate_site import _parse_page
from sitegen.validate import _parse_page
with tempfile.TemporaryDirectory(dir=ROOT / "tests") as tmp:
path = Path(tmp) / "index.html"
@@ -193,13 +193,13 @@ class SharingCards(unittest.TestCase):
def test_one_card_per_section_at_the_open_graph_size(self):
import struct
for section in sitediagrams.OG_SECTIONS:
for section in diagrams.OG_SECTIONS:
with self.subTest(section=section):
data = (ROOT / "docs_assets" / "og" / f"{section}.png").read_bytes()
self.assertEqual(data[:8], b"\x89PNG\r\n\x1a\n")
self.assertEqual(struct.unpack(">II", data[16:24]), (1200, 630))
mark = (ROOT / "docs_assets" / "brand" / "logo.svg").read_text(encoding="utf-8")
ET.fromstring(sitediagrams.og_card_svg(section, mark))
ET.fromstring(diagrams.og_card_svg(section, mark))
def test_the_template_names_every_section(self):
from sitegen import starlight as sitestarlight
@@ -207,7 +207,7 @@ class SharingCards(unittest.TestCase):
named = {sitestarlight.og_section("index.md", "")} | {
sitestarlight.og_section("wiki/page.md", level)
for level in ("start", "setup", "explore", "reference", "contribute")}
self.assertEqual(named, set(sitediagrams.OG_SECTIONS))
self.assertEqual(named, set(diagrams.OG_SECTIONS))
for section in named:
with self.subTest(section=section):
self.assertTrue((ROOT / "docs_assets" / "og" / f"{section}.png").is_file())
+2 -2
View File
@@ -20,7 +20,7 @@ import unittest
from pathlib import Path
import generate_site
import sitediagrams
from sitegen import diagrams
from model import siteinputs
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -82,7 +82,7 @@ class TheGivenProfilesAndPlatforms(_Inputs):
registry.write_text(registry.read_text().replace("release_pack: true", "release_pack: false"))
self.use(platforms=self.platforms)
self.assertFalse(generate_site.has_release_pack("retroarch"))
self.assertEqual(sitediagrams.registry()["retroarch"].get("release_pack"), False)
self.assertEqual(diagrams.registry()["retroarch"].get("release_pack"), False)
class TheCollectionDoesNotDependOnTheWorkingDirectory(unittest.TestCase):
+16 -16
View File
@@ -6,37 +6,37 @@ import tests
import datetime as dt
import unittest
import site_insights as si
from sitegen import insights
PAGE = "https://abdess.github.io/retrobios/emulators/mgba/"
class FileNamesInSearches(unittest.TestCase):
def test_each_name_carries_what_the_project_knows(self) -> None:
queries = [si.Query("gba_bios.bin download", PAGE, 1, 300, 8.0),
si.Query("where to put GBA_BIOS.BIN", PAGE, 0, 50, 9.0),
si.Query("dsp1b.rom snes", PAGE, 0, 40, 9.0),
si.Query("mystery.pup", PAGE, 0, 10, 30.0),
si.Query("gba bios", PAGE, 5, 900, 7.0)]
rows = si.searched_files(queries, held={"gba_bios.bin"}, declared={"gba_bios.bin", "dsp1b.rom"})
queries = [insights.Query("gba_bios.bin download", PAGE, 1, 300, 8.0),
insights.Query("where to put GBA_BIOS.BIN", PAGE, 0, 50, 9.0),
insights.Query("dsp1b.rom snes", PAGE, 0, 40, 9.0),
insights.Query("mystery.pup", PAGE, 0, 10, 30.0),
insights.Query("gba bios", PAGE, 5, 900, 7.0)]
rows = insights.searched_files(queries, held={"gba_bios.bin"}, declared={"gba_bios.bin", "dsp1b.rom"})
self.assertEqual(rows, [("gba_bios.bin", 350, "held"), ("dsp1b.rom", 40, "declared, not held"),
("mystery.pup", 10, "unknown")])
class SearchGaps(unittest.TestCase):
def test_first_page_rarely_clicked(self) -> None:
low = si.Query("swanstation", PAGE, 3, 540, 5.6)
fine = si.Query("nethersx2 bios", PAGE, 54, 484, 4.6)
far = si.Query("xbox bios", PAGE, 0, 900, 10.7)
self.assertEqual(si.missed_clicks([low, fine, far]), [low])
self.assertEqual(si.near_first_page([low, fine, far]), [far])
low = insights.Query("swanstation", PAGE, 3, 540, 5.6)
fine = insights.Query("nethersx2 bios", PAGE, 54, 484, 4.6)
far = insights.Query("xbox bios", PAGE, 0, 900, 10.7)
self.assertEqual(insights.missed_clicks([low, fine, far]), [low])
self.assertEqual(insights.near_first_page([low, fine, far]), [far])
class SiteActions(unittest.TestCase):
def test_events_are_grouped_by_kind_and_pages_apart(self) -> None:
hits = [("/emulators/mgba/", 40), ("search-none/kenji nx", 3), ("search-none/dsp1b.rom", 7),
("helpful/no", 2), ("/old/link/ [404]", 5), ("download/Batocera_43.1_BIOS_Pack.zip", 9)]
actions = si.site_actions(hits)
actions = insights.site_actions(hits)
self.assertEqual(actions["search-none"], [("dsp1b.rom", 7), ("kenji nx", 3)])
self.assertEqual(actions["404"], [("/old/link/", 5)])
self.assertEqual(actions["pages"], [("/emulators/mgba/", 40)])
@@ -45,8 +45,8 @@ class SiteActions(unittest.TestCase):
class TheReport(unittest.TestCase):
def test_a_skipped_source_leaves_no_section(self) -> None:
text = si.report(dt.date(2026, 10, 1), dt.date(2026, 10, 28),
[si.Query("gba_bios.bin", PAGE, 1, 300, 8.0)], None, None,
text = insights.report(dt.date(2026, 10, 1), dt.date(2026, 10, 28),
[insights.Query("gba_bios.bin", PAGE, 1, 300, 8.0)], None, None,
held={"gba_bios.bin"}, declared=set())
self.assertIn("## Google searches", text)
self.assertIn("| gba_bios.bin | /emulators/mgba/ | 300 | 0.3% | 8.0 |", text)
@@ -56,7 +56,7 @@ class TheReport(unittest.TestCase):
def test_names_come_from_profiles_and_the_collection(self) -> None:
db = {"indexes": {"by_name": {"SCPH5501.BIN": ["x"]}}}
profiles = {"p": {"files": [{"name": "bios/dsp1b.rom", "aliases": ["DSP1B.bin"]}, "str"]}}
held, declared = si.collection_names(db, profiles)
held, declared = insights.collection_names(db, profiles)
self.assertEqual(held, {"scph5501.bin"})
self.assertEqual(declared, {"dsp1b.rom", "dsp1b.bin"})
+17 -17
View File
@@ -23,7 +23,7 @@ import yaml
import check_freshness
import generate_site as gs
import sitediagrams
from sitegen import diagrams
from model import collection
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -127,7 +127,7 @@ class SourcePathsFreshness(unittest.TestCase):
def test_a_recorded_build_file_tree_is_pinned(self):
"""The record holds the platform trees pin_build reads at a commit,
and the check called them orphaned."""
import sitesources
from sitegen import sources as sitegen_sources
pin = "a" * 40
profile = {"pin_build": [{"repo": "https://github.com/o/r", "revision": pin,
@@ -135,7 +135,7 @@ class SourcePathsFreshness(unittest.TestCase):
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "source-paths.json"
path.write_text(json.dumps({f"github.com/o/r@{pin}": ["p.mk"]}), encoding="utf-8")
with mock.patch.object(sitesources, "SOURCE_PATHS", path):
with mock.patch.object(sitegen_sources, "SOURCE_PATHS", path):
finding = check_freshness.check_source_paths({"p": profile})
self.assertEqual(finding.status, check_freshness.OK, finding.detail)
@@ -150,11 +150,11 @@ class SourcePathsFreshness(unittest.TestCase):
"""fbneo moved to two new pins while fbneo_cps12 kept the old ones:
no recorded tree was orphaned, so the check said OK and 174 citations
stayed unlinked."""
import sitesources
from sitegen import sources as sitegen_sources
profile = _profile("geolith")
trees = [sitesources.tree_key(r, p) for r, p in sitesources.profile_trees(profile)]
record = json.loads(sitesources.SOURCE_PATHS.read_text(encoding="utf-8"))
trees = [sitegen_sources.tree_key(r, p) for r, p in sitegen_sources.profile_trees(profile)]
record = json.loads(sitegen_sources.SOURCE_PATHS.read_text(encoding="utf-8"))
for key in trees:
record.pop(key, None)
# Kept pinned by another profile, as fbneo_cps12 kept the old FBNeo trees.
@@ -162,18 +162,18 @@ class SourcePathsFreshness(unittest.TestCase):
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "source-paths.json"
path.write_text(json.dumps(record), encoding="utf-8")
with mock.patch.object(sitesources, "SOURCE_PATHS", path):
with mock.patch.object(sitegen_sources, "SOURCE_PATHS", path):
finding = check_freshness.check_source_paths({"geolith": profile})
self.assertEqual(finding.status, check_freshness.STALE)
self.assertIn("1 pinned trees not recorded", finding.detail)
def test_a_tree_read_with_no_cited_path_is_recorded(self):
import sitesources
from sitegen import sources as sitegen_sources
profile = {"source": "https://github.com/o/r", "source_commit": "e" * 40,
"files": [{"source_ref": "src/a.c:5"}]}
with mock.patch.object(sitesources, "_cached_tree", return_value=frozenset({"x.c"})):
held, unread = sitesources.build_source_paths({"p": profile}, [Path("tmp")])
with mock.patch.object(sitegen_sources, "_cached_tree", return_value=frozenset({"x.c"})):
held, unread = sitegen_sources.build_source_paths({"p": profile}, [Path("tmp")])
self.assertEqual(held, {"github.com/o/r@" + "e" * 40: []})
self.assertEqual(unread, [])
@@ -183,14 +183,14 @@ class OptionsGlanceFromTheParser(unittest.TestCase):
table, and not the hand-written glance above it."""
def test_every_parser_option_has_a_group(self):
named = {flag for _label, flags in sitediagrams.GLANCE_GROUPS for flag in flags}
self.assertEqual(set(sitediagrams.installer_flags()) - named, set())
self.assertEqual(named - set(sitediagrams.installer_flags()), set())
named = {flag for _label, flags in diagrams.GLANCE_GROUPS for flag in flags}
self.assertEqual(set(diagrams.installer_flags()) - named, set())
self.assertEqual(named - set(diagrams.installer_flags()), set())
def test_an_option_no_group_names_still_lands(self):
with mock.patch.object(sitediagrams, "installer_flags",
with mock.patch.object(diagrams, "installer_flags",
return_value=["--platform", "--brand-new"]):
lines = sitediagrams.options_glance()
lines = diagrams.options_glance()
self.assertEqual(lines, [
"- **Where and for what**: [`--platform`](#option-platform)",
"- **Other**: [`--brand-new`](#option-brand-new)",
@@ -198,10 +198,10 @@ class OptionsGlanceFromTheParser(unittest.TestCase):
def test_the_source_holds_no_list(self):
text = (REPO_ROOT / "wiki" / "installer.md").read_text(encoding="utf-8")
section = text[text.index(sitediagrams.GLANCE_HEADING):text.index("\n## One line")]
section = text[text.index(diagrams.GLANCE_HEADING):text.index("\n## One line")]
self.assertNotIn("\n- ", section)
with self.assertRaises(ValueError):
sitediagrams.expand_glance(f"# x\n\n{sitediagrams.GLANCE_HEADING}\n\n- a\n\n## y\n")
diagrams.expand_glance(f"# x\n\n{diagrams.GLANCE_HEADING}\n\n- a\n\n## y\n")
class FaqInstallsFromWhatYouHold(unittest.TestCase):
+12 -12
View File
@@ -22,7 +22,7 @@ import unittest
from html.parser import HTMLParser
from pathlib import Path
import sitediagrams
from sitegen import diagrams
from sitegen import entries as siteentries
from sitegen import steps as sitesteps
from model.guides import TERMINALS
@@ -184,8 +184,8 @@ class PageReadsOnce:
def test_a_figure_says_its_words_once(self):
for name, page in self.pages.items():
text = _letters(page.text)
for image_id in sitediagrams.IMAGE_IDS:
figure = sitediagrams.figures()[image_id]
for image_id in diagrams.IMAGE_IDS:
figure = diagrams.figures()[image_id]
with self.subTest(page=name, image=image_id):
self.assertLessEqual(text.count(_letters(figure.desc)), 1)
self.assertLessEqual(text.count(_letters(figure.caption)), 1)
@@ -322,26 +322,26 @@ class DiagramsAreImages(unittest.TestCase):
the words once. Each theme has its files, coloured as the page is."""
def test_no_inline_drawing_and_no_alt(self):
for html in [*(sitediagrams.figure_html(i) for i in sitediagrams.IMAGE_IDS),
for html in [*(diagrams.figure_html(i) for i in diagrams.IMAGE_IDS),
*("".join(sitesteps.steps_figure(tab)) for tab in sitesteps.STEPS)]:
with self.subTest(html=html[:60]):
self.assertNotIn("<svg", html)
self.assertEqual(set(re.findall(r'<img [^>]*alt="([^"]*)"', html)), {""})
self.assertEqual(len(re.findall(r"<picture ", html)), len(sitediagrams.THEMES))
self.assertEqual(len(re.findall(r"<picture ", html)), len(diagrams.THEMES))
def test_every_image_has_its_file(self):
files = {**sitediagrams.figure_files(), **sitesteps.steps_files()}
pages = [*(sitediagrams.figure_html(i) for i in sitediagrams.IMAGE_IDS),
files = {**diagrams.figure_files(), **sitesteps.steps_files()}
pages = [*(diagrams.figure_html(i) for i in diagrams.IMAGE_IDS),
*("".join(sitesteps.steps_figure(tab)) for tab in sitesteps.STEPS)]
named = {url.rsplit("/", 1)[1] for html in pages
for url in re.findall(r'(?:src|srcset)="([^"]+)"', html)}
self.assertEqual(named, set(files))
def test_the_figure_says_its_desc_once(self):
for image_id in sitediagrams.IMAGE_IDS:
figure = sitediagrams.figures()[image_id]
for image_id in diagrams.IMAGE_IDS:
figure = diagrams.figures()[image_id]
with self.subTest(image=image_id):
text = read(sitediagrams.figure_html(image_id)).text
text = read(diagrams.figure_html(image_id)).text
self.assertEqual(text.count(figure.desc), 1)
self.assertIn(figure.caption, text)
@@ -355,13 +355,13 @@ class DiagramsAreImages(unittest.TestCase):
for key, token in tokens.items():
with self.subTest(theme=theme, token=token):
value = re.search(rf"{token}:\s*(#[0-9a-f]+);", block).group(1)
self.assertEqual(sitediagrams.THEMES[theme][key], value)
self.assertEqual(diagrams.THEMES[theme][key], value)
def test_a_file_carries_its_theme(self):
for name, text in sitesteps.steps_files().items():
theme = name.rsplit("-", 1)[1].removesuffix(".svg")
with self.subTest(file=name):
self.assertIn(f".rb-d-box{{fill:{sitediagrams.THEMES[theme]['fill']}", text)
self.assertIn(f".rb-d-box{{fill:{diagrams.THEMES[theme]['fill']}", text)
self.assertTrue(text.startswith("<svg "))
+2 -2
View File
@@ -187,7 +187,7 @@ class NothingIsLost(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
from model.database import load_database
from generate_readme import compute_coverage
from sitegen.readme import compute_coverage
db = load_database(str(REPO_ROOT / "database.json"))
cls.pages = {}
@@ -337,7 +337,7 @@ class APlatformWeighsNoMoreThanBefore(unittest.TestCase):
with its parts rose from 18,854 to 21,875 elements."""
def test_pages_elements_and_bytes(self):
from validate_site import _PageParser
from sitegen.validate import _PageParser
for name, (pages, elements, size) in BEFORE_WEIGHT.items():
paths, weight = [], 0
+22 -21
View File
@@ -59,9 +59,10 @@ from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from resolve.reconcile import HASH_FIELDS, _hash_values
from resolve.categories import EntryCategories
from sitesources import launcher_ref_markdown, list_source
from sitegen.sources import launcher_ref_markdown, list_source
import check_platform_folder
import sitesources
from sitegen import sources
import release_record
from core import upstream
@@ -884,16 +885,16 @@ class SourceLinksGoWhereTheFileIs(unittest.TestCase):
}
def tearDown(self):
sitesources._tree_paths.cache_clear()
sources._tree_paths.cache_clear()
def _render(self, tree: frozenset[str]) -> str:
original = sitesources._tree_paths
sitesources._tree_paths = lambda repo, pin: tree
original = sources._tree_paths
sources._tree_paths = lambda repo, pin: tree
try:
return sitesources._source_ref_markdown(
return sources._source_ref_markdown(
self.PROFILE, "src/emulator.cpp:234; src/core/loader/ncch.cpp:151-164")
finally:
sitesources._tree_paths = original
sources._tree_paths = original
def test_a_path_the_tree_lacks_is_not_linked(self):
text = self._render(frozenset({"src/emulator.cpp"}))
@@ -911,7 +912,7 @@ class SourceLinksGoWhereTheFileIs(unittest.TestCase):
def test_every_rendered_link_is_in_its_cached_tree(self):
"""Offline: each link the pages render points at a path the cached
tree of its repository holds."""
if not sitesources.TREE_CACHE.is_dir():
if not sources.TREE_CACHE.is_dir():
raise unittest.SkipTest("no cached tree listings")
from model.profiles import load_emulator_profiles
@@ -923,11 +924,11 @@ class SourceLinksGoWhereTheFileIs(unittest.TestCase):
if not isinstance(entry, dict) or not entry.get("source_ref"):
continue
for slug, pin, path in link.findall(
sitesources._source_ref_markdown(profile, entry["source_ref"])):
sources._source_ref_markdown(profile, entry["source_ref"])):
from core import upstream
repo = upstream.parse_repo(f"https://github.com/{slug}")
held = sitesources.tree_holds(repo, pin, urllib.parse.unquote(path))
held = sources.tree_holds(repo, pin, urllib.parse.unquote(path))
if held is None:
continue
checked += 1
@@ -1103,7 +1104,7 @@ class SourceLinksOnlyWhereTheFileIs(unittest.TestCase):
def test_an_address_in_a_binary_reads_as_one(self):
profile = {"source": "https://github.com/o/r", "source_commit": "e" * 40}
text = sitesources._source_ref_markdown(
text = sources._source_ref_markdown(
profile, "Nesoid 2.5.0 libnes.so 0x455a4-0x45694 (setter), 0x8094-0x80ac")
self.assertEqual(text, "offset `0x455a4-0x45694` in `Nesoid 2.5.0 libnes.so` (setter), "
"offset `0x8094-0x80ac` in `Nesoid 2.5.0 libnes.so`")
@@ -1111,13 +1112,13 @@ class SourceLinksOnlyWhereTheFileIs(unittest.TestCase):
def test_only_a_recorded_path_links(self):
profile = {"source": "https://github.com/o/r", "source_commit": "e" * 40}
repo = upstream.parse_repo("https://github.com/o/r")
record = {sitesources.tree_key(repo, "e" * 40): frozenset({"src/a.c"})}
with mock.patch.object(sitesources, "_verified", return_value=record):
sitesources._tree_paths.cache_clear()
record = {sources.tree_key(repo, "e" * 40): frozenset({"src/a.c"})}
with mock.patch.object(sources, "_verified", return_value=record):
sources._tree_paths.cache_clear()
try:
text = sitesources._source_ref_markdown(profile, "src/a.c:5, src/b.c:7")
text = sources._source_ref_markdown(profile, "src/a.c:5, src/b.c:7")
finally:
sitesources._tree_paths.cache_clear()
sources._tree_paths.cache_clear()
self.assertIn("[`src/a.c:5`](https://github.com/o/r/blob/" + "e" * 40 + "/src/a.c#L5)", text)
self.assertIn("`src/b.c:7`", text)
self.assertNotIn("src/b.c#", text)
@@ -1125,9 +1126,9 @@ class SourceLinksOnlyWhereTheFileIs(unittest.TestCase):
def test_the_writer_keeps_held_paths_only(self):
profile = {"source": "https://github.com/o/r", "source_commit": "e" * 40,
"notes": "see src/c.c:3", "files": [{"source_ref": "src/a.c:5, gone.c:1"}]}
with mock.patch.object(sitesources, "_cached_tree",
with mock.patch.object(sources, "_cached_tree",
return_value=frozenset({"src/a.c", "src/c.c", "x.c"})):
held, unread = sitesources.build_source_paths({"p": profile}, [TMP])
held, unread = sources.build_source_paths({"p": profile}, [TMP])
self.assertEqual(held, {"github.com/o/r@" + "e" * 40: ["src/a.c", "src/c.c"]})
self.assertEqual(unread, [])
@@ -1137,15 +1138,15 @@ class SourceLinksOnlyWhereTheFileIs(unittest.TestCase):
# cached tree dropped its four recorded paths.
profile = {"source": "https://github.com/o/r", "source_commit": "e" * 40,
"files": [{"source_ref": "src/a.c:5"}]}
with mock.patch.object(sitesources, "_cached_tree", return_value=None), \
with mock.patch.object(sources, "_cached_tree", return_value=None), \
mock.patch.object(sitesources.upstream, "list_directory",
side_effect=upstream.UpstreamError("HTTP 404")):
held, unread = sitesources.build_source_paths({"p": profile}, [TMP])
held, unread = sources.build_source_paths({"p": profile}, [TMP])
self.assertEqual(held, {})
self.assertEqual(unread, ["github.com/o/r@" + "e" * 40])
def test_every_rendered_link_is_recorded(self):
record = json.loads(sitesources.SOURCE_PATHS.read_text(encoding="utf-8"))
record = json.loads(sources.SOURCE_PATHS.read_text(encoding="utf-8"))
pages = sorted(_built(DOCS / "emulators").rglob("*.md*")) + sorted(DOCS.glob("gaps*.md*"))
import measurement_records
@@ -1170,7 +1171,7 @@ class SourceLinksOnlyWhereTheFileIs(unittest.TestCase):
def test_the_record_is_read_by_the_deploy(self):
"""The record is committed where the build reads it, sorted."""
record = json.loads(sitesources.SOURCE_PATHS.read_text(encoding="utf-8"))
record = json.loads(sources.SOURCE_PATHS.read_text(encoding="utf-8"))
self.assertGreater(len(record), 300)
for key, paths in record.items():
self.assertRegex(key, r"^[a-z0-9.-]+/.+@[0-9a-f]{40}$")
+10 -10
View File
@@ -136,7 +136,7 @@ class StructuredBlocks(unittest.TestCase):
return "\n".join(generate_site._render_structured_blocks(profile))
@mock.patch("sitesources.tree_holds", lambda *_args: True) # a path the record confirms
@mock.patch("sitegen.sources.tree_holds", lambda *_args: True) # a path the record confirms
def test_a_source_ref_in_a_block_is_a_pinned_link(self):
"""186 citations in analysis and firmware blocks were plain code."""
page = self.render(self.profile("analysis", {"tmss": {
@@ -264,15 +264,15 @@ class CitationsKeepTheirAnnotations(unittest.TestCase):
reused it: abuse's two lsf lines lost "(lsf default)" and "(lsf
override)", the only words saying which one wins."""
@mock.patch("sitesources.tree_holds", lambda *_args: True)
@mock.patch("sitegen.sources.tree_holds", lambda *_args: True)
def test_each_part_shows_what_the_profile_wrote_beside_it(self):
import sitesources
from sitegen import sources
profile = {"source": "https://github.com/Xenoveritas/abuse",
"source_commit": "a" * 40}
ref = ("src/loader2.cpp:284 (lsf default), src/netcfg.cpp:204 (lsf override), "
"libretro.cpp:1520-1521 candidates_a1200, 30-31 (see <system_dir>), src/x.c:1")
(label, items), = sitesources.source_ref_items(profile, ref)
(label, items), = sources.source_ref_items(profile, ref)
texts = [text for text, _role in items]
self.assertTrue(texts[0].endswith(") (lsf default)"), texts[0])
self.assertTrue(texts[1].endswith(") (lsf override)"), texts[1])
@@ -290,9 +290,9 @@ class CitationsKeepTheirAnnotations(unittest.TestCase):
self.assertEqual(ref_annotation("0x53c338-0x53c36f (dreamBios row)"), "(dreamBios row)")
def test_a_binary_citation_keeps_its_annotation(self):
import sitesources
from sitegen import sources
(_label, items), = sitesources.source_ref_items(
(_label, items), = sources.source_ref_items(
{}, "demul.exe 0x6b4d80-0x6b4ea3 (dc table), 0x53ca4d-0x53ca7e (load, fatal)")
self.assertEqual([text for text, _ in items], [
"offset `0x6b4d80-0x6b4ea3` in `demul.exe` (dc table)",
@@ -304,13 +304,13 @@ class ForgesUpstreamDoesNotRead(unittest.TestCase):
"""Profiles pinned on SourceForge, voidpoint.io, Bitbucket or Software
Heritage showed no revision, and their citations were plain code."""
@mock.patch("sitesources.tree_holds", lambda *_args: True) # a path the record confirms
@mock.patch("sitegen.sources.tree_holds", lambda *_args: True) # a path the record confirms
def links(self, url: str, ref: str, **extra: str) -> tuple[str, str]:
import sitesources
from sitegen import sources
profile = {"source": url, "source_commit": "f6c00044" + "0" * 32, **extra}
return (sitesources.revision_markdown(profile),
sitesources._source_ref_markdown(profile, ref))
return (sources.revision_markdown(profile),
sources._source_ref_markdown(profile, ref))
def test_bitbucket(self):
revision, ref = self.links("https://bitbucket.org/linuxwolf6/splitwolf",
+6 -6
View File
@@ -32,7 +32,7 @@ from html.parser import HTMLParser
import generate_site as gs
from sitegen import starlight as sitestarlight
import validate_site
from sitegen import validate
import generate_site
from model.registry import list_registered_platforms
from model.profiles import load_emulator_profiles
@@ -329,24 +329,24 @@ class Descriptions(unittest.TestCase):
def test_the_check_counts_templates(self) -> None:
pages = {}
for n in range(12):
page = validate_site.Page(Path(f"/s/p{n}/index.html"))
page = validate.Page(Path(f"/s/p{n}/index.html"))
page.h1 = f"Core {n}"
page.title = f"Core {n} BIOS files - RetroBIOS"
page.descriptions = [f"Core {n}: emulator firmware profile with paths."]
pages[page.path] = page
issues = validate_site._check_description_templates(pages, Path("/s"))
issues = validate._check_description_templates(pages, Path("/s"))
self.assertEqual(len(issues), 1)
self.assertIn("12 pages share", issues[0])
for page in list(pages.values())[:2]:
page.descriptions = [f"{page.h1} emulates a console of its own {page.h1[-1]}x."]
self.assertEqual(validate_site._check_description_templates(pages, Path("/s")), [])
self.assertEqual(validate._check_description_templates(pages, Path("/s")), [])
def test_built_descriptions_are_not_templates(self) -> None:
if not (DIST / "index.html").is_file():
self.skipTest("site not built")
pages = {path.resolve(): validate_site._parse_page(path) for path in DIST.rglob("*.html")}
pages = {path.resolve(): validate._parse_page(path) for path in DIST.rglob("*.html")}
content = {path: page for path, page in pages.items() if not page.redirect}
self.assertEqual(validate_site._check_description_templates(content, DIST.resolve()), [])
self.assertEqual(validate._check_description_templates(content, DIST.resolve()), [])
QUERIES = _gate_queries()
+4 -4
View File
@@ -16,7 +16,7 @@ import unittest
import xml.etree.ElementTree as ET
from pathlib import Path
import sitediagrams
from sitegen import diagrams
from sitegen import steps as sitesteps
from model.guides import TERMINALS
@@ -85,11 +85,11 @@ class TheBuiltPageHoldsThem(unittest.TestCase):
html = page.read_text(encoding="utf-8")
for tab in sitesteps.STEPS:
for layout in ("wide", "narrow"):
for theme in sitediagrams.THEMES:
for theme in diagrams.THEMES:
name = f"{sitesteps.stem(tab)}-{layout}-{theme}.svg"
with self.subTest(file=name):
self.assertIn(f"/retrobios/{sitediagrams.DIAGRAM_DIR}/{name}", html)
self.assertTrue((DIST / sitediagrams.DIAGRAM_DIR / name).is_file())
self.assertIn(f"/retrobios/{diagrams.DIAGRAM_DIR}/{name}", html)
self.assertTrue((DIST / diagrams.DIAGRAM_DIR / name).is_file())
if __name__ == "__main__":
+7 -7
View File
@@ -11,7 +11,7 @@ import tempfile
import unittest
from pathlib import Path
from validate_site import validate_site
from sitegen.validate import validate_site
ROOT = Path(__file__).resolve().parent.parent
TMP_ROOT = ROOT / "tmp" / "tests"
@@ -209,9 +209,9 @@ class TheSiteStaysWithinItsBudgets(unittest.TestCase):
'<script src="javascripts/site.js"></script>'), [])
def test_a_page_over_its_size(self):
import validate_site as module
from sitegen import validate
issues = self._issues("<p>" + "x" * module.MAX_PAGE_BYTES + "</p>")
issues = self._issues("<p>" + "x" * validate.MAX_PAGE_BYTES + "</p>")
self.assertTrue(any("over the" in issue and "HTML" in issue for issue in issues), issues)
def test_a_skipped_heading_level(self):
@@ -230,13 +230,13 @@ class TheSiteStaysWithinItsBudgets(unittest.TestCase):
self.assertTrue(any("drawn by a script at runtime" in issue for issue in issues))
def test_a_search_index_over_its_budget(self):
import validate_site as module
from sitegen import validate
index = self.site / "pagefind" / "index"
index.mkdir(parents=True)
(index / "en_big.pf_index").write_bytes(b"x" * (module.MAX_PAGEFIND_CHUNK_BYTES + 1))
(index / "en_big.pf_index").write_bytes(b"x" * (validate.MAX_PAGEFIND_CHUNK_BYTES + 1))
(self.site / "pagefind" / "pagefind.en_x.pf_meta").write_bytes(
b"x" * (module.MAX_PAGEFIND_META_BYTES + 1))
b"x" * (validate.MAX_PAGEFIND_META_BYTES + 1))
issues = self._issues("")
self.assertTrue(any("en_big.pf_index" in issue for issue in issues), issues)
self.assertTrue(any(".pf_meta" in issue for issue in issues), issues)
@@ -307,7 +307,7 @@ class EveryTestDependencyIsInstalledInCi(unittest.TestCase):
def test_a_contributor_installs_what_ci_installs(self):
# The contributing page installed pyyaml and jsonschema only, so the
# markdown test skipped on a contributor's machine and ran in CI.
from generate_readme import generate_contributing
from sitegen.readme import generate_contributing
command = next(
line for line in generate_contributing().splitlines() if "pip install" in line
+29 -29
View File
@@ -41,7 +41,7 @@ from pathlib import Path
import yaml
import importlib.util
import sitediagrams
from sitegen import diagrams
from model.guides import INSTALL_SH
from tests import sitepages
import build_port
@@ -134,7 +134,7 @@ class InstallCommandsHaveEveryForm(unittest.TestCase):
"<!-- os-tabs windows: --platform retroarch --dest E:\\x -->\n```sh\n"
f"curl -fsSL {INSTALL_SH} \\\n | sh -s -- --platform retroarch --dest /a/b\n```\n"
)
text = sitediagrams.expand_commands(page)
text = diagrams.expand_commands(page)
windows, rest = text.split('<TabItem label="macOS">', 1)
self.assertIn("--dest E:\\x", windows)
self.assertNotIn("/a/b", windows)
@@ -142,7 +142,7 @@ class InstallCommandsHaveEveryForm(unittest.TestCase):
def test_a_marked_block_without_an_install_command_fails_the_build(self):
with self.assertRaises(ValueError):
sitediagrams.expand_commands("<!-- os-tabs -->\n```sh\nls -l\n```\n")
diagrams.expand_commands("<!-- os-tabs -->\n```sh\nls -l\n```\n")
class FirstInstallEnds(unittest.TestCase):
@@ -248,7 +248,7 @@ class SetupCount(unittest.TestCase):
def test_one_count(self):
from model.registry import list_registered_platforms
self.assertEqual(len(sitediagrams.setups()),
self.assertEqual(len(diagrams.setups()),
len(list_registered_platforms(str(REPO_ROOT / "platforms"))))
def test_every_rendered_count_agrees(self):
@@ -258,9 +258,9 @@ class SetupCount(unittest.TestCase):
text = path.read_text(encoding="utf-8")
found.update(int(n) for n in re.findall(r"(?:RetroArch|EmuDeck|Batocera) and (\d+) more", text))
found.update(int(n) for n in re.findall(
r"and (\d+) more", sitediagrams.og_card_svg("home", "<svg></svg>")))
r"and (\d+) more", diagrams.og_card_svg("home", "<svg></svg>")))
self.assertTrue(found)
self.assertEqual(found, {len(sitediagrams.setups()) - 3})
self.assertEqual(found, {len(diagrams.setups()) - 3})
class Vocabulary(unittest.TestCase):
@@ -281,7 +281,7 @@ class Vocabulary(unittest.TestCase):
self.assertNotIn("game menu", text)
for figure in ("bios-chain", "install-flow"):
with self.subTest(figure=figure):
self.assertNotIn("rontend", sitediagrams.figure_html(figure))
self.assertNotIn("rontend", diagrams.figure_html(figure))
class NavigationPlaces(unittest.TestCase):
@@ -338,30 +338,30 @@ class DiagramText(unittest.TestCase):
"""V17: 11 px text in fixed-height boxes, paths broken mid-token."""
def test_text_reads_at_14_px_in_the_column(self):
self.assertGreaterEqual(sitediagrams.TEXT_SIZE * sitediagrams.COLUMN / sitediagrams.WIDE, 14)
self.assertGreaterEqual(diagrams.TEXT_SIZE * diagrams.COLUMN / diagrams.WIDE, 14)
def test_no_box_holds_more_than_three_lines(self):
wide = sitediagrams.WIDE - 2
wide = diagrams.WIDE - 2
layouts = { # the box width of each wide layout: flow, grid of two, columns
"bios-chain": (sitediagrams._bios_chain_boxes(), (wide - 26 * 3) / 4),
"install-flow": (sitediagrams._install_boxes(), (wide - 18) / 2),
"verification-modes": (sitediagrams._mode_boxes(), (wide - 16 * 2) / 3),
"bios-chain": (diagrams._bios_chain_boxes(), (wide - 26 * 3) / 4),
"install-flow": (diagrams._install_boxes(), (wide - 18) / 2),
"verification-modes": (diagrams._mode_boxes(), (wide - 16 * 2) / 3),
}
for name, (boxes, box_width) in layouts.items():
for width in (sitediagrams.NARROW - 2, box_width):
for width in (diagrams.NARROW - 2, box_width):
for box in boxes:
with self.subTest(figure=name, box=box.title, width=width):
self.assertLessEqual(len(sitediagrams.box_lines(box, width)[1]),
sitediagrams.MAX_BOX_LINES)
self.assertLessEqual(len(diagrams.box_lines(box, width)[1]),
diagrams.MAX_BOX_LINES)
def test_a_path_is_mono_on_its_own_line(self):
html = sitediagrams.svg(sitediagrams.figures()["bios-chain"], "wide")
html = diagrams.svg(diagrams.figures()["bios-chain"], "wide")
self.assertRegex(html, r'<text [^>]*style="font-family: var\(--sl-font-mono[^>]*>/userdata/bios/</text>')
def test_boxes_of_a_row_share_one_height(self):
for layout in (sitediagrams.flow, sitediagrams.columns):
for vertical, total in ((False, sitediagrams.WIDE), (True, sitediagrams.NARROW)):
_width, _height, body = layout(sitediagrams._bios_chain_boxes(), vertical, total)
for layout in (diagrams.flow, diagrams.columns):
for vertical, total in ((False, diagrams.WIDE), (True, diagrams.NARROW)):
_width, _height, body = layout(diagrams._bios_chain_boxes(), vertical, total)
heights = {float(h) for h in re.findall(r'<rect [^>]*height="([\d.]+)"[^>]*class="rb-d-box',
"".join(body))}
with self.subTest(layout=layout.__name__, vertical=vertical):
@@ -381,13 +381,13 @@ class ExampleHashesStayOutOfSearch(unittest.TestCase):
self.assertIn("data-pagefind-ignore", context)
def test_a_fenced_hash_is_wrapped(self):
out = sitediagrams.hide_hashes("```sh\nx 490f666e1afb15b7362b406ed1cea246\n```\n")
out = diagrams.hide_hashes("```sh\nx 490f666e1afb15b7362b406ed1cea246\n```\n")
self.assertTrue(out.startswith("<div data-pagefind-ignore>\n\n```sh"))
def test_only_wiki_pages_are_touched(self):
page = "Hash `490f666e1afb15b7362b406ed1cea246`.\n"
self.assertEqual(sitediagrams.prepare_page(page, Path("systems/sony.md")), page)
self.assertIn("data-pagefind-ignore", sitediagrams.prepare_page(page, Path("wiki/x.md")))
self.assertEqual(diagrams.prepare_page(page, Path("systems/sony.md")), page)
self.assertIn("data-pagefind-ignore", diagrams.prepare_page(page, Path("wiki/x.md")))
class InstallerOptionsAtAGlance(unittest.TestCase):
@@ -397,7 +397,7 @@ class InstallerOptionsAtAGlance(unittest.TestCase):
def test_every_option_of_the_parser_has_a_row(self):
source = (REPO_ROOT / "install.py").read_text(encoding="utf-8")
declared = set(re.findall(r'parser\.add_argument\(\s*"(--[a-z-]+)"', source))
listed = {usage.split()[0].rstrip(",") for usage, _ in sitediagrams.installer_options()}
listed = {usage.split()[0].rstrip(",") for usage, _ in diagrams.installer_options()}
self.assertEqual(declared | {"--help"}, listed)
def test_the_built_page_opens_on_a_link_per_option(self):
@@ -405,7 +405,7 @@ class InstallerOptionsAtAGlance(unittest.TestCase):
glance = text.index("## Options at a glance")
self.assertLess(glance, text.index("## One line"))
listed = text[glance:text.index("## One line")]
for usage, _ in sitediagrams.installer_options():
for usage, _ in diagrams.installer_options():
flag = usage.split()[0].rstrip(",")
with self.subTest(option=flag):
self.assertIn(f"[`{flag}`](#option-{flag.lstrip('-')})", listed)
@@ -969,11 +969,11 @@ class OneOptionsTable(unittest.TestCase):
def test_each_option_links_to_its_row(self):
# The glance is written from the parser when the page is built.
glance = _section(sitediagrams.expand_glance(self.text), "Options at a glance")
glance = _section(diagrams.expand_glance(self.text), "Options at a glance")
table = _section(self.text, "Options")
self.assertNotIn("installer-options", glance)
self.assertNotIn("|", glance)
for usage, _ in sitediagrams.installer_options():
for usage, _ in diagrams.installer_options():
flag = usage.split()[0].rstrip(",")
anchor = f"option-{flag.lstrip('-')}"
with self.subTest(option=flag):
@@ -1032,7 +1032,7 @@ class NoSetupFoundGivesEachSystemItsFolder(unittest.TestCase):
self.assertEqual(folders["Linux"], f"`{expected['Linux']}/`")
self.assertEqual(folders["Steam Deck and Linux Flatpak"], f"`{expected['Steam Deck']}/`")
tabs = sitediagrams.expand_commands(self.section)
tabs = diagrams.expand_commands(self.section)
parts = re.split(r'<TabItem label="([^"]+)">', tabs)
bodies = dict(zip(parts[1::2], parts[2::2]))
self.assertEqual(set(bodies), set(expected))
@@ -1061,7 +1061,7 @@ class OsTabsTakeOptionsPerSystem(unittest.TestCase):
f"```sh\ncurl -fsSL {INSTALL_SH} | sh -s -- --dest /l\n```\n")
def test_each_named_tab_uses_its_own(self):
parts = re.split(r'<TabItem label="([^"]+)">', sitediagrams.expand_commands(self.PAGE))
parts = re.split(r'<TabItem label="([^"]+)">', diagrams.expand_commands(self.PAGE))
bodies = dict(zip(parts[1::2], parts[2::2]))
self.assertIn("--dest E:\\x\n", bodies["Windows"])
self.assertIn("--dest /m\n", bodies["macOS"])
@@ -1071,7 +1071,7 @@ class OsTabsTakeOptionsPerSystem(unittest.TestCase):
def test_text_before_a_system_name_fails_the_build(self):
page = self.PAGE.replace("os-tabs windows:", "os-tabs typo windows:")
with self.assertRaises(ValueError):
sitediagrams.expand_commands(page)
diagrams.expand_commands(page)
class MostEmulatorsNotEvery(unittest.TestCase):
+8 -7
View File
@@ -19,6 +19,7 @@ from pathlib import Path
from unittest import mock
import sitesources
from sitegen import sources
from core import upstream
from model.profiles import load_emulator_profiles
from model.sourceref import ref_role, source_ref_values, split_source_ref
@@ -37,15 +38,15 @@ class BinaryContinuationsAreNotLinked(unittest.TestCase):
}
def tearDown(self):
sitesources._tree_paths.cache_clear()
sources._tree_paths.cache_clear()
def _render(self, value: str) -> str:
original = sitesources._tree_paths
sitesources._tree_paths = lambda repo, pin: frozenset({"FPLoader.cpp"})
original = sources._tree_paths
sources._tree_paths = lambda repo, pin: frozenset({"FPLoader.cpp"})
try:
return sitesources._source_ref_markdown(self.PROFILE, value)
return sources._source_ref_markdown(self.PROFILE, value)
finally:
sitesources._tree_paths = original
sources._tree_paths = original
def test_an_address_continuing_a_binary_range(self):
text = self._render("BAM.dll 1.5-408 .text:0x100ae843-0x100ae8a7, 0x10037130-0x100371de")
@@ -99,7 +100,7 @@ class TheSevenProfilesCiteHeldPaths(unittest.TestCase):
missing, checked = [], 0
for key in PROFILES:
profile = profiles[key]
candidates = sitesources._forge_sources(profile)
candidates = sources._forge_sources(profile)
values = [e["source_ref"] for e in profile.get("files") or []
if isinstance(e, dict) and e.get("source_ref")]
values += [d["source_ref"] for d in profile.get("data_directories") or []
@@ -110,7 +111,7 @@ class TheSevenProfilesCiteHeldPaths(unittest.TestCase):
_role, path = ref_role(part.path)
if " " in path or sitesources.is_binary_citation(path):
continue
verdicts = [sitesources.tree_holds(r, p, path) for r, p in candidates]
verdicts = [sources.tree_holds(r, p, path) for r, p in candidates]
if None in verdicts:
continue
checked += 1
+2 -2
View File
@@ -97,9 +97,9 @@ class SlugPlatform(unittest.TestCase):
def test_the_readme_fraction_does_not_count_it(self):
# The README's second column is what the pack has: a held file the
# platform has no folder for was counted there.
import generate_readme
from sitegen import readme
coverage = generate_readme.compute_coverage(
coverage = readme.compute_coverage(
"slugs", "platforms", self.db, emulators_dir="emulators"
)
self.assertEqual(coverage["core_present"], 0)