"""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 core.text import series
from romrecipes import ledger
from devtools import prchecks
from model import releaserecord
from core.artifacts import write_if_changed
from core.paths import DB_FILE, REPO_ROOT
from core.sizes import size_text
from core import upstream
from installer_build.module import installer_module
from model.composition import compute_composition, count_catalog_matched
from model.guides import PACKAGE_COMMAND, install_command
from model.largefiles import load_registered_paths
from model.profiles import load_emulator_profiles, unique_emulator_profiles
from model.registry import list_registered_platforms
from model.systems import system_index
from resolve.review import LARGE_FILE_ISSUE_URL
from sitegen.config import REPO_SLUG, REPO_URL, SITE_URL, UPLOAD_ROOT
from sitegen.coverage import platform_coverages
from sitegen.demovariants import demo_description
from sitegen.extraction import extract_targets
from sitegen.releasepacks import download_links, release_totals
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]:
"""The README's ZIP table: one row per setup the release carries a pack
for, then the sentence linking every other setup to its get/ page."""
by_name = sorted(coverages, key=lambda n: coverages[n]["platform"])
released = [name for name in by_name if release_totals(name, record)[0]]
lines = [
"| 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:,} | {size_text(size) if size else '-'} |"
f" {extract_paths.get(display, '')} |"
f" {download_links(name, record, 'Download', site=SITE_URL)} |"
)
others = [name for name in by_name if name not in released]
return [
*lines,
"",
"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)
+ ".",
]
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"
)
# The installer demo (scripts/make_demo.py): the recording and what it shows.
DEMO_GIF = "docs_assets/demo/install.gif"
REPO = REPO_SLUG
# 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"{UPLOAD_ROOT}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 {size_text(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 _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]:
"""Contributors from the GitHub API, bots and the owner left out. Empty
when the API cannot be read, or under RETROBIOS_OFFLINE: the caller then
keeps the published list."""
if os.environ.get("RETROBIOS_OFFLINE"):
return []
url = f"https://api.github.com/repos/{REPO}/contributors"
try:
body = upstream.fetch_body(url, accept_json=True, timeout=10, user_agent="retrobios-readme/1.0")
data = json.loads(body) if body is not None else []
except (upstream.UpstreamError, ValueError) as exc:
print(f"contributors: {exc}", file=sys.stderr)
return []
owner = REPO.split("/")[0]
return [
c
for c in data
if isinstance(c, dict)
and not c.get("login", "").endswith("[bot]")
and c.get("type") == "User"
and c.get("login") != owner
]
_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",
f"{REPO_URL}/actions/workflows/validate.yml/badge.svg?branch=main",
f"{REPO_URL}/actions/workflows/validate.yml"),
)
def badge_row() -> str:
badges = " ".join(f''
for alt, image, link in BADGES)
return f'
{badges}
' 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 = DB_FILE) -> 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 = releaserecord.load_advertised(platforms_dir=platforms_dir) extract_paths = _extract_cells(platforms_dir) lines = [ '',
" ',
"
The BIOS files emulators need, put in the right folder and checked.
', "", '' f'Website · ' f'Get the files · ' f'A game does not start · ' f'Questions' "
", "", 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 {series(sorted(c['platform'] for c in coverages.values()))}, 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_module().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.", "", *download_table(coverages, extract_paths, record), "", "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(ledger.rebuild_counts()), f"- Public data: [JSON, CSV and SQLite]({SITE_URL}data/), the metadata under MIT", "", "