mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-26 11:28:51 -06:00
refactor: site commands keep only their options
This commit is contained in:
1 parent
206dae3163
commit
231002a7c0
49 files changed
+4354
-4290
No files matched your search
@@ -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
@@ -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"",
|
||||
"",
|
||||
"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
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
@@ -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
@@ -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
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
@@ -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")
|
||||
@@ -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"",
|
||||
"",
|
||||
"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")
|
||||
@@ -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)
|
||||
@@ -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,
|
||||
|
||||
@@ -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
@@ -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
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user