diff --git a/scripts/generate_readme.py b/scripts/generate_readme.py index 36bec2751..36e5f75ba 100644 --- a/scripts/generate_readme.py +++ b/scripts/generate_readme.py @@ -18,7 +18,7 @@ sys.path.insert(0, os.path.dirname(__file__)) from core.cli import add_repo_inputs from model.database import load_database from core.artifacts import repository_output_lock -from sitegen.readme import write_readme, generate_readme +from sitegen.readme import README_PATH, load_readme_inputs, render_readme, write_readme def main() -> None: @@ -35,10 +35,10 @@ def main() -> None: # Coverage resolves against data/: a refresh swapping a tree mid-read # published counts taken from half of it. - with repository_output_lock("README.md"), contextlib.ExitStack() as held: + with repository_output_lock(str(README_PATH)), contextlib.ExitStack() as held: hold_data_dirs(held, load_data_dir_registry(args.platforms_dir)) - readme = generate_readme(db, args.platforms_dir, args.db) - write_readme(readme) + inputs = load_readme_inputs(db, args.platforms_dir, args.db) + write_readme(render_readme(inputs)) if __name__ == "__main__": diff --git a/scripts/sitegen/readme.py b/scripts/sitegen/readme.py index 126ee92cf..4e36c78eb 100644 --- a/scripts/sitegen/readme.py +++ b/scripts/sitegen/readme.py @@ -6,12 +6,14 @@ import json import re import sys from collections.abc import Callable +from dataclasses import dataclass from datetime import datetime, timezone +from pathlib import Path from core.text import series from romrecipes import ledger from devtools import prchecks -from model import releaserecord +from model import releaserecord, siteinputs from core.artifacts import write_if_changed from core.paths import DB_FILE, REPO_ROOT from core.sizes import size_text @@ -94,6 +96,8 @@ def collection_line(total_files: int, comp: dict) -> str: # The installer demo (scripts/make_demo.py): the recording and what it shows. DEMO_GIF = "docs_assets/demo/install.gif" REPO = REPO_SLUG +README_PATH = REPO_ROOT / "README.md" +CONTRIBUTING_PATH = REPO_ROOT / "CONTRIBUTING.md" # 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" @@ -122,7 +126,7 @@ def clone_line(db: dict) -> str: ) -def _existing_contributor_block(readme_path: str = "README.md") -> list[str]: +def _existing_contributor_block(readme_path: str | Path = README_PATH) -> 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. @@ -219,22 +223,78 @@ def archive_line(counts: dict[str, int]) -> str: 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") +@dataclass(frozen=True) +class ReadmeInputs: + """Everything the README text is made of, gathered before it is written.""" - platform_names = list_registered_platforms(platforms_dir) + total_files: int + coverages: dict + profiles: dict + record: dict + extract_paths: dict[str, str] + archive_counts: dict[str, int] + clone: str + # The list from the GitHub API, and the published block kept from the + # README when the request returned nothing. + contributors: list[dict] + kept_contributors: list[str] + generated_at: str + +def load_readme_inputs(db: dict, platforms_dir: str, db_path: str = DB_FILE) -> ReadmeInputs: + """Read the registry, the coverages, the profiles, the release record and the contributors.""" from model.registry import load_data_dir_registry + platform_names = list_registered_platforms(platforms_dir) 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) + load_emulator_profiles(str(siteinputs.current().emulators), skip_aliases=False) ) + contributors = fetch_contributors() + kept: list[str] = [] + 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_PATH) + if kept: + print("contributors: request failed, keeping the published list") + return ReadmeInputs( + total_files=db.get("total_files", 0), + coverages=coverages, + profiles=profiles, + record=releaserecord.load_advertised(REPO_ROOT / releaserecord.RECORD, platforms_dir), + extract_paths=_extract_cells(platforms_dir), + archive_counts=ledger.rebuild_counts(), + clone=clone_line(db), + contributors=contributors, + kept_contributors=kept, + generated_at=datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + ) + + +def _contributor_lines(inputs: ReadmeInputs) -> list[str]: + if not inputs.contributors: + return inputs.kept_contributors + [""] if inputs.kept_contributors else [] + lines = ["## Contributors", ""] + for c in inputs.contributors: + login = c["login"] + avatar = c.get("avatar_url", "") + url = c.get("html_url", f"https://github.com/{login}") + lines.append( + f'{login}' + ) + return [*lines, ""] + + +def render_readme(inputs: ReadmeInputs) -> str: + """The README text from its gathered inputs.""" + total_files = inputs.total_files + ts = inputs.generated_at + coverages = inputs.coverages + profiles = inputs.profiles emulator_count = len(profiles) profile_files = [f for prof in profiles.values() for f in prof.get("files") or [] if isinstance(f, dict)] @@ -253,8 +313,8 @@ def generate_readme(db: dict, platforms_dir: str, db_path: str = DB_FILE) -> str # 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) + record = inputs.record + extract_paths = inputs.extract_paths lines = [ '

', " ", @@ -342,13 +402,13 @@ def generate_readme(db: dict, platforms_dir: str, db_path: str = DB_FILE) -> str " 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()), + archive_line(inputs.archive_counts), f"- Public data: [JSON, CSV and SQLite]({SITE_URL}data/), the metadata under MIT", "", "

", "For developers: build a pack", "", - clone_line(db), + inputs.clone, "", "```bash", "python scripts/generate_pack.py --platform retroarch --output-dir dist/", @@ -365,30 +425,7 @@ def generate_readme(db: dict, platforms_dir: str, db_path: str = DB_FILE) -> str "", ] - 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'{login}' - ) - lines.append("") + lines.extend(_contributor_lines(inputs)) lines.extend( [ @@ -579,13 +616,13 @@ def generate_contributing() -> str: def write_readme(readme: str) -> None: - status = "Generated" if write_if_changed("README.md", readme) else "Unchanged" + status = "Generated" if write_if_changed(str(README_PATH), readme) else "Unchanged" print(f"{status} ./README.md") contributing = generate_contributing() status = ( "Generated" - if write_if_changed("CONTRIBUTING.md", contributing) + if write_if_changed(str(CONTRIBUTING_PATH), contributing) else "Unchanged" ) print(f"{status} ./CONTRIBUTING.md") diff --git a/tests/readmeinputs.py b/tests/readmeinputs.py new file mode 100644 index 000000000..0efabc362 --- /dev/null +++ b/tests/readmeinputs.py @@ -0,0 +1,42 @@ +"""Fixture inputs for the README renderer, so a test reads the text it writes.""" + +from __future__ import annotations + +import dataclasses + +from sitegen.readme import ReadmeInputs + +# One setup a release carries a pack for, one served by the command alone. +RELEASED_SIZE = 16011 * 1024 * 1024 +RECORD = { + "packs": { + "RetroArch_BIOS_Pack.zip": { + "platforms": ["retroarch"], + "files": 4525, + "extracted_size": RELEASED_SIZE, + }, + }, +} + + +def readme_inputs(**changes: object) -> ReadmeInputs: + """A small, offline set of inputs, with *changes* applied.""" + inputs = ReadmeInputs( + total_files=19526, + coverages={ + "retroarch": {"platform": "RetroArch"}, + "recalbox": {"platform": "Recalbox"}, + }, + profiles={ + "core": {"files": [{"name": "a.bin", "source_ref": "src/a.c:120"}]}, + "closed": {"upstream": "closed source", "files": [{"name": "b.bin"}]}, + }, + record=RECORD, + extract_paths={"RetroArch": "`system`"}, + archive_counts={"total": 3, "exact": 2, "canonical": 1}, + clone="Packs are built from a clone.", + contributors=[], + kept_contributors=[], + generated_at="2026-01-01T00:00:00Z", + ) + return dataclasses.replace(inputs, **changes) # type: ignore[arg-type] diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index 2084c3aac..2dde6a4a7 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -3467,6 +3467,57 @@ class ContributorsSurviveAFailedRequest(unittest.TestCase): "the section is present but empty", ) + def test_a_failed_request_republishes_the_kept_block(self): + from sitegen.readme import render_readme + from tests.readmeinputs import readme_inputs + + kept = ["## Contributors", "", 'a'] + text = render_readme(readme_inputs(kept_contributors=kept)) + self.assertIn("\n".join(kept) + "\n\n\n## Community tools", text) + + def test_a_fetched_list_replaces_the_kept_block(self): + from sitegen.readme import render_readme + from tests.readmeinputs import readme_inputs + + text = render_readme(readme_inputs( + contributors=[{"login": "someone", "avatar_url": "https://a/x"}], + kept_contributors=["## Contributors", "", "stale"], + )) + self.assertIn( + '## Contributors\n\nsomeone\n', text) + self.assertNotIn("stale", text) + + def test_no_list_and_nothing_kept_leaves_the_section_out(self): + from sitegen.readme import render_readme + from tests.readmeinputs import readme_inputs + + self.assertNotIn("## Contributors", render_readme(readme_inputs())) + + def test_the_loader_keeps_the_published_block_when_the_request_fails(self): + import tempfile + + from sitegen import readme + + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "README.md" + path.write_text("# T\n\n## Contributors\n\nkept line\n\n## Other\n", encoding="utf-8") + with mock.patch.object(readme, "README_PATH", path), \ + mock.patch.object(readme, "fetch_contributors", return_value=[]), \ + mock.patch.object(readme, "list_registered_platforms", return_value=[]), \ + mock.patch("model.registry.load_data_dir_registry", return_value={}), \ + mock.patch.object(readme, "platform_coverages", return_value={}), \ + mock.patch.object(readme, "load_emulator_profiles", return_value={}), \ + mock.patch.object(readme.releaserecord, "load_advertised", return_value={}), \ + mock.patch.object(readme, "_extract_cells", return_value={}), \ + mock.patch.object(readme.ledger, "rebuild_counts", + return_value={"total": 0, "exact": 0, "canonical": 0}), \ + mock.patch.object(readme, "clone_line", return_value=""), \ + mock.patch("sys.stdout", new_callable=io.StringIO): + inputs = readme.load_readme_inputs({}, "platforms") + self.assertEqual(inputs.kept_contributors, ["## Contributors", "", "kept line"]) + self.assertIn("## Contributors\n\nkept line\n", readme.render_readme(inputs)) + def test_the_contributor_list_is_not_asked_offline(self): from sitegen import readme diff --git a/tests/test_doc_pages.py b/tests/test_doc_pages.py index 3dd4c02c7..759b422e5 100644 --- a/tests/test_doc_pages.py +++ b/tests/test_doc_pages.py @@ -796,11 +796,10 @@ class ReadmeInstallerOptions(unittest.TestCase): def test_quick_install_gives_the_powershell_form_and_the_page(self): from sitegen import readme as sitegen_readme + from tests.readmeinputs import readme_inputs - source = inspect.getsource(sitegen_readme.generate_readme) - self.assertIn("wiki/installer/#passing-options", source) + readme = sitegen_readme.render_readme(readme_inputs()) self.assertIn("## Passing options", _page("installer.md")) - readme = (ROOT / "README.md").read_text(encoding="utf-8") quick = _section(readme, "Install in one line") # The README gives the bare line and sends options to the page that # writes their PowerShell form: an option after `| iex` reaches iex. @@ -816,10 +815,11 @@ class PublishedNumbersShareOneFormat(unittest.TestCase): from core.sizes import size_text from sitegen import readme as sitegen_readme - readme_source = (inspect.getsource(sitegen_readme.generate_readme) - + inspect.getsource(sitegen_readme.download_table)) - self.assertNotIn("size_mb", readme_source) - self.assertIn("size_text(size)", readme_source) + from tests.readmeinputs import RELEASED_SIZE, readme_inputs + + rendered = sitegen_readme.render_readme(readme_inputs()) + self.assertIn(f"| RetroArch | 4,525 | {size_text(RELEASED_SIZE)} |", rendered) + self.assertIn("19,526 files in the collection", rendered) self.assertIn("{total_files:,}", script_source("generate_site.py")) self.assertEqual(size_text(16011 * 1024 * 1024), "15.6 GB")