diff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.yml index 4e02819eb..99388aa40 100644 --- a/.github/workflows/deploy-site.yml +++ b/.github/workflows/deploy-site.yml @@ -12,7 +12,6 @@ on: # Every script the build runs or imports, and no other # (tests/test_workflow_paths.py). - "scripts/acquire/provenance.py" - - "scripts/build_port.py" - "scripts/core/__init__.py" - "scripts/core/anchors.py" - "scripts/core/artifacts.py" @@ -27,10 +26,16 @@ on: - "scripts/core/sect233r1.py" - "scripts/core/upstream.py" - "scripts/core/ziptools.py" - - "scripts/generate_event_schema.py" + - "scripts/devtools/__init__.py" + - "scripts/devtools/prchecks.py" - "scripts/generate_readme.py" - "scripts/generate_site.py" - "scripts/indexnow.py" + - "scripts/installer_build/__init__.py" + - "scripts/installer_build/eventschema.py" + - "scripts/installer_build/handhelds.py" + - "scripts/installer_build/pins.py" + - "scripts/installer_build/port.py" - "scripts/model/__init__.py" - "scripts/model/alternatives.py" - "scripts/model/cliargs.py" @@ -47,6 +52,7 @@ on: - "scripts/model/profiles.py" - "scripts/model/region.py" - "scripts/model/registry.py" + - "scripts/model/releaserecord.py" - "scripts/model/retired.py" - "scripts/model/safeparse.py" - "scripts/model/siteinputs.py" @@ -67,9 +73,8 @@ on: - "scripts/packs/paths.py" - "scripts/packs/slots.py" - "scripts/packs/verdicts.py" - - "scripts/pr_checks.py" - "scripts/refresh_data_dirs.py" - - "scripts/release_record.py" + - "scripts/release/restore.py" - "scripts/resolve/__init__.py" - "scripts/resolve/archives.py" - "scripts/resolve/categories.py" diff --git a/scripts/autorun.py b/scripts/autorun.py index f7e2aa7fa..b8b8962c2 100644 --- a/scripts/autorun.py +++ b/scripts/autorun.py @@ -196,7 +196,7 @@ class Context: def check_subject(subject: str, body: str = "") -> list[str]: """What the repository's commit rules refuse in this message, checked when the job list loads instead of two hours into the job.""" - from commit_rules import problems + from devtools.commitrules import problems return problems(f"{subject}\n\n{body}" if body else subject) diff --git a/scripts/build_installer.py b/scripts/build_installer.py index c9773c3a9..c52bc3fec 100644 --- a/scripts/build_installer.py +++ b/scripts/build_installer.py @@ -22,324 +22,10 @@ Usage: from __future__ import annotations import argparse -import ast -import heapq import sys -from collections.abc import Iterator -from dataclasses import dataclass, field -from pathlib import Path from core.artifacts import write_text_atomic -from core.paths import REPO_ROOT - -ROOT = REPO_ROOT -PACKAGE = "installer" -OUTPUT = "install.py" -COMMAND = "python scripts/build_installer.py" -SHEBANG = "#!/usr/bin/env python3\n" -NOTICE = ( - "# Generated by scripts/build_installer.py from the installer/ package. Edit\n" - "# the modules there and run the script: a change made here is overwritten.\n" -) -# C extensions a Python built without their libraries lacks. The installer -# imports them behind a guard that says so, instead of stopping on a -# ModuleNotFoundError traceback. -GUARDED = frozenset({"unicodedata", "zlib"}) -GUARD = ( - "# Built as C extensions that a Python compiled without their libraries\n" - "# lacks: the run stopped on a ModuleNotFoundError traceback.\n" - "try:\n" - "{imports}" - "except ImportError as _missing:\n" - ' print(f"Error: this Python was built without its {{_missing.name}} module, which "\n' - ' "the installer needs. Run it with another Python 3.8 or newer.", file=sys.stderr)\n' - " sys.exit(1)\n" -) -LINE_LENGTH = 120 -MARKER_WIDTH = 79 -_SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda, - ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp) - - -class BuildError(Exception): - """The package cannot be joined into one module.""" - - -@dataclass -class Module: - name: str - body: str - statements: list[ast.stmt] - plain: set[tuple[str, str | None]] = field(default_factory=set) - froms: set[tuple[str, str]] = field(default_factory=set) - imports: dict[str, set[str]] = field(default_factory=dict) - type_imports: dict[str, set[str]] = field(default_factory=dict) - defines: set[str] = field(default_factory=set) - - -def _is_docstring(node: ast.stmt) -> bool: - return (isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant) - and isinstance(node.value.value, str)) - - -def _is_type_checking_block(node: ast.stmt) -> bool: - return (isinstance(node, ast.If) and isinstance(node.test, ast.Name) - and node.test.id == "TYPE_CHECKING" and not node.orelse) - - -def _is_stdlib(module: str) -> bool: - return module.split(".")[0] in sys.stdlib_module_names - - -def _package_import(module: Module, node: ast.ImportFrom, where: str, type_only: bool) -> None: - """Record an import from another module of the package.""" - parts = (node.module or "").split(".") - if node.level or len(parts) != 2 or parts[0] != PACKAGE: - raise BuildError(f"{where}:{node.lineno}: import from {PACKAGE}. by its full name") - for alias in node.names: - if alias.asname and alias.asname != alias.name: - raise BuildError(f"{where}:{node.lineno}: {alias.name} imported as {alias.asname}: " - "one namespace keeps one name") - target = module.type_imports if type_only else module.imports - target.setdefault(parts[1], set()).update(alias.name for alias in node.names) - - -def _stdlib_import(module: Module, node: ast.Import | ast.ImportFrom, where: str) -> None: - if isinstance(node, ast.Import): - for alias in node.names: - if not _is_stdlib(alias.name): - raise BuildError(f"{where}:{node.lineno}: {alias.name} is not in the standard library") - module.plain.add((alias.name, alias.asname)) - return - for alias in node.names: - if alias.asname and alias.asname != alias.name: - raise BuildError(f"{where}:{node.lineno}: {alias.name} imported as {alias.asname}") - module.froms.add((node.module or "", alias.name)) - - -def _read_header(module: Module, header: list[ast.stmt], where: str) -> None: - for node in header: - if isinstance(node, ast.If): - for sub in node.body: - if not isinstance(sub, ast.ImportFrom): - raise BuildError(f"{where}:{sub.lineno}: a TYPE_CHECKING block holds imports only") - _package_import(module, sub, where, type_only=True) - elif isinstance(node, ast.ImportFrom) and node.module == "__future__": - continue - elif isinstance(node, ast.ImportFrom) and (node.level or not _is_stdlib(node.module or "")): - _package_import(module, node, where, type_only=False) - elif isinstance(node, (ast.Import, ast.ImportFrom)): - _stdlib_import(module, node, where) - - -def _check_nested_imports(statements: list[ast.stmt], where: str) -> None: - """Imports below the header are joined as written: inside functions, standard library only.""" - for statement in statements: - for node in ast.walk(statement): - if isinstance(node, ast.Import): - names = [alias.name for alias in node.names] - elif isinstance(node, ast.ImportFrom): - names = [node.module or "." * node.level] - else: - continue - for name in names: - if node.col_offset == 0 or not _is_stdlib(name): - raise BuildError(f"{where}:{node.lineno}: import {name} below the header " - "(module imports go first, nested ones from the standard library)") - - -def _header_length(tree: ast.Module, where: str) -> int: - """How many leading statements are the docstring, the imports and the TYPE_CHECKING block.""" - body = tree.body - if not body or not _is_docstring(body[0]): - raise BuildError(f"{where}: no module docstring") - count = 1 - while count < len(body) and (isinstance(body[count], (ast.Import, ast.ImportFrom)) - or _is_type_checking_block(body[count])): - count += 1 - future = any(isinstance(node, ast.ImportFrom) and node.module == "__future__" - and any(alias.name == "annotations" for alias in node.names) for node in body[:count]) - if not future: - raise BuildError(f"{where}: no 'from __future__ import annotations', which install.py holds") - return count - - -def _module_scope(node: ast.AST) -> Iterator[ast.AST]: - """The nodes of the module scope, the scopes it opens yielded but not entered.""" - stack = [node] - while stack: - current = stack.pop() - yield current - if current is not node and isinstance(current, _SCOPES): - continue - if isinstance(current, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)): - continue - stack.extend(ast.iter_child_nodes(current)) - - -def _defined_names(statements: list[ast.stmt]) -> set[str]: - names: set[str] = set() - for statement in statements: - for node in _module_scope(statement): - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): - names.add(node.name) - elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store): - names.add(node.id) - elif isinstance(node, ast.ExceptHandler) and node.name: - names.add(node.name) - return names - - -def read_module(path: Path) -> Module: - where = f"{PACKAGE}/{path.name}" - source = path.read_text(encoding="utf-8") - tree = ast.parse(source, filename=where) - count = _header_length(tree, where) - lines = source.splitlines(keepends=True) - start = tree.body[count - 1].end_lineno or 0 - module = Module(path.stem, "".join(lines[start:]).strip("\n"), tree.body[count:]) - _read_header(module, tree.body[1:count], where) - _check_nested_imports(module.statements, where) - module.defines = _defined_names(module.statements) - if "TYPE_CHECKING" in {node.id for statement in module.statements for node in ast.walk(statement) - if isinstance(node, ast.Name)}: - raise BuildError(f"{where}: TYPE_CHECKING read below the header") - return module - - -def read_package(package: Path) -> dict[str, Module]: - modules = {path.stem: read_module(path) for path in sorted(package.glob("*.py")) - if path.name != "__init__.py"} - owners: dict[str, str] = {} - imported = {alias or name.split(".")[0] for module in modules.values() for name, alias in module.plain} - imported |= {name for module in modules.values() for _source, name in module.froms} - for module in modules.values(): - for name in sorted(module.defines): - if name in owners: - raise BuildError(f"{name} is defined in {owners[name]}.py and {module.name}.py") - if name in imported: - raise BuildError(f"{module.name}.py defines {name}, a name the standard library imports bind") - owners[name] = module.name - for module in modules.values(): - for other, names in sorted([*module.imports.items(), *module.type_imports.items()]): - if other not in modules or other == module.name: - raise BuildError(f"{module.name}.py imports from {PACKAGE}.{other}, not another module of it") - for name in sorted(names - modules[other].defines): - raise BuildError(f"{module.name}.py imports {name} from {other}.py, which does not define it") - return modules - - -def module_order(modules: dict[str, Module]) -> list[str]: - """Each module after the ones it imports outside TYPE_CHECKING, ties in name order.""" - waiting = {name: len(module.imports) for name, module in modules.items()} - users: dict[str, set[str]] = {name: set() for name in modules} - for name, module in modules.items(): - for dep in module.imports: - users[dep].add(name) - ready = [name for name, count in waiting.items() if count == 0] - heapq.heapify(ready) - order: list[str] = [] - while ready: - name = heapq.heappop(ready) - order.append(name) - for user in users[name]: - waiting[user] -= 1 - if waiting[user] == 0: - heapq.heappush(ready, user) - if len(order) != len(modules): - cycle = sorted(name for name, count in waiting.items() if count) - raise BuildError(f"import cycle among {', '.join(cycle)}") - return order - - -def _loads_at_import(statement: ast.stmt) -> Iterator[ast.Name]: - """The names a statement reads when the module runs, not when its functions are called.""" - stack: list[ast.AST] = [statement] - while stack: - node = stack.pop() - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)): - args = node.args - stack.extend(default for default in [*args.defaults, *args.kw_defaults] if default is not None) - stack.extend(getattr(node, "decorator_list", [])) - continue - if isinstance(node, ast.AnnAssign): - stack.extend(child for child in (node.target, node.value) if child is not None) - continue - if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load): - yield node - stack.extend(ast.iter_child_nodes(node)) - - -def check_import_time(modules: dict[str, Module], order: list[str]) -> None: - position = {name: index for index, name in enumerate(order)} - owners = {name: module.name for module in modules.values() for name in module.defines} - for module in modules.values(): - for statement in module.statements: - for node in _loads_at_import(statement): - owner = owners.get(node.id) - if owner is not None and position[owner] > position[module.name]: - raise BuildError(f"{module.name}.py:{node.lineno}: {node.id} is read at import time " - f"but {owner}.py comes later") - - -def _type_key(name: str) -> tuple[int, str]: - if len(name) > 1 and name.isupper(): - return (0, name) - return (1 if name[0].isupper() else 2, name) - - -def _from_line(module: str, names: set[str]) -> str: - ordered = sorted(names, key=_type_key) - line = f"from {module} import {', '.join(ordered)}" - if len(line) <= LINE_LENGTH: - return line + "\n" - return f"from {module} import (\n" + "".join(f" {name},\n" for name in ordered) + ")\n" - - -def import_header(modules: dict[str, Module]) -> tuple[str, str]: - """The merged standard library imports, and the guard of the C extensions among them.""" - plain = {entry for module in modules.values() for entry in module.plain} - guarded = sorted(name for name, alias in plain if name in GUARDED and alias is None) - lines = [f"import {name}" + (f" as {alias}" if alias else "") + "\n" - for name, alias in sorted(plain, key=lambda entry: (entry[0].lower(), entry[1] or "")) - if name not in guarded] - froms: dict[str, set[str]] = {} - for module in modules.values(): - for source, name in module.froms: - if (source, name) != ("typing", "TYPE_CHECKING"): - froms.setdefault(source, set()).add(name) - lines += [_from_line(source, names) for source, names in sorted(froms.items())] - guard = GUARD.format(imports="".join(f" import {name}\n" for name in guarded)) if guarded else "" - return "".join(lines), guard - - -def _marker(name: str) -> str: - head = f"# --- {PACKAGE}/{name}.py " - return head + "-" * max(3, MARKER_WIDTH - len(head)) + "\n" - - -def _docstring(package: Path) -> str: - text = (package / "__init__.py").read_text(encoding="utf-8").strip("\n") - body = ast.parse(text).body - if len(body) != 1 or not _is_docstring(body[0]): - raise BuildError(f"{PACKAGE}/__init__.py holds the docstring of install.py and nothing else") - return text + "\n" - - -def build(package: Path) -> str: - """install.py as the package gives it.""" - docstring = _docstring(package) - modules = read_package(package) - order = module_order(modules) - check_import_time(modules, order) - imports, guard = import_header(modules) - parts = [SHEBANG, NOTICE, docstring, "from __future__ import annotations\n\n", imports] - if guard: - parts += ["\n", guard] - for name in order: - if modules[name].body: - parts += ["\n\n", _marker(name), "\n", modules[name].body, "\n"] - return "".join(parts) +from installer_build.amalgamate import BuildError, COMMAND, OUTPUT, PACKAGE, ROOT, build def main(argv: list[str] | None = None) -> int: diff --git a/scripts/build_port.py b/scripts/build_port.py index 042bd51a5..7d79f21e6 100644 --- a/scripts/build_port.py +++ b/scripts/build_port.py @@ -33,169 +33,12 @@ from __future__ import annotations import argparse import hashlib -import re import sys -import zipfile from pathlib import Path from core.artifacts import ArtifactLockBusy, artifact_lock from core.paths import REPO_ROOT - -PORT_DIR = "retrobios" -PORT_SCRIPT = "RetroBIOS.sh" -PORT_ZIP = "RetroBIOS.zip" -BATOCERA_ZIP = "RetroBIOS-batocera.zip" -MUOS_APP = "RetroBIOS.muxapp" -TOOLS_ZIP = "RetroBIOS-tools.zip" -# Every launcher archive the site serves. -ARCHIVES = (PORT_ZIP, BATOCERA_ZIP, MUOS_APP, TOOLS_ZIP) -# Which release pack serves each platform, read by tui.txt offline. -PACKS_TABLE = "packs.txt" -_PIN = re.compile(r'^DEFAULT_INSTALL_SHA256="([0-9a-f]{64})"$', re.MULTILINE) - - -def pinned_installer_sha256(root: Path = REPO_ROOT) -> str: - """The SHA-256 install.sh accepts for install.py.""" - found = _PIN.search((root / "install.sh").read_text(encoding="utf-8")) - if found is None: - raise ValueError("install.sh pins no installer SHA-256") - return found.group(1) - - -def _engine(folder: str, root: Path, mapping: bool = True) -> list[tuple[str, Path | None]]: - """What every launcher runs: the installer, the interface launcher, the - event reader, the licenses, and the gptokeyb mapping where one is read.""" - shared = root / "ports" / "shared" - members = [ - (f"{folder}/install.py", root / "install.py"), - (f"{folder}/tui.txt", shared / "tui.txt"), - (f"{folder}/rbevents.py", shared / "rbevents.py"), - (f"{folder}/licenses/LICENSE-retrobios.txt", root / "LICENSE"), - (f"{folder}/licenses/NOTICE-retrobios.txt", root / "NOTICE"), - # Written by build_archive from the registry. - (f"{folder}/{PACKS_TABLE}", None), - ] - if mapping: - members.append((f"{folder}/retrobios.gptk", shared / "retrobios.gptk")) - return members - - -def archive_members(name: str, root: Path = REPO_ROOT) -> list[tuple[str, Path | None]]: - """(name in the archive, source file) for every member of *name*, sorted. - The source is None for the packs table build_archive writes.""" - ports = root / "ports" - if name == PORT_ZIP: - source = ports / "RetroBIOS" - members = [ - (PORT_SCRIPT, source / PORT_SCRIPT), - (f"{PORT_DIR}/port.json", source / "port.json"), - (f"{PORT_DIR}/gameinfo.xml", source / "gameinfo.xml"), - (f"{PORT_DIR}/{PORT_DIR}.md", source / "README.md"), - *_engine(PORT_DIR, root), - ] - members += [ - (f"{PORT_DIR}/{path.relative_to(source / PORT_DIR).as_posix()}", path) - for path in sorted((source / PORT_DIR).rglob("*")) - if path.is_file() and "__pycache__" not in path.parts - ] - elif name == BATOCERA_ZIP: - source = ports / "batocera" - members = [ - (PORT_SCRIPT, source / PORT_SCRIPT), - (f"{PORT_SCRIPT}.keys", source / f"{PORT_SCRIPT}.keys"), - (f"{PORT_DIR}/README.md", source / "README.md"), - # evmapy reads RetroBIOS.sh.keys: no gptokeyb there. - *_engine(PORT_DIR, root, mapping=False), - ] - elif name == MUOS_APP: - source = ports / "muos" - members = [ - ("RetroBIOS/mux_launch.sh", source / "mux_launch.sh"), - ("RetroBIOS/README.md", source / "README.md"), - # muOS draws an application's list glyph from glyph/.png - # in its own folder (apply_app_glyph, frontend common/ui/glyph.c): - # `# ICON: retrobios` resolved to nothing without it. - ("RetroBIOS/glyph/retrobios.png", source / "glyph" / "retrobios.png"), - *_engine("RetroBIOS", root), - ] - elif name == TOOLS_ZIP: - source = ports / "tools" - members = [ - (PORT_SCRIPT, source / PORT_SCRIPT), - (f"{PORT_DIR}/README.md", source / "README.md"), - *_engine(PORT_DIR, root), - ] - else: - raise ValueError(f"no launcher archive is named {name}") - names = [member for member, _path in members] - if len(set(names)) != len(names): - raise ValueError(f"two members of {name} share a name") - return sorted(members) - - -def release_pack_labels(root: Path = REPO_ROOT) -> dict[str, str]: - """Platform -> the platform part of the release pack that serves it. - - Only the platforms the registry marks release_pack have a pack, grouped - as the release builds them (pipeline.py). install.py - refuses a pack whose name does not spell the platform, so a platform - outside these groups has no pack to copy, whatever its file list. - """ - from resolve.grouping import group_identical_platforms - from model.registry import list_release_pack_platforms - from model.platforms import load_platform_config - from packs.naming import _name_part, _platform_pack_stem - - platforms_dir = str(root / "platforms") - pool = list_release_pack_platforms(platforms_dir) - labels: dict[str, str] = {} - for group, representative in group_identical_platforms(pool, platforms_dir): - stem = _platform_pack_stem(group, representative, platforms_dir) - config = load_platform_config(representative, platforms_dir) - version = config.get("version", config.get("dat_version", "")) - tag = f"_{_name_part(str(version))}" if version else "" - label = stem[: -len(tag)] if tag and stem.endswith(tag) else stem - for platform in group: - labels[platform] = label - return dict(sorted(labels.items())) - - -def _packs_table(root: Path) -> bytes: - return "".join(f"{platform}\t{label}\n" - for platform, label in release_pack_labels(root).items()).encode() - - -def build_archive(name: str, output: Path, root: Path = REPO_ROOT) -> Path: - """Write the launcher archive *name* to *output* and return it.""" - pinned = pinned_installer_sha256(root) - actual = hashlib.sha256((root / "install.py").read_bytes()).hexdigest() - if actual != pinned: - raise ValueError( - f"install.py is {actual[:12]}, install.sh pins {pinned[:12]}: " - "re-pin the bootstraps before building the launchers" - ) - # The packs' member writer: imported here, as it loads the whole - # pack builder, which a caller reading ARCHIVES does not need. - from packs.archive import _add_pack_member - - members = archive_members(name, root) - output.parent.mkdir(parents=True, exist_ok=True) - scratch = output.with_name(f".{output.name}.tmp") - table = output.with_name(f".{output.name}.{PACKS_TABLE}") - table.write_bytes(_packs_table(root)) - try: - with zipfile.ZipFile(scratch, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as zf: - for member, path in members: - _add_pack_member(zf, str(path or table), member) - finally: - table.unlink() - scratch.replace(output) - return output - - -def build_port(output: Path, root: Path = REPO_ROOT) -> Path: - """Write the PortMaster port archive to *output* and return it.""" - return build_archive(PORT_ZIP, output, root) +from installer_build.port import ARCHIVES, build_archive def main() -> int: diff --git a/scripts/build_pypi.py b/scripts/build_pypi.py index 87fff8027..71f7c973e 100644 --- a/scripts/build_pypi.py +++ b/scripts/build_pypi.py @@ -25,105 +25,9 @@ Usage: from __future__ import annotations import argparse -import datetime -import hashlib -import os -import shutil -import subprocess -import tempfile from pathlib import Path -from sitegen.bootstrap import PIN -from model.guides import SH_NAME -from core.paths import REPO_ROOT - -ROOT = REPO_ROOT -PACKAGE_DIR = ROOT / "packaging" / "pypi" -DEFAULT_OUTPUT = ROOT / "tmp" / "pypi-dist" -MODULE = "retrobios" - -# The launcher. runpy runs install.py as __main__, so its own __main__ block -# keeps the exit codes it gives a reader that left (141) and Ctrl+C (130). -LAUNCHER = '''"""The RetroBIOS installer, install.py, run as the retrobios command.""" - -import os -import runpy -from pathlib import Path - -__version__ = "{version}" - - -def main() -> None: - # The hints give back the command that ran this, not python3 install.py. - os.environ["RETROBIOS_BOOTSTRAP"] = "pypi" - runpy.run_path(str(Path(__file__).with_name("install.py")), run_name="__main__") -''' - - -def package_version(stamps: list[int]) -> str: - """The version of install.py from its commit times, newest first (UTC).""" - if not stamps: - raise ValueError("install.py has no commit to date the package by") - day = datetime.datetime.fromtimestamp(stamps[0], datetime.timezone.utc).date() - rank = sum(1 for stamp in stamps - if datetime.datetime.fromtimestamp(stamp, datetime.timezone.utc).date() == day) - base = f"{day.year}.{day.month}.{day.day}" - return base if rank == 1 else f"{base}.{rank}" - - -def install_py_commits() -> list[int]: - """Commit times of install.py, newest first, from git.""" - out = subprocess.run(["git", "log", "--format=%ct", "--", "install.py"], cwd=ROOT, - capture_output=True, text=True, check=True).stdout - return [int(line) for line in out.split()] - - -def installer_bytes() -> bytes: - """install.py, refused unless it is the one install.sh pins: the package - then runs the installer the one-line command runs, under the same id.""" - data = (ROOT / "install.py").read_bytes() - pins = PIN[SH_NAME].findall((ROOT / "install.sh").read_text(encoding="utf-8")) - if pins != [hashlib.sha256(data).hexdigest()]: - raise ValueError("install.py is not the installer install.sh pins: recompute the pin") - return data - - -def stage(folder: Path, version: str) -> None: - """The project as the backend reads it.""" - module = folder / MODULE - module.mkdir(parents=True) - for name in ("pyproject.toml", "README.md"): - shutil.copyfile(PACKAGE_DIR / name, folder / name) - shutil.copyfile(ROOT / "LICENSE", folder / "LICENSE") - shutil.copyfile(PACKAGE_DIR / MODULE / "__main__.py", module / "__main__.py") - (module / "__init__.py").write_text(LAUNCHER.format(version=version), encoding="utf-8") - (module / "install.py").write_bytes(installer_bytes()) - - -def build(output_dir: Path) -> tuple[Path, Path]: - """The wheel and the sdist in output_dir, replacing earlier builds there.""" - stamps = install_py_commits() - version = package_version(stamps) - output_dir.mkdir(parents=True, exist_ok=True) - for pattern in ("*.whl", "*.tar.gz"): - for old in output_dir.glob(f"{MODULE}-{pattern}"): - old.unlink() - scratch = ROOT / "tmp" - scratch.mkdir(exist_ok=True) - with tempfile.TemporaryDirectory(prefix="pypi-stage-", dir=scratch) as name: - folder = Path(name) / "retrobios" - stage(folder, version) - # Without a flag, uv builds the sdist, then the wheel from that sdist: - # what a user building from the sdist gets is what is published. - subprocess.run( - ["uv", "build", "--quiet", "--out-dir", str(output_dir.resolve()), str(folder)], - check=True, env={**os.environ, "SOURCE_DATE_EPOCH": str(stamps[0])}) - wheel = output_dir / f"{MODULE}-{version}-py3-none-any.whl" - sdist = output_dir / f"{MODULE}-{version}.tar.gz" - for path in (wheel, sdist): - if not path.is_file(): - raise RuntimeError(f"uv build wrote no {path.name}") - return wheel, sdist +from installer_build.pypi import DEFAULT_OUTPUT, build def main() -> int: diff --git a/scripts/check_buildbot_system.py b/scripts/check_buildbot_system.py index a3e1a3380..0fda48bee 100644 --- a/scripts/check_buildbot_system.py +++ b/scripts/check_buildbot_system.py @@ -13,163 +13,19 @@ Usage: from __future__ import annotations import argparse -import importlib.util import json import logging import os -import subprocess import sys -import urllib.error -import urllib.parse -import urllib.request -from pathlib import Path from core.cli import InputMissing -from model.safeparse import yaml_load - -log = logging.getLogger(__name__) - -BUILDBOT_SYSTEM_URL = "https://buildbot.libretro.com/assets/system/" -INDEX_URL = BUILDBOT_SYSTEM_URL + ".index" -USER_AGENT = "retrobios/1.0" -REQUEST_TIMEOUT = 15 - -DEFAULT_REGISTRY = "platforms/_data_dirs.yml" -VERSIONS_FILE = "data/.versions.json" - - -def fetch_index() -> set[str]: - """Fetch .index from buildbot, return set of ZIP filenames.""" - req = urllib.request.Request(INDEX_URL, headers={"User-Agent": USER_AGENT}) - with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as resp: - return { - line.strip() for line in resp.read().decode().splitlines() if line.strip() - } - - -def load_tracked_entries( - registry_path: str = DEFAULT_REGISTRY, -) -> dict[str, tuple[str, str]]: - """Load buildbot entries from _data_dirs.yml. - - Returns {decoded_zip_name: (key, source_url)}. - """ - if importlib.util.find_spec("yaml") is None: - print("Error: PyYAML required", file=sys.stderr) - sys.exit(1) - with open(registry_path) as f: - data = yaml_load(f) or {} - entries: dict[str, tuple[str, str]] = {} - for key, entry in data.get("data_directories", {}).items(): - url = entry.get("source_url", "") - if "buildbot.libretro.com/assets/system" not in url: - continue - zip_name = urllib.parse.unquote(url.rsplit("/", 1)[-1]) - entries[zip_name] = (key, url) - return entries - - -def get_remote_etag(url: str) -> str | None: - """HEAD request to get ETag.""" - try: - req = urllib.request.Request( - url, method="HEAD", headers={"User-Agent": USER_AGENT} - ) - with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as resp: - return resp.headers.get("ETag") or resp.headers.get("Last-Modified") or "" - except (urllib.error.URLError, OSError): - return None - - -def load_versions(versions_path: str = VERSIONS_FILE) -> dict: - """Load cached version/ETag data.""" - path = Path(versions_path) - if not path.exists(): - return {} - with open(path) as f: - return json.load(f) - - -def check(registry_path: str = DEFAULT_REGISTRY) -> dict: - """Run the buildbot check. Returns structured report.""" - try: - index_zips = fetch_index() - except (urllib.error.URLError, OSError) as exc: - log.warning("buildbot unreachable: %s", exc) - return {"error": str(exc), "entries": []} - - tracked = load_tracked_entries(registry_path) - versions = load_versions() - - buildbot_set = set(index_zips) - tracked_set = set(tracked.keys()) - - results: list[dict] = [{"zip": z, "status": "NEW", "key": None} for z in sorted(buildbot_set - tracked_set)] - - for z in sorted(tracked_set - buildbot_set): - key, _ = tracked[z] - results.append({"zip": z, "status": "STALE", "key": key}) - - for z in sorted(tracked_set & buildbot_set): - key, url = tracked[z] - stored = versions.get(key, {}).get("sha", "") - remote = get_remote_etag(url) - if remote is None: - status = "UNKNOWN" - elif remote == stored: - status = "OK" - else: - status = "UPDATED" - results.append( - { - "zip": z, - "status": status, - "key": key, - "stored_etag": stored, - "remote_etag": remote or "", - } - ) - - return {"entries": results} - - -def print_report(report: dict) -> None: - """Print human-readable report.""" - if report.get("error"): - print(f"WARNING: {report['error']}") - return - entries = report["entries"] - print(f"Buildbot system check ({len(entries)} entries):") - for e in entries: - pad = 40 - len(e["zip"]) - dots = "." * max(pad, 2) - print(f" {e['zip']} {dots} {e['status']}") - counts: dict[str, int] = {} - for e in entries: - counts[e["status"]] = counts.get(e["status"], 0) + 1 - parts = [f"{v} {k.lower()}" for k, v in sorted(counts.items())] - print(f"\nSummary: {', '.join(parts)}") - - -def update_changed(report: dict) -> list[str]: - """Refresh entries that have changed and return the keys whose refresh failed.""" - failed: list[str] = [] - for e in report.get("entries", []): - if e["status"] == "UPDATED" and e.get("key"): - log.info("refreshing %s ...", e["key"]) - result = subprocess.run( - [ - sys.executable, - "scripts/refresh_data_dirs.py", - "--force", - "--key", - e["key"], - ], - check=False, - ) - if result.returncode != 0: - log.error("refresh of %s failed (exit %d)", e["key"], result.returncode) - failed.append(e["key"]) - return failed +from scraper.buildbot_system import ( + DEFAULT_REGISTRY, + check, + pending, + print_report, + unanswered, + update_changed, +) def main() -> None: @@ -219,16 +75,6 @@ def main() -> None: raise SystemExit(1) -def pending(report: dict) -> list[dict]: - """Entries a maintainer has to act on: not tracked yet, or gone.""" - return [e for e in report.get("entries", []) if e["status"] in ("NEW", "STALE")] - - -def unanswered(report: dict) -> list[dict]: - """Tracked entries whose remote version could not be read.""" - return [e for e in report.get("entries", []) if e["status"] == "UNKNOWN"] - - if __name__ == "__main__": from core.cli import run_cli diff --git a/scripts/check_freshness.py b/scripts/check_freshness.py index 4ed8b9f3a..dd322c620 100644 --- a/scripts/check_freshness.py +++ b/scripts/check_freshness.py @@ -59,7 +59,7 @@ from exporter.originals import ( source_revision, wanted_sources, ) -import pin_installer +from installer_build import pins as installer_build_pins from packs import datadirs from core import upstream from core.cli import InputMissing, require_directory, suggest_names @@ -1049,15 +1049,15 @@ def _check_buildbot_system() -> Finding: The registry entries are refreshed above. An asset published since, or one the buildbot no longer serves, is only seen by reading its .index. """ - import check_buildbot_system + from scraper import buildbot_system with contextlib.redirect_stdout(io.StringIO()): - report = check_buildbot_system.check( + report = buildbot_system.check( str(REPO_ROOT / "platforms" / "_data_dirs.yml") ) if report.get("error"): return Finding("data", "buildbot system", UNKNOWN, detail="index unreachable") - todo = check_buildbot_system.pending(report) + todo = buildbot_system.pending(report) if not todo: return Finding("data", "buildbot system", OK) every = [f"{e['status'].lower()} {e['zip']}" for e in todo] @@ -1499,14 +1499,14 @@ def check_ci(cache_dir: str, offline: bool) -> list[Finding]: def _check_installer_pins() -> Finding: """The bootstraps pin install.py by SHA-256, so a stale pin refuses every install.""" - stale = pin_installer.stale_pins(REPO_ROOT) + stale = installer_build_pins.stale_pins(REPO_ROOT) return Finding( "ci", "install.py pin", STALE if stale else OK, - local=pin_installer.installer_sha256(REPO_ROOT)[:12], + local=installer_build_pins.installer_sha256(REPO_ROOT)[:12], detail=( - f"pin outdated in {', '.join(stale)}, {pin_installer.COMMAND} writes it" + f"pin outdated in {', '.join(stale)}, {installer_build_pins.COMMAND} writes it" if stale else "install.sh and install.ps1 match" ), ) diff --git a/scripts/check_release.py b/scripts/check_release.py index 00660a8bc..d342b3849 100644 --- a/scripts/check_release.py +++ b/scripts/check_release.py @@ -22,150 +22,23 @@ Usage: from __future__ import annotations import argparse -import hashlib import json import subprocess import sys -from dataclasses import dataclass from pathlib import Path -from check_release_assets import digests_of from model.registry import list_release_pack_platforms from core.cli import require_directory -from model.largefiles import LARGE_FILES_REPO -from release_record import RECORD, load_record - -SUMS = "SHA256SUMS.txt" -SIGNATURE = SUMS + ".sig" -@dataclass(frozen=True) -class Asset: - size: int - sha256: str | None - - -@dataclass(frozen=True) -class Finding: - kind: str - name: str - detail: str - - -def parse_sums(text: str) -> dict[str, str]: - """`sha256sum` output: digest, then a space and a mode character.""" - sums: dict[str, str] = {} - for line in text.splitlines(): - line = line.strip() - if not line: - continue - digest, _, name = line.partition(" ") - if len(digest) != 64 or not name: - raise ValueError(f"not a sha256sum line: {line!r}") - sums[name.lstrip(" *")] = digest.lower() - return sums - - -def _registry_findings(packs: dict, released: set[str]) -> list[Finding]: - """Each platform marked release_pack has a pack, and each pack serves one.""" - served = {p for pack in packs.values() for p in pack.get("platforms", ())} - findings = [Finding("no-pack", platform, "release_pack: true, no pack in release.json") - for platform in sorted(released - served)] - findings.extend(Finding( - "not-released", pack_name, - "serves no platform marked release_pack in platforms/_registry.yml", - ) for pack_name, pack in sorted(packs.items()) if not set(pack.get("platforms", ())) & released) - return findings - - -def compare_release( - record: dict, - sums: dict[str, str], - assets: dict[str, Asset], - tag: str, - local_files: dict[str, str] | None = None, - released: set[str] | None = None, -) -> list[Finding]: - """Every way the release can differ from what was built. - - *local_files* maps a file kept beside the packs (the checksum list, its - signature) to its local sha256: the copy on the release must be that one. - *released* names the platforms the registry marks release_pack: each one - has a recorded pack, and no recorded pack serves only other platforms. - """ - findings: list[Finding] = [] - if record.get("tag") != tag: - findings.append(Finding("tag", tag, f"release.json records {record.get('tag')}")) - if released is not None: - findings += _registry_findings(record.get("packs", {}), released) - - recorded = { - name: pack_name - for pack_name, pack in record.get("packs", {}).items() - for name in pack.get("assets", []) - } - expected = set(recorded) | set(sums) | {SUMS} | set(local_files or ()) - allowed = expected | {SIGNATURE} - - findings.extend(Finding("missing", name, "not attached to the release") - for name in sorted(expected - set(assets))) - findings.extend(Finding("extra", name, "attached but neither recorded nor listed") - for name in sorted(set(assets) - allowed)) - findings.extend(Finding("unlisted", name, f"absent from {SUMS}") - for name in sorted(set(recorded) - set(sums))) - findings.extend(Finding("unrecorded", name, f"listed in {SUMS}, absent from release.json") - for name in sorted(set(sums) - set(recorded))) - - wanted = {**sums, **(local_files or {})} - for name, digest in sorted(wanted.items()): - asset = assets.get(name) - if asset is None: - continue - if asset.sha256 is None: - findings.append(Finding("unverified", name, "the release gives no sha256")) - elif asset.sha256 != digest: - findings.append(Finding( - "content", name, f"release sha256 {asset.sha256[:12]} != {digest[:12]}" - )) - - for pack_name, pack in sorted(record.get("packs", {}).items()): - parts = [assets[name].size for name in pack.get("assets", []) if name in assets] - if len(parts) == len(pack.get("assets", [])) and sum(parts) != pack.get("download_size"): - findings.append(Finding( - "size", pack_name, - f"assets total {sum(parts)} bytes, release.json says {pack.get('download_size')}", - )) - return findings - - -def _sha256(path: Path) -> str: - digest = hashlib.sha256() - with open(path, "rb") as handle: - for chunk in iter(lambda: handle.read(1 << 20), b""): - digest.update(chunk) - return digest.hexdigest() - - -def fetch_assets(tag: str) -> tuple[dict[str, Asset], bool]: - """Name, size and sha256 of every asset of *tag*, and whether it is a draft.""" - result = subprocess.run( - ["gh", "release", "view", tag, "-R", LARGE_FILES_REPO, "--json", "assets,isDraft"], - capture_output=True, text=True, check=True, - ) - data = json.loads(result.stdout) - digests = digests_of(data["assets"]) - return ( - {a["name"]: Asset(a["size"], digests.get(a["name"])) for a in data["assets"]}, - bool(data.get("isDraft")), - ) - - -def fetch_sums(tag: str) -> str: - """The checksum list as attached to *tag*.""" - result = subprocess.run( - ["gh", "release", "download", tag, "-R", LARGE_FILES_REPO, - "--pattern", SUMS, "--output", "-"], - capture_output=True, text=True, check=True, - ) - return result.stdout +from model.releaserecord import RECORD, load_record +from release.check import ( + SIGNATURE, + SUMS, + _sha256, + compare_release, + fetch_assets, + fetch_sums, + parse_sums, +) def main() -> int: diff --git a/scripts/check_release_assets.py b/scripts/check_release_assets.py index 6324155f8..9a2fd9b90 100644 --- a/scripts/check_release_assets.py +++ b/scripts/check_release_assets.py @@ -15,310 +15,22 @@ Usage: from __future__ import annotations import argparse -import hashlib import json -import os -import re import subprocess import sys -from collections.abc import Iterable -from typing import NamedTuple -from model.composition import composition_tier from model.database import load_database -from model.largefiles import LARGE_FILES_RELEASE, LARGE_FILES_REPO, asset_names, registered_paths - - -class AssetFinding(NamedTuple): - """A difference between the release and the collection.""" - - kind: str - path: str - size: int - published: int | None - - -def expected_assets(db: dict, gitignore_text: str) -> dict[str, int]: - """Map each gitignored database path to the size the manifests carry.""" - ignored = set(registered_paths(gitignore_text)) - return { - entry["path"]: entry["size"] - for entry in db.get("files", {}).values() - if entry.get("path") in ignored - } - - -def _spellings(name: str) -> list[str]: - """Names the release may publish an asset under. - - GitHub rewrites spaces to dots in asset names, so a file whose name - carries spaces is published under the dotted form. - """ - return [name, name.replace(" ", ".")] if " " in name else [name] - - -def compare( - expected: dict[str, int], - assets: dict[str, int], - notes_current: bool = True, - registered: Iterable[str] | None = None, - expected_digests: dict[str, str] | None = None, - asset_digests: dict[str, str] | None = None, -) -> list[AssetFinding]: - """Files the release lacks or serves at another size, sorted by kind. - - At the same size, the sha256 the release lists for an asset is held - against the collection's: a dump rebuilt at its old size and never - re-uploaded was invisible to a size comparison. - - *registered* is every path .gitignore lists. An asset name depends on - which other paths share its basename, so it defaults to *expected* only - when the caller has nothing wider. A release description that no longer - matches what render_notes() would write is a finding of its own: the - page is what a reader checks a download against. - """ - findings: list[AssetFinding] = [] - if not notes_current: - findings.append(AssetFinding("notes", "release description", 0, None)) - names = asset_names([*(registered or ()), *expected]) - for path, size in sorted(expected.items()): - served = next( - (name for name in _spellings(names[path]) if name in assets), None - ) - if not served: - findings.append(AssetFinding("missing", path, size, None)) - continue - published = assets[served] - if published != size: - findings.append(AssetFinding("size", path, size, published)) - else: - ours = (expected_digests or {}).get(path) - theirs = (asset_digests or {}).get(served) - if ours and theirs and ours != theirs: - findings.append(AssetFinding("content", path, size, published)) - return sorted(findings) - - -def expected_digests(db: dict, gitignore_text: str) -> dict[str, str]: - """sha256 of each gitignored database path.""" - ignored = set(registered_paths(gitignore_text)) - return { - entry["path"]: entry["sha256"].lower() - for entry in db.get("files", {}).values() - if entry.get("path") in ignored and entry.get("sha256") - } - - -def digests_of(assets_json: list[dict]) -> dict[str, str]: - """sha256 the release lists for each asset, by name.""" - return { - a["name"]: str(a["digest"]).removeprefix("sha256:").lower() - for a in assets_json - if str(a.get("digest") or "").startswith("sha256:") - } - - -ASSET_URL = f"https://github.com/{LARGE_FILES_REPO}/releases/download/{LARGE_FILES_RELEASE}/" -NOT_INDEXED = "Not indexed" -SECTIONS = ( - "Console firmware", - "Arcade", - "Computer", - "Game engine data", - "Virtual machine firmware", - "Other", - NOT_INDEXED, +from model.largefiles import registered_paths +from release.assets import ( + cache_hashes, + compare, + expected_assets, + expected_digests, + fetch_release, + profile_descriptions, + registry_bundles, + render_notes, ) -_ROW = re.compile( - r"^\| \[(?P[^\]]+)\]\([^)]*\) \| (?P[^|]*?) \| [^|]* \|" - r"(?: `(?P[0-9a-f]{40})` \|)?$", - re.M, -) -_HEADING = re.compile(r"^## (.+)$", re.M) - - -def parse_notes(body: str) -> dict[str, tuple[str, str, str]]: - """Name -> (section, description, sha1) for every row of a release page.""" - rows: dict[str, tuple[str, str, str]] = {} - section = "" - for line in body.splitlines(): - heading = _HEADING.match(line) - if heading: - section = heading.group(1).strip() - continue - row = _ROW.match(line) - if row: - rows[row.group("name")] = ( - section, row.group("desc").strip(), row.group("sha1") or "" - ) - return rows - - -def _section_for(path: str) -> str: - parts = path.split("/") - top = parts[1] if len(parts) > 1 else "" - if top in ("Nintendo", "Sony", "Sega", "Microsoft", "NEC", "SNK"): - return "Console firmware" - if top == "Arcade" or "/samples/" in path: - return "Arcade" - if top == "QEMU": - return "Virtual machine firmware" - if composition_tier(path) == "game_data": - return "Game engine data" - if top in ("Apple", "Commodore", "Atari", "Sinclair", "Amstrad"): - return "Computer" - return "Other" - - -def _mib(size: int) -> str: - return f"{round(size / 1048576)} MB" - - -def render_notes( - db: dict, - gitignore_text: str, - assets: dict[str, int], - previous: str, - descriptions: dict[str, str], - bundles: dict[str, str], - cache_sha1: dict[str, str], -) -> str: - """The release page, from what the release actually serves. - - Every asset gets one row. A file the database indexes carries its - database SHA1, a data-directory bundle carries the hash of its cached - copy when one exists, and anything else is listed apart with its size only, - so the page never vouches for bytes nobody indexed. Descriptions and - sections already written by hand are kept by name. - """ - known = parse_notes(previous) - names = asset_names(registered_paths(gitignore_text)) - indexed: dict[str, tuple[str, str]] = {} - for sha1, entry in db.get("files", {}).items(): - path = entry.get("path", "") - if path in names: - for candidate in _spellings(names[path]): - indexed[candidate] = (sha1, path) - - rows: dict[str, list[tuple[int, str]]] = {section: [] for section in SECTIONS} - for name, size in assets.items(): - section, description, previous_sha1 = known.get(name, ("", "", "")) - if name in indexed: - sha1, path = indexed[name] - section = section if section in SECTIONS[:-1] else _section_for(path) - stem = name.split(".")[0] + "." + name.split(".")[1] if name.count(".") > 1 else name - description = description or descriptions.get(name) or descriptions.get(stem) or path - elif name in bundles: - sha1 = cache_sha1.get(name, previous_sha1) - section = section if section in SECTIONS[:-1] else "Game engine data" - description = description or bundles[name] - else: - sha1 = "" - section = NOT_INDEXED - description = description or name - link = f"[{name}]({ASSET_URL}{name})" - if section == NOT_INDEXED: - line = f"| {link} | {description} | {_mib(size)} |" - else: - line = f"| {link} | {description} | {_mib(size)} | `{sha1}` |" - rows[section].append((-size, line)) - - out = [ - "Files too large for the git repository (GitHub 100MB limit), plus game engine data packs.", - "Downloaded automatically by `generate_pack.py` when not present locally.", - "Manual: `gh release download large-files`", - ] - for section in SECTIONS: - if not rows[section]: - continue - out += ["", f"## {section}", ""] - if section == NOT_INDEXED: - out += [ - "Assets the collection does not index: no database entry names them, " - "so no hash is vouched for here.", - "", - "| File | Description | Size |", - "|------|-------------|-----:|", - ] - else: - out += ["| File | Description | Size | SHA1 |", "|------|-------------|-----:|------|"] - out += [line for _, line in sorted(rows[section])] - total = sum(assets.values()) - out += ["", f"{len(assets)} files, {total / 1073741824:.1f} GB total. Verify a download with `sha1sum `.", ""] - return "\n".join(out) - - -def profile_descriptions(emulators_dir: str = "emulators") -> dict[str, str]: - """Name -> description, from the first profile that declares the file.""" - from model.profiles import load_emulator_profiles - - found: dict[str, str] = {} - for profile in load_emulator_profiles(emulators_dir).values(): - for entry in profile.get("files", []): - name = str(entry.get("name") or "") - if name and entry.get("description"): - found.setdefault(name, str(entry["description"])) - return found - - -def registry_bundles(registry_path: str = "platforms/_data_dirs.yml") -> dict[str, str]: - """Asset name -> description for data directories served from the release.""" - from model.safeparse import yaml_load - - with open(registry_path, encoding="utf-8") as handle: - registry = yaml_load(handle) or {} - bundles: dict[str, str] = {} - for entry in (registry.get("data_directories") or registry).values(): - if not isinstance(entry, dict): - continue - url = str(entry.get("source_url") or "") - if url.startswith(ASSET_URL): - bundles[url[len(ASSET_URL):]] = str(entry.get("description") or "") - return bundles - - -def cache_hashes(names: set[str], cache_dir: str = ".cache/large") -> dict[str, str]: - """SHA1 of the cached copy of each named asset that the cache holds.""" - hashes: dict[str, str] = {} - for name in names: - path = os.path.join(cache_dir, name) - if os.path.isfile(path): - digest = hashlib.sha1() - with open(path, "rb") as handle: - for chunk in iter(lambda: handle.read(1 << 20), b""): - digest.update(chunk) - hashes[name] = digest.hexdigest() - return hashes - - -def fetch_release() -> tuple[dict[str, int], str, dict[str, str]]: - """Name and size of every asset of the large-files release, its page, - and the sha256 it lists per asset.""" - result = subprocess.run( - [ - "gh", "release", "view", LARGE_FILES_RELEASE, - "-R", LARGE_FILES_REPO, "--json", "assets,body", - ], - capture_output=True, text=True, check=True, - ) - data = json.loads(result.stdout) - return ( - {a["name"]: a["size"] for a in data["assets"]}, - data.get("body", ""), - digests_of(data["assets"]), - ) - - -def fetch_assets() -> dict[str, int]: - """Name and size of every asset of the large-files release.""" - result = subprocess.run( - [ - "gh", "release", "view", LARGE_FILES_RELEASE, - "-R", LARGE_FILES_REPO, "--json", "assets", - ], - capture_output=True, text=True, check=True, - ) - return {a["name"]: a["size"] for a in json.loads(result.stdout)["assets"]} def main() -> int: diff --git a/scripts/commit_rules.py b/scripts/commit_rules.py index 1da6d7b1b..7978f2dd3 100644 --- a/scripts/commit_rules.py +++ b/scripts/commit_rules.py @@ -11,44 +11,10 @@ Usage as a hook: python scripts/commit_rules.py MESSAGE_FILE from __future__ import annotations import argparse -import re import sys from pathlib import Path -MAX_SUBJECT = 50 -SUBJECT_TYPES = re.compile(r"^(feat|refactor|chore|docs|fix): [a-z0-9]") -REFUSED_WORDS = re.compile( - r"\b(bug|regression|revert|dead code|broken|wrong|hack|workaround|" - r"comprehensive|implement)", - re.IGNORECASE, -) -# A numbered pointer at a private review ("audit 24", "review 3", "round 5") -# names notes no clone holds. tests/test_prose_style.py refuses the same tags -# in tracked files, and history cannot be rewritten once pushed. -REVIEW_TAG = re.compile( - r"\b(audit|review|round|batch|finding)s? #?\d+|\baudit (batch|findings?)\b" - r"|[a-z]+_audit_\d+", - re.IGNORECASE, -) -CO_AUTHOR = re.compile(r"^co-authored-by", re.IGNORECASE | re.MULTILINE) - - -def problems(message: str) -> list[str]: - """What this repository refuses in a commit message, first line first.""" - found = [] - subject = message.split("\n", 1)[0] - if len(subject) > MAX_SUBJECT: - found.append(f"subject is {len(subject)} characters, {MAX_SUBJECT} at most: {subject}") - if not SUBJECT_TYPES.match(subject): - found.append("subject must read 'type: description' (feat, refactor, chore, docs, fix)") - text = "\n".join(line for line in message.splitlines() if not line.startswith("#")) - if REFUSED_WORDS.search(text): - found.append("the message uses a word this repository's history does not carry") - if REVIEW_TAG.search(text): - found.append("say what the change does, not which review asked for it") - if CO_AUTHOR.search(message): - found.append("no Co-Authored-By trailer here") - return found +from devtools.commitrules import problems def main(argv: list[str]) -> int: diff --git a/scripts/devtools/__init__.py b/scripts/devtools/__init__.py new file mode 100644 index 000000000..db033d87a --- /dev/null +++ b/scripts/devtools/__init__.py @@ -0,0 +1 @@ +"""The repository's own rules: commit messages and the checks CI runs on a pull request.""" diff --git a/scripts/devtools/commitrules.py b/scripts/devtools/commitrules.py new file mode 100644 index 000000000..665a83616 --- /dev/null +++ b/scripts/devtools/commitrules.py @@ -0,0 +1,41 @@ +"""Commit message rules of this repository, in one place.""" + +from __future__ import annotations + +import re + + +MAX_SUBJECT = 50 +SUBJECT_TYPES = re.compile(r"^(feat|refactor|chore|docs|fix): [a-z0-9]") +REFUSED_WORDS = re.compile( + r"\b(bug|regression|revert|dead code|broken|wrong|hack|workaround|" + r"comprehensive|implement)", + re.IGNORECASE, +) +# A numbered pointer at a private review ("audit 24", "review 3", "round 5") +# names notes no clone holds. tests/test_prose_style.py refuses the same tags +# in tracked files, and history cannot be rewritten once pushed. +REVIEW_TAG = re.compile( + r"\b(audit|review|round|batch|finding)s? #?\d+|\baudit (batch|findings?)\b" + r"|[a-z]+_audit_\d+", + re.IGNORECASE, +) +CO_AUTHOR = re.compile(r"^co-authored-by", re.IGNORECASE | re.MULTILINE) + + +def problems(message: str) -> list[str]: + """What this repository refuses in a commit message, first line first.""" + found = [] + subject = message.split("\n", 1)[0] + if len(subject) > MAX_SUBJECT: + found.append(f"subject is {len(subject)} characters, {MAX_SUBJECT} at most: {subject}") + if not SUBJECT_TYPES.match(subject): + found.append("subject must read 'type: description' (feat, refactor, chore, docs, fix)") + text = "\n".join(line for line in message.splitlines() if not line.startswith("#")) + if REFUSED_WORDS.search(text): + found.append("the message uses a word this repository's history does not carry") + if REVIEW_TAG.search(text): + found.append("say what the change does, not which review asked for it") + if CO_AUTHOR.search(message): + found.append("no Co-Authored-By trailer here") + return found diff --git a/scripts/devtools/prchecks.py b/scripts/devtools/prchecks.py new file mode 100644 index 000000000..a1e7efc4b --- /dev/null +++ b/scripts/devtools/prchecks.py @@ -0,0 +1,99 @@ +"""The checks validate.yml runs on a pull request, in its order.""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import sys +from dataclasses import dataclass, field + +from core.paths import REPO_ROOT + + +ROOT = REPO_ROOT + + +@dataclass(frozen=True) +class Step: + command: str + why: str + needs: str = "" + provider: str = "" + env: dict[str, str] = field(default_factory=dict) + # validate.yml marks the step continue-on-error: its failure is shown + # and does not fail the run. + may_fail: bool = False + + +# The order of validate.yml: data fetched, site generated and built, then the +# suite, its 3.8 run and the built-site check. +STEPS: tuple[Step, ...] = ( + Step("python scripts/validate_pr.py --changed", "the BIOS files the branch adds"), + Step("python scripts/validate_schemas.py --source-only", "profiles and platform files"), + Step("mypy", "no type error in install.py, installer/ and scripts/", needs="mypy", + provider='pip install -e ".[dev]"'), + Step("ruff check .", "the lint rules of pyproject.toml", needs="ruff", + provider='pip install -e ".[dev]"'), + Step("python scripts/build_installer.py --check", "install.py is the one installer/ builds"), + Step("python scripts/profile_sync.py --added --strict", "each profile the branch adds"), + Step("vermin --no-tips -t=3.8- --violations install.py installer", "the installer stays on Python 3.8", + needs="vermin", provider="the pip line of CONTRIBUTING.md"), + Step("shellcheck --version", "the launcher test runs shellcheck", needs="shellcheck", + provider="the shellcheck package"), + Step("python scripts/export_native.py --all --refresh-cache", + "files the exporter tests compare with"), + Step("python scripts/refresh_data_dirs.py", "data directories the pack-building tests read"), + Step("python scripts/generate_site.py", "the pages the site tests read"), + Step("npm ci --prefix website", "the site's packages, Node 24", + needs="npm", provider="Node 24"), + # Node's compile cache lands in /tmp, a 4 GB tmpfs here: one build + # filled it and every later command failed with ENOSPC. + Step("npm run build --prefix website", "the built site", + needs="npm", provider="Node 24", env={"NODE_DISABLE_COMPILE_CACHE": "1"}), + Step("python scripts/run_tests.py --jobs 4", "the suite, one process per module", + env={"RETROBIOS_OFFLINE": "1"}), + Step("python3.8 -m unittest tests.test_install_tui", "the full screen on the installer's floor", + needs="python3.8", provider="a Python 3.8 with pyte", + env={"RETROBIOS_OFFLINE": "1"}), + Step("python scripts/validate_site.py --site-dir website/dist", "links and page budgets"), +) + + +def argv(command: str) -> list[str]: + """The command, with `python` run by the interpreter running this script.""" + words = command.split() + return [sys.executable, *words[1:]] if words[0] == "python" else words + + +def shown(step: Step) -> str: + return step.command + + +def execute(step: Step) -> int: + env = {**os.environ, **step.env} + return subprocess.run(argv(step.command), cwd=ROOT, env=env, check=False).returncode + + +def run(steps: tuple[Step, ...] = STEPS) -> int: + failed: list[str] = [] + allowed: list[str] = [] + not_run: list[str] = [] + for step in steps: + print(f"\n== {shown(step)}", flush=True) + if step.needs and shutil.which(step.needs) is None: + print(f"not run: {step.needs} is not installed ({step.provider})") + not_run.append(f"{shown(step)} ({step.needs}: {step.provider})") + continue + code = execute(step) + if code: + (allowed if step.may_fail else failed).append(f"{shown(step)} (exit {code})") + print() + for line in failed: + print(f"FAILED {line}") + for line in allowed: + print(f"FAILED {line}, continue-on-error in CI as well") + for line in not_run: + print(f"NOT RUN {line}") + print(f"{len(steps) - len(failed) - len(allowed) - len(not_run)}/{len(steps)} checks passed") + return 1 if failed else 0 diff --git a/scripts/generate_event_schema.py b/scripts/generate_event_schema.py index e0f973e50..7705e2542 100644 --- a/scripts/generate_event_schema.py +++ b/scripts/generate_event_schema.py @@ -8,96 +8,11 @@ from __future__ import annotations import argparse -import importlib.util -import json import sys from pathlib import Path from core.artifacts import write_text_atomic -from core.paths import REPO_ROOT - -ROOT = REPO_ROOT -OUTPUT = ROOT / "schemas" / "install-events.schema.json" - -_spec = importlib.util.spec_from_file_location("install", ROOT / "install.py") -if _spec is None or _spec.loader is None: - raise ImportError(f"cannot load {ROOT / 'install.py'}") -_install = importlib.util.module_from_spec(_spec) -_spec.loader.exec_module(_install) - -EVENT_KEYS: dict[str, tuple[str, ...]] = _install.EVENT_KEYS -EVENT_SCHEMA: int = _install.EVENT_SCHEMA - -_TEXT = {"type": "string"} -_COUNT = {"type": "integer", "minimum": 0} -_FLAG = {"type": "boolean"} -_NAMES = {"type": "array", "items": {"type": "string"}} -_RECORDS = {"type": "array", "items": {"type": "object"}} - -# The JSON type of each key, whatever kind carries it. A key EVENT_KEYS -# gains without a line here stops the generator. -KEY_TYPES: dict[str, dict] = { - **dict.fromkeys(( - "installer", "os", "os_name", "stage", "reason", "platform", "message", - "folder", "dest", "system", "name", "bios_dir", "path", "member", - "list_version", "installed_version", "board", "core", "date", "moved_to", - ), _TEXT), - "mode": {"enum": ["install", "check", "dry-run", "list", "remove", "restore", "pack"]}, - "source": {"enum": ["remove", "install"]}, - "state": {"enum": ["present", "wrong_hash", "missing"]}, - "status": {"enum": ["applied", "written", "unreadable", "not_written", "listed", "made", - "deleted", "not_deleted", "planned", "failed"]}, - **dict.fromkeys(( - "files", "files_done", "files_total", "bytes", "bytes_done", "bytes_total", - "bytes_local", "bytes_network", "size", "present", "missing", "wrong_hash", - "bytes_needed", "data_missing", "not_installable", "installed", "up_to_date", - "pending", "code", "games", "recognised", "not_games", "gone", - ), _COUNT), - **dict.fromkeys(("truncated", "ok", "interrupted", "required_only", "applied", "info", - "backup"), _FLAG), - **dict.fromkeys(("systems", "other_drives", "dests", "written", "choice", "parts"), - _NAMES), - **dict.fromkeys(("platforms", "failed", "skipped", "left_out", "kept", "found", - "fallback"), _RECORDS), -} - - -def _kind(kind: str, keys: tuple[str, ...]) -> dict: - properties: dict[str, dict] = {"event": {"const": kind}} - for key in keys: - properties[key] = ( - {"const": EVENT_SCHEMA} if (kind, key) == ("start", "schema") else KEY_TYPES[key] - ) - return { - "type": "object", - "additionalProperties": False, - "required": ["event", *keys], - "properties": properties, - } - - -def build_schema() -> dict: - """One line of the stream: an object of one of the kinds, with exactly its keys.""" - return { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://abdess.github.io/retrobios/api/v1/schemas/install-events.schema.json", - "title": "RetroBIOS installer event", - "description": ( - f"One line of install.py --events, event schema {EVENT_SCHEMA}. Written from " - "EVENT_KEYS in install.py by scripts/generate_event_schema.py. The schema " - "gains kinds, never keys on an existing kind: a reader skips a kind it " - "does not know." - ), - "type": "object", - "required": ["event"], - "properties": {"event": {"enum": list(EVENT_KEYS)}}, - "oneOf": [{"$ref": f"#/$defs/{kind}"} for kind in EVENT_KEYS], - "$defs": {kind: _kind(kind, keys) for kind, keys in EVENT_KEYS.items()}, - } - - -def render(schema: dict) -> str: - return json.dumps(schema, indent=2, ensure_ascii=False) + "\n" +from installer_build.eventschema import OUTPUT, build_schema, render def main(argv: list[str] | None = None) -> int: diff --git a/scripts/generate_games_index.py b/scripts/generate_games_index.py index 20beeb499..2a8616ad9 100644 --- a/scripts/generate_games_index.py +++ b/scripts/generate_games_index.py @@ -48,13 +48,7 @@ from model.platforms import load_platform_config, native_layer from core.artifacts import repository_output_lock from core.cli import run_cli from model.region import normalize_declared -from romfolders import ( - ProfileResolver, - Resolution, - SystemResolver, - folder_names, - load_setups, -) +from model.romfolders import ProfileResolver, Resolution, SystemResolver, folder_names, load_setups from core.artifacts import write_text_atomic from model.safeparse import yaml_load diff --git a/scripts/generate_installer_doc.py b/scripts/generate_installer_doc.py index a16af81c4..174d86e64 100644 --- a/scripts/generate_installer_doc.py +++ b/scripts/generate_installer_doc.py @@ -29,645 +29,12 @@ to the next. from __future__ import annotations import argparse -import ast -import contextlib -import http.server -import importlib.util -import json -import os -import re -import shutil -import socket -import socketserver -import subprocess import sys -import tempfile -import threading -import zipfile -from pathlib import Path, PurePosixPath -from typing import TYPE_CHECKING, Any, Callable +from pathlib import Path -from sitegen import handheld as sitehandheld from core.artifacts import write_text_atomic -from core.paths import REPO_ROOT -if TYPE_CHECKING: - from install import LocalCopy, Progress, _OsRule - -ROOT = REPO_ROOT -PAGE = ROOT / "wiki" / "installer.md" -INSTALLER = ROOT / "install.py" - -_spec = importlib.util.spec_from_file_location("install", INSTALLER) -if _spec is None or _spec.loader is None: - raise ImportError(f"cannot load {INSTALLER}") -_install = importlib.util.module_from_spec(_spec) -_spec.loader.exec_module(_install) - -BLOCK = re.compile( - r"(?P\n)(?P.*?)" - r"(?P)", re.S) -_CELL = re.compile(r"(? list[str]: - return [cell.strip() for cell in _CELL.split(line.strip().strip("|"))] - - -def _rows(body: str) -> list[list[str]]: - lines = [line for line in body.splitlines() if line.startswith("|")] - return [_cells(line) for line in lines[2:]] - - -def _prose(body: str, key: re.Pattern[str], width: int) -> dict[str, list[str]]: - """The prose cells of each row, by the key its first cell holds.""" - kept = {} - for cells in _rows(body): - found = key.search(cells[0]) - if found: - kept[found.group(1)] = (cells[1:] + [""] * width)[:width] - return kept - - -def _table(heading: list[str], rows: list[list[str]]) -> str: - lines = ["| " + " | ".join(heading) + " |", - "|" + "|".join("-" * (len(cell) + 2) for cell in heading) + "|"] - lines += ["| " + " | ".join(row) + " |" for row in rows] - return "\n".join(lines) + "\n" - - -def _with_prose(name: str, facts: list[tuple[str, str]], body: str, key: str, - width: int) -> list[list[str]]: - """Each row's first cell from install.py, the rest from the page, whose - last cell must be written.""" - prose = _prose(body, re.compile(key), width) - missing = [fact for fact, _cell in facts if not prose.get(fact, [""])[-1]] - if missing: - raise MissingProse(f"{name}: no text for {', '.join(missing)}") - return [[cell, *prose[fact]] for fact, cell in facts] - - -def option_rows(body: str) -> list[list[str]]: - facts = [] - # argparse's own --help last, after the options of the run. - for action in sorted(_install.build_parser()._actions, - key=lambda action: isinstance(action, argparse._HelpAction)): - flags = sorted(action.option_strings, key=lambda flag: not flag.startswith("--")) - metavar = "" if action.nargs == 0 else (action.metavar or action.dest.upper()) - shown = ", ".join(f"`{flag} {metavar}`" if metavar else f"`{flag}`" for flag in flags) - facts.append((flags[0], f'{shown}')) - return _with_prose("options", facts, body, r"`(--[a-z-]+)", 1) - - -def exit_codes() -> list[int]: - """The codes install.py exits with: its sys.exit calls, 0 for a run - that returns, 2 for an option argparse refuses.""" - codes = {0, 2} - for node in ast.walk(ast.parse(INSTALLER.read_text(encoding="utf-8"))): - if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) - and node.func.attr == "exit" and getattr(node.func.value, "id", "") == "sys" - and node.args): - continue - given = node.args[0] - for value in ((given.body, given.orelse) if isinstance(given, ast.IfExp) else (given,)): - if isinstance(value, ast.Constant) and isinstance(value.value, int): - codes.add(value.value) - return sorted(codes) - - -def exit_rows(body: str) -> list[list[str]]: - facts = [(str(code), f"`{code}`") for code in exit_codes()] - return _with_prose("exit-codes", facts, body, r"`(\d+)`", 1) - - -def event_rows(body: str) -> list[list[str]]: - facts = [(kind, f"`{kind}`") for kind in _install.EVENT_KEYS] - rows = _with_prose("events", facts, body, r"`([a-z_]+)`", 2) - for row, keys in zip(rows, _install.EVENT_KEYS.values()): - row[1] = ", ".join(f"`{key}`" for key in keys) - return rows - - -def pad_rows(body: str) -> list[list[str]]: - facts = [(route, f"`{route}`") for route in _install.TUI_PAD_ROUTES] - return _with_prose("pad-routes", facts, body, r"`([a-z_]+)`", 2) - - -def route_keys() -> str: - routes = _install.TUI_ROUTES - actions = list(next(iter(routes.values())).help) - unnamed = [action for action in actions if action not in ACTIONS] - if unnamed or any(list(route.help) != actions for route in routes.values()): - raise MissingProse(f"route-keys: TUI_ROUTES actions {unnamed or 'differ by route'} " - "need a name in ACTIONS") - heading = ["Action", *(ROUTE_HEADINGS.get(name, f"`{name}`") for name in routes)] - rows = [[ACTIONS[action], *(route.help[action] or "none" for route in routes.values())] - for action in actions] - return _table(heading, rows) - - -# Card markers that are files with no extension: the MiSTer binary. -_BARE_FILES = frozenset({"MiSTer"}) - - -def _marker(rule: _OsRule) -> str: - """A card rule's evidence in words: the file or folder, and the line it - holds for a rule that reads one.""" - if rule.method == "file_matches": - path, pattern = rule.values - line = re.sub(r"\\s\*\$$", "", re.sub(r"^(\^|\\A)", "", pattern)).replace("\\", "") - return f"`{path}` holding the line `{line}`" - named = ", ".join(f"`{value}`" if PurePosixPath(value).suffix or value in _BARE_FILES - else f"`{value}/`" for value in rule.values) - if rule.method == "games_part": - # Told on the games part beside its bios folder, on a drive the - # system does not call fixed (install.games_part). - return f"{named} beside `bios/`, on a drive that is not a fixed disk" - return named - - -def _list_words(plat: str) -> str: - name = _install.display_name(plat) - return f"{name}'{'' if name.endswith('s') else 's'} list" - - -def card_marker_rows() -> list[list[str]]: - """The files that name a card or a SHARE drive, in the order they are - read: install.py's card rules, then its SHARE drive files.""" - rows = [[_marker(rule), rule.name, - f"`{rule.bios or 'bios'}`, {_list_words(rule.manifest)}"] - for rule in _install._card_rules()] - hostname = "system.hostname=BATOCERA" - for plat, marker in _install._SHARE_DRIVES: - name = _install.display_name(plat) - evidence = (f"`{marker}` holding `{hostname}` or no hostname line, and no KNULLI file " - "above" if plat == "batocera" else f"`{marker}`") - rows.append([evidence, f"{name} SHARE drive", f"`bios`, {_list_words(plat)}"]) - rows.append([f"`{_install._SHARE_DRIVES[0][1]}` with any other hostname, and no KNULLI " - "file above, or the files of two SHARE drives", - "named by neither: the run says which systems it could be", - "the folder of the system named with `--platform`"]) - return rows - - -# The folder the line menu example names: a home that is no one's. -MENU_FOLDER = "/home/me/.config/retroarch/system" - - -def line_menu() -> str: - """The line menu of a RetroArch run, g then Enter pressed, as install.py - prints it for the RetroArch list (install/retroarch.json): the very - function line mode runs, its questions answered here. The page carried - a copy typed by hand, whose keys and counts drifted from the installer.""" - import io - from unittest import mock - - manifest = json.loads((ROOT / "install" / "retroarch.json").read_text(encoding="utf-8")) - files = [*manifest["files"], *(manifest.get("case_variants") or [])] - folder = Path(MENU_FOLDER) - out = io.StringIO() - answers = iter(["g", ""]) - - def answer(prompt: str) -> str: - given = next(answers) - print(f"{prompt}{given}".rstrip()) - return given - - invocation = _install.Invocation() - invocation.os_type = "linux" - environment = {key: value for key, value in os.environ.items() - if key not in (_install.OFFLINE_VARIABLE, "RETROBIOS_BOOTSTRAP")} - with mock.patch.dict(os.environ, environment, clear=True), \ - mock.patch.object(_install, "_INVOCATION", invocation), \ - mock.patch.object(_install, "_ask", answer), \ - mock.patch.object(_install, "folder_warnings", return_value=[]), \ - contextlib.redirect_stdout(out): - cut = [False] - - def command(choice: object) -> str: - invocation.chosen["retroarch"] = ( - (_install.chosen_flags(choice) if choice is not None else []) - + ([("--no-game-data", None)] if cut[0] else [])) - return invocation.command("retroarch", folder) - - context = _install.MenuContext( - "retroarch", files, manifest.get("omitted_files") or [], name="RetroArch", - data_trees=manifest.get("data_directories") or [], bios_path=folder, - manifest=manifest) - _install._prompt_custom_selection( - context, choosable=_install.records_selection(files), command=command, cut=cut) - return "```\n" + out.getvalue().strip("\n") + "\n```" - - -# The home and the card the run samples show, in place of the sandbox's. -SHOWN_HOME = "/home/me" -SHOWN_CARD = "" -RETROARCH_CFG = ('system_directory = "~/.config/retroarch/system"\n' - 'savefile_directory = "~/.config/retroarch/saves"\n') - - -class _ListHandler(http.server.SimpleHTTPRequestHandler): - """Serves the committed file lists, install/.json, and nothing - else: a sample that asks for a file is a sample that downloads.""" - - def __init__(self, request: socket.socket | tuple[bytes, socket.socket], - client_address: tuple[str, int], server: socketserver.BaseServer) -> None: - super().__init__(request, client_address, server, directory=str(ROOT)) - - def do_GET(self) -> None: - if not re.fullmatch(r"/install/[a-z0-9_-]+\.json", self.path): - self.send_error(404) - return - super().do_GET() - - def log_message(self, *_args: object) -> None: - return - - -class _LoopbackServer(http.server.ThreadingHTTPServer): - """The list server, named by its number: HTTPServer.server_bind looks - 127.0.0.1 up with socket.getfqdn, a DNS query wherever /etc/hosts does - not name it.""" - - def server_bind(self) -> None: - socketserver.TCPServer.server_bind(self) - host, port = self.server_address[:2] - if not isinstance(host, str): - raise TypeError(f"the list server needs a host name, not {host!r}") - self.server_name, self.server_port = host, port - - -# The list the reasons and the copy are shown with: four files, each with -# the contents its name says, read as RetroArch's. -SMALL_LIST = { - "scph5500.bin": (b"J" * 64, ["sony-playstation"], ["japan"], None), - "scph5501.bin": (b"U" * 64, ["sony-playstation"], ["north-america"], - ["beetle_psx", "pcsx_rearmed"]), - "gba_bios.bin": (b"G" * 32, ["nintendo-gba"], None, ["mgba"]), - "pcsx/extra.bin": (b"E" * 8, ["sony-playstation"], None, ["pcsx_rearmed"]), -} - - -def write_small_list(path: Path) -> None: - import hashlib - - files = [] - for dest, (data, systems, regions, cores) in SMALL_LIST.items(): - files.append({"dest": dest, "size": len(data), "sha1": hashlib.sha1(data).hexdigest(), - "sha256": hashlib.sha256(data).hexdigest(), - "md5": hashlib.md5(data).hexdigest(), "systems": systems, - "cores": cores, "repo_path": f"bios/{dest}", - **({"regions": regions} if regions else {})}) - path.write_text(json.dumps({ - "manifest_version": 2, "platform": "retroarch", "display_name": "RetroArch", - "base_destination": "system", "files": files, "total_files": len(files), - "total_size": sum(entry["size"] for entry in files)}), encoding="utf-8") - - -def _child(spec: dict) -> int: - """install.main() as the sample runs it, in its own process. Only the - transport and the machine are stood in for: no connection leaves the - loopback, detection finds the card folder the spec names, a file or a - data tree of a landed run reports its bytes written without fetching - them, and a held run finds every file and tree in place. The counts, - sizes and words are the installer's own.""" - import concurrent.futures - from unittest import mock - - real_connect = socket.create_connection - - # The rest of the arguments are create_connection's own, passed through. - def loopback_only(address: tuple[str, int], *args: Any, **kwargs: Any) -> socket.socket: - if address[0] not in ("127.0.0.1", "localhost"): - raise OSError(f"the sample makes no request to {address[0]}") - return real_connect(address, *args, **kwargs) - - real_download = _install._download_one - - def landed(f: dict, bios: Path, verbose: bool = False, progress: Progress | None = None, - copy: LocalCopy | None = None) -> tuple[str, bool, str]: - if copy is not None: - # A copy from this machine is made for real: it is local. - return real_download(f, bios, verbose, progress, copy) - if progress is not None: - progress.add(f["size"]) - return f["dest"], True, "" - - def held(files: list[dict], _bios: Path, **_kwargs: object) -> tuple: - return [], list(files), [] - - def tree_landed(entry: dict, _bios: Path, state: object = None, - _progress: object = None) -> dict: - return {"present": 0, "installed": len(entry["files"]), "changed": 0, - "absent": 0, "error": "", "not_kept": []} - - def tree_held(entry: dict, bios: Path, remember: bool = False) -> tuple: - return bios / entry.get("dest", ""), {}, len(entry["files"]) - - patches: list[contextlib.AbstractContextManager[object]] = [ - mock.patch.object(socket, "create_connection", loopback_only), - # One worker and the submission order: the progress lines of a log. - mock.patch.object(concurrent.futures, "as_completed", list), - mock.patch.object(sys, "argv", ["install.py", *spec["argv"]]), - ] - if spec.get("card"): - patches += [ - mock.patch.object(_install, "detect_platforms", - lambda _os: [(spec["platform"], Path(spec["card"]))]), - mock.patch.object(_install, "_mounted_cards", list), - ] - if spec.get("landed"): - patches.append(mock.patch.object(_install, "_download_one", landed)) - patches.append(mock.patch.object(_install, "install_data_directory", tree_landed)) - if spec.get("held"): - patches.append(mock.patch.object(_install, "check_local", held)) - patches.append(mock.patch.object(_install, "data_directory_state", tree_held)) - with contextlib.ExitStack() as stack: - for patch in patches: - stack.enter_context(patch) - try: - _install.main() - except SystemExit as exc: - return exc.code if isinstance(exc.code, int) else 1 - return 0 - - -# What the process of a run sample executes, the spec as its one argument. -CHILD = ("import json, sys; sys.path.insert(0, 'scripts'); import generate_installer_doc; " - "sys.exit(generate_installer_doc._child(json.loads(sys.argv[1])))") - - -class Sandbox: - """A home with a RetroArch config and a card folder, under tmp/, and the - committed file lists served on the loopback. Every run sample of the page - is printed here.""" - - def __enter__(self) -> Sandbox: - (ROOT / "tmp").mkdir(exist_ok=True) - self.root = Path(tempfile.mkdtemp(prefix="installer-doc-", dir=ROOT / "tmp")) - self.home = self.root / "home" - self.card = self.root / "card" - config = self.home / ".config" / "retroarch" / "retroarch.cfg" - config.parent.mkdir(parents=True) - config.write_text(RETROARCH_CFG, encoding="utf-8") - self.server = _LoopbackServer(("127.0.0.1", 0), _ListHandler) - threading.Thread(target=self.server.serve_forever, daemon=True).start() - return self - - def __exit__(self, *_exc: object) -> None: - self.server.shutdown() - self.server.server_close() - shutil.rmtree(self.root) - - def small(self, kind: str) -> str: - """A run over SMALL_LIST in a home of its own: "refused", a --check - of a folder holding a copy of each kind a check names, or "from", a - run copying from an old card what it holds and downloading the rest.""" - home = self.root / kind - system = home / ".config" / "retroarch" / "system" - system.mkdir(parents=True) - (system.parent / "retroarch.cfg").write_text(RETROARCH_CFG, encoding="utf-8") - listed = home / "list.json" - write_small_list(listed) - data = {dest: entry[0] for dest, entry in SMALL_LIST.items()} - if kind == "refused": - (system / "scph5500.bin").write_bytes(data["scph5500.bin"]) - (system / "scph5501.bin").write_bytes(data["scph5500.bin"]) - (system / "system").mkdir() - (system / "system" / "gba_bios.bin").write_bytes(data["gba_bios.bin"]) - with zipfile.ZipFile(system / "PSX BIOS.zip", "w") as archive: - archive.writestr("extra.bin", data["pcsx/extra.bin"]) - # A check that flags a file ends on 3, as documented. - return self.run("retroarch", "--check", "--verbose", "--manifest", str(listed), - home=home, codes=(3,)) - old = home / "old" - old.mkdir() - for dest in ("scph5500.bin", "scph5501.bin"): - (old / dest).write_bytes(data[dest]) - return self.run("retroarch", "--yes", "--verbose", "--manifest", str(listed), - "--from", str(old), home=home, landed=True) - - def run(self, platform: str, *argv: str, landed: bool = False, - held: bool = False, home: Path | None = None, codes: tuple = (0,)) -> str: - """What install.py prints for the run, the sandbox read as a user's - home and card.""" - home = home or self.home - card = self.card / "userdata" / "bios" if platform != "retroarch" else None - if card is not None: - card.mkdir(parents=True, exist_ok=True) - args = ["--plain", "--platform", platform, *argv] - spec = {"platform": platform, "argv": args, - "card": str(card) if card else None, "landed": landed, "held": held} - env = {"PATH": os.environ.get("PATH", ""), "HOME": str(home), - "RETROBIOS_OS": "linux", "LANG": "C.UTF-8", - "RETROBIOS_BASE_URL": f"http://127.0.0.1:{self.server.server_address[1]}"} - done = subprocess.run( - [sys.executable, "-s", "-c", CHILD, json.dumps(spec)], - cwd=ROOT, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, - check=False) - if done.returncode not in codes: - raise SampleFailed(f"install.py {' '.join(args)} exited " - f"{done.returncode}: {done.stderr.strip()[-2000:]}") - return done.stdout.replace(str(home), SHOWN_HOME).replace(str(self.card), SHOWN_CARD) - - -# The runs printed in this process, by what they read: the page is rendered -# more than once by --check and by the tests, from the same installer and lists. -_RUNS: dict[tuple, str] = {} - - -def _stamp(platform: str) -> tuple[int, int]: - return (hash(INSTALLER.read_bytes()), - hash((ROOT / "install" / f"{platform}.json").read_bytes())) - - -class _LazySandbox: - """A Sandbox opened at the first run a rendering asks for, and only then.""" - - def __init__(self, stack: contextlib.ExitStack) -> None: - self.stack = stack - self.box: Sandbox | None = None - - def run(self, platform: str, *argv: str, landed: bool = False, held: bool = False) -> str: - key = (platform, argv, landed, held, _stamp(platform)) - if key in _RUNS: - return _RUNS[key] - if self.box is None: - self.box = self.stack.enter_context(Sandbox()) - _RUNS[key] = self.box.run(platform, *argv, landed=landed, held=held) - return _RUNS[key] - - def small(self, kind: str) -> str: - key = ("small", kind, _stamp("retroarch")) - if key not in _RUNS: - if self.box is None: - self.box = self.stack.enter_context(Sandbox()) - _RUNS[key] = self.box.small(kind) - return _RUNS[key] - - -class SampleFailed(Exception): - """A run sample install.py could not print.""" - - -def _lines_from(text: str, first: str, last: str | None = None, count: int | None = None - ) -> list[str]: - """The lines of a run from the one starting with first, through the one - starting with last or for count lines.""" - lines = text.splitlines() - start = next((i for i, line in enumerate(lines) if line.startswith(first)), None) - if start is None: - raise SampleFailed(f"the run printed no line starting {first!r}") - if count is not None: - return lines[start:start + count] - if last is None: - raise ValueError("_lines_from needs last or count") - end = next((i for i in range(start, len(lines)) if lines[i].startswith(last)), None) - if end is None: - raise SampleFailed(f"the run printed no line starting {last!r} after {first!r}") - return lines[start:end + 1] - - -def _fenced(lines: list[str]) -> str: - return "```\n" + "\n".join(lines) + "\n```" - - -def list_date(platform: str) -> str: - """The day the committed list was generated, which dates its samples.""" - manifest = json.loads((ROOT / "install" / f"{platform}.json").read_text(encoding="utf-8")) - return manifest["generated"][:10] - - -# The platform of the run walked through under Reading a run. -WALKTHROUGH = "batocera" -# A system of the RetroArch list one core pulls most of: the sample of the -# line naming it. A list where it no longer does fails the rendering, and -# another system is named here. -BULK_SYSTEM = "sony-playstation" - - -def _bulk_line(box: Sandbox | _LazySandbox) -> str: - run = box.run("retroarch", "--dry-run", "--verbose", "--system", BULK_SYSTEM) - found = [line for line in run.splitlines() if re.match(r" \S+ pulls ", line)] - if len(found) != 1: - raise SampleFailed(f"a RetroArch run with --system {BULK_SYSTEM} names no core " - "pulling most of its download: name another BULK_SYSTEM") - return found[0] - - -def sample_writers(box: Sandbox | _LazySandbox) -> dict[str, Callable[[str], str]]: - """The run samples, each from the run that prints it: the walk through a - run reads its --verbose lines, the default sample the lines it hides them - from.""" - def default_run() -> str: - return box.run(WALKTHROUGH, "--yes", "--jobs", "1", landed=True) - - def install_run() -> str: - return box.run(WALKTHROUGH, "--yes", "--jobs", "1", "--verbose", landed=True) - - def check_run() -> str: - return box.run(WALKTHROUGH, "--check", "--verbose", held=True) - - def dry_run() -> str: - return box.run("retroarch", "--dry-run", "--verbose") - - return { - "run-default": lambda _body: _fenced( - _lines_from(default_run(), "Installing ", "Next: ")), - "dry-run": lambda _body: ( - f"A RetroArch dry run into an empty folder, with the list of " - f"{list_date('retroarch')}, printed this:\n\n" - + _fenced(_lines_from(dry_run(), "Fetching file index", " 0 in place"))), - "run-date": lambda _body: ( - f"Each line a first install prints, and what it means. The run below is a\n" - f"{_install.display_name(WALKTHROUGH)} install into an empty folder, from the " - f"list of {list_date(WALKTHROUGH)}.\nThe figures change with each release."), - "run-first-lines": lambda _body: _fenced( - _lines_from(install_run(), "Looking for setups", " Found")), - "run-index": lambda _body: _fenced( - _lines_from(install_run(), "Fetching file index", " 0 in place")), - "run-download": lambda _body: _fenced( - _lines_from(install_run(), "Downloading ", count=4)), - "run-end": lambda _body: _fenced( - _lines_from(install_run(), "Done.", "To check this later")), - "bulk-hint": lambda _body: ( - f"RetroArch with `--system {BULK_SYSTEM}`, from the list of " - f"{list_date('retroarch')}:\n\n" - + _fenced([_bulk_line(box)])), - "run-check": lambda _body: _fenced( - _lines_from(check_run(), "Checking existing files", - " Every file on the list is in place")), - "check-refused": lambda _body: _fenced(_refused_lines(box.small("refused"))), - "from-run": lambda _body: _fenced( - _lines_from(box.small("from"), "Done.", count=2)), - } - - -def _refused_lines(text: str) -> list[str]: - """The files a check flags, each with its reason and where its cores read it.""" - lines = text.splitlines() - start = next((i for i, line in enumerate(lines) - if re.fullmatch(r" \d+ files? [a-z ]+\.", line)), None) - if start is None: - raise SampleFailed("the check printed no files not in place") - end = max(i for i, line in enumerate(lines) if line.lstrip().startswith("read by ")) - return lines[start:end + 1] - - -def render(page: str) -> str: - """The page with each marked table and run sample written from install.py.""" - writers = { - "options": lambda body: _table(["Option", "Effect"], option_rows(body)), - "exit-codes": lambda body: _table(["Code", "Meaning"], exit_rows(body)), - "events": lambda body: _table(["Kind", "Keys", "When"], event_rows(body)), - "pad-routes": lambda body: _table(["Value", "Input", "Set by"], pad_rows(body)), - "route-keys": lambda _body: route_keys(), - "card-markers": lambda _body: _table(["On the card", "System", "Files go to"], - card_marker_rows()), - "line-menu": lambda _body: line_menu(), - # Where each handheld launcher goes, written from the site's own - # description of it (sitehandheld.LAUNCHERS). - "handheld": lambda _body: "\n".join(sitehandheld.table_rows()), - "handheld-downloads": lambda _body: "\n".join(sitehandheld.download_rows()), - } - seen = [] - with contextlib.ExitStack() as stack: - box = _LazySandbox(stack) - writers.update(sample_writers(box)) - - def write(match: re.Match[str]) -> str: - name = match.group("name") - if name not in writers: - raise MissingProse(f"no table is written for the marker {name!r}") - seen.append(name) - table = writers[name](match.group("body")) - return f"{match.group('open')}\n{table}\n{match.group('close')}" - - text = BLOCK.sub(write, page) - absent = sorted(set(writers) - set(seen)) - if absent: - raise MissingProse(f"markers missing from the page: {', '.join(absent)}") - return text +from installer_build.installerdoc import MissingProse, PAGE, SampleFailed, render def main(argv: list[str] | None = None) -> int: diff --git a/scripts/generate_launcher_index.py b/scripts/generate_launcher_index.py index 2046362c1..b493d4137 100644 --- a/scripts/generate_launcher_index.py +++ b/scripts/generate_launcher_index.py @@ -16,92 +16,11 @@ place on the card. Where each system's files go is install.py's APP_PLACES. from __future__ import annotations import argparse -import hashlib -import importlib.util -import json import sys from pathlib import Path from core.artifacts import write_text_atomic -from build_port import ( - BATOCERA_ZIP, - MUOS_APP, - REPO_ROOT, - TOOLS_ZIP, - _packs_table, - archive_members, - pinned_installer_sha256, -) - -OUTPUT = REPO_ROOT / "install" / "launchers" / "index.json" - -_spec = importlib.util.spec_from_file_location("install", REPO_ROOT / "install.py") -if _spec is None or _spec.loader is None: - raise ImportError(f"cannot load {REPO_ROOT / 'install.py'}") -_install = importlib.util.module_from_spec(_spec) -_spec.loader.exec_module(_install) - -# The archive whose members each system gets, by its key in APP_PLACES. -LAUNCHER_ARCHIVES = {"muos": MUOS_APP, "knulli": BATOCERA_ZIP, "rocknix": TOOLS_ZIP} - - -def _entry(field: str, name: str, source: Path | None, root: Path) -> dict: - """A member as the list records it: where it comes from, its size and - hash, and whether it is executable in the repository.""" - if source is None: - data = _packs_table(root) - origin: dict = {"content": data.decode("utf-8")} - executable = False - else: - data = source.read_bytes() - origin = {"repo_path": source.relative_to(root).as_posix()} - executable = bool(source.stat().st_mode & 0o111) - return {field: name, **origin, "size": len(data), - "sha256": hashlib.sha256(data).hexdigest(), "executable": executable} - - -def _member_bytes(entry: dict, root: Path) -> bytes: - if "content" in entry: - return entry["content"].encode("utf-8") - return (root / entry["repo_path"]).read_bytes() - - -def build_index(root: Path = REPO_ROOT) -> dict: - """Every launcher a card can carry, from the archives' members.""" - actual = hashlib.sha256((root / "install.py").read_bytes()).hexdigest() - if actual != pinned_installer_sha256(root): - raise ValueError("install.py is not the installer install.sh pins: re-pin the " - "bootstraps before writing the launcher list") - places = {place.key: place for place in _install.APP_PLACES.values()} - if set(places) != set(LAUNCHER_ARCHIVES): - raise ValueError(f"APP_PLACES names {sorted(places)}, the archives " - f"{sorted(LAUNCHER_ARCHIVES)}") - launchers: dict[str, dict] = {} - for key, archive in sorted(LAUNCHER_ARCHIVES.items()): - folder = places[key].folder - members = archive_members(archive, root) - if archive == MUOS_APP: - entries = [_entry("name", name, source, root) for name, source in members] - data = _install.app_archive([(entry, _member_bytes(entry, root)) - for entry in entries]) - launchers[key] = { - "archive": {"dest": f"{folder}/{archive}", "size": len(data), - "sha256": hashlib.sha256(data).hexdigest()}, - "members": entries, - } - else: - # Executable only where the menu starts the script as a program: - # a mode a FAT card cannot hold is refused by its driver. - files = [_entry("dest", f"{folder}/{name}", source, root) - for name, source in members] - for entry in files: - entry["executable"] = entry["executable"] and places[key].executable - launchers[key] = {"files": files} - return {"schema": _install.APP_SCHEMA, "launchers": launchers} - - -def render(index: dict) -> str: - return json.dumps(index, indent=2, ensure_ascii=False) + "\n" +from installer_build.launcherindex import OUTPUT, build_index, render def main(argv: list[str] | None = None) -> int: diff --git a/scripts/installer_build/__init__.py b/scripts/installer_build/__init__.py new file mode 100644 index 000000000..f4e97d6ed --- /dev/null +++ b/scripts/installer_build/__init__.py @@ -0,0 +1 @@ +"""What ships install.py: the build from installer/, the bootstrap pins, the handheld launchers, the PyPI package and the installer's generated files.""" diff --git a/scripts/installer_build/amalgamate.py b/scripts/installer_build/amalgamate.py new file mode 100644 index 000000000..c29961d13 --- /dev/null +++ b/scripts/installer_build/amalgamate.py @@ -0,0 +1,322 @@ +"""install.py joined from the modules of the installer/ package.""" + +from __future__ import annotations + +import ast +import heapq +import sys +from collections.abc import Iterator +from dataclasses import dataclass, field +from pathlib import Path + +from core.paths import REPO_ROOT + + +ROOT = REPO_ROOT +PACKAGE = "installer" +OUTPUT = "install.py" +COMMAND = "python scripts/build_installer.py" +SHEBANG = "#!/usr/bin/env python3\n" +NOTICE = ( + "# Generated by scripts/build_installer.py from the installer/ package. Edit\n" + "# the modules there and run the script: a change made here is overwritten.\n" +) +# C extensions a Python built without their libraries lacks. The installer +# imports them behind a guard that says so, instead of stopping on a +# ModuleNotFoundError traceback. +GUARDED = frozenset({"unicodedata", "zlib"}) +GUARD = ( + "# Built as C extensions that a Python compiled without their libraries\n" + "# lacks: the run stopped on a ModuleNotFoundError traceback.\n" + "try:\n" + "{imports}" + "except ImportError as _missing:\n" + ' print(f"Error: this Python was built without its {{_missing.name}} module, which "\n' + ' "the installer needs. Run it with another Python 3.8 or newer.", file=sys.stderr)\n' + " sys.exit(1)\n" +) +LINE_LENGTH = 120 +MARKER_WIDTH = 79 +_SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda, + ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp) + + +class BuildError(Exception): + """The package cannot be joined into one module.""" + + +@dataclass +class Module: + name: str + body: str + statements: list[ast.stmt] + plain: set[tuple[str, str | None]] = field(default_factory=set) + froms: set[tuple[str, str]] = field(default_factory=set) + imports: dict[str, set[str]] = field(default_factory=dict) + type_imports: dict[str, set[str]] = field(default_factory=dict) + defines: set[str] = field(default_factory=set) + + +def _is_docstring(node: ast.stmt) -> bool: + return (isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant) + and isinstance(node.value.value, str)) + + +def _is_type_checking_block(node: ast.stmt) -> bool: + return (isinstance(node, ast.If) and isinstance(node.test, ast.Name) + and node.test.id == "TYPE_CHECKING" and not node.orelse) + + +def _is_stdlib(module: str) -> bool: + return module.split(".")[0] in sys.stdlib_module_names + + +def _package_import(module: Module, node: ast.ImportFrom, where: str, type_only: bool) -> None: + """Record an import from another module of the package.""" + parts = (node.module or "").split(".") + if node.level or len(parts) != 2 or parts[0] != PACKAGE: + raise BuildError(f"{where}:{node.lineno}: import from {PACKAGE}. by its full name") + for alias in node.names: + if alias.asname and alias.asname != alias.name: + raise BuildError(f"{where}:{node.lineno}: {alias.name} imported as {alias.asname}: " + "one namespace keeps one name") + target = module.type_imports if type_only else module.imports + target.setdefault(parts[1], set()).update(alias.name for alias in node.names) + + +def _stdlib_import(module: Module, node: ast.Import | ast.ImportFrom, where: str) -> None: + if isinstance(node, ast.Import): + for alias in node.names: + if not _is_stdlib(alias.name): + raise BuildError(f"{where}:{node.lineno}: {alias.name} is not in the standard library") + module.plain.add((alias.name, alias.asname)) + return + for alias in node.names: + if alias.asname and alias.asname != alias.name: + raise BuildError(f"{where}:{node.lineno}: {alias.name} imported as {alias.asname}") + module.froms.add((node.module or "", alias.name)) + + +def _read_header(module: Module, header: list[ast.stmt], where: str) -> None: + for node in header: + if isinstance(node, ast.If): + for sub in node.body: + if not isinstance(sub, ast.ImportFrom): + raise BuildError(f"{where}:{sub.lineno}: a TYPE_CHECKING block holds imports only") + _package_import(module, sub, where, type_only=True) + elif isinstance(node, ast.ImportFrom) and node.module == "__future__": + continue + elif isinstance(node, ast.ImportFrom) and (node.level or not _is_stdlib(node.module or "")): + _package_import(module, node, where, type_only=False) + elif isinstance(node, (ast.Import, ast.ImportFrom)): + _stdlib_import(module, node, where) + + +def _check_nested_imports(statements: list[ast.stmt], where: str) -> None: + """Imports below the header are joined as written: inside functions, standard library only.""" + for statement in statements: + for node in ast.walk(statement): + if isinstance(node, ast.Import): + names = [alias.name for alias in node.names] + elif isinstance(node, ast.ImportFrom): + names = [node.module or "." * node.level] + else: + continue + for name in names: + if node.col_offset == 0 or not _is_stdlib(name): + raise BuildError(f"{where}:{node.lineno}: import {name} below the header " + "(module imports go first, nested ones from the standard library)") + + +def _header_length(tree: ast.Module, where: str) -> int: + """How many leading statements are the docstring, the imports and the TYPE_CHECKING block.""" + body = tree.body + if not body or not _is_docstring(body[0]): + raise BuildError(f"{where}: no module docstring") + count = 1 + while count < len(body) and (isinstance(body[count], (ast.Import, ast.ImportFrom)) + or _is_type_checking_block(body[count])): + count += 1 + future = any(isinstance(node, ast.ImportFrom) and node.module == "__future__" + and any(alias.name == "annotations" for alias in node.names) for node in body[:count]) + if not future: + raise BuildError(f"{where}: no 'from __future__ import annotations', which install.py holds") + return count + + +def _module_scope(node: ast.AST) -> Iterator[ast.AST]: + """The nodes of the module scope, the scopes it opens yielded but not entered.""" + stack = [node] + while stack: + current = stack.pop() + yield current + if current is not node and isinstance(current, _SCOPES): + continue + if isinstance(current, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)): + continue + stack.extend(ast.iter_child_nodes(current)) + + +def _defined_names(statements: list[ast.stmt]) -> set[str]: + names: set[str] = set() + for statement in statements: + for node in _module_scope(statement): + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + names.add(node.name) + elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store): + names.add(node.id) + elif isinstance(node, ast.ExceptHandler) and node.name: + names.add(node.name) + return names + + +def read_module(path: Path) -> Module: + where = f"{PACKAGE}/{path.name}" + source = path.read_text(encoding="utf-8") + tree = ast.parse(source, filename=where) + count = _header_length(tree, where) + lines = source.splitlines(keepends=True) + start = tree.body[count - 1].end_lineno or 0 + module = Module(path.stem, "".join(lines[start:]).strip("\n"), tree.body[count:]) + _read_header(module, tree.body[1:count], where) + _check_nested_imports(module.statements, where) + module.defines = _defined_names(module.statements) + if "TYPE_CHECKING" in {node.id for statement in module.statements for node in ast.walk(statement) + if isinstance(node, ast.Name)}: + raise BuildError(f"{where}: TYPE_CHECKING read below the header") + return module + + +def read_package(package: Path) -> dict[str, Module]: + modules = {path.stem: read_module(path) for path in sorted(package.glob("*.py")) + if path.name != "__init__.py"} + owners: dict[str, str] = {} + imported = {alias or name.split(".")[0] for module in modules.values() for name, alias in module.plain} + imported |= {name for module in modules.values() for _source, name in module.froms} + for module in modules.values(): + for name in sorted(module.defines): + if name in owners: + raise BuildError(f"{name} is defined in {owners[name]}.py and {module.name}.py") + if name in imported: + raise BuildError(f"{module.name}.py defines {name}, a name the standard library imports bind") + owners[name] = module.name + for module in modules.values(): + for other, names in sorted([*module.imports.items(), *module.type_imports.items()]): + if other not in modules or other == module.name: + raise BuildError(f"{module.name}.py imports from {PACKAGE}.{other}, not another module of it") + for name in sorted(names - modules[other].defines): + raise BuildError(f"{module.name}.py imports {name} from {other}.py, which does not define it") + return modules + + +def module_order(modules: dict[str, Module]) -> list[str]: + """Each module after the ones it imports outside TYPE_CHECKING, ties in name order.""" + waiting = {name: len(module.imports) for name, module in modules.items()} + users: dict[str, set[str]] = {name: set() for name in modules} + for name, module in modules.items(): + for dep in module.imports: + users[dep].add(name) + ready = [name for name, count in waiting.items() if count == 0] + heapq.heapify(ready) + order: list[str] = [] + while ready: + name = heapq.heappop(ready) + order.append(name) + for user in users[name]: + waiting[user] -= 1 + if waiting[user] == 0: + heapq.heappush(ready, user) + if len(order) != len(modules): + cycle = sorted(name for name, count in waiting.items() if count) + raise BuildError(f"import cycle among {', '.join(cycle)}") + return order + + +def _loads_at_import(statement: ast.stmt) -> Iterator[ast.Name]: + """The names a statement reads when the module runs, not when its functions are called.""" + stack: list[ast.AST] = [statement] + while stack: + node = stack.pop() + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)): + args = node.args + stack.extend(default for default in [*args.defaults, *args.kw_defaults] if default is not None) + stack.extend(getattr(node, "decorator_list", [])) + continue + if isinstance(node, ast.AnnAssign): + stack.extend(child for child in (node.target, node.value) if child is not None) + continue + if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load): + yield node + stack.extend(ast.iter_child_nodes(node)) + + +def check_import_time(modules: dict[str, Module], order: list[str]) -> None: + position = {name: index for index, name in enumerate(order)} + owners = {name: module.name for module in modules.values() for name in module.defines} + for module in modules.values(): + for statement in module.statements: + for node in _loads_at_import(statement): + owner = owners.get(node.id) + if owner is not None and position[owner] > position[module.name]: + raise BuildError(f"{module.name}.py:{node.lineno}: {node.id} is read at import time " + f"but {owner}.py comes later") + + +def _type_key(name: str) -> tuple[int, str]: + if len(name) > 1 and name.isupper(): + return (0, name) + return (1 if name[0].isupper() else 2, name) + + +def _from_line(module: str, names: set[str]) -> str: + ordered = sorted(names, key=_type_key) + line = f"from {module} import {', '.join(ordered)}" + if len(line) <= LINE_LENGTH: + return line + "\n" + return f"from {module} import (\n" + "".join(f" {name},\n" for name in ordered) + ")\n" + + +def import_header(modules: dict[str, Module]) -> tuple[str, str]: + """The merged standard library imports, and the guard of the C extensions among them.""" + plain = {entry for module in modules.values() for entry in module.plain} + guarded = sorted(name for name, alias in plain if name in GUARDED and alias is None) + lines = [f"import {name}" + (f" as {alias}" if alias else "") + "\n" + for name, alias in sorted(plain, key=lambda entry: (entry[0].lower(), entry[1] or "")) + if name not in guarded] + froms: dict[str, set[str]] = {} + for module in modules.values(): + for source, name in module.froms: + if (source, name) != ("typing", "TYPE_CHECKING"): + froms.setdefault(source, set()).add(name) + lines += [_from_line(source, names) for source, names in sorted(froms.items())] + guard = GUARD.format(imports="".join(f" import {name}\n" for name in guarded)) if guarded else "" + return "".join(lines), guard + + +def _marker(name: str) -> str: + head = f"# --- {PACKAGE}/{name}.py " + return head + "-" * max(3, MARKER_WIDTH - len(head)) + "\n" + + +def _docstring(package: Path) -> str: + text = (package / "__init__.py").read_text(encoding="utf-8").strip("\n") + body = ast.parse(text).body + if len(body) != 1 or not _is_docstring(body[0]): + raise BuildError(f"{PACKAGE}/__init__.py holds the docstring of install.py and nothing else") + return text + "\n" + + +def build(package: Path) -> str: + """install.py as the package gives it.""" + docstring = _docstring(package) + modules = read_package(package) + order = module_order(modules) + check_import_time(modules, order) + imports, guard = import_header(modules) + parts = [SHEBANG, NOTICE, docstring, "from __future__ import annotations\n\n", imports] + if guard: + parts += ["\n", guard] + for name in order: + if modules[name].body: + parts += ["\n\n", _marker(name), "\n", modules[name].body, "\n"] + return "".join(parts) diff --git a/scripts/installer_build/eventschema.py b/scripts/installer_build/eventschema.py new file mode 100644 index 000000000..8cdeae9e3 --- /dev/null +++ b/scripts/installer_build/eventschema.py @@ -0,0 +1,92 @@ +"""schemas/install-events.schema.json, from install.py's EVENT_KEYS.""" + +from __future__ import annotations + +import importlib.util +import json + +from core.paths import REPO_ROOT + + +ROOT = REPO_ROOT +OUTPUT = ROOT / "schemas" / "install-events.schema.json" + +_spec = importlib.util.spec_from_file_location("install", ROOT / "install.py") +if _spec is None or _spec.loader is None: + raise ImportError(f"cannot load {ROOT / 'install.py'}") +_install = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(_install) + +EVENT_KEYS: dict[str, tuple[str, ...]] = _install.EVENT_KEYS +EVENT_SCHEMA: int = _install.EVENT_SCHEMA + +_TEXT = {"type": "string"} +_COUNT = {"type": "integer", "minimum": 0} +_FLAG = {"type": "boolean"} +_NAMES = {"type": "array", "items": {"type": "string"}} +_RECORDS = {"type": "array", "items": {"type": "object"}} + +# The JSON type of each key, whatever kind carries it. A key EVENT_KEYS +# gains without a line here stops the generator. +KEY_TYPES: dict[str, dict] = { + **dict.fromkeys(( + "installer", "os", "os_name", "stage", "reason", "platform", "message", + "folder", "dest", "system", "name", "bios_dir", "path", "member", + "list_version", "installed_version", "board", "core", "date", "moved_to", + ), _TEXT), + "mode": {"enum": ["install", "check", "dry-run", "list", "remove", "restore", "pack"]}, + "source": {"enum": ["remove", "install"]}, + "state": {"enum": ["present", "wrong_hash", "missing"]}, + "status": {"enum": ["applied", "written", "unreadable", "not_written", "listed", "made", + "deleted", "not_deleted", "planned", "failed"]}, + **dict.fromkeys(( + "files", "files_done", "files_total", "bytes", "bytes_done", "bytes_total", + "bytes_local", "bytes_network", "size", "present", "missing", "wrong_hash", + "bytes_needed", "data_missing", "not_installable", "installed", "up_to_date", + "pending", "code", "games", "recognised", "not_games", "gone", + ), _COUNT), + **dict.fromkeys(("truncated", "ok", "interrupted", "required_only", "applied", "info", + "backup"), _FLAG), + **dict.fromkeys(("systems", "other_drives", "dests", "written", "choice", "parts"), + _NAMES), + **dict.fromkeys(("platforms", "failed", "skipped", "left_out", "kept", "found", + "fallback"), _RECORDS), +} + + +def _kind(kind: str, keys: tuple[str, ...]) -> dict: + properties: dict[str, dict] = {"event": {"const": kind}} + for key in keys: + properties[key] = ( + {"const": EVENT_SCHEMA} if (kind, key) == ("start", "schema") else KEY_TYPES[key] + ) + return { + "type": "object", + "additionalProperties": False, + "required": ["event", *keys], + "properties": properties, + } + + +def build_schema() -> dict: + """One line of the stream: an object of one of the kinds, with exactly its keys.""" + return { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://abdess.github.io/retrobios/api/v1/schemas/install-events.schema.json", + "title": "RetroBIOS installer event", + "description": ( + f"One line of install.py --events, event schema {EVENT_SCHEMA}. Written from " + "EVENT_KEYS in install.py by scripts/generate_event_schema.py. The schema " + "gains kinds, never keys on an existing kind: a reader skips a kind it " + "does not know." + ), + "type": "object", + "required": ["event"], + "properties": {"event": {"enum": list(EVENT_KEYS)}}, + "oneOf": [{"$ref": f"#/$defs/{kind}"} for kind in EVENT_KEYS], + "$defs": {kind: _kind(kind, keys) for kind, keys in EVENT_KEYS.items()}, + } + + +def render(schema: dict) -> str: + return json.dumps(schema, indent=2, ensure_ascii=False) + "\n" diff --git a/scripts/installer_build/handhelds.py b/scripts/installer_build/handhelds.py new file mode 100644 index 000000000..6ac6ea487 --- /dev/null +++ b/scripts/installer_build/handhelds.py @@ -0,0 +1,126 @@ +"""Where each handheld launcher archive goes on the card, and which menu starts it. + +LAUNCHERS is the one description of it. The handheld tables of wiki/installer.md are +written from it (installer_build/installerdoc.py), and so is the block each +get// page and the handheld page carry (sitegen/handheld.py). +""" + +from __future__ import annotations + +from dataclasses import dataclass, field + +from installer_build.port import BATOCERA_ZIP, MUOS_APP, PORT_ZIP, TOOLS_ZIP + + +# Below the site's root: get/handheld/RetroBIOS.zip. +SERVED_DIR = "get/handheld" +# The page of the systems no registered platform answers for. It shares +# its name with the handheld guide (platforms/linux-handhelds.md), so the +# sidebar files it with that guide, as get/batocera.md is with +# platforms/batocera.md. +GROUP_PAGE = "linux-handhelds" + + +@dataclass(frozen=True) +class Launcher: + """One row of the installer's handheld table. + + *systems* are named as the installer page names them. *copy_to* is + where the file goes, and *places* gives a system its own folder when + the row's systems differ there. *lead* opens the row's first cell. + """ + + archive: str + systems: tuple[str, ...] + copy_to: str + start: str + extracted: bool = False + lead: str = "" + places: tuple[tuple[str, tuple[str, ...]], ...] = field(default=()) + + def folder_for(self, system: str) -> str: + return next((folder for folder, systems in self.places if system in systems), + self.copy_to) + + +LAUNCHERS: tuple[Launcher, ...] = ( + Launcher(MUOS_APP, ("muOS",), + "`ARCHIVE` at the root of the card, then install it from the Archive Manager", + "Applications"), + Launcher(PORT_ZIP, ("ArkOS", "dArkOS", "ROCKNIX", "AmberELEC", "JELOS", "KNULLI"), + "PortMaster's `autoinstall` folder", "Ports, after opening PortMaster once", + lead="Any other system with [PortMaster](https://portmaster.games/)", + places=(("`/roms/ports/PortMaster/autoinstall/`", ("ROCKNIX", "AmberELEC")), + ("`/roms/tools/PortMaster/autoinstall/`", ("ArkOS",)), + ("`/userdata/system/.local/share/PortMaster/autoinstall/`", ("KNULLI",)))), + Launcher(BATOCERA_ZIP, ("Batocera", "KNULLI"), "`roms/ports` on the SHARE partition", + "Ports, after updating the game list", extracted=True), + Launcher(TOOLS_ZIP, ("ArkOS", "dArkOS"), "`tools` on the EASYROMS partition", + "Options, then Tools", extracted=True), + Launcher(TOOLS_ZIP, ("ROCKNIX", "JELOS"), + "`/storage/.config/modules`, over the network share or SSH", "Tools", + extracted=True), + Launcher(TOOLS_ZIP, ("AmberELEC",), "`/storage/.config/distribution/modules`", "Tools", + extracted=True), +) + +# The registered platform whose get/ page answers for a system. A system +# outside this map is on the handheld page. +PLATFORM_OF = {"Batocera": "batocera", "KNULLI": "knulli", "ROCKNIX": "rocknix", + "AmberELEC": "amberelec"} + + +def systems() -> list[str]: + """Every system a launcher runs on, in table order.""" + return list(dict.fromkeys(name for launcher in LAUNCHERS for name in launcher.systems)) + + +def page_of(system: str) -> str: + """The site page that holds the download for *system*.""" + return f"get/{PLATFORM_OF.get(system, GROUP_PAGE)}.md" + + +def launchers_for(system: str) -> list[Launcher]: + """The launchers of *system*, its own menu first and PortMaster last.""" + own = [launcher for launcher in LAUNCHERS if system in launcher.systems] + return sorted(own, key=lambda launcher: launcher.archive == PORT_ZIP) + + +def table_rows() -> list[str]: + """The handheld table of the installer page, each system linked to the + page that holds its download. The page sits in wiki/.""" + def name(system: str) -> str: + return f"[{system}](../{page_of(system)})" + + rows = ["| System | File | Copy it to | Start it from |", + "|--------|------|------------|---------------|"] + for launcher in LAUNCHERS: + names = ", ".join(name(system) for system in launcher.systems) + first = f"{launcher.lead}: {names}" if launcher.lead else names + file = f"`{launcher.archive}`" + (", extracted" if launcher.extracted else "") + copy_to = launcher.copy_to + if launcher.places: + copy_to += ": " + ", ".join( + f"{folder} on {' and '.join(where)}" for folder, where in launcher.places) + rows.append(f"| {first} | {file} | {copy_to} | {launcher.start} |") + return rows + + +def _anchor(system: str) -> str: + """Where *system*'s downloads sit on its page.""" + return "on-the-handheld" if system in PLATFORM_OF else system.casefold() + + +def download_rows() -> list[str]: + """The short table that opens the installer's handheld section: each + system, its files as links to the site's copies, and its page. The + page sits in wiki/.""" + rows = ["| System | Download | Steps |", "|--------|----------|-------|"] + for system in systems(): + files = ", ".join( + f"[{launcher.archive}](../{SERVED_DIR}/{launcher.archive})" + + (" (PortMaster)" if launcher.archive == PORT_ZIP else "") + for launcher in launchers_for(system)) + page = f"../{page_of(system)}#{_anchor(system)}" + rows.append(f"| {system} | {files} | [{system} steps]({page}) |") + return rows diff --git a/scripts/installer_build/installerdoc.py b/scripts/installer_build/installerdoc.py new file mode 100644 index 000000000..6856c33f9 --- /dev/null +++ b/scripts/installer_build/installerdoc.py @@ -0,0 +1,645 @@ +"""The marked tables of wiki/installer.md, written from install.py.""" + +from __future__ import annotations + +import argparse +import ast +import contextlib +import http.server +import importlib.util +import json +import os +import re +import shutil +import socket +import socketserver +import subprocess +import sys +import tempfile +import threading +import zipfile +from pathlib import Path, PurePosixPath +from typing import Any, Callable, TYPE_CHECKING + +from core.paths import REPO_ROOT +from installer_build import handhelds + +if TYPE_CHECKING: + from install import LocalCopy, Progress, _OsRule + + +ROOT = REPO_ROOT +PAGE = ROOT / "wiki" / "installer.md" +INSTALLER = ROOT / "install.py" + +_spec = importlib.util.spec_from_file_location("install", INSTALLER) +if _spec is None or _spec.loader is None: + raise ImportError(f"cannot load {INSTALLER}") +_install = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(_install) + +BLOCK = re.compile( + r"(?P\n)(?P.*?)" + r"(?P)", re.S) +_CELL = re.compile(r"(? list[str]: + return [cell.strip() for cell in _CELL.split(line.strip().strip("|"))] + + +def _rows(body: str) -> list[list[str]]: + lines = [line for line in body.splitlines() if line.startswith("|")] + return [_cells(line) for line in lines[2:]] + + +def _prose(body: str, key: re.Pattern[str], width: int) -> dict[str, list[str]]: + """The prose cells of each row, by the key its first cell holds.""" + kept = {} + for cells in _rows(body): + found = key.search(cells[0]) + if found: + kept[found.group(1)] = (cells[1:] + [""] * width)[:width] + return kept + + +def _table(heading: list[str], rows: list[list[str]]) -> str: + lines = ["| " + " | ".join(heading) + " |", + "|" + "|".join("-" * (len(cell) + 2) for cell in heading) + "|"] + lines += ["| " + " | ".join(row) + " |" for row in rows] + return "\n".join(lines) + "\n" + + +def _with_prose(name: str, facts: list[tuple[str, str]], body: str, key: str, + width: int) -> list[list[str]]: + """Each row's first cell from install.py, the rest from the page, whose + last cell must be written.""" + prose = _prose(body, re.compile(key), width) + missing = [fact for fact, _cell in facts if not prose.get(fact, [""])[-1]] + if missing: + raise MissingProse(f"{name}: no text for {', '.join(missing)}") + return [[cell, *prose[fact]] for fact, cell in facts] + + +def option_rows(body: str) -> list[list[str]]: + facts = [] + # argparse's own --help last, after the options of the run. + for action in sorted(_install.build_parser()._actions, + key=lambda action: isinstance(action, argparse._HelpAction)): + flags = sorted(action.option_strings, key=lambda flag: not flag.startswith("--")) + metavar = "" if action.nargs == 0 else (action.metavar or action.dest.upper()) + shown = ", ".join(f"`{flag} {metavar}`" if metavar else f"`{flag}`" for flag in flags) + facts.append((flags[0], f'{shown}')) + return _with_prose("options", facts, body, r"`(--[a-z-]+)", 1) + + +def exit_codes() -> list[int]: + """The codes install.py exits with: its sys.exit calls, 0 for a run + that returns, 2 for an option argparse refuses.""" + codes = {0, 2} + for node in ast.walk(ast.parse(INSTALLER.read_text(encoding="utf-8"))): + if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) + and node.func.attr == "exit" and getattr(node.func.value, "id", "") == "sys" + and node.args): + continue + given = node.args[0] + for value in ((given.body, given.orelse) if isinstance(given, ast.IfExp) else (given,)): + if isinstance(value, ast.Constant) and isinstance(value.value, int): + codes.add(value.value) + return sorted(codes) + + +def exit_rows(body: str) -> list[list[str]]: + facts = [(str(code), f"`{code}`") for code in exit_codes()] + return _with_prose("exit-codes", facts, body, r"`(\d+)`", 1) + + +def event_rows(body: str) -> list[list[str]]: + facts = [(kind, f"`{kind}`") for kind in _install.EVENT_KEYS] + rows = _with_prose("events", facts, body, r"`([a-z_]+)`", 2) + for row, keys in zip(rows, _install.EVENT_KEYS.values()): + row[1] = ", ".join(f"`{key}`" for key in keys) + return rows + + +def pad_rows(body: str) -> list[list[str]]: + facts = [(route, f"`{route}`") for route in _install.TUI_PAD_ROUTES] + return _with_prose("pad-routes", facts, body, r"`([a-z_]+)`", 2) + + +def route_keys() -> str: + routes = _install.TUI_ROUTES + actions = list(next(iter(routes.values())).help) + unnamed = [action for action in actions if action not in ACTIONS] + if unnamed or any(list(route.help) != actions for route in routes.values()): + raise MissingProse(f"route-keys: TUI_ROUTES actions {unnamed or 'differ by route'} " + "need a name in ACTIONS") + heading = ["Action", *(ROUTE_HEADINGS.get(name, f"`{name}`") for name in routes)] + rows = [[ACTIONS[action], *(route.help[action] or "none" for route in routes.values())] + for action in actions] + return _table(heading, rows) + + +# Card markers that are files with no extension: the MiSTer binary. +_BARE_FILES = frozenset({"MiSTer"}) + + +def _marker(rule: _OsRule) -> str: + """A card rule's evidence in words: the file or folder, and the line it + holds for a rule that reads one.""" + if rule.method == "file_matches": + path, pattern = rule.values + line = re.sub(r"\\s\*\$$", "", re.sub(r"^(\^|\\A)", "", pattern)).replace("\\", "") + return f"`{path}` holding the line `{line}`" + named = ", ".join(f"`{value}`" if PurePosixPath(value).suffix or value in _BARE_FILES + else f"`{value}/`" for value in rule.values) + if rule.method == "games_part": + # Told on the games part beside its bios folder, on a drive the + # system does not call fixed (install.games_part). + return f"{named} beside `bios/`, on a drive that is not a fixed disk" + return named + + +def _list_words(plat: str) -> str: + name = _install.display_name(plat) + return f"{name}'{'' if name.endswith('s') else 's'} list" + + +def card_marker_rows() -> list[list[str]]: + """The files that name a card or a SHARE drive, in the order they are + read: install.py's card rules, then its SHARE drive files.""" + rows = [[_marker(rule), rule.name, + f"`{rule.bios or 'bios'}`, {_list_words(rule.manifest)}"] + for rule in _install._card_rules()] + hostname = "system.hostname=BATOCERA" + for plat, marker in _install._SHARE_DRIVES: + name = _install.display_name(plat) + evidence = (f"`{marker}` holding `{hostname}` or no hostname line, and no KNULLI file " + "above" if plat == "batocera" else f"`{marker}`") + rows.append([evidence, f"{name} SHARE drive", f"`bios`, {_list_words(plat)}"]) + rows.append([f"`{_install._SHARE_DRIVES[0][1]}` with any other hostname, and no KNULLI " + "file above, or the files of two SHARE drives", + "named by neither: the run says which systems it could be", + "the folder of the system named with `--platform`"]) + return rows + + +# The folder the line menu example names: a home that is no one's. +MENU_FOLDER = "/home/me/.config/retroarch/system" + + +def line_menu() -> str: + """The line menu of a RetroArch run, g then Enter pressed, as install.py + prints it for the RetroArch list (install/retroarch.json): the very + function line mode runs, its questions answered here. The page carried + a copy typed by hand, whose keys and counts drifted from the installer.""" + import io + from unittest import mock + + manifest = json.loads((ROOT / "install" / "retroarch.json").read_text(encoding="utf-8")) + files = [*manifest["files"], *(manifest.get("case_variants") or [])] + folder = Path(MENU_FOLDER) + out = io.StringIO() + answers = iter(["g", ""]) + + def answer(prompt: str) -> str: + given = next(answers) + print(f"{prompt}{given}".rstrip()) + return given + + invocation = _install.Invocation() + invocation.os_type = "linux" + environment = {key: value for key, value in os.environ.items() + if key not in (_install.OFFLINE_VARIABLE, "RETROBIOS_BOOTSTRAP")} + with mock.patch.dict(os.environ, environment, clear=True), \ + mock.patch.object(_install, "_INVOCATION", invocation), \ + mock.patch.object(_install, "_ask", answer), \ + mock.patch.object(_install, "folder_warnings", return_value=[]), \ + contextlib.redirect_stdout(out): + cut = [False] + + def command(choice: object) -> str: + invocation.chosen["retroarch"] = ( + (_install.chosen_flags(choice) if choice is not None else []) + + ([("--no-game-data", None)] if cut[0] else [])) + return invocation.command("retroarch", folder) + + context = _install.MenuContext( + "retroarch", files, manifest.get("omitted_files") or [], name="RetroArch", + data_trees=manifest.get("data_directories") or [], bios_path=folder, + manifest=manifest) + _install._prompt_custom_selection( + context, choosable=_install.records_selection(files), command=command, cut=cut) + return "```\n" + out.getvalue().strip("\n") + "\n```" + + +# The home and the card the run samples show, in place of the sandbox's. +SHOWN_HOME = "/home/me" +SHOWN_CARD = "" +RETROARCH_CFG = ('system_directory = "~/.config/retroarch/system"\n' + 'savefile_directory = "~/.config/retroarch/saves"\n') + + +class _ListHandler(http.server.SimpleHTTPRequestHandler): + """Serves the committed file lists, install/.json, and nothing + else: a sample that asks for a file is a sample that downloads.""" + + def __init__(self, request: socket.socket | tuple[bytes, socket.socket], + client_address: tuple[str, int], server: socketserver.BaseServer) -> None: + super().__init__(request, client_address, server, directory=str(ROOT)) + + def do_GET(self) -> None: + if not re.fullmatch(r"/install/[a-z0-9_-]+\.json", self.path): + self.send_error(404) + return + super().do_GET() + + def log_message(self, *_args: object) -> None: + return + + +class _LoopbackServer(http.server.ThreadingHTTPServer): + """The list server, named by its number: HTTPServer.server_bind looks + 127.0.0.1 up with socket.getfqdn, a DNS query wherever /etc/hosts does + not name it.""" + + def server_bind(self) -> None: + socketserver.TCPServer.server_bind(self) + host, port = self.server_address[:2] + if not isinstance(host, str): + raise TypeError(f"the list server needs a host name, not {host!r}") + self.server_name, self.server_port = host, port + + +# The list the reasons and the copy are shown with: four files, each with +# the contents its name says, read as RetroArch's. +SMALL_LIST = { + "scph5500.bin": (b"J" * 64, ["sony-playstation"], ["japan"], None), + "scph5501.bin": (b"U" * 64, ["sony-playstation"], ["north-america"], + ["beetle_psx", "pcsx_rearmed"]), + "gba_bios.bin": (b"G" * 32, ["nintendo-gba"], None, ["mgba"]), + "pcsx/extra.bin": (b"E" * 8, ["sony-playstation"], None, ["pcsx_rearmed"]), +} + + +def write_small_list(path: Path) -> None: + import hashlib + + files = [] + for dest, (data, systems, regions, cores) in SMALL_LIST.items(): + files.append({"dest": dest, "size": len(data), "sha1": hashlib.sha1(data).hexdigest(), + "sha256": hashlib.sha256(data).hexdigest(), + "md5": hashlib.md5(data).hexdigest(), "systems": systems, + "cores": cores, "repo_path": f"bios/{dest}", + **({"regions": regions} if regions else {})}) + path.write_text(json.dumps({ + "manifest_version": 2, "platform": "retroarch", "display_name": "RetroArch", + "base_destination": "system", "files": files, "total_files": len(files), + "total_size": sum(entry["size"] for entry in files)}), encoding="utf-8") + + +def _child(spec: dict) -> int: + """install.main() as the sample runs it, in its own process. Only the + transport and the machine are stood in for: no connection leaves the + loopback, detection finds the card folder the spec names, a file or a + data tree of a landed run reports its bytes written without fetching + them, and a held run finds every file and tree in place. The counts, + sizes and words are the installer's own.""" + import concurrent.futures + from unittest import mock + + real_connect = socket.create_connection + + # The rest of the arguments are create_connection's own, passed through. + def loopback_only(address: tuple[str, int], *args: Any, **kwargs: Any) -> socket.socket: + if address[0] not in ("127.0.0.1", "localhost"): + raise OSError(f"the sample makes no request to {address[0]}") + return real_connect(address, *args, **kwargs) + + real_download = _install._download_one + + def landed(f: dict, bios: Path, verbose: bool = False, progress: Progress | None = None, + copy: LocalCopy | None = None) -> tuple[str, bool, str]: + if copy is not None: + # A copy from this machine is made for real: it is local. + return real_download(f, bios, verbose, progress, copy) + if progress is not None: + progress.add(f["size"]) + return f["dest"], True, "" + + def held(files: list[dict], _bios: Path, **_kwargs: object) -> tuple: + return [], list(files), [] + + def tree_landed(entry: dict, _bios: Path, state: object = None, + _progress: object = None) -> dict: + return {"present": 0, "installed": len(entry["files"]), "changed": 0, + "absent": 0, "error": "", "not_kept": []} + + def tree_held(entry: dict, bios: Path, remember: bool = False) -> tuple: + return bios / entry.get("dest", ""), {}, len(entry["files"]) + + patches: list[contextlib.AbstractContextManager[object]] = [ + mock.patch.object(socket, "create_connection", loopback_only), + # One worker and the submission order: the progress lines of a log. + mock.patch.object(concurrent.futures, "as_completed", list), + mock.patch.object(sys, "argv", ["install.py", *spec["argv"]]), + ] + if spec.get("card"): + patches += [ + mock.patch.object(_install, "detect_platforms", + lambda _os: [(spec["platform"], Path(spec["card"]))]), + mock.patch.object(_install, "_mounted_cards", list), + ] + if spec.get("landed"): + patches.append(mock.patch.object(_install, "_download_one", landed)) + patches.append(mock.patch.object(_install, "install_data_directory", tree_landed)) + if spec.get("held"): + patches.append(mock.patch.object(_install, "check_local", held)) + patches.append(mock.patch.object(_install, "data_directory_state", tree_held)) + with contextlib.ExitStack() as stack: + for patch in patches: + stack.enter_context(patch) + try: + _install.main() + except SystemExit as exc: + return exc.code if isinstance(exc.code, int) else 1 + return 0 + + +# What the process of a run sample executes, the spec as its one argument. +CHILD = ("import json, sys; sys.path.insert(0, 'scripts'); " + "from installer_build import installerdoc; " + "sys.exit(installerdoc._child(json.loads(sys.argv[1])))") + + +class Sandbox: + """A home with a RetroArch config and a card folder, under tmp/, and the + committed file lists served on the loopback. Every run sample of the page + is printed here.""" + + def __enter__(self) -> Sandbox: + (ROOT / "tmp").mkdir(exist_ok=True) + self.root = Path(tempfile.mkdtemp(prefix="installer-doc-", dir=ROOT / "tmp")) + self.home = self.root / "home" + self.card = self.root / "card" + config = self.home / ".config" / "retroarch" / "retroarch.cfg" + config.parent.mkdir(parents=True) + config.write_text(RETROARCH_CFG, encoding="utf-8") + self.server = _LoopbackServer(("127.0.0.1", 0), _ListHandler) + threading.Thread(target=self.server.serve_forever, daemon=True).start() + return self + + def __exit__(self, *_exc: object) -> None: + self.server.shutdown() + self.server.server_close() + shutil.rmtree(self.root) + + def small(self, kind: str) -> str: + """A run over SMALL_LIST in a home of its own: "refused", a --check + of a folder holding a copy of each kind a check names, or "from", a + run copying from an old card what it holds and downloading the rest.""" + home = self.root / kind + system = home / ".config" / "retroarch" / "system" + system.mkdir(parents=True) + (system.parent / "retroarch.cfg").write_text(RETROARCH_CFG, encoding="utf-8") + listed = home / "list.json" + write_small_list(listed) + data = {dest: entry[0] for dest, entry in SMALL_LIST.items()} + if kind == "refused": + (system / "scph5500.bin").write_bytes(data["scph5500.bin"]) + (system / "scph5501.bin").write_bytes(data["scph5500.bin"]) + (system / "system").mkdir() + (system / "system" / "gba_bios.bin").write_bytes(data["gba_bios.bin"]) + with zipfile.ZipFile(system / "PSX BIOS.zip", "w") as archive: + archive.writestr("extra.bin", data["pcsx/extra.bin"]) + # A check that flags a file ends on 3, as documented. + return self.run("retroarch", "--check", "--verbose", "--manifest", str(listed), + home=home, codes=(3,)) + old = home / "old" + old.mkdir() + for dest in ("scph5500.bin", "scph5501.bin"): + (old / dest).write_bytes(data[dest]) + return self.run("retroarch", "--yes", "--verbose", "--manifest", str(listed), + "--from", str(old), home=home, landed=True) + + def run(self, platform: str, *argv: str, landed: bool = False, + held: bool = False, home: Path | None = None, codes: tuple = (0,)) -> str: + """What install.py prints for the run, the sandbox read as a user's + home and card.""" + home = home or self.home + card = self.card / "userdata" / "bios" if platform != "retroarch" else None + if card is not None: + card.mkdir(parents=True, exist_ok=True) + args = ["--plain", "--platform", platform, *argv] + spec = {"platform": platform, "argv": args, + "card": str(card) if card else None, "landed": landed, "held": held} + env = {"PATH": os.environ.get("PATH", ""), "HOME": str(home), + "RETROBIOS_OS": "linux", "LANG": "C.UTF-8", + "RETROBIOS_BASE_URL": f"http://127.0.0.1:{self.server.server_address[1]}"} + done = subprocess.run( + [sys.executable, "-s", "-c", CHILD, json.dumps(spec)], + cwd=ROOT, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, + check=False) + if done.returncode not in codes: + raise SampleFailed(f"install.py {' '.join(args)} exited " + f"{done.returncode}: {done.stderr.strip()[-2000:]}") + return done.stdout.replace(str(home), SHOWN_HOME).replace(str(self.card), SHOWN_CARD) + + +# The runs printed in this process, by what they read: the page is rendered +# more than once by --check and by the tests, from the same installer and lists. +_RUNS: dict[tuple, str] = {} + + +def _stamp(platform: str) -> tuple[int, int]: + return (hash(INSTALLER.read_bytes()), + hash((ROOT / "install" / f"{platform}.json").read_bytes())) + + +class _LazySandbox: + """A Sandbox opened at the first run a rendering asks for, and only then.""" + + def __init__(self, stack: contextlib.ExitStack) -> None: + self.stack = stack + self.box: Sandbox | None = None + + def run(self, platform: str, *argv: str, landed: bool = False, held: bool = False) -> str: + key = (platform, argv, landed, held, _stamp(platform)) + if key in _RUNS: + return _RUNS[key] + if self.box is None: + self.box = self.stack.enter_context(Sandbox()) + _RUNS[key] = self.box.run(platform, *argv, landed=landed, held=held) + return _RUNS[key] + + def small(self, kind: str) -> str: + key = ("small", kind, _stamp("retroarch")) + if key not in _RUNS: + if self.box is None: + self.box = self.stack.enter_context(Sandbox()) + _RUNS[key] = self.box.small(kind) + return _RUNS[key] + + +class SampleFailed(Exception): + """A run sample install.py could not print.""" + + +def _lines_from(text: str, first: str, last: str | None = None, count: int | None = None + ) -> list[str]: + """The lines of a run from the one starting with first, through the one + starting with last or for count lines.""" + lines = text.splitlines() + start = next((i for i, line in enumerate(lines) if line.startswith(first)), None) + if start is None: + raise SampleFailed(f"the run printed no line starting {first!r}") + if count is not None: + return lines[start:start + count] + if last is None: + raise ValueError("_lines_from needs last or count") + end = next((i for i in range(start, len(lines)) if lines[i].startswith(last)), None) + if end is None: + raise SampleFailed(f"the run printed no line starting {last!r} after {first!r}") + return lines[start:end + 1] + + +def _fenced(lines: list[str]) -> str: + return "```\n" + "\n".join(lines) + "\n```" + + +def list_date(platform: str) -> str: + """The day the committed list was generated, which dates its samples.""" + manifest = json.loads((ROOT / "install" / f"{platform}.json").read_text(encoding="utf-8")) + return manifest["generated"][:10] + + +# The platform of the run walked through under Reading a run. +WALKTHROUGH = "batocera" +# A system of the RetroArch list one core pulls most of: the sample of the +# line naming it. A list where it no longer does fails the rendering, and +# another system is named here. +BULK_SYSTEM = "sony-playstation" + + +def _bulk_line(box: Sandbox | _LazySandbox) -> str: + run = box.run("retroarch", "--dry-run", "--verbose", "--system", BULK_SYSTEM) + found = [line for line in run.splitlines() if re.match(r" \S+ pulls ", line)] + if len(found) != 1: + raise SampleFailed(f"a RetroArch run with --system {BULK_SYSTEM} names no core " + "pulling most of its download: name another BULK_SYSTEM") + return found[0] + + +def sample_writers(box: Sandbox | _LazySandbox) -> dict[str, Callable[[str], str]]: + """The run samples, each from the run that prints it: the walk through a + run reads its --verbose lines, the default sample the lines it hides them + from.""" + def default_run() -> str: + return box.run(WALKTHROUGH, "--yes", "--jobs", "1", landed=True) + + def install_run() -> str: + return box.run(WALKTHROUGH, "--yes", "--jobs", "1", "--verbose", landed=True) + + def check_run() -> str: + return box.run(WALKTHROUGH, "--check", "--verbose", held=True) + + def dry_run() -> str: + return box.run("retroarch", "--dry-run", "--verbose") + + return { + "run-default": lambda _body: _fenced( + _lines_from(default_run(), "Installing ", "Next: ")), + "dry-run": lambda _body: ( + f"A RetroArch dry run into an empty folder, with the list of " + f"{list_date('retroarch')}, printed this:\n\n" + + _fenced(_lines_from(dry_run(), "Fetching file index", " 0 in place"))), + "run-date": lambda _body: ( + f"Each line a first install prints, and what it means. The run below is a\n" + f"{_install.display_name(WALKTHROUGH)} install into an empty folder, from the " + f"list of {list_date(WALKTHROUGH)}.\nThe figures change with each release."), + "run-first-lines": lambda _body: _fenced( + _lines_from(install_run(), "Looking for setups", " Found")), + "run-index": lambda _body: _fenced( + _lines_from(install_run(), "Fetching file index", " 0 in place")), + "run-download": lambda _body: _fenced( + _lines_from(install_run(), "Downloading ", count=4)), + "run-end": lambda _body: _fenced( + _lines_from(install_run(), "Done.", "To check this later")), + "bulk-hint": lambda _body: ( + f"RetroArch with `--system {BULK_SYSTEM}`, from the list of " + f"{list_date('retroarch')}:\n\n" + + _fenced([_bulk_line(box)])), + "run-check": lambda _body: _fenced( + _lines_from(check_run(), "Checking existing files", + " Every file on the list is in place")), + "check-refused": lambda _body: _fenced(_refused_lines(box.small("refused"))), + "from-run": lambda _body: _fenced( + _lines_from(box.small("from"), "Done.", count=2)), + } + + +def _refused_lines(text: str) -> list[str]: + """The files a check flags, each with its reason and where its cores read it.""" + lines = text.splitlines() + start = next((i for i, line in enumerate(lines) + if re.fullmatch(r" \d+ files? [a-z ]+\.", line)), None) + if start is None: + raise SampleFailed("the check printed no files not in place") + end = max(i for i, line in enumerate(lines) if line.lstrip().startswith("read by ")) + return lines[start:end + 1] + + +def render(page: str) -> str: + """The page with each marked table and run sample written from install.py.""" + writers = { + "options": lambda body: _table(["Option", "Effect"], option_rows(body)), + "exit-codes": lambda body: _table(["Code", "Meaning"], exit_rows(body)), + "events": lambda body: _table(["Kind", "Keys", "When"], event_rows(body)), + "pad-routes": lambda body: _table(["Value", "Input", "Set by"], pad_rows(body)), + "route-keys": lambda _body: route_keys(), + "card-markers": lambda _body: _table(["On the card", "System", "Files go to"], + card_marker_rows()), + "line-menu": lambda _body: line_menu(), + # Where each handheld launcher goes, written from the site's own + # description of it (handhelds.LAUNCHERS). + "handheld": lambda _body: "\n".join(handhelds.table_rows()), + "handheld-downloads": lambda _body: "\n".join(handhelds.download_rows()), + } + seen = [] + with contextlib.ExitStack() as stack: + box = _LazySandbox(stack) + writers.update(sample_writers(box)) + + def write(match: re.Match[str]) -> str: + name = match.group("name") + if name not in writers: + raise MissingProse(f"no table is written for the marker {name!r}") + seen.append(name) + table = writers[name](match.group("body")) + return f"{match.group('open')}\n{table}\n{match.group('close')}" + + text = BLOCK.sub(write, page) + absent = sorted(set(writers) - set(seen)) + if absent: + raise MissingProse(f"markers missing from the page: {', '.join(absent)}") + return text diff --git a/scripts/installer_build/launcherindex.py b/scripts/installer_build/launcherindex.py new file mode 100644 index 000000000..54235d10e --- /dev/null +++ b/scripts/installer_build/launcherindex.py @@ -0,0 +1,89 @@ +"""install/launchers/index.json: the handheld launchers as files for a card.""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +from pathlib import Path + +from core.paths import REPO_ROOT +from installer_build.port import ( + BATOCERA_ZIP, + MUOS_APP, + TOOLS_ZIP, + _packs_table, + archive_members, + pinned_installer_sha256, +) + + +OUTPUT = REPO_ROOT / "install" / "launchers" / "index.json" + +_spec = importlib.util.spec_from_file_location("install", REPO_ROOT / "install.py") +if _spec is None or _spec.loader is None: + raise ImportError(f"cannot load {REPO_ROOT / 'install.py'}") +_install = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(_install) + +# The archive whose members each system gets, by its key in APP_PLACES. +LAUNCHER_ARCHIVES = {"muos": MUOS_APP, "knulli": BATOCERA_ZIP, "rocknix": TOOLS_ZIP} + + +def _entry(field: str, name: str, source: Path | None, root: Path) -> dict: + """A member as the list records it: where it comes from, its size and + hash, and whether it is executable in the repository.""" + if source is None: + data = _packs_table(root) + origin: dict = {"content": data.decode("utf-8")} + executable = False + else: + data = source.read_bytes() + origin = {"repo_path": source.relative_to(root).as_posix()} + executable = bool(source.stat().st_mode & 0o111) + return {field: name, **origin, "size": len(data), + "sha256": hashlib.sha256(data).hexdigest(), "executable": executable} + + +def _member_bytes(entry: dict, root: Path) -> bytes: + if "content" in entry: + return entry["content"].encode("utf-8") + return (root / entry["repo_path"]).read_bytes() + + +def build_index(root: Path = REPO_ROOT) -> dict: + """Every launcher a card can carry, from the archives' members.""" + actual = hashlib.sha256((root / "install.py").read_bytes()).hexdigest() + if actual != pinned_installer_sha256(root): + raise ValueError("install.py is not the installer install.sh pins: re-pin the " + "bootstraps before writing the launcher list") + places = {place.key: place for place in _install.APP_PLACES.values()} + if set(places) != set(LAUNCHER_ARCHIVES): + raise ValueError(f"APP_PLACES names {sorted(places)}, the archives " + f"{sorted(LAUNCHER_ARCHIVES)}") + launchers: dict[str, dict] = {} + for key, archive in sorted(LAUNCHER_ARCHIVES.items()): + folder = places[key].folder + members = archive_members(archive, root) + if archive == MUOS_APP: + entries = [_entry("name", name, source, root) for name, source in members] + data = _install.app_archive([(entry, _member_bytes(entry, root)) + for entry in entries]) + launchers[key] = { + "archive": {"dest": f"{folder}/{archive}", "size": len(data), + "sha256": hashlib.sha256(data).hexdigest()}, + "members": entries, + } + else: + # Executable only where the menu starts the script as a program: + # a mode a FAT card cannot hold is refused by its driver. + files = [_entry("dest", f"{folder}/{name}", source, root) + for name, source in members] + for entry in files: + entry["executable"] = entry["executable"] and places[key].executable + launchers[key] = {"files": files} + return {"schema": _install.APP_SCHEMA, "launchers": launchers} + + +def render(index: dict) -> str: + return json.dumps(index, indent=2, ensure_ascii=False) + "\n" diff --git a/scripts/installer_build/pins.py b/scripts/installer_build/pins.py new file mode 100644 index 000000000..7edf2cb84 --- /dev/null +++ b/scripts/installer_build/pins.py @@ -0,0 +1,58 @@ +"""The SHA-256 of install.py in the bootstraps that pin it.""" + +from __future__ import annotations + +import hashlib +import re +from pathlib import Path + +from core.paths import REPO_ROOT +from model.guides import PS1_NAME, SH_NAME + + +ROOT = REPO_ROOT +INSTALLER = "install.py" +# Each bootstrap and its one pin line, the value between the two groups. +PINS: dict[str, re.Pattern[str]] = { + "install.sh": re.compile(r'^(DEFAULT_INSTALL_SHA256=")[0-9a-f]{64}(")', re.M), + "install.ps1": re.compile(r'^(\s*\$defaultInstallSha256 = ")[0-9a-f]{64}(")', re.M), +} +COMMAND = "python scripts/pin_installer.py" + + +def installer_sha256(root: Path = ROOT) -> str: + return hashlib.sha256((root / INSTALLER).read_bytes()).hexdigest() + + +def stale_pins(root: Path = ROOT) -> list[str]: + """The bootstraps whose pin is not the SHA-256 of install.py.""" + digest = installer_sha256(root) + stale = [] + for name, pin in PINS.items(): + found = pin.search((root / name).read_bytes().decode("utf-8")) + if found is None: + raise ValueError(f"{name}: no installer pin line") + if found.group(0) != f"{found.group(1)}{digest}{found.group(2)}": + stale.append(name) + return stale + + +def write_pins(root: Path = ROOT) -> list[str]: + """Rewrite each stale pin. Returns the bootstraps written.""" + digest = installer_sha256(root) + written = [] + for name in stale_pins(root): + path = root / name + text = path.read_bytes().decode("utf-8") + new, count = PINS[name].subn(rf"\g<1>{digest}\g<2>", text) + if count != 1: + raise ValueError(f"{name}: {count} installer pin lines, expected 1") + path.write_bytes(new.encode("utf-8")) + written.append(name) + return written + + +PIN: dict[str, re.Pattern[str]] = { + SH_NAME: re.compile(r'^DEFAULT_INSTALL_SHA256="([0-9a-f]{64})"', re.M), + PS1_NAME: re.compile(r'^\s*\$defaultInstallSha256 = "([0-9a-f]{64})"', re.M), +} diff --git a/scripts/installer_build/port.py b/scripts/installer_build/port.py new file mode 100644 index 000000000..eeb973e21 --- /dev/null +++ b/scripts/installer_build/port.py @@ -0,0 +1,167 @@ +"""The handheld launchers of ports/ built into their archives.""" + +from __future__ import annotations + +import hashlib +import re +import zipfile +from pathlib import Path + +from core.paths import REPO_ROOT + + +PORT_DIR = "retrobios" +PORT_SCRIPT = "RetroBIOS.sh" +PORT_ZIP = "RetroBIOS.zip" +BATOCERA_ZIP = "RetroBIOS-batocera.zip" +MUOS_APP = "RetroBIOS.muxapp" +TOOLS_ZIP = "RetroBIOS-tools.zip" +# Every launcher archive the site serves. +ARCHIVES = (PORT_ZIP, BATOCERA_ZIP, MUOS_APP, TOOLS_ZIP) +# Which release pack serves each platform, read by tui.txt offline. +PACKS_TABLE = "packs.txt" +_PIN = re.compile(r'^DEFAULT_INSTALL_SHA256="([0-9a-f]{64})"$', re.MULTILINE) + + +def pinned_installer_sha256(root: Path = REPO_ROOT) -> str: + """The SHA-256 install.sh accepts for install.py.""" + found = _PIN.search((root / "install.sh").read_text(encoding="utf-8")) + if found is None: + raise ValueError("install.sh pins no installer SHA-256") + return found.group(1) + + +def _engine(folder: str, root: Path, mapping: bool = True) -> list[tuple[str, Path | None]]: + """What every launcher runs: the installer, the interface launcher, the + event reader, the licenses, and the gptokeyb mapping where one is read.""" + shared = root / "ports" / "shared" + members = [ + (f"{folder}/install.py", root / "install.py"), + (f"{folder}/tui.txt", shared / "tui.txt"), + (f"{folder}/rbevents.py", shared / "rbevents.py"), + (f"{folder}/licenses/LICENSE-retrobios.txt", root / "LICENSE"), + (f"{folder}/licenses/NOTICE-retrobios.txt", root / "NOTICE"), + # Written by build_archive from the registry. + (f"{folder}/{PACKS_TABLE}", None), + ] + if mapping: + members.append((f"{folder}/retrobios.gptk", shared / "retrobios.gptk")) + return members + + +def archive_members(name: str, root: Path = REPO_ROOT) -> list[tuple[str, Path | None]]: + """(name in the archive, source file) for every member of *name*, sorted. + The source is None for the packs table build_archive writes.""" + ports = root / "ports" + if name == PORT_ZIP: + source = ports / "RetroBIOS" + members = [ + (PORT_SCRIPT, source / PORT_SCRIPT), + (f"{PORT_DIR}/port.json", source / "port.json"), + (f"{PORT_DIR}/gameinfo.xml", source / "gameinfo.xml"), + (f"{PORT_DIR}/{PORT_DIR}.md", source / "README.md"), + *_engine(PORT_DIR, root), + ] + members += [ + (f"{PORT_DIR}/{path.relative_to(source / PORT_DIR).as_posix()}", path) + for path in sorted((source / PORT_DIR).rglob("*")) + if path.is_file() and "__pycache__" not in path.parts + ] + elif name == BATOCERA_ZIP: + source = ports / "batocera" + members = [ + (PORT_SCRIPT, source / PORT_SCRIPT), + (f"{PORT_SCRIPT}.keys", source / f"{PORT_SCRIPT}.keys"), + (f"{PORT_DIR}/README.md", source / "README.md"), + # evmapy reads RetroBIOS.sh.keys: no gptokeyb there. + *_engine(PORT_DIR, root, mapping=False), + ] + elif name == MUOS_APP: + source = ports / "muos" + members = [ + ("RetroBIOS/mux_launch.sh", source / "mux_launch.sh"), + ("RetroBIOS/README.md", source / "README.md"), + # muOS draws an application's list glyph from glyph/.png + # in its own folder (apply_app_glyph, frontend common/ui/glyph.c): + # `# ICON: retrobios` resolved to nothing without it. + ("RetroBIOS/glyph/retrobios.png", source / "glyph" / "retrobios.png"), + *_engine("RetroBIOS", root), + ] + elif name == TOOLS_ZIP: + source = ports / "tools" + members = [ + (PORT_SCRIPT, source / PORT_SCRIPT), + (f"{PORT_DIR}/README.md", source / "README.md"), + *_engine(PORT_DIR, root), + ] + else: + raise ValueError(f"no launcher archive is named {name}") + names = [member for member, _path in members] + if len(set(names)) != len(names): + raise ValueError(f"two members of {name} share a name") + return sorted(members) + + +def release_pack_labels(root: Path = REPO_ROOT) -> dict[str, str]: + """Platform -> the platform part of the release pack that serves it. + + Only the platforms the registry marks release_pack have a pack, grouped + as the release builds them (pipeline.py). install.py + refuses a pack whose name does not spell the platform, so a platform + outside these groups has no pack to copy, whatever its file list. + """ + from resolve.grouping import group_identical_platforms + from model.registry import list_release_pack_platforms + from model.platforms import load_platform_config + from packs.naming import _name_part, _platform_pack_stem + + platforms_dir = str(root / "platforms") + pool = list_release_pack_platforms(platforms_dir) + labels: dict[str, str] = {} + for group, representative in group_identical_platforms(pool, platforms_dir): + stem = _platform_pack_stem(group, representative, platforms_dir) + config = load_platform_config(representative, platforms_dir) + version = config.get("version", config.get("dat_version", "")) + tag = f"_{_name_part(str(version))}" if version else "" + label = stem[: -len(tag)] if tag and stem.endswith(tag) else stem + for platform in group: + labels[platform] = label + return dict(sorted(labels.items())) + + +def _packs_table(root: Path) -> bytes: + return "".join(f"{platform}\t{label}\n" + for platform, label in release_pack_labels(root).items()).encode() + + +def build_archive(name: str, output: Path, root: Path = REPO_ROOT) -> Path: + """Write the launcher archive *name* to *output* and return it.""" + pinned = pinned_installer_sha256(root) + actual = hashlib.sha256((root / "install.py").read_bytes()).hexdigest() + if actual != pinned: + raise ValueError( + f"install.py is {actual[:12]}, install.sh pins {pinned[:12]}: " + "re-pin the bootstraps before building the launchers" + ) + # The packs' member writer: imported here, as it loads the whole + # pack builder, which a caller reading ARCHIVES does not need. + from packs.archive import _add_pack_member + + members = archive_members(name, root) + output.parent.mkdir(parents=True, exist_ok=True) + scratch = output.with_name(f".{output.name}.tmp") + table = output.with_name(f".{output.name}.{PACKS_TABLE}") + table.write_bytes(_packs_table(root)) + try: + with zipfile.ZipFile(scratch, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as zf: + for member, path in members: + _add_pack_member(zf, str(path or table), member) + finally: + table.unlink() + scratch.replace(output) + return output + + +def build_port(output: Path, root: Path = REPO_ROOT) -> Path: + """Write the PortMaster port archive to *output* and return it.""" + return build_archive(PORT_ZIP, output, root) diff --git a/scripts/installer_build/pypi.py b/scripts/installer_build/pypi.py new file mode 100644 index 000000000..68d5386e9 --- /dev/null +++ b/scripts/installer_build/pypi.py @@ -0,0 +1,104 @@ +"""The `retrobios` package PyPI serves: install.py as a command.""" + +from __future__ import annotations + +import datetime +import hashlib +import os +import shutil +import subprocess +import tempfile +from pathlib import Path + +from core.paths import REPO_ROOT +from model.guides import SH_NAME +from installer_build.pins import PIN + + +ROOT = REPO_ROOT +PACKAGE_DIR = ROOT / "packaging" / "pypi" +DEFAULT_OUTPUT = ROOT / "tmp" / "pypi-dist" +MODULE = "retrobios" + +# The launcher. runpy runs install.py as __main__, so its own __main__ block +# keeps the exit codes it gives a reader that left (141) and Ctrl+C (130). +LAUNCHER = '''"""The RetroBIOS installer, install.py, run as the retrobios command.""" + +import os +import runpy +from pathlib import Path + +__version__ = "{version}" + + +def main() -> None: + # The hints give back the command that ran this, not python3 install.py. + os.environ["RETROBIOS_BOOTSTRAP"] = "pypi" + runpy.run_path(str(Path(__file__).with_name("install.py")), run_name="__main__") +''' + + +def package_version(stamps: list[int]) -> str: + """The version of install.py from its commit times, newest first (UTC).""" + if not stamps: + raise ValueError("install.py has no commit to date the package by") + day = datetime.datetime.fromtimestamp(stamps[0], datetime.timezone.utc).date() + rank = sum(1 for stamp in stamps + if datetime.datetime.fromtimestamp(stamp, datetime.timezone.utc).date() == day) + base = f"{day.year}.{day.month}.{day.day}" + return base if rank == 1 else f"{base}.{rank}" + + +def install_py_commits() -> list[int]: + """Commit times of install.py, newest first, from git.""" + out = subprocess.run(["git", "log", "--format=%ct", "--", "install.py"], cwd=ROOT, + capture_output=True, text=True, check=True).stdout + return [int(line) for line in out.split()] + + +def installer_bytes() -> bytes: + """install.py, refused unless it is the one install.sh pins: the package + then runs the installer the one-line command runs, under the same id.""" + data = (ROOT / "install.py").read_bytes() + pins = PIN[SH_NAME].findall((ROOT / "install.sh").read_text(encoding="utf-8")) + if pins != [hashlib.sha256(data).hexdigest()]: + raise ValueError("install.py is not the installer install.sh pins: recompute the pin") + return data + + +def stage(folder: Path, version: str) -> None: + """The project as the backend reads it.""" + module = folder / MODULE + module.mkdir(parents=True) + for name in ("pyproject.toml", "README.md"): + shutil.copyfile(PACKAGE_DIR / name, folder / name) + shutil.copyfile(ROOT / "LICENSE", folder / "LICENSE") + shutil.copyfile(PACKAGE_DIR / MODULE / "__main__.py", module / "__main__.py") + (module / "__init__.py").write_text(LAUNCHER.format(version=version), encoding="utf-8") + (module / "install.py").write_bytes(installer_bytes()) + + +def build(output_dir: Path) -> tuple[Path, Path]: + """The wheel and the sdist in output_dir, replacing earlier builds there.""" + stamps = install_py_commits() + version = package_version(stamps) + output_dir.mkdir(parents=True, exist_ok=True) + for pattern in ("*.whl", "*.tar.gz"): + for old in output_dir.glob(f"{MODULE}-{pattern}"): + old.unlink() + scratch = ROOT / "tmp" + scratch.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(prefix="pypi-stage-", dir=scratch) as name: + folder = Path(name) / "retrobios" + stage(folder, version) + # Without a flag, uv builds the sdist, then the wheel from that sdist: + # what a user building from the sdist gets is what is published. + subprocess.run( + ["uv", "build", "--quiet", "--out-dir", str(output_dir.resolve()), str(folder)], + check=True, env={**os.environ, "SOURCE_DATE_EPOCH": str(stamps[0])}) + wheel = output_dir / f"{MODULE}-{version}-py3-none-any.whl" + sdist = output_dir / f"{MODULE}-{version}.tar.gz" + for path in (wheel, sdist): + if not path.is_file(): + raise RuntimeError(f"uv build wrote no {path.name}") + return wheel, sdist diff --git a/scripts/model/releaserecord.py b/scripts/model/releaserecord.py new file mode 100644 index 000000000..75ce6c963 --- /dev/null +++ b/scripts/model/releaserecord.py @@ -0,0 +1,70 @@ +"""The committed release record, release.json, as the README, the site and the release tools read it.""" + +from __future__ import annotations + +import json +from pathlib import Path + +from model.registry import list_release_pack_platforms + + +RECORD = "release.json" +# The record's format, which release.schema.json pins: a reader holding the +# file alone can tell which shape it reads. +SCHEMA_VERSION = 1 +# Each registered platform has a page at get// on the site: the +# current pack's files, or the command when no release publishes one. The +# address outlives every release, so a link written elsewhere keeps working. +GET_DIR = "get" + + +def load_record(path: str | Path = RECORD) -> dict: + """The committed record, empty when no release has written one.""" + try: + with open(path, encoding="utf-8") as handle: + return json.load(handle) + except (OSError, json.JSONDecodeError): + return {} + + +def get_page(platform: str, site: str = "") -> str: + """The permanent download address of a platform, under *site*.""" + return f"{site}{GET_DIR}/{platform}/" + + +def advertised(record: dict, platforms_dir: str = "platforms") -> dict: + """The record as the download tables show it: release_pack platforms only. + + A release cut before a platform lost its release_pack still holds that + platform's pack. The tables follow the registry, so a platform left out + is offered the command, and a pack two platforms shared names the one + still released. + """ + if not record: + return {} + released = set(list_release_pack_platforms(platforms_dir)) + packs = {} + for name, pack in record.get("packs", {}).items(): + serves = [p for p in pack.get("platforms", ()) if p in released] + if serves: + packs[name] = {**pack, "platforms": serves} + return {**record, "packs": packs} + + +def load_advertised(path: str | Path = RECORD, platforms_dir: str = "platforms") -> dict: + """The committed record, reduced to the platforms a release publishes.""" + return advertised(load_record(path), platforms_dir) + + +def pack_name_for(platform: str, record: dict) -> str | None: + """Name of the release pack that serves a platform, if it has one.""" + for name, pack in sorted(record.get("packs", {}).items()): + if platform in pack.get("platforms", ()): + return name + return None + + +def pack_for(platform: str, record: dict) -> dict | None: + """The pack of the release that serves a platform, if it has one.""" + name = pack_name_for(platform, record) + return record["packs"][name] if name else None diff --git a/scripts/romfolders.py b/scripts/model/romfolders.py similarity index 100% rename from scripts/romfolders.py rename to scripts/model/romfolders.py diff --git a/scripts/pin_installer.py b/scripts/pin_installer.py index db852865f..4b3cb458a 100644 --- a/scripts/pin_installer.py +++ b/scripts/pin_installer.py @@ -13,52 +13,8 @@ Usage: from __future__ import annotations import argparse -import hashlib -import re import sys -from pathlib import Path -from core.paths import REPO_ROOT - -ROOT = REPO_ROOT -INSTALLER = "install.py" -# Each bootstrap and its one pin line, the value between the two groups. -PINS: dict[str, re.Pattern[str]] = { - "install.sh": re.compile(r'^(DEFAULT_INSTALL_SHA256=")[0-9a-f]{64}(")', re.M), - "install.ps1": re.compile(r'^(\s*\$defaultInstallSha256 = ")[0-9a-f]{64}(")', re.M), -} -COMMAND = "python scripts/pin_installer.py" - - -def installer_sha256(root: Path = ROOT) -> str: - return hashlib.sha256((root / INSTALLER).read_bytes()).hexdigest() - - -def stale_pins(root: Path = ROOT) -> list[str]: - """The bootstraps whose pin is not the SHA-256 of install.py.""" - digest = installer_sha256(root) - stale = [] - for name, pin in PINS.items(): - found = pin.search((root / name).read_bytes().decode("utf-8")) - if found is None: - raise ValueError(f"{name}: no installer pin line") - if found.group(0) != f"{found.group(1)}{digest}{found.group(2)}": - stale.append(name) - return stale - - -def write_pins(root: Path = ROOT) -> list[str]: - """Rewrite each stale pin. Returns the bootstraps written.""" - digest = installer_sha256(root) - written = [] - for name in stale_pins(root): - path = root / name - text = path.read_bytes().decode("utf-8") - new, count = PINS[name].subn(rf"\g<1>{digest}\g<2>", text) - if count != 1: - raise ValueError(f"{name}: {count} installer pin lines, expected 1") - path.write_bytes(new.encode("utf-8")) - written.append(name) - return written +from installer_build.pins import COMMAND, INSTALLER, installer_sha256, stale_pins, write_pins def main() -> int: diff --git a/scripts/pr_checks.py b/scripts/pr_checks.py index b2a442784..dac5bb6eb 100644 --- a/scripts/pr_checks.py +++ b/scripts/pr_checks.py @@ -13,99 +13,7 @@ absent (npm, python3.8, vermin) is reported as not run, with what provides it. from __future__ import annotations import argparse -import os -import shutil -import subprocess -import sys -from dataclasses import dataclass, field -from core.paths import REPO_ROOT - -ROOT = REPO_ROOT - - -@dataclass(frozen=True) -class Step: - command: str - why: str - needs: str = "" - provider: str = "" - env: dict[str, str] = field(default_factory=dict) - # validate.yml marks the step continue-on-error: its failure is shown - # and does not fail the run. - may_fail: bool = False - - -# The order of validate.yml: data fetched, site generated and built, then the -# suite, its 3.8 run and the built-site check. -STEPS: tuple[Step, ...] = ( - Step("python scripts/validate_pr.py --changed", "the BIOS files the branch adds"), - Step("python scripts/validate_schemas.py --source-only", "profiles and platform files"), - Step("mypy", "no type error in install.py, installer/ and scripts/", needs="mypy", - provider='pip install -e ".[dev]"'), - Step("ruff check .", "the lint rules of pyproject.toml", needs="ruff", - provider='pip install -e ".[dev]"'), - Step("python scripts/build_installer.py --check", "install.py is the one installer/ builds"), - Step("python scripts/profile_sync.py --added --strict", "each profile the branch adds"), - Step("vermin --no-tips -t=3.8- --violations install.py installer", "the installer stays on Python 3.8", - needs="vermin", provider="the pip line of CONTRIBUTING.md"), - Step("shellcheck --version", "the launcher test runs shellcheck", needs="shellcheck", - provider="the shellcheck package"), - Step("python scripts/export_native.py --all --refresh-cache", - "files the exporter tests compare with"), - Step("python scripts/refresh_data_dirs.py", "data directories the pack-building tests read"), - Step("python scripts/generate_site.py", "the pages the site tests read"), - Step("npm ci --prefix website", "the site's packages, Node 24", - needs="npm", provider="Node 24"), - # Node's compile cache lands in /tmp, a 4 GB tmpfs here: one build - # filled it and every later command failed with ENOSPC. - Step("npm run build --prefix website", "the built site", - needs="npm", provider="Node 24", env={"NODE_DISABLE_COMPILE_CACHE": "1"}), - Step("python scripts/run_tests.py --jobs 4", "the suite, one process per module", - env={"RETROBIOS_OFFLINE": "1"}), - Step("python3.8 -m unittest tests.test_install_tui", "the full screen on the installer's floor", - needs="python3.8", provider="a Python 3.8 with pyte", - env={"RETROBIOS_OFFLINE": "1"}), - Step("python scripts/validate_site.py --site-dir website/dist", "links and page budgets"), -) - - -def argv(command: str) -> list[str]: - """The command, with `python` run by the interpreter running this script.""" - words = command.split() - return [sys.executable, *words[1:]] if words[0] == "python" else words - - -def shown(step: Step) -> str: - return step.command - - -def execute(step: Step) -> int: - env = {**os.environ, **step.env} - return subprocess.run(argv(step.command), cwd=ROOT, env=env, check=False).returncode - - -def run(steps: tuple[Step, ...] = STEPS) -> int: - failed: list[str] = [] - allowed: list[str] = [] - not_run: list[str] = [] - for step in steps: - print(f"\n== {shown(step)}", flush=True) - if step.needs and shutil.which(step.needs) is None: - print(f"not run: {step.needs} is not installed ({step.provider})") - not_run.append(f"{shown(step)} ({step.needs}: {step.provider})") - continue - code = execute(step) - if code: - (allowed if step.may_fail else failed).append(f"{shown(step)} (exit {code})") - print() - for line in failed: - print(f"FAILED {line}") - for line in allowed: - print(f"FAILED {line}, continue-on-error in CI as well") - for line in not_run: - print(f"NOT RUN {line}") - print(f"{len(steps) - len(failed) - len(allowed) - len(not_run)}/{len(steps)} checks passed") - return 1 if failed else 0 +from devtools.prchecks import STEPS, run, shown def main() -> int: diff --git a/scripts/release/__init__.py b/scripts/release/__init__.py new file mode 100644 index 000000000..8cfe585c3 --- /dev/null +++ b/scripts/release/__init__.py @@ -0,0 +1 @@ +"""Release artifacts: what the packs of a release hold, its notes, and the checks of its assets.""" diff --git a/scripts/release/assets.py b/scripts/release/assets.py new file mode 100644 index 000000000..943bceb50 --- /dev/null +++ b/scripts/release/assets.py @@ -0,0 +1,306 @@ +"""The large-files release compared with the files the collection keeps out of git.""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import subprocess +from collections.abc import Iterable +from typing import NamedTuple + +from model.composition import composition_tier +from model.largefiles import LARGE_FILES_RELEASE, LARGE_FILES_REPO, asset_names, registered_paths + + +class AssetFinding(NamedTuple): + """A difference between the release and the collection.""" + + kind: str + path: str + size: int + published: int | None + + +def expected_assets(db: dict, gitignore_text: str) -> dict[str, int]: + """Map each gitignored database path to the size the manifests carry.""" + ignored = set(registered_paths(gitignore_text)) + return { + entry["path"]: entry["size"] + for entry in db.get("files", {}).values() + if entry.get("path") in ignored + } + + +def _spellings(name: str) -> list[str]: + """Names the release may publish an asset under. + + GitHub rewrites spaces to dots in asset names, so a file whose name + carries spaces is published under the dotted form. + """ + return [name, name.replace(" ", ".")] if " " in name else [name] + + +def compare( + expected: dict[str, int], + assets: dict[str, int], + notes_current: bool = True, + registered: Iterable[str] | None = None, + expected_digests: dict[str, str] | None = None, + asset_digests: dict[str, str] | None = None, +) -> list[AssetFinding]: + """Files the release lacks or serves at another size, sorted by kind. + + At the same size, the sha256 the release lists for an asset is held + against the collection's: a dump rebuilt at its old size and never + re-uploaded was invisible to a size comparison. + + *registered* is every path .gitignore lists. An asset name depends on + which other paths share its basename, so it defaults to *expected* only + when the caller has nothing wider. A release description that no longer + matches what render_notes() would write is a finding of its own: the + page is what a reader checks a download against. + """ + findings: list[AssetFinding] = [] + if not notes_current: + findings.append(AssetFinding("notes", "release description", 0, None)) + names = asset_names([*(registered or ()), *expected]) + for path, size in sorted(expected.items()): + served = next( + (name for name in _spellings(names[path]) if name in assets), None + ) + if not served: + findings.append(AssetFinding("missing", path, size, None)) + continue + published = assets[served] + if published != size: + findings.append(AssetFinding("size", path, size, published)) + else: + ours = (expected_digests or {}).get(path) + theirs = (asset_digests or {}).get(served) + if ours and theirs and ours != theirs: + findings.append(AssetFinding("content", path, size, published)) + return sorted(findings) + + +def expected_digests(db: dict, gitignore_text: str) -> dict[str, str]: + """sha256 of each gitignored database path.""" + ignored = set(registered_paths(gitignore_text)) + return { + entry["path"]: entry["sha256"].lower() + for entry in db.get("files", {}).values() + if entry.get("path") in ignored and entry.get("sha256") + } + + +def digests_of(assets_json: list[dict]) -> dict[str, str]: + """sha256 the release lists for each asset, by name.""" + return { + a["name"]: str(a["digest"]).removeprefix("sha256:").lower() + for a in assets_json + if str(a.get("digest") or "").startswith("sha256:") + } + + +ASSET_URL = f"https://github.com/{LARGE_FILES_REPO}/releases/download/{LARGE_FILES_RELEASE}/" +NOT_INDEXED = "Not indexed" +SECTIONS = ( + "Console firmware", + "Arcade", + "Computer", + "Game engine data", + "Virtual machine firmware", + "Other", + NOT_INDEXED, +) +_ROW = re.compile( + r"^\| \[(?P[^\]]+)\]\([^)]*\) \| (?P[^|]*?) \| [^|]* \|" + r"(?: `(?P[0-9a-f]{40})` \|)?$", + re.M, +) +_HEADING = re.compile(r"^## (.+)$", re.M) + + +def parse_notes(body: str) -> dict[str, tuple[str, str, str]]: + """Name -> (section, description, sha1) for every row of a release page.""" + rows: dict[str, tuple[str, str, str]] = {} + section = "" + for line in body.splitlines(): + heading = _HEADING.match(line) + if heading: + section = heading.group(1).strip() + continue + row = _ROW.match(line) + if row: + rows[row.group("name")] = ( + section, row.group("desc").strip(), row.group("sha1") or "" + ) + return rows + + +def _section_for(path: str) -> str: + parts = path.split("/") + top = parts[1] if len(parts) > 1 else "" + if top in ("Nintendo", "Sony", "Sega", "Microsoft", "NEC", "SNK"): + return "Console firmware" + if top == "Arcade" or "/samples/" in path: + return "Arcade" + if top == "QEMU": + return "Virtual machine firmware" + if composition_tier(path) == "game_data": + return "Game engine data" + if top in ("Apple", "Commodore", "Atari", "Sinclair", "Amstrad"): + return "Computer" + return "Other" + + +def _mib(size: int) -> str: + return f"{round(size / 1048576)} MB" + + +def render_notes( + db: dict, + gitignore_text: str, + assets: dict[str, int], + previous: str, + descriptions: dict[str, str], + bundles: dict[str, str], + cache_sha1: dict[str, str], +) -> str: + """The release page, from what the release actually serves. + + Every asset gets one row. A file the database indexes carries its + database SHA1, a data-directory bundle carries the hash of its cached + copy when one exists, and anything else is listed apart with its size only, + so the page never vouches for bytes nobody indexed. Descriptions and + sections already written by hand are kept by name. + """ + known = parse_notes(previous) + names = asset_names(registered_paths(gitignore_text)) + indexed: dict[str, tuple[str, str]] = {} + for sha1, entry in db.get("files", {}).items(): + path = entry.get("path", "") + if path in names: + for candidate in _spellings(names[path]): + indexed[candidate] = (sha1, path) + + rows: dict[str, list[tuple[int, str]]] = {section: [] for section in SECTIONS} + for name, size in assets.items(): + section, description, previous_sha1 = known.get(name, ("", "", "")) + if name in indexed: + sha1, path = indexed[name] + section = section if section in SECTIONS[:-1] else _section_for(path) + stem = name.split(".")[0] + "." + name.split(".")[1] if name.count(".") > 1 else name + description = description or descriptions.get(name) or descriptions.get(stem) or path + elif name in bundles: + sha1 = cache_sha1.get(name, previous_sha1) + section = section if section in SECTIONS[:-1] else "Game engine data" + description = description or bundles[name] + else: + sha1 = "" + section = NOT_INDEXED + description = description or name + link = f"[{name}]({ASSET_URL}{name})" + if section == NOT_INDEXED: + line = f"| {link} | {description} | {_mib(size)} |" + else: + line = f"| {link} | {description} | {_mib(size)} | `{sha1}` |" + rows[section].append((-size, line)) + + out = [ + "Files too large for the git repository (GitHub 100MB limit), plus game engine data packs.", + "Downloaded automatically by `generate_pack.py` when not present locally.", + "Manual: `gh release download large-files`", + ] + for section in SECTIONS: + if not rows[section]: + continue + out += ["", f"## {section}", ""] + if section == NOT_INDEXED: + out += [ + "Assets the collection does not index: no database entry names them, " + "so no hash is vouched for here.", + "", + "| File | Description | Size |", + "|------|-------------|-----:|", + ] + else: + out += ["| File | Description | Size | SHA1 |", "|------|-------------|-----:|------|"] + out += [line for _, line in sorted(rows[section])] + total = sum(assets.values()) + out += ["", f"{len(assets)} files, {total / 1073741824:.1f} GB total. Verify a download with `sha1sum `.", ""] + return "\n".join(out) + + +def profile_descriptions(emulators_dir: str = "emulators") -> dict[str, str]: + """Name -> description, from the first profile that declares the file.""" + from model.profiles import load_emulator_profiles + + found: dict[str, str] = {} + for profile in load_emulator_profiles(emulators_dir).values(): + for entry in profile.get("files", []): + name = str(entry.get("name") or "") + if name and entry.get("description"): + found.setdefault(name, str(entry["description"])) + return found + + +def registry_bundles(registry_path: str = "platforms/_data_dirs.yml") -> dict[str, str]: + """Asset name -> description for data directories served from the release.""" + from model.safeparse import yaml_load + + with open(registry_path, encoding="utf-8") as handle: + registry = yaml_load(handle) or {} + bundles: dict[str, str] = {} + for entry in (registry.get("data_directories") or registry).values(): + if not isinstance(entry, dict): + continue + url = str(entry.get("source_url") or "") + if url.startswith(ASSET_URL): + bundles[url[len(ASSET_URL):]] = str(entry.get("description") or "") + return bundles + + +def cache_hashes(names: set[str], cache_dir: str = ".cache/large") -> dict[str, str]: + """SHA1 of the cached copy of each named asset that the cache holds.""" + hashes: dict[str, str] = {} + for name in names: + path = os.path.join(cache_dir, name) + if os.path.isfile(path): + digest = hashlib.sha1() + with open(path, "rb") as handle: + for chunk in iter(lambda: handle.read(1 << 20), b""): + digest.update(chunk) + hashes[name] = digest.hexdigest() + return hashes + + +def fetch_release() -> tuple[dict[str, int], str, dict[str, str]]: + """Name and size of every asset of the large-files release, its page, + and the sha256 it lists per asset.""" + result = subprocess.run( + [ + "gh", "release", "view", LARGE_FILES_RELEASE, + "-R", LARGE_FILES_REPO, "--json", "assets,body", + ], + capture_output=True, text=True, check=True, + ) + data = json.loads(result.stdout) + return ( + {a["name"]: a["size"] for a in data["assets"]}, + data.get("body", ""), + digests_of(data["assets"]), + ) + + +def fetch_assets() -> dict[str, int]: + """Name and size of every asset of the large-files release.""" + result = subprocess.run( + [ + "gh", "release", "view", LARGE_FILES_RELEASE, + "-R", LARGE_FILES_REPO, "--json", "assets", + ], + capture_output=True, text=True, check=True, + ) + return {a["name"]: a["size"] for a in json.loads(result.stdout)["assets"]} diff --git a/scripts/release/check.py b/scripts/release/check.py new file mode 100644 index 000000000..aa0cc6723 --- /dev/null +++ b/scripts/release/check.py @@ -0,0 +1,145 @@ +"""A dated release compared with release.json and the checksum list.""" + +from __future__ import annotations + +import hashlib +import json +import subprocess +from dataclasses import dataclass +from pathlib import Path + +from release.assets import digests_of +from model.largefiles import LARGE_FILES_REPO + + +SUMS = "SHA256SUMS.txt" +SIGNATURE = SUMS + ".sig" +@dataclass(frozen=True) +class Asset: + size: int + sha256: str | None + + +@dataclass(frozen=True) +class Finding: + kind: str + name: str + detail: str + + +def parse_sums(text: str) -> dict[str, str]: + """`sha256sum` output: digest, then a space and a mode character.""" + sums: dict[str, str] = {} + for line in text.splitlines(): + line = line.strip() + if not line: + continue + digest, _, name = line.partition(" ") + if len(digest) != 64 or not name: + raise ValueError(f"not a sha256sum line: {line!r}") + sums[name.lstrip(" *")] = digest.lower() + return sums + + +def _registry_findings(packs: dict, released: set[str]) -> list[Finding]: + """Each platform marked release_pack has a pack, and each pack serves one.""" + served = {p for pack in packs.values() for p in pack.get("platforms", ())} + findings = [Finding("no-pack", platform, "release_pack: true, no pack in release.json") + for platform in sorted(released - served)] + findings.extend(Finding( + "not-released", pack_name, + "serves no platform marked release_pack in platforms/_registry.yml", + ) for pack_name, pack in sorted(packs.items()) if not set(pack.get("platforms", ())) & released) + return findings + + +def compare_release( + record: dict, + sums: dict[str, str], + assets: dict[str, Asset], + tag: str, + local_files: dict[str, str] | None = None, + released: set[str] | None = None, +) -> list[Finding]: + """Every way the release can differ from what was built. + + *local_files* maps a file kept beside the packs (the checksum list, its + signature) to its local sha256: the copy on the release must be that one. + *released* names the platforms the registry marks release_pack: each one + has a recorded pack, and no recorded pack serves only other platforms. + """ + findings: list[Finding] = [] + if record.get("tag") != tag: + findings.append(Finding("tag", tag, f"release.json records {record.get('tag')}")) + if released is not None: + findings += _registry_findings(record.get("packs", {}), released) + + recorded = { + name: pack_name + for pack_name, pack in record.get("packs", {}).items() + for name in pack.get("assets", []) + } + expected = set(recorded) | set(sums) | {SUMS} | set(local_files or ()) + allowed = expected | {SIGNATURE} + + findings.extend(Finding("missing", name, "not attached to the release") + for name in sorted(expected - set(assets))) + findings.extend(Finding("extra", name, "attached but neither recorded nor listed") + for name in sorted(set(assets) - allowed)) + findings.extend(Finding("unlisted", name, f"absent from {SUMS}") + for name in sorted(set(recorded) - set(sums))) + findings.extend(Finding("unrecorded", name, f"listed in {SUMS}, absent from release.json") + for name in sorted(set(sums) - set(recorded))) + + wanted = {**sums, **(local_files or {})} + for name, digest in sorted(wanted.items()): + asset = assets.get(name) + if asset is None: + continue + if asset.sha256 is None: + findings.append(Finding("unverified", name, "the release gives no sha256")) + elif asset.sha256 != digest: + findings.append(Finding( + "content", name, f"release sha256 {asset.sha256[:12]} != {digest[:12]}" + )) + + for pack_name, pack in sorted(record.get("packs", {}).items()): + parts = [assets[name].size for name in pack.get("assets", []) if name in assets] + if len(parts) == len(pack.get("assets", [])) and sum(parts) != pack.get("download_size"): + findings.append(Finding( + "size", pack_name, + f"assets total {sum(parts)} bytes, release.json says {pack.get('download_size')}", + )) + return findings + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with open(path, "rb") as handle: + for chunk in iter(lambda: handle.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def fetch_assets(tag: str) -> tuple[dict[str, Asset], bool]: + """Name, size and sha256 of every asset of *tag*, and whether it is a draft.""" + result = subprocess.run( + ["gh", "release", "view", tag, "-R", LARGE_FILES_REPO, "--json", "assets,isDraft"], + capture_output=True, text=True, check=True, + ) + data = json.loads(result.stdout) + digests = digests_of(data["assets"]) + return ( + {a["name"]: Asset(a["size"], digests.get(a["name"])) for a in data["assets"]}, + bool(data.get("isDraft")), + ) + + +def fetch_sums(tag: str) -> str: + """The checksum list as attached to *tag*.""" + result = subprocess.run( + ["gh", "release", "download", tag, "-R", LARGE_FILES_REPO, + "--pattern", SUMS, "--output", "-"], + capture_output=True, text=True, check=True, + ) + return result.stdout diff --git a/scripts/release/notes.py b/scripts/release/notes.py new file mode 100644 index 000000000..0dc110b12 --- /dev/null +++ b/scripts/release/notes.py @@ -0,0 +1,255 @@ +"""The notes of a release, written from its record and the registry.""" + +from __future__ import annotations + +import json +import re +import subprocess +from collections.abc import Callable + +from model.guides import install_command +from model.platforms import load_platform_config +from model.registry import ( + list_registered_platforms, + list_release_pack_platforms, + load_platform_registry, +) +from release import record as release_record + + +REPO = "Abdess/retrobios" +OWNER = "Abdess" +SITE = "https://abdess.github.io/retrobios/" +# The handheld app is served by the site, built from its own commit, never +# attached to a release. The installer's handheld section opens on the +# download of every system. +HANDHELD_PAGE = "wiki/installer/#on-a-handheld-the-retrobios-port" + + +def _display(pack: str) -> str: + """RetroArch_Lakka_v1.22.2_BIOS_Pack.zip reads as RetroArch Lakka v1.22.2.""" + return pack.split("_BIOS_Pack", 1)[0].replace("_", " ") + + +def _owner(name: str, pack: dict) -> str: + """The platform a pack is named after: RetroArch_Lakka is RetroArch's.""" + key = _match_key(name) + return sorted( + pack.get("platforms", ()), key=lambda p: key.find(_match_key(p)) % (len(key) + 1) + )[0] + + +def _extract_folders(record: dict, platforms_dir: str) -> dict[str, str]: + """Pack name to the folder the registry says it extracts into.""" + registry = load_platform_registry(platforms_dir) + folders: dict[str, str] = {} + for name, pack in sorted(record.get("packs", {}).items()): + folder = registry.get(_owner(name, pack), {}).get("extract_to") + if folder: + folders[name] = folder + return folders + + +def without_pack(platforms_dir: str) -> list[str]: + """Display names of the registered setups no release publishes a ZIP for.""" + released = set(list_release_pack_platforms(platforms_dir)) + names = [ + str(load_platform_config(key, platforms_dir).get("platform", key)) + for key in list_registered_platforms(platforms_dir) + if key not in released + ] + return sorted(names, key=str.casefold) + + +def no_pack_paragraph(platforms_dir: str) -> list[str]: + """One paragraph naming the setups served by the command alone. The + packs published are the most downloaded ones (wiki/release-process.md, + "Which platforms get a pack").""" + names = without_pack(platforms_dir) + if not names: + return [] + listed = ", ".join(names[:-1]) + f" and {names[-1]}" if len(names) > 1 else names[0] + return [ + ("Only the most used setups have a pack, to keep the release small." + f" For {listed}, use the command above."), + "", + ] + + +def _match_key(value: str) -> str: + """Letters and digits only: the platform is `misterfpga`, the pack MiSTer_FPGA.""" + return re.sub(r"[^a-z0-9]", "", value.lower()) + + +def _link(pack: dict, tag: str) -> str: + """The pack's files on this release, one link per part.""" + base = f"https://github.com/{REPO}/releases/download/{tag}" + assets = pack["assets"] + if len(assets) == 1: + return f"[Download]({base}/{assets[0]})" + return ", ".join(f"[part {i}]({base}/{name})" for i, name in enumerate(assets, 1)) + + +# Words the published notes of v2026.10.10 carried by hand: "never from a +# forum list" judged lists other people keep, and "a game never stops on a +# missing file" was a claim the gap analysis contradicts. Text about other +# projects says what changed, not who erred (wiki/release-process.md). +REFUSED = ("their file", "theirs", "of ours", "corrected", "wrong", "drift", + "left out", "never seen", "forum", "never stops", "never fails") + + +def refused_words(text: str) -> list[str]: + """The refused phrases the text holds, case ignored.""" + lowered = text.lower() + return [phrase for phrase in REFUSED if phrase in lowered] + + +Run = Callable[[list[str]], str] + + +def _run(argv: list[str]) -> str: + return subprocess.run(argv, capture_output=True, text=True, check=True).stdout + + +def previous_record_commit(tag: str, run: Run | None = None) -> str: + """The commit that recorded the release before *tag*: the oldest commit + of the run of release.json changes that name the previous tag.""" + run = run or _run + shas = run(["git", "log", "--format=%H", "--", "release.json"]).split() + previous, base = None, None + for sha in shas: + recorded = json.loads(run(["git", "show", f"{sha}:release.json"])).get("tag") + if previous is None: + if recorded != tag: + previous, base = recorded, sha + elif recorded == previous: + base = sha + else: + break + if base is None: + raise ValueError(f"release.json records no release before {tag}") + return base + + +# Accounts that never helped: the owner's own, GitHub's placeholder for a +# deleted account, and spam (issue 32 by Bappo0 and pull request 67 by +# prakashmagat50-byte, both empty or garbage). +LEFT_OUT = frozenset(("Abdess", "Abdess76", "ghost", "Bappo0", "prakashmagat50-byte")) + + +def _person(login: str | None) -> str | None: + """The login to thank, None for the owner, a bot, a deleted account, + spam, or work GitHub links to no account.""" + if not login or login in LEFT_OUT or login.endswith("[bot]") or login.startswith("app/"): + return None + return login + + +def _logins(text: str) -> set[str]: + """One login per line, as `gh api --paginate --jq` prints them.""" + return {person for line in text.splitlines() if (person := _person(line.strip()))} + + +def _authors(text: str) -> set[str]: + """The authors of a `gh pr list` or `gh issue list --json author`.""" + return {person for item in json.loads(text) + if not (item.get("author") or {}).get("is_bot") + and (person := _person((item.get("author") or {}).get("login")))} + + +def gather_thanks(run: Run | None = None, repo: str = REPO) -> list[str]: + """Everyone who helped since the repository started, each named once: + commit authors as the commits API links them to an account and every + pull request author, merged or not, then issue authors, then whoever + commented on an issue or a pull request.""" + run = run or _run + code = _logins(run(["gh", "api", "--paginate", f"repos/{repo}/commits", + "--jq", ".[] | .author.login // empty"])) + code |= _authors(run(["gh", "pr", "list", "-R", repo, "--state", "all", + "--limit", "10000", "--json", "number,author"])) + reports = _authors(run(["gh", "issue", "list", "-R", repo, "--state", "all", + "--limit", "10000", "--json", "number,author"])) - code + helped = set() + for path in (f"repos/{repo}/issues/comments", f"repos/{repo}/pulls/comments"): + helped |= _logins(run(["gh", "api", "--paginate", path, "--jq", ".[] | .user.login"])) + helped -= code | reports + lines = [] + for label, people in (("Code and data", code), ("Reports", reports), + ("Help in issues", helped)): + if people: + names = [f"@{login}" for login in sorted(people, key=str.casefold)] + listed = names[0] if len(names) == 1 else f"{', '.join(names[:-1])} and {names[-1]}" + lines.append(f"- **{label}**: {listed}.") + return lines + + +def changelog_url(base: str, tag: str, repo: str = REPO) -> str: + return f"https://github.com/{repo}/compare/{base[:9]}...{tag}" + + +def closing_lines(thanks: list[str], changelog: str) -> list[str]: + """The Thanks section, left out when nobody is to thank, and the full + changelog line.""" + # Folded: the lists run to a hundred names. GitHub renders the markdown + # inside only with a blank line on each side of it. + lines = (["### Thanks", "", "
", + "Everyone who helped since the start", "", + *thanks, "", "
", ""] + if thanks else []) + return [*lines, f"**Full changelog**: {changelog}", ""] + + +def render(record: dict, platforms_dir: str, whats_new: str, + closing: list[str] | None = None) -> str: + packs = record.get("packs", {}) + folders = _extract_folders(record, platforms_dir) + tag = str(record.get("tag", "")) + lines = [ + "### Get the BIOS files", + "", + "Paste this in a terminal. It finds the setup and installs the missing BIOS files.", + "", + "**Linux, macOS, Steam Deck**", + "```sh", + install_command("sh"), + "```", + "", + "**Windows**", + "```powershell", + install_command("powershell"), + "```", + "", + f"**On a handheld**: [get the app for the system]({SITE}{HANDHELD_PAGE}).", + "", + "### Full packs", + "", + "Large downloads, for a device without internet. Extract into the BIOS folder.", + "", + ] + if any(len(pack["assets"]) > 1 for pack in packs.values()): + lines += [ + ("A pack in parts: each part is an ordinary ZIP. Extract every part into" + " the same folder. Nothing needs joining."), + "", + ] + lines += [ + "| Platform | Download | Size | Files | Extract to |", + "|----------|----------|-----:|------:|-----------|", + ] + for name, pack in sorted(packs.items(), key=lambda item: -item[1]["extracted_size"]): + folder = folders.get(name) + lines.append( + f"| {_display(name)} | {_link(pack, tag)} |" + f" {release_record.size_text(pack['extracted_size'])} | {pack['files']:,} |" + f" {f'`{folder}`' if folder else '-'} |" + ) + lines += [ + "", + f"Files no pack holds yet: [gap analysis]({SITE}gaps/).", + "", + *no_pack_paragraph(platforms_dir), + whats_new.strip(), + "", + *(closing or []), + ] + return "\n".join(lines) diff --git a/scripts/release/record.py b/scripts/release/record.py new file mode 100644 index 000000000..3c3913626 --- /dev/null +++ b/scripts/release/record.py @@ -0,0 +1,122 @@ +"""What the packs of a release hold, read from the archives when the release is cut.""" + +from __future__ import annotations + +import json +import zipfile +from pathlib import Path + +from core.artifacts import artifact_lock +from model.registry import list_release_pack_platforms +from model.releaserecord import SCHEMA_VERSION, pack_name_for +from packs import parts + + +class UnfinishedSplitError(Exception): + """A pack lies beside its own parts: a split is running or was killed.""" + + +class NotAReleasePackError(Exception): + """A pack in the directory is not the full pack of a registered platform.""" + + +def release_owners(platforms_dir: str = "platforms") -> dict[str, list[str]]: + """Full pack file name to the platforms it serves, as the builder names it. + + Rebuilt from the name builder, never matched by substring: matched by + substring, RetroArch_v1.22.2_AndroidArm64V8A_BIOS_Pack.zip sorts before + the full pack and was taken for the RetroArch pack. Only the platforms + marked release_pack own a release pack. + """ + from packs import naming + + platforms = list_release_pack_platforms(platforms_dir) + owners: dict[str, list[str]] = {} + for platform, names in naming._expected_pack_names( + platforms, platforms_dir, None, None + ).items(): + for name in names: + owners.setdefault(name, []).append(platform) + return {name: sorted(serves) for name, serves in owners.items()} + + +def build_record( + dist: Path, + tag: str, + platforms_dir: str = "platforms", + owners: dict[str, list[str]] | None = None, +) -> dict: + """Read every pack of a directory, parts counted once across them. + + Read under the shared artifact lock, so a split that is reading its parts + back cannot be recorded half done. A pack still beside its parts after + that is a split that never finished: summed, it doubled the download size + and named an asset that is never published. Each pack carries the + platforms it serves, so a reader finds a platform's pack by that list + after a later version or grouping has renamed the pack main would build. + """ + if owners is None: + owners = release_owners(platforms_dir) + with artifact_lock(str(dist), exclusive=False): + return _read_record(Path(dist), tag, owners) + + +def _read_record(dist: Path, tag: str, owners: dict[str, list[str]]) -> dict: + assets: dict[str, list[Path]] = {} + for path in sorted(dist.glob("*_BIOS_Pack*.zip")): + assets.setdefault(parts.pack_of(path.name), []).append(path) + for paths in assets.values(): + whole = [p for p in paths if not parts.is_part(p.name)] + if whole and len(paths) > len(whole): + raise UnfinishedSplitError( + f"{whole[0].name} lies beside its parts: the split did not finish" + ) + foreign = sorted(name for name in assets if name not in owners) + if foreign: + raise NotAReleasePackError( + f"not the full pack of a registered platform: {', '.join(foreign)}" + " (a narrowed or older build left in the directory)" + ) + + packs = {} + for name, paths in sorted(assets.items()): + members: dict[str, int] = {} + for path in paths: + with zipfile.ZipFile(path) as archive: + # A part's marker names its siblings and is not pack content: + # the manifest's pack_files is counted before any split. + for info in archive.infolist(): + if not parts.is_marker(info.filename): + members[info.filename] = info.file_size + packs[name] = { + "files": len(members), + "extracted_size": sum(members.values()), + "download_size": sum(path.stat().st_size for path in paths), + "assets": [path.name for path in paths], + "platforms": owners[name], + } + return {"schema_version": SCHEMA_VERSION, "tag": tag, "packs": packs} + + +def manifest_mismatches(record: dict, install_dir: str | Path) -> list[str]: + """Packs whose archive does not hold what their install manifest expects.""" + found = [] + for manifest_path in sorted(Path(install_dir).glob("*.json")): + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + expected = manifest.get("pack_files") + name = pack_name_for(manifest_path.stem, record) + if expected is None or name is None: + continue + pack = record["packs"][name] + if pack["files"] != expected: + found.append( + f"{name} holds {pack['files']} files, " + f"install/{manifest_path.name} expects {expected}" + ) + return found + + +def size_text(count: int) -> str: + if count >= 1024**3: + return f"{count / 1024**3:.1f} GB" + return f"{count / 1024**2:.0f} MB" diff --git a/scripts/release/restore.py b/scripts/release/restore.py new file mode 100644 index 000000000..a87fea85c --- /dev/null +++ b/scripts/release/restore.py @@ -0,0 +1,114 @@ +"""Gitignored large files restored into the checkout from the release cache.""" + +from __future__ import annotations + +import contextlib +import hashlib +import os +import sys +import tempfile + +from core.artifacts import copy_file_atomic, set_plain_mode +from model.database import load_database + + +def gitignored_paths(gitignore: str) -> set[str]: + """Paths the repository keeps out of git, as written in .gitignore. + + A missing file raises: read as empty, it left nothing to restore and + nothing unsatisfied, and the run exited 0 with every asset absent. + """ + with open(gitignore) as f: + return { + line.strip() for line in f if line.strip().startswith("bios/") + } + + +def index_cache(cache_dir: str) -> dict[str, str]: + """Map SHA1 to cached file path for every asset in the cache.""" + index: dict[str, str] = {} + for name in sorted(os.listdir(cache_dir)): + # A download in progress writes `..tmp` beside the + # cache and renames it when done: it is partial, and may be gone by + # the time it is opened. + if name.endswith(".tmp"): + continue + path = os.path.join(cache_dir, name) + if not os.path.isfile(path): + continue + digest = hashlib.sha1() + with open(path, "rb") as f: + for chunk in iter(lambda: f.read(1 << 20), b""): + digest.update(chunk) + index[digest.hexdigest()] = path + return index + + +def _copy_verified(source: str, path: str, sha1: str) -> bool: + """Copy *source* to *path* only if the copy hashes to *sha1*. + + The cache was hashed before the copy, and another run can replace a + cached name in between (a re-uploaded asset): the copy is what counts. + Whole or absent: a scan running beside a plain copy hashed the truncated + file and published that in the database. + """ + handle, scratch = tempfile.mkstemp( + dir=os.path.dirname(os.path.abspath(path)), + prefix=f".{os.path.basename(path)}.", suffix=".tmp", + ) + os.close(handle) + try: + copy_file_atomic(source, scratch) + digest = hashlib.sha1() + with open(scratch, "rb") as f: + for chunk in iter(lambda: f.read(1 << 20), b""): + digest.update(chunk) + if digest.hexdigest() != sha1: + print(f"Changed in the cache while restoring: {source}", file=sys.stderr) + return False + set_plain_mode(scratch) + os.replace(scratch, path) + return True + finally: + with contextlib.suppress(FileNotFoundError): + os.unlink(scratch) + + +def restore( + cache_dir: str, db_path: str, gitignore: str +) -> tuple[int, list[str]]: + ignored = gitignored_paths(gitignore) + # No cache is not nothing to do: the paths it would have supplied are + # still missing, and the check below is the one that must say so. + if os.path.isdir(cache_dir): + index = index_cache(cache_dir) + else: + print(f"No cache at {cache_dir}") + index = {} + db = load_database(db_path) + restored = 0 + unsatisfied: list[str] = [] + for sha1, entry in db.get("files", {}).items(): + path = entry.get("path", "") + if path not in ignored or os.path.exists(path): + continue + source = index.get(sha1) + if not source: + unsatisfied.append(path) + continue + os.makedirs(os.path.dirname(path), exist_ok=True) + if not _copy_verified(source, path, sha1): + unsatisfied.append(path) + continue + print(f"Restored: {path}") + restored += 1 + print(f"Total: {restored} files restored") + if unsatisfied: + # Every consumer downstream resolves against the disk, so a path the + # cache cannot supply is not a smaller restore: it drops entries from + # the manifest and inflates the missing count the README publishes. + print(f"Unsatisfied: {len(unsatisfied)} declared paths the cache " + "cannot supply", file=sys.stderr) + for path in sorted(unsatisfied)[:10]: + print(f" {path}", file=sys.stderr) + return restored, unsatisfied diff --git a/scripts/release/sync.py b/scripts/release/sync.py new file mode 100644 index 000000000..869403877 --- /dev/null +++ b/scripts/release/sync.py @@ -0,0 +1,126 @@ +"""Upload of the large-files assets the release lacks or serves out of date.""" + +from __future__ import annotations + +import hashlib +import os +import shutil +import subprocess +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path + +from model.largefiles import LARGE_FILES_RELEASE, LARGE_FILES_REPO, asset_names, registered_paths +from release.assets import compare, expected_assets, expected_digests, fetch_release + + +STAGING = Path("tmp") / "sync_release_assets" +OUT_OF_DATE = ("missing", "size", "content") + + +@dataclass(frozen=True) +class Upload: + path: str + asset: str + kind: str + verdict: str # upload, refused + reason: str = "" + + +def sha1_of(path: Path) -> str: + digest = hashlib.sha1() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def database_sha1(db: dict) -> dict[str, str]: + return { + entry["path"]: str(entry.get("sha1") or key).lower() + for key, entry in db.get("files", {}).items() + if entry.get("path") + } + + +def plan_uploads( + root: Path, + db: dict, + gitignore_text: str, + findings: list, + hasher: Callable[[Path], str] = sha1_of, +) -> list[Upload]: + """Each out-of-date asset, cleared for upload or refused with its reason.""" + names = asset_names([*registered_paths(gitignore_text), + *expected_assets(db, gitignore_text)]) + recorded = database_sha1(db) + plans = [] + for kind, path, _size, _published in findings: + if kind not in OUT_OF_DATE: + continue + local = root / path + if not local.is_file(): + plans.append(Upload(path, names[path], kind, "refused", "no local file")) + continue + first, second = hasher(local), hasher(local) + if first != second: + plans.append(Upload(path, names[path], kind, "refused", + f"two reads disagree ({first[:12]} != {second[:12]})")) + elif first != recorded.get(path): + plans.append(Upload(path, names[path], kind, "refused", + f"sha1 {first[:12]} is not the database's " + f"{str(recorded.get(path))[:12]}")) + else: + plans.append(Upload(path, names[path], kind, "upload")) + return plans + + +def gh_upload(staged: Path) -> int: + return subprocess.run( + ["gh", "release", "upload", LARGE_FILES_RELEASE, str(staged), "--clobber", + "-R", LARGE_FILES_REPO], + check=False, + ).returncode + + +def stage(root: Path, plan: Upload) -> Path: + """The file under its asset name: gh names an asset after the file.""" + staged = root / STAGING / plan.asset + staged.parent.mkdir(parents=True, exist_ok=True) + if staged.exists(): + staged.unlink() + try: + os.link(root / plan.path, staged) + except OSError: + shutil.copy2(root / plan.path, staged) + return staged + + +def upload_all( + root: Path, plans: list[Upload], upload: Callable[[Path], int] = gh_upload +) -> list[str]: + """Upload every cleared plan, twice at most, and return the failures.""" + failed = [] + for plan in plans: + if plan.verdict != "upload": + continue + staged = stage(root, plan) + try: + if upload(staged) != 0 and upload(staged) != 0: + failed.append(plan.path) + finally: + staged.unlink() + return failed + + +def open_findings( + db: dict, gitignore_text: str, fetch: Callable[[], tuple] = fetch_release +) -> list: + assets, _body, digests = fetch() + return compare( + expected_assets(db, gitignore_text), + assets, + registered=registered_paths(gitignore_text), + expected_digests=expected_digests(db, gitignore_text), + asset_digests=digests, + ) diff --git a/scripts/release_notes.py b/scripts/release_notes.py index 19001e905..594efdbff 100644 --- a/scripts/release_notes.py +++ b/scripts/release_notes.py @@ -26,265 +26,26 @@ Usage: from __future__ import annotations import argparse -import json -import re import subprocess import sys -from collections.abc import Callable from pathlib import Path -import release_record -from model.registry import ( - list_registered_platforms, - list_release_pack_platforms, - load_platform_registry, -) -from model.platforms import load_platform_config +from model import releaserecord from core.cli import require_directory from core.artifacts import write_text_atomic -from model.guides import install_command - -REPO = "Abdess/retrobios" -OWNER = "Abdess" -SITE = "https://abdess.github.io/retrobios/" -# The handheld app is served by the site, built from its own commit, never -# attached to a release. The installer's handheld section opens on the -# download of every system. -HANDHELD_PAGE = "wiki/installer/#on-a-handheld-the-retrobios-port" - - -def _display(pack: str) -> str: - """RetroArch_Lakka_v1.22.2_BIOS_Pack.zip reads as RetroArch Lakka v1.22.2.""" - return pack.split("_BIOS_Pack", 1)[0].replace("_", " ") - - -def _owner(name: str, pack: dict) -> str: - """The platform a pack is named after: RetroArch_Lakka is RetroArch's.""" - key = _match_key(name) - return sorted( - pack.get("platforms", ()), key=lambda p: key.find(_match_key(p)) % (len(key) + 1) - )[0] - - -def _extract_folders(record: dict, platforms_dir: str) -> dict[str, str]: - """Pack name to the folder the registry says it extracts into.""" - registry = load_platform_registry(platforms_dir) - folders: dict[str, str] = {} - for name, pack in sorted(record.get("packs", {}).items()): - folder = registry.get(_owner(name, pack), {}).get("extract_to") - if folder: - folders[name] = folder - return folders - - -def without_pack(platforms_dir: str) -> list[str]: - """Display names of the registered setups no release publishes a ZIP for.""" - released = set(list_release_pack_platforms(platforms_dir)) - names = [ - str(load_platform_config(key, platforms_dir).get("platform", key)) - for key in list_registered_platforms(platforms_dir) - if key not in released - ] - return sorted(names, key=str.casefold) - - -def no_pack_paragraph(platforms_dir: str) -> list[str]: - """One paragraph naming the setups served by the command alone. The - packs published are the most downloaded ones (wiki/release-process.md, - "Which platforms get a pack").""" - names = without_pack(platforms_dir) - if not names: - return [] - listed = ", ".join(names[:-1]) + f" and {names[-1]}" if len(names) > 1 else names[0] - return [ - ("Only the most used setups have a pack, to keep the release small." - f" For {listed}, use the command above."), - "", - ] - - -def _match_key(value: str) -> str: - """Letters and digits only: the platform is `misterfpga`, the pack MiSTer_FPGA.""" - return re.sub(r"[^a-z0-9]", "", value.lower()) - - -def _link(pack: dict, tag: str) -> str: - """The pack's files on this release, one link per part.""" - base = f"https://github.com/{REPO}/releases/download/{tag}" - assets = pack["assets"] - if len(assets) == 1: - return f"[Download]({base}/{assets[0]})" - return ", ".join(f"[part {i}]({base}/{name})" for i, name in enumerate(assets, 1)) - - -# Words the published notes of v2026.10.10 carried by hand: "never from a -# forum list" judged lists other people keep, and "a game never stops on a -# missing file" was a claim the gap analysis contradicts. Text about other -# projects says what changed, not who erred (wiki/release-process.md). -REFUSED = ("their file", "theirs", "of ours", "corrected", "wrong", "drift", - "left out", "never seen", "forum", "never stops", "never fails") - - -def refused_words(text: str) -> list[str]: - """The refused phrases the text holds, case ignored.""" - lowered = text.lower() - return [phrase for phrase in REFUSED if phrase in lowered] - - -Run = Callable[[list[str]], str] - - -def _run(argv: list[str]) -> str: - return subprocess.run(argv, capture_output=True, text=True, check=True).stdout - - -def previous_record_commit(tag: str, run: Run | None = None) -> str: - """The commit that recorded the release before *tag*: the oldest commit - of the run of release.json changes that name the previous tag.""" - run = run or _run - shas = run(["git", "log", "--format=%H", "--", "release.json"]).split() - previous, base = None, None - for sha in shas: - recorded = json.loads(run(["git", "show", f"{sha}:release.json"])).get("tag") - if previous is None: - if recorded != tag: - previous, base = recorded, sha - elif recorded == previous: - base = sha - else: - break - if base is None: - raise ValueError(f"release.json records no release before {tag}") - return base - - -# Accounts that never helped: the owner's own, GitHub's placeholder for a -# deleted account, and spam (issue 32 by Bappo0 and pull request 67 by -# prakashmagat50-byte, both empty or garbage). -LEFT_OUT = frozenset(("Abdess", "Abdess76", "ghost", "Bappo0", "prakashmagat50-byte")) - - -def _person(login: str | None) -> str | None: - """The login to thank, None for the owner, a bot, a deleted account, - spam, or work GitHub links to no account.""" - if not login or login in LEFT_OUT or login.endswith("[bot]") or login.startswith("app/"): - return None - return login - - -def _logins(text: str) -> set[str]: - """One login per line, as `gh api --paginate --jq` prints them.""" - return {person for line in text.splitlines() if (person := _person(line.strip()))} - - -def _authors(text: str) -> set[str]: - """The authors of a `gh pr list` or `gh issue list --json author`.""" - return {person for item in json.loads(text) - if not (item.get("author") or {}).get("is_bot") - and (person := _person((item.get("author") or {}).get("login")))} - - -def gather_thanks(run: Run | None = None, repo: str = REPO) -> list[str]: - """Everyone who helped since the repository started, each named once: - commit authors as the commits API links them to an account and every - pull request author, merged or not, then issue authors, then whoever - commented on an issue or a pull request.""" - run = run or _run - code = _logins(run(["gh", "api", "--paginate", f"repos/{repo}/commits", - "--jq", ".[] | .author.login // empty"])) - code |= _authors(run(["gh", "pr", "list", "-R", repo, "--state", "all", - "--limit", "10000", "--json", "number,author"])) - reports = _authors(run(["gh", "issue", "list", "-R", repo, "--state", "all", - "--limit", "10000", "--json", "number,author"])) - code - helped = set() - for path in (f"repos/{repo}/issues/comments", f"repos/{repo}/pulls/comments"): - helped |= _logins(run(["gh", "api", "--paginate", path, "--jq", ".[] | .user.login"])) - helped -= code | reports - lines = [] - for label, people in (("Code and data", code), ("Reports", reports), - ("Help in issues", helped)): - if people: - names = [f"@{login}" for login in sorted(people, key=str.casefold)] - listed = names[0] if len(names) == 1 else f"{', '.join(names[:-1])} and {names[-1]}" - lines.append(f"- **{label}**: {listed}.") - return lines - - -def changelog_url(base: str, tag: str, repo: str = REPO) -> str: - return f"https://github.com/{repo}/compare/{base[:9]}...{tag}" - - -def closing_lines(thanks: list[str], changelog: str) -> list[str]: - """The Thanks section, left out when nobody is to thank, and the full - changelog line.""" - # Folded: the lists run to a hundred names. GitHub renders the markdown - # inside only with a blank line on each side of it. - lines = (["### Thanks", "", "
", - "Everyone who helped since the start", "", - *thanks, "", "
", ""] - if thanks else []) - return [*lines, f"**Full changelog**: {changelog}", ""] - - -def render(record: dict, platforms_dir: str, whats_new: str, - closing: list[str] | None = None) -> str: - packs = record.get("packs", {}) - folders = _extract_folders(record, platforms_dir) - tag = str(record.get("tag", "")) - lines = [ - "### Get the BIOS files", - "", - "Paste this in a terminal. It finds the setup and installs the missing BIOS files.", - "", - "**Linux, macOS, Steam Deck**", - "```sh", - install_command("sh"), - "```", - "", - "**Windows**", - "```powershell", - install_command("powershell"), - "```", - "", - f"**On a handheld**: [get the app for the system]({SITE}{HANDHELD_PAGE}).", - "", - "### Full packs", - "", - "Large downloads, for a device without internet. Extract into the BIOS folder.", - "", - ] - if any(len(pack["assets"]) > 1 for pack in packs.values()): - lines += [ - ("A pack in parts: each part is an ordinary ZIP. Extract every part into" - " the same folder. Nothing needs joining."), - "", - ] - lines += [ - "| Platform | Download | Size | Files | Extract to |", - "|----------|----------|-----:|------:|-----------|", - ] - for name, pack in sorted(packs.items(), key=lambda item: -item[1]["extracted_size"]): - folder = folders.get(name) - lines.append( - f"| {_display(name)} | {_link(pack, tag)} |" - f" {release_record.size_text(pack['extracted_size'])} | {pack['files']:,} |" - f" {f'`{folder}`' if folder else '-'} |" - ) - lines += [ - "", - f"Files no pack holds yet: [gap analysis]({SITE}gaps/).", - "", - *no_pack_paragraph(platforms_dir), - whats_new.strip(), - "", - *(closing or []), - ] - return "\n".join(lines) +from release.notes import ( + changelog_url, + closing_lines, + gather_thanks, + previous_record_commit, + refused_words, + render, +) def main() -> int: parser = argparse.ArgumentParser(allow_abbrev=False, description="Write a release's notes") - parser.add_argument("--record", default=release_record.RECORD, type=Path, + parser.add_argument("--record", default=releaserecord.RECORD, type=Path, help="release record (default: %(default)s)") parser.add_argument("--whats-new", required=True, type=Path, help="what changed since the previous release, written by hand") @@ -297,7 +58,7 @@ def main() -> int: args = parser.parse_args() require_directory(args.platforms_dir, "--platforms-dir") - record = release_record.load_record(args.record) + record = releaserecord.load_record(args.record) if not record.get("packs"): print(f"Error: {args.record} records no pack", file=sys.stderr) return 1 diff --git a/scripts/release_record.py b/scripts/release_record.py index 48b2ae529..4f783d48b 100644 --- a/scripts/release_record.py +++ b/scripts/release_record.py @@ -19,183 +19,17 @@ from __future__ import annotations import argparse import json import sys -import zipfile from pathlib import Path -from packs import parts -from core.artifacts import ArtifactLockBusy, artifact_lock, write_text_atomic -from model.registry import list_release_pack_platforms - -RECORD = "release.json" -# The record's format, which release.schema.json pins: a reader holding the -# file alone can tell which shape it reads. -SCHEMA_VERSION = 1 -# Each registered platform has a page at get// on the site: the -# current pack's files, or the command when no release publishes one. The -# address outlives every release, so a link written elsewhere keeps working. -GET_DIR = "get" - - -class UnfinishedSplitError(Exception): - """A pack lies beside its own parts: a split is running or was killed.""" - - -class NotAReleasePackError(Exception): - """A pack in the directory is not the full pack of a registered platform.""" - - -def release_owners(platforms_dir: str = "platforms") -> dict[str, list[str]]: - """Full pack file name to the platforms it serves, as the builder names it. - - Rebuilt from the name builder, never matched by substring: matched by - substring, RetroArch_v1.22.2_AndroidArm64V8A_BIOS_Pack.zip sorts before - the full pack and was taken for the RetroArch pack. Only the platforms - marked release_pack own a release pack. - """ - from packs import naming - - platforms = list_release_pack_platforms(platforms_dir) - owners: dict[str, list[str]] = {} - for platform, names in naming._expected_pack_names( - platforms, platforms_dir, None, None - ).items(): - for name in names: - owners.setdefault(name, []).append(platform) - return {name: sorted(serves) for name, serves in owners.items()} - - -def build_record( - dist: Path, - tag: str, - platforms_dir: str = "platforms", - owners: dict[str, list[str]] | None = None, -) -> dict: - """Read every pack of a directory, parts counted once across them. - - Read under the shared artifact lock, so a split that is reading its parts - back cannot be recorded half done. A pack still beside its parts after - that is a split that never finished: summed, it doubled the download size - and named an asset that is never published. Each pack carries the - platforms it serves, so a reader finds a platform's pack by that list - after a later version or grouping has renamed the pack main would build. - """ - if owners is None: - owners = release_owners(platforms_dir) - with artifact_lock(str(dist), exclusive=False): - return _read_record(Path(dist), tag, owners) - - -def _read_record(dist: Path, tag: str, owners: dict[str, list[str]]) -> dict: - assets: dict[str, list[Path]] = {} - for path in sorted(dist.glob("*_BIOS_Pack*.zip")): - assets.setdefault(parts.pack_of(path.name), []).append(path) - for paths in assets.values(): - whole = [p for p in paths if not parts.is_part(p.name)] - if whole and len(paths) > len(whole): - raise UnfinishedSplitError( - f"{whole[0].name} lies beside its parts: the split did not finish" - ) - foreign = sorted(name for name in assets if name not in owners) - if foreign: - raise NotAReleasePackError( - f"not the full pack of a registered platform: {', '.join(foreign)}" - " (a narrowed or older build left in the directory)" - ) - - packs = {} - for name, paths in sorted(assets.items()): - members: dict[str, int] = {} - for path in paths: - with zipfile.ZipFile(path) as archive: - # A part's marker names its siblings and is not pack content: - # the manifest's pack_files is counted before any split. - for info in archive.infolist(): - if not parts.is_marker(info.filename): - members[info.filename] = info.file_size - packs[name] = { - "files": len(members), - "extracted_size": sum(members.values()), - "download_size": sum(path.stat().st_size for path in paths), - "assets": [path.name for path in paths], - "platforms": owners[name], - } - return {"schema_version": SCHEMA_VERSION, "tag": tag, "packs": packs} - - -def load_record(path: str | Path = RECORD) -> dict: - """The committed record, empty when no release has written one.""" - try: - with open(path, encoding="utf-8") as handle: - return json.load(handle) - except (OSError, json.JSONDecodeError): - return {} - - -def get_page(platform: str, site: str = "") -> str: - """The permanent download address of a platform, under *site*.""" - return f"{site}{GET_DIR}/{platform}/" - - -def advertised(record: dict, platforms_dir: str = "platforms") -> dict: - """The record as the download tables show it: release_pack platforms only. - - A release cut before a platform lost its release_pack still holds that - platform's pack. The tables follow the registry, so a platform left out - is offered the command, and a pack two platforms shared names the one - still released. - """ - if not record: - return {} - released = set(list_release_pack_platforms(platforms_dir)) - packs = {} - for name, pack in record.get("packs", {}).items(): - serves = [p for p in pack.get("platforms", ()) if p in released] - if serves: - packs[name] = {**pack, "platforms": serves} - return {**record, "packs": packs} - - -def load_advertised(path: str | Path = RECORD, platforms_dir: str = "platforms") -> dict: - """The committed record, reduced to the platforms a release publishes.""" - return advertised(load_record(path), platforms_dir) - - -def pack_name_for(platform: str, record: dict) -> str | None: - """Name of the release pack that serves a platform, if it has one.""" - for name, pack in sorted(record.get("packs", {}).items()): - if platform in pack.get("platforms", ()): - return name - return None - - -def pack_for(platform: str, record: dict) -> dict | None: - """The pack of the release that serves a platform, if it has one.""" - name = pack_name_for(platform, record) - return record["packs"][name] if name else None - - -def manifest_mismatches(record: dict, install_dir: str | Path) -> list[str]: - """Packs whose archive does not hold what their install manifest expects.""" - found = [] - for manifest_path in sorted(Path(install_dir).glob("*.json")): - manifest = json.loads(manifest_path.read_text(encoding="utf-8")) - expected = manifest.get("pack_files") - name = pack_name_for(manifest_path.stem, record) - if expected is None or name is None: - continue - pack = record["packs"][name] - if pack["files"] != expected: - found.append( - f"{name} holds {pack['files']} files, " - f"install/{manifest_path.name} expects {expected}" - ) - return found - - -def size_text(count: int) -> str: - if count >= 1024**3: - return f"{count / 1024**3:.1f} GB" - return f"{count / 1024**2:.0f} MB" +from core.artifacts import ArtifactLockBusy, write_text_atomic +from model.releaserecord import RECORD +from release.record import ( + NotAReleasePackError, + UnfinishedSplitError, + build_record, + manifest_mismatches, + size_text, +) def main() -> int: diff --git a/scripts/restore_large_files.py b/scripts/restore_large_files.py index c3c4d83ea..d77f3e071 100644 --- a/scripts/restore_large_files.py +++ b/scripts/restore_large_files.py @@ -17,117 +17,9 @@ Usage: from __future__ import annotations import argparse -import contextlib -import hashlib import os -import sys -import tempfile -from core.artifacts import set_plain_mode -from core.artifacts import copy_file_atomic -from model.database import load_database - - -def gitignored_paths(gitignore: str) -> set[str]: - """Paths the repository keeps out of git, as written in .gitignore. - - A missing file raises: read as empty, it left nothing to restore and - nothing unsatisfied, and the run exited 0 with every asset absent. - """ - with open(gitignore) as f: - return { - line.strip() for line in f if line.strip().startswith("bios/") - } - - -def index_cache(cache_dir: str) -> dict[str, str]: - """Map SHA1 to cached file path for every asset in the cache.""" - index: dict[str, str] = {} - for name in sorted(os.listdir(cache_dir)): - # A download in progress writes `..tmp` beside the - # cache and renames it when done: it is partial, and may be gone by - # the time it is opened. - if name.endswith(".tmp"): - continue - path = os.path.join(cache_dir, name) - if not os.path.isfile(path): - continue - digest = hashlib.sha1() - with open(path, "rb") as f: - for chunk in iter(lambda: f.read(1 << 20), b""): - digest.update(chunk) - index[digest.hexdigest()] = path - return index - - -def _copy_verified(source: str, path: str, sha1: str) -> bool: - """Copy *source* to *path* only if the copy hashes to *sha1*. - - The cache was hashed before the copy, and another run can replace a - cached name in between (a re-uploaded asset): the copy is what counts. - Whole or absent: a scan running beside a plain copy hashed the truncated - file and published that in the database. - """ - handle, scratch = tempfile.mkstemp( - dir=os.path.dirname(os.path.abspath(path)), - prefix=f".{os.path.basename(path)}.", suffix=".tmp", - ) - os.close(handle) - try: - copy_file_atomic(source, scratch) - digest = hashlib.sha1() - with open(scratch, "rb") as f: - for chunk in iter(lambda: f.read(1 << 20), b""): - digest.update(chunk) - if digest.hexdigest() != sha1: - print(f"Changed in the cache while restoring: {source}", file=sys.stderr) - return False - set_plain_mode(scratch) - os.replace(scratch, path) - return True - finally: - with contextlib.suppress(FileNotFoundError): - os.unlink(scratch) - - -def restore( - cache_dir: str, db_path: str, gitignore: str -) -> tuple[int, list[str]]: - ignored = gitignored_paths(gitignore) - # No cache is not nothing to do: the paths it would have supplied are - # still missing, and the check below is the one that must say so. - if os.path.isdir(cache_dir): - index = index_cache(cache_dir) - else: - print(f"No cache at {cache_dir}") - index = {} - db = load_database(db_path) - restored = 0 - unsatisfied: list[str] = [] - for sha1, entry in db.get("files", {}).items(): - path = entry.get("path", "") - if path not in ignored or os.path.exists(path): - continue - source = index.get(sha1) - if not source: - unsatisfied.append(path) - continue - os.makedirs(os.path.dirname(path), exist_ok=True) - if not _copy_verified(source, path, sha1): - unsatisfied.append(path) - continue - print(f"Restored: {path}") - restored += 1 - print(f"Total: {restored} files restored") - if unsatisfied: - # Every consumer downstream resolves against the disk, so a path the - # cache cannot supply is not a smaller restore: it drops entries from - # the manifest and inflates the missing count the README publishes. - print(f"Unsatisfied: {len(unsatisfied)} declared paths the cache " - "cannot supply", file=sys.stderr) - for path in sorted(unsatisfied)[:10]: - print(f" {path}", file=sys.stderr) - return restored, unsatisfied +from release.restore import restore def main() -> None: diff --git a/scripts/scraper/buildbot_system.py b/scripts/scraper/buildbot_system.py new file mode 100644 index 000000000..76762acea --- /dev/null +++ b/scripts/scraper/buildbot_system.py @@ -0,0 +1,171 @@ +"""The buildbot system directory compared with the data directory registry, by HTTP ETag.""" + +from __future__ import annotations + +import importlib.util +import json +import logging +import subprocess +import sys +import urllib.error +import urllib.parse +import urllib.request +from pathlib import Path + +from model.safeparse import yaml_load + + +log = logging.getLogger(__name__) + +BUILDBOT_SYSTEM_URL = "https://buildbot.libretro.com/assets/system/" +INDEX_URL = BUILDBOT_SYSTEM_URL + ".index" +USER_AGENT = "retrobios/1.0" +REQUEST_TIMEOUT = 15 + +DEFAULT_REGISTRY = "platforms/_data_dirs.yml" +VERSIONS_FILE = "data/.versions.json" + + +def fetch_index() -> set[str]: + """Fetch .index from buildbot, return set of ZIP filenames.""" + req = urllib.request.Request(INDEX_URL, headers={"User-Agent": USER_AGENT}) + with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as resp: + return { + line.strip() for line in resp.read().decode().splitlines() if line.strip() + } + + +def load_tracked_entries( + registry_path: str = DEFAULT_REGISTRY, +) -> dict[str, tuple[str, str]]: + """Load buildbot entries from _data_dirs.yml. + + Returns {decoded_zip_name: (key, source_url)}. + """ + if importlib.util.find_spec("yaml") is None: + print("Error: PyYAML required", file=sys.stderr) + sys.exit(1) + with open(registry_path) as f: + data = yaml_load(f) or {} + entries: dict[str, tuple[str, str]] = {} + for key, entry in data.get("data_directories", {}).items(): + url = entry.get("source_url", "") + if "buildbot.libretro.com/assets/system" not in url: + continue + zip_name = urllib.parse.unquote(url.rsplit("/", 1)[-1]) + entries[zip_name] = (key, url) + return entries + + +def get_remote_etag(url: str) -> str | None: + """HEAD request to get ETag.""" + try: + req = urllib.request.Request( + url, method="HEAD", headers={"User-Agent": USER_AGENT} + ) + with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as resp: + return resp.headers.get("ETag") or resp.headers.get("Last-Modified") or "" + except (urllib.error.URLError, OSError): + return None + + +def load_versions(versions_path: str = VERSIONS_FILE) -> dict: + """Load cached version/ETag data.""" + path = Path(versions_path) + if not path.exists(): + return {} + with open(path) as f: + return json.load(f) + + +def check(registry_path: str = DEFAULT_REGISTRY) -> dict: + """Run the buildbot check. Returns structured report.""" + try: + index_zips = fetch_index() + except (urllib.error.URLError, OSError) as exc: + log.warning("buildbot unreachable: %s", exc) + return {"error": str(exc), "entries": []} + + tracked = load_tracked_entries(registry_path) + versions = load_versions() + + buildbot_set = set(index_zips) + tracked_set = set(tracked.keys()) + + results: list[dict] = [{"zip": z, "status": "NEW", "key": None} for z in sorted(buildbot_set - tracked_set)] + + for z in sorted(tracked_set - buildbot_set): + key, _ = tracked[z] + results.append({"zip": z, "status": "STALE", "key": key}) + + for z in sorted(tracked_set & buildbot_set): + key, url = tracked[z] + stored = versions.get(key, {}).get("sha", "") + remote = get_remote_etag(url) + if remote is None: + status = "UNKNOWN" + elif remote == stored: + status = "OK" + else: + status = "UPDATED" + results.append( + { + "zip": z, + "status": status, + "key": key, + "stored_etag": stored, + "remote_etag": remote or "", + } + ) + + return {"entries": results} + + +def print_report(report: dict) -> None: + """Print human-readable report.""" + if report.get("error"): + print(f"WARNING: {report['error']}") + return + entries = report["entries"] + print(f"Buildbot system check ({len(entries)} entries):") + for e in entries: + pad = 40 - len(e["zip"]) + dots = "." * max(pad, 2) + print(f" {e['zip']} {dots} {e['status']}") + counts: dict[str, int] = {} + for e in entries: + counts[e["status"]] = counts.get(e["status"], 0) + 1 + parts = [f"{v} {k.lower()}" for k, v in sorted(counts.items())] + print(f"\nSummary: {', '.join(parts)}") + + +def update_changed(report: dict) -> list[str]: + """Refresh entries that have changed and return the keys whose refresh failed.""" + failed: list[str] = [] + for e in report.get("entries", []): + if e["status"] == "UPDATED" and e.get("key"): + log.info("refreshing %s ...", e["key"]) + result = subprocess.run( + [ + sys.executable, + "scripts/refresh_data_dirs.py", + "--force", + "--key", + e["key"], + ], + check=False, + ) + if result.returncode != 0: + log.error("refresh of %s failed (exit %d)", e["key"], result.returncode) + failed.append(e["key"]) + return failed + + +def pending(report: dict) -> list[dict]: + """Entries a maintainer has to act on: not tracked yet, or gone.""" + return [e for e in report.get("entries", []) if e["status"] in ("NEW", "STALE")] + + +def unanswered(report: dict) -> list[dict]: + """Tracked entries whose remote version could not be read.""" + return [e for e in report.get("entries", []) if e["status"] == "UNKNOWN"] diff --git a/scripts/sitegen/bootstrap.py b/scripts/sitegen/bootstrap.py index 8c0af4e60..a868e189b 100644 --- a/scripts/sitegen/bootstrap.py +++ b/scripts/sitegen/bootstrap.py @@ -23,6 +23,7 @@ from pathlib import Path from core.artifacts import write_if_changed from model.guides import PS1_NAME, SH_NAME +from installer_build.pins import PIN REPO_RAW = "https://raw.githubusercontent.com/Abdess/retrobios" @@ -37,10 +38,6 @@ ADVICE: dict[str, re.Pattern[str]] = { SH_NAME: re.compile(r'^(MISMATCH_ADVICE=")[^"]*(")', re.M), PS1_NAME: re.compile(r'^(\s*\$mismatchAdvice = ")[^"]*(")', re.M), } -PIN: dict[str, re.Pattern[str]] = { - SH_NAME: re.compile(r'^DEFAULT_INSTALL_SHA256="([0-9a-f]{64})"', re.M), - PS1_NAME: re.compile(r'^\s*\$defaultInstallSha256 = "([0-9a-f]{64})"', re.M), -} # What the served copy says of a refused installer. It names a commit's # install.py, which never changes, and both downloaders fail on a short # transfer before the hash is read: neither a cut download nor caches of diff --git a/scripts/sitegen/build.py b/scripts/sitegen/build.py index 04a06572d..df435f9d9 100644 --- a/scripts/sitegen/build.py +++ b/scripts/sitegen/build.py @@ -12,7 +12,7 @@ from dataclasses import dataclass from pathlib import Path from romrecipes import ledger -import release_record +from model import releaserecord from model import siteinputs from model.collection import _group_by_manufacturer, _slug from model.composition import compute_composition @@ -27,6 +27,7 @@ from packs.crossref import FileConsumers from acquire.provenance import build_report, profile_needs from resolve.cores import resolve_platform_cores from resolve.review import load_platform_hashes, load_profile_hashes +from installer_build.handhelds import GROUP_PAGE from sitegen import ( agents as siteagents, bootstrap as sitebootstrap, @@ -575,11 +576,11 @@ def _write_guide_pages(run: _SiteRun) -> None: # One permanent download address per registered platform: the README's # table links each of them. print("Generating download pages...") - get_dir = docs / release_record.GET_DIR + get_dir = docs / releaserecord.GET_DIR get_dir.mkdir(parents=True, exist_ok=True) for name in run.platform_names: write_if_changed(str(get_dir / f"{name}.md"), generate_get_page(name)) - write_if_changed(str(get_dir / f"{sitehandheld.GROUP_PAGE}.md"), + write_if_changed(str(get_dir / f"{GROUP_PAGE}.md"), sitehandheld.group_page(_REPO_ROOT)) write_if_changed(str(get_dir / "index.md"), generate_get_index()) diff --git a/scripts/sitegen/config.py b/scripts/sitegen/config.py index fdaa77b85..2df1bc163 100644 --- a/scripts/sitegen/config.py +++ b/scripts/sitegen/config.py @@ -4,7 +4,7 @@ from __future__ import annotations from datetime import datetime, timezone -import release_record +from model import releaserecord from core.paths import REPO_ROOT from model.safeparse import require_yaml @@ -22,7 +22,7 @@ RELEASE_URL = f"{REPO_URL}/releases/latest" DATA_LICENSE = "MIT (LICENSE: scripts, tooling, schemas, documentation and metadata)" SITE_URL = "https://abdess.github.io/retrobios/" GENERATED_DIRS = ["platforms", "systems", "emulators", "wiki", "api", "downloads", "files", - release_record.GET_DIR] + releaserecord.GET_DIR] # Generated directories of files served as they are, not pages. PUBLIC_DIRS = ("api", "downloads") diff --git a/scripts/sitegen/decorate.py b/scripts/sitegen/decorate.py index d119f652e..81c81e3e7 100644 --- a/scripts/sitegen/decorate.py +++ b/scripts/sitegen/decorate.py @@ -8,7 +8,7 @@ import sys import urllib.parse from pathlib import Path -import release_record +from model import releaserecord from model import siteinputs from model.database import load_database from sitegen import markup, measurements as sitemeasurements, starlight as sitestarlight @@ -83,7 +83,7 @@ def page_level(relative: Path) -> str: path = relative.as_posix() if path in ("index.md", "which-pack.md"): return "start" - if relative.parts[0] in ("platforms", release_record.GET_DIR): + if relative.parts[0] in ("platforms", releaserecord.GET_DIR): return "setup" if relative.parts[0] in ("systems", "emulators") or path == "explore.md": return "explore" diff --git a/scripts/sitegen/descriptions.py b/scripts/sitegen/descriptions.py index 728f6c901..30a7311b0 100644 --- a/scripts/sitegen/descriptions.py +++ b/scripts/sitegen/descriptions.py @@ -6,7 +6,7 @@ import html import re from pathlib import Path -import release_record +from model import releaserecord from sitegen import measurements as sitemeasurements from sitegen.config import SITE_NAME @@ -133,7 +133,7 @@ def _section_description(markdown: str, relative: Path, title: str, browser: str """The description of a download, system, emulator or platform page, or None for a page of another section.""" key = relative.as_posix() - if key.startswith(f"{release_record.GET_DIR}/"): + if key.startswith(f"{releaserecord.GET_DIR}/"): size = re.search(r"^- (.+ to download\b.*?)\.?$", markdown, re.M) if size: return _shorten(f"{title}: the BIOS pack of this setup, {_plain_markdown(size[1])}. " diff --git a/scripts/sitegen/getpages.py b/scripts/sitegen/getpages.py index c61c6ccb8..fd01041a9 100644 --- a/scripts/sitegen/getpages.py +++ b/scripts/sitegen/getpages.py @@ -5,11 +5,12 @@ from __future__ import annotations import json import re -import release_record +from model import releaserecord from model import siteinputs from model.guides import DEVICE_GROUPS, GROUP_TILES, GUIDES, HANDHELD_GUIDE from model.platforms import load_platform_config from model.registry import load_platform_registry +from installer_build.handhelds import GROUP_PAGE from sitegen import handheld as sitehandheld, markup from sitegen.config import RELEASE_URL, REPO_URL, _REPO_ROOT from sitegen.descriptions import PAGE_DATA @@ -55,15 +56,15 @@ def generate_get_page(platform_name: str) -> str: never touches it: committing release.json rebuilds it.""" config = load_platform_config(platform_name, str(siteinputs.current().platforms)) display = config.get("platform", platform_name) - record = release_record.load_advertised() - pack = release_record.pack_for(platform_name, record) + record = releaserecord.load_advertised() + pack = releaserecord.pack_for(platform_name, record) released = has_release_pack(platform_name) title = get_page_title(platform_name, display) # The page changes with the release it lists: its tag is its date, the # one the sitemap gives (vYYYY.MM.DD). tag_date = re.fullmatch(r"v(\d{4})\.(\d{2})\.(\d{2})", str(record.get("tag", ""))) if released and pack and tag_date: - PAGE_DATA[f"{release_record.GET_DIR}/{platform_name}.md"] = {"dateModified": "-".join(tag_date.groups())} + PAGE_DATA[f"{releaserecord.GET_DIR}/{platform_name}.md"] = {"dateModified": "-".join(tag_date.groups())} if released and pack and pack.get("assets"): description = (f"The BIOS pack for {display}: {_fmt_size(pack['download_size'])} to " "download. The address stays the same and always gives the latest ZIP.") @@ -147,6 +148,6 @@ def generate_get_index() -> str: # handheld guide. if any(HANDHELD_GUIDE and tile.link == HANDHELD_GUIDE.path for tile in GROUP_TILES.get(group, ())): - lines.append(f"- [{sitehandheld.GROUP_TITLE}]({sitehandheld.GROUP_PAGE}.md)") + lines.append(f"- [{sitehandheld.GROUP_TITLE}]({GROUP_PAGE}.md)") lines.append("") return "\n".join(lines) diff --git a/scripts/sitegen/guidepage.py b/scripts/sitegen/guidepage.py index 2af8e3bfa..130ef1fad 100644 --- a/scripts/sitegen/guidepage.py +++ b/scripts/sitegen/guidepage.py @@ -5,7 +5,7 @@ from __future__ import annotations import html import json -import release_record +from model import releaserecord from model import siteinputs from model.collection import _profiles_on_disk from model.guides import ( @@ -19,6 +19,7 @@ from model.guides import ( from model.platforms import load_platform_config from model.registry import load_platform_registry from resolve.nativemode import digest_algorithm +from installer_build.handhelds import GROUP_PAGE from sitegen import handheld as sitehandheld, markup from sitegen.config import _REPO_ROOT from sitegen.guides import platform_args, terminal_tabs @@ -40,7 +41,7 @@ def no_zip_line(display: str) -> str: def get_page_link(platform_name: str, prefix: str = "") -> str: """The platform's permanent download page, as a site link.""" - return f"{prefix}{release_record.GET_DIR}/{platform_name}.md" + return f"{prefix}{releaserecord.GET_DIR}/{platform_name}.md" def get_page_title(platform_name: str, display: str) -> str: @@ -85,7 +86,7 @@ def _pack_buttons(platform_name: str, label: str = "Pack", prefix: str = "../", display = display or load_platform_config(platform_name, str(siteinputs.current().platforms)).get( "platform", platform_name) return f"{no_zip_line(display)} [Why no ZIP?]({prefix}{NO_ZIP_FAQ})" - record = release_record.load_advertised() + record = releaserecord.load_advertised() buttons = download_links( platform_name, record, @@ -204,7 +205,7 @@ def _share_tabs(name: str, share: str) -> tuple[dict[str, str], dict[str, str]]: def _offline_line(name: str) -> list[str]: """The offline line, on a setup whose ZIP a release publishes: the installer reads that ZIP with no network (`--from-pack`).""" - pack = release_record.pack_for(name, release_record.load_advertised()) + pack = releaserecord.pack_for(name, releaserecord.load_advertised()) return [OFFLINE_LINE, ""] if pack and pack.get("assets") else [] @@ -291,7 +292,7 @@ def _computer_first(name: str, guide: Guide) -> bool: """A system that runs only on its own device, with a ZIP to download: a beginner fills its folder from a computer more easily than from a terminal on the TV. Without a ZIP the command is the only route.""" - pack = release_record.pack_for(name, release_record.load_advertised()) + pack = releaserecord.pack_for(name, releaserecord.load_advertised()) return guide.run == ("device",) and bool(pack and pack.get("assets")) @@ -309,8 +310,8 @@ def _guide_download(name: str, display: str, guide: Guide, extract_to: str | Non heading: str) -> list[str]: """The pack: its buttons, its size, and where it is unzipped.""" lines = [heading, ""] - record = release_record.load_advertised() - pack = release_record.pack_for(name, record) + record = releaserecord.load_advertised() + pack = releaserecord.pack_for(name, record) network = any(label.startswith("From ") for label, _path in guide.folders) if pack and pack.get("assets"): parts = len(pack["assets"]) @@ -457,7 +458,7 @@ def generate_handheld_guide(guide: HandheldGuide) -> str: *_offline_line(guide.uses), f"On {sitehandheld.joined(sitehandheld.group_systems(), 'or')}: " f"[{sitehandheld.GROUP_TITLE}]" - f"(../get/{sitehandheld.GROUP_PAGE}.md).", + f"(../get/{GROUP_PAGE}.md).", "", "## Fill the card from a computer { #install }", "", diff --git a/scripts/sitegen/handheld.py b/scripts/sitegen/handheld.py index 954eb3b00..6cb7b9354 100644 --- a/scripts/sitegen/handheld.py +++ b/scripts/sitegen/handheld.py @@ -8,86 +8,30 @@ get/handheld/, beside the bootstraps that pin the same installer does not pin: a stale pin stops the site build, the last good archives staying served. -LAUNCHERS is the one description of where each archive goes on the card -and which menu starts it. The handheld tables of wiki/installer.md are -written from it (scripts/generate_installer_doc.py), and so is the block -each get// page and the handheld page carry. +LAUNCHERS (installer_build/handhelds.py) is the one description of where +each archive goes on the card and which menu starts it. The handheld +tables of wiki/installer.md are written from it, and so is the block each +get// page and the handheld page carry, written here. """ from __future__ import annotations import hashlib import tempfile -from dataclasses import dataclass, field +from dataclasses import dataclass from pathlib import Path from sitegen import markup from core.artifacts import write_bytes_atomic -from build_port import ARCHIVES, BATOCERA_ZIP, MUOS_APP, PORT_ZIP, TOOLS_ZIP, build_archive -from core.paths import REPO_ROOT - -# Below the site's root: get/handheld/RetroBIOS.zip. -SERVED_DIR = "get/handheld" -# The page of the systems no registered platform answers for. It shares -# its name with the handheld guide (platforms/linux-handhelds.md), so the -# sidebar files it with that guide, as get/batocera.md is with -# platforms/batocera.md. -GROUP_PAGE = "linux-handhelds" -GROUP_TITLE = "RetroBIOS app for handhelds" - - -@dataclass(frozen=True) -class Launcher: - """One row of the installer's handheld table. - - *systems* are named as the installer page names them. *copy_to* is - where the file goes, and *places* gives a system its own folder when - the row's systems differ there. *lead* opens the row's first cell. - """ - - archive: str - systems: tuple[str, ...] - copy_to: str - start: str - extracted: bool = False - lead: str = "" - places: tuple[tuple[str, tuple[str, ...]], ...] = field(default=()) - - def folder_for(self, system: str) -> str: - return next((folder for folder, systems in self.places if system in systems), - self.copy_to) - - -LAUNCHERS: tuple[Launcher, ...] = ( - Launcher(MUOS_APP, ("muOS",), - "`ARCHIVE` at the root of the card, then install it from the Archive Manager", - "Applications"), - Launcher(PORT_ZIP, ("ArkOS", "dArkOS", "ROCKNIX", "AmberELEC", "JELOS", "KNULLI"), - "PortMaster's `autoinstall` folder", "Ports, after opening PortMaster once", - lead="Any other system with [PortMaster](https://portmaster.games/)", - places=(("`/roms/ports/PortMaster/autoinstall/`", ("ROCKNIX", "AmberELEC")), - ("`/roms/tools/PortMaster/autoinstall/`", ("ArkOS",)), - ("`/userdata/system/.local/share/PortMaster/autoinstall/`", ("KNULLI",)))), - Launcher(BATOCERA_ZIP, ("Batocera", "KNULLI"), "`roms/ports` on the SHARE partition", - "Ports, after updating the game list", extracted=True), - Launcher(TOOLS_ZIP, ("ArkOS", "dArkOS"), "`tools` on the EASYROMS partition", - "Options, then Tools", extracted=True), - Launcher(TOOLS_ZIP, ("ROCKNIX", "JELOS"), - "`/storage/.config/modules`, over the network share or SSH", "Tools", - extracted=True), - Launcher(TOOLS_ZIP, ("AmberELEC",), "`/storage/.config/distribution/modules`", "Tools", - extracted=True), +from installer_build.port import ( + ARCHIVES, + PORT_ZIP, + build_archive, ) +from core.paths import REPO_ROOT +from installer_build.handhelds import Launcher, PLATFORM_OF, SERVED_DIR, launchers_for, systems -# The registered platform whose get/ page answers for a system. A system -# outside this map is on the handheld page. -PLATFORM_OF = {"Batocera": "batocera", "KNULLI": "knulli", "ROCKNIX": "rocknix", - "AmberELEC": "amberelec"} - - -def systems() -> list[str]: - """Every system a launcher runs on, in table order.""" - return list(dict.fromkeys(name for launcher in LAUNCHERS for name in launcher.systems)) +GROUP_TITLE = "RetroBIOS app for handhelds" def group_systems() -> list[str]: @@ -99,17 +43,6 @@ def joined(names: list[str], last: str = "and") -> str: return names[0] if len(names) == 1 else f"{', '.join(names[:-1])} {last} {names[-1]}" -def page_of(system: str) -> str: - """The site page that holds the download for *system*.""" - return f"get/{PLATFORM_OF.get(system, GROUP_PAGE)}.md" - - -def launchers_for(system: str) -> list[Launcher]: - """The launchers of *system*, its own menu first and PortMaster last.""" - own = [launcher for launcher in LAUNCHERS if system in launcher.systems] - return sorted(own, key=lambda launcher: launcher.archive == PORT_ZIP) - - @dataclass(frozen=True) class Served: data: bytes @@ -155,46 +88,6 @@ def write_launchers(public: Path, root: Path = REPO_ROOT) -> list[Path]: return written -def table_rows() -> list[str]: - """The handheld table of the installer page, each system linked to the - page that holds its download. The page sits in wiki/.""" - def name(system: str) -> str: - return f"[{system}](../{page_of(system)})" - - rows = ["| System | File | Copy it to | Start it from |", - "|--------|------|------------|---------------|"] - for launcher in LAUNCHERS: - names = ", ".join(name(system) for system in launcher.systems) - first = f"{launcher.lead}: {names}" if launcher.lead else names - file = f"`{launcher.archive}`" + (", extracted" if launcher.extracted else "") - copy_to = launcher.copy_to - if launcher.places: - copy_to += ": " + ", ".join( - f"{folder} on {' and '.join(where)}" for folder, where in launcher.places) - rows.append(f"| {first} | {file} | {copy_to} | {launcher.start} |") - return rows - - -def _anchor(system: str) -> str: - """Where *system*'s downloads sit on its page.""" - return "on-the-handheld" if system in PLATFORM_OF else system.casefold() - - -def download_rows() -> list[str]: - """The short table that opens the installer's handheld section: each - system, its files as links to the site's copies, and its page. The - page sits in wiki/.""" - rows = ["| System | Download | Steps |", "|--------|----------|-------|"] - for system in systems(): - files = ", ".join( - f"[{launcher.archive}](../{SERVED_DIR}/{launcher.archive})" - + (" (PortMaster)" if launcher.archive == PORT_ZIP else "") - for launcher in launchers_for(system)) - page = f"../{page_of(system)}#{_anchor(system)}" - rows.append(f"| {system} | {files} | [{system} steps]({page}) |") - return rows - - def _launcher_block(launcher: Launcher, system: str, root: Path) -> list[str]: archive = served(launcher.archive, root) verb = "Unzip it into" if launcher.extracted else "Copy it to" diff --git a/scripts/sitegen/platformindex.py b/scripts/sitegen/platformindex.py index 3286428d0..00fbff342 100644 --- a/scripts/sitegen/platformindex.py +++ b/scripts/sitegen/platformindex.py @@ -2,7 +2,7 @@ from __future__ import annotations -import release_record +from model import releaserecord from model.guides import DEVICE_GROUPS, GROUP_TILES, GUIDES from resolve.nativemode import check_label from sitegen import markup @@ -66,7 +66,7 @@ def setup_table(coverages: dict) -> list[str]: ] for name, cov in sorted(coverages.items(), key=lambda item: item[1]["platform"].casefold()): listed = f"{cov['total']:,}" if cov["total"] else "No list of its own" - files, _size = release_totals(name, release_record.load_advertised()) + files, _size = release_totals(name, releaserecord.load_advertised()) zipped = (f"{files:,}" if files else "No ZIP yet" if has_release_pack(name) else "No ZIP") lines.append( diff --git a/scripts/sitegen/publish.py b/scripts/sitegen/publish.py index 7e4d74cb5..04c370f2a 100644 --- a/scripts/sitegen/publish.py +++ b/scripts/sitegen/publish.py @@ -6,7 +6,7 @@ import json import shutil from pathlib import Path -import release_record +from model import releaserecord from sitegen.config import _REPO_ROOT from sitegen.write import _record, write_if_changed @@ -21,7 +21,7 @@ def write_release_advertised(generated: Path) -> None: generated.mkdir(parents=True, exist_ok=True) write_if_changed( str(generated / "release-advertised.json"), - json.dumps(release_record.load_advertised(), ensure_ascii=False, indent=1, + json.dumps(releaserecord.load_advertised(), ensure_ascii=False, indent=1, sort_keys=True) + "\n", ) diff --git a/scripts/sitegen/readme.py b/scripts/sitegen/readme.py index d6bcf4e20..88dc0b078 100644 --- a/scripts/sitegen/readme.py +++ b/scripts/sitegen/readme.py @@ -12,8 +12,8 @@ from pathlib import Path from types import ModuleType from romrecipes import ledger -import pr_checks -import release_record +from devtools import prchecks +from model import releaserecord from core.artifacts import write_if_changed from core.cli import InputMissing from core.github import github_token @@ -247,7 +247,7 @@ def release_totals(platform_name: str, record: dict) -> tuple[int | None, int | lands after the release. Returns (None, None) for a platform the release carries no pack for. """ - pack = release_record.pack_for(platform_name, record) + pack = releaserecord.pack_for(platform_name, record) if not pack: return None, None return pack["files"], pack["extracted_size"] @@ -271,7 +271,7 @@ def asset_links( *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) + pack = releaserecord.pack_for(platform_name, record) tag = record.get("tag") assets = pack.get("assets") if pack else None def link(text: str, url: str) -> str: @@ -308,13 +308,13 @@ def download_links( 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) + page = page or releaserecord.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) + pack = releaserecord.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) @@ -619,7 +619,7 @@ def generate_readme(db: dict, platforms_dir: str, db_path: str = "database.json" # 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) + record = releaserecord.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]] @@ -833,8 +833,8 @@ def contributing_text( .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) + width = max(len(prchecks.shown(step)) for step in prchecks.STEPS) + steps = "\n".join(f"{prchecks.shown(step):<{width}} # {step.why}" for step in prchecks.STEPS) return f"""{title} ## Add a BIOS file diff --git a/scripts/sitegen/validate.py b/scripts/sitegen/validate.py index 9d7f81ec0..5f5e876fb 100644 --- a/scripts/sitegen/validate.py +++ b/scripts/sitegen/validate.py @@ -419,23 +419,23 @@ def _check_get_pages( 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 import releaserecord 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)) + record = releaserecord.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" + rel = f"{releaserecord.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) + pack = releaserecord.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)) diff --git a/scripts/sitegen/versions.py b/scripts/sitegen/versions.py index e1ef0a13a..928106b1e 100644 --- a/scripts/sitegen/versions.py +++ b/scripts/sitegen/versions.py @@ -5,7 +5,7 @@ from __future__ import annotations import re from datetime import datetime -import release_record +from model import releaserecord from model import siteinputs from model.composition import count_catalog_matched from model.platforms import load_platform_config @@ -67,7 +67,7 @@ def release_line(platform_name: str, record: dict) -> list[str]: """Which release the buttons serve, with its checksums and signature, and the version gap when the page describes a newer platform than the pack.""" tag = record.get("tag") - pack_name = release_record.pack_name_for(platform_name, record) + pack_name = releaserecord.pack_name_for(platform_name, record) if not tag or not pack_name: return [] base = f"{REPO_URL}/releases/download/{tag}" @@ -107,7 +107,7 @@ def setup_version(platform_name: str, record: dict | None = None) -> str: config = load_platform_config(platform_name, str(siteinputs.current().platforms)) except FileNotFoundError: return "" - pack_name = release_record.pack_name_for(platform_name, record or {}) + pack_name = releaserecord.pack_name_for(platform_name, record or {}) version = ( _pack_version(pack_name, _pack_platforms(platform_name, record or {}, pack_name)) if pack_name else "" diff --git a/scripts/sitegen/whichpack.py b/scripts/sitegen/whichpack.py index d72f09391..8c0198549 100644 --- a/scripts/sitegen/whichpack.py +++ b/scripts/sitegen/whichpack.py @@ -2,7 +2,7 @@ from __future__ import annotations -import release_record +from model import releaserecord from core.paths import REPO_ROOT from core.ziptools import build_zip_contents_index from model import siteinputs @@ -78,7 +78,7 @@ def _pack_cell(name: str, record: dict, prefix: str = "") -> str: """The pack's parts and size, or the command where the release has none.""" if not has_release_pack(name): return f"No ZIP. [{NO_PACK}]({prefix}platforms/{name}.md#install)." - pack = release_record.pack_for(name, record) + pack = releaserecord.pack_for(name, record) if record.get("tag") and not (pack and pack.get("assets")): return f"No ZIP yet. [{NO_PACK}]({prefix}platforms/{name}.md#install)." # One small button to the setup's get/ page, which lists every part, and @@ -108,7 +108,7 @@ def _folder_row(key: str, display: dict[str, str], registry: dict, record: dict, whose ZIP holds its own top folder says where to unzip it, and the BIOS folder itself when it has no ZIP to unzip.""" guide = GUIDES[key] - pack = release_record.pack_for(key, record) + pack = releaserecord.pack_for(key, record) zipped = bool(pack and pack.get("assets")) folder = (f"Unzip into `{own_root[key]}`" if key in own_root and zipped else _folder_cell(key, guide)) @@ -197,7 +197,7 @@ def generate_which_pack() -> str: The tiles are the choice. Open tables under them listed every setup a second time and made the page 11,800 px tall on a phone.""" registry = load_platform_registry(str(siteinputs.current().platforms)) - record = release_record.load_advertised() + record = releaserecord.load_advertised() display = {key: load_platform_config(key, str(siteinputs.current().platforms)).get("platform", key) for key in registry} all_tabs = ("windows", "macos", "linux", "steamdeck", "android") @@ -235,7 +235,7 @@ def generate_which_pack() -> str: _folder_tables(registry, record, display)), ] pending = any(has_release_pack(key) and not (pack and pack.get("assets")) - for key, pack in ((key, release_record.pack_for(key, record)) for key in registry)) + for key, pack in ((key, releaserecord.pack_for(key, record)) for key in registry)) if record.get("tag") and pending: lines += ["Setups added after the last release have no ZIP until the next one.", ""] lines += ["No ZIP on a row: the command serves that setup. ZIPs are made for the " diff --git a/scripts/sync_release_assets.py b/scripts/sync_release_assets.py index 72053fb7d..547b537e2 100644 --- a/scripts/sync_release_assets.py +++ b/scripts/sync_release_assets.py @@ -24,129 +24,12 @@ Usage: from __future__ import annotations import argparse -import hashlib -import os -import shutil import subprocess import sys -from collections.abc import Callable -from dataclasses import dataclass from pathlib import Path -from check_release_assets import compare, expected_assets, expected_digests, fetch_release from model.database import load_database -from model.largefiles import LARGE_FILES_RELEASE, LARGE_FILES_REPO, asset_names, registered_paths - -STAGING = Path("tmp") / "sync_release_assets" -OUT_OF_DATE = ("missing", "size", "content") - - -@dataclass(frozen=True) -class Upload: - path: str - asset: str - kind: str - verdict: str # upload, refused - reason: str = "" - - -def sha1_of(path: Path) -> str: - digest = hashlib.sha1() - with path.open("rb") as handle: - for chunk in iter(lambda: handle.read(1 << 20), b""): - digest.update(chunk) - return digest.hexdigest() - - -def database_sha1(db: dict) -> dict[str, str]: - return { - entry["path"]: str(entry.get("sha1") or key).lower() - for key, entry in db.get("files", {}).items() - if entry.get("path") - } - - -def plan_uploads( - root: Path, - db: dict, - gitignore_text: str, - findings: list, - hasher: Callable[[Path], str] = sha1_of, -) -> list[Upload]: - """Each out-of-date asset, cleared for upload or refused with its reason.""" - names = asset_names([*registered_paths(gitignore_text), - *expected_assets(db, gitignore_text)]) - recorded = database_sha1(db) - plans = [] - for kind, path, _size, _published in findings: - if kind not in OUT_OF_DATE: - continue - local = root / path - if not local.is_file(): - plans.append(Upload(path, names[path], kind, "refused", "no local file")) - continue - first, second = hasher(local), hasher(local) - if first != second: - plans.append(Upload(path, names[path], kind, "refused", - f"two reads disagree ({first[:12]} != {second[:12]})")) - elif first != recorded.get(path): - plans.append(Upload(path, names[path], kind, "refused", - f"sha1 {first[:12]} is not the database's " - f"{str(recorded.get(path))[:12]}")) - else: - plans.append(Upload(path, names[path], kind, "upload")) - return plans - - -def gh_upload(staged: Path) -> int: - return subprocess.run( - ["gh", "release", "upload", LARGE_FILES_RELEASE, str(staged), "--clobber", - "-R", LARGE_FILES_REPO], - check=False, - ).returncode - - -def stage(root: Path, plan: Upload) -> Path: - """The file under its asset name: gh names an asset after the file.""" - staged = root / STAGING / plan.asset - staged.parent.mkdir(parents=True, exist_ok=True) - if staged.exists(): - staged.unlink() - try: - os.link(root / plan.path, staged) - except OSError: - shutil.copy2(root / plan.path, staged) - return staged - - -def upload_all( - root: Path, plans: list[Upload], upload: Callable[[Path], int] = gh_upload -) -> list[str]: - """Upload every cleared plan, twice at most, and return the failures.""" - failed = [] - for plan in plans: - if plan.verdict != "upload": - continue - staged = stage(root, plan) - try: - if upload(staged) != 0 and upload(staged) != 0: - failed.append(plan.path) - finally: - staged.unlink() - return failed - - -def open_findings( - db: dict, gitignore_text: str, fetch: Callable[[], tuple] = fetch_release -) -> list: - assets, _body, digests = fetch() - return compare( - expected_assets(db, gitignore_text), - assets, - registered=registered_paths(gitignore_text), - expected_digests=expected_digests(db, gitignore_text), - asset_digests=digests, - ) +from release.sync import OUT_OF_DATE, open_findings, plan_uploads, upload_all def main() -> int: diff --git a/scripts/validate_schemas.py b/scripts/validate_schemas.py index 035d4c924..ad500e422 100644 --- a/scripts/validate_schemas.py +++ b/scripts/validate_schemas.py @@ -804,14 +804,14 @@ def _semantic_standalone_checks(path: Path, layouts: object) -> list[str]: def _event_schema_errors() -> list[str]: """install-events.schema.json is EVENT_KEYS written out, and a valid schema.""" - import generate_event_schema + from installer_build import eventschema - path = ROOT / "schemas" / generate_event_schema.OUTPUT.name + path = ROOT / "schemas" / eventschema.OUTPUT.name label = path.relative_to(ROOT).as_posix() if not path.is_file(): return [f"{label}: missing, run python scripts/generate_event_schema.py"] - if path.read_text(encoding="utf-8") != generate_event_schema.render( - generate_event_schema.build_schema() + if path.read_text(encoding="utf-8") != eventschema.render( + eventschema.build_schema() ): return [f"{label}: differs from EVENT_KEYS in install.py, run " "python scripts/generate_event_schema.py"] diff --git a/tests/sources.py b/tests/sources.py index 729d67de9..b15eb063f 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -29,6 +29,22 @@ COMMANDS = { "refresh_data_dirs.py": ("packs/datadirs.py",), "split_pack.py": ("packs/parts.py",), "dedup.py": ("model/nodedup.py",), + "release_record.py": ("model/releaserecord.py", "release/record.py"), + "release_notes.py": ("release/notes.py",), + "check_release.py": ("release/check.py",), + "check_release_assets.py": ("release/assets.py",), + "sync_release_assets.py": ("release/sync.py",), + "restore_large_files.py": ("release/restore.py",), + "build_installer.py": ("installer_build/amalgamate.py",), + "pin_installer.py": ("installer_build/pins.py",), + "build_port.py": ("installer_build/port.py",), + "build_pypi.py": ("installer_build/pypi.py",), + "generate_launcher_index.py": ("installer_build/launcherindex.py",), + "generate_event_schema.py": ("installer_build/eventschema.py",), + "generate_installer_doc.py": ("installer_build/installerdoc.py",), + "commit_rules.py": ("devtools/commitrules.py",), + "pr_checks.py": ("devtools/prchecks.py",), + "check_buildbot_system.py": ("scraper/buildbot_system.py",), "generate_site.py": ( "sitegen/config.py", "sitegen/emulatorsindex.py", diff --git a/tests/test_atomic_artifacts.py b/tests/test_atomic_artifacts.py index f4991afa5..f6d5032b8 100644 --- a/tests/test_atomic_artifacts.py +++ b/tests/test_atomic_artifacts.py @@ -51,7 +51,6 @@ class WholeOrNothing(unittest.TestCase): class EveryWriterGoesThroughIt(unittest.TestCase): def test_manifests_record_and_restore_use_the_atomic_helpers(self): - scripts = REPO_ROOT / "scripts" for name, helper in ( ("generate_pack.py", "write_text_atomic("), ("release_record.py", "write_text_atomic("), @@ -63,8 +62,8 @@ class EveryWriterGoesThroughIt(unittest.TestCase): pack = script_source("generate_pack.py") self.assertNotIn('with open(path, "w") as f:\n f.write(new_json)', pack) self.assertNotIn("json.dump(result, f", pack) - self.assertNotIn("args.output.write_text(", (scripts / "release_record.py").read_text()) - self.assertNotIn("shutil.copy2(source, path)", (scripts / "restore_large_files.py").read_text()) + self.assertNotIn("args.output.write_text(", script_source("release_record.py")) + self.assertNotIn("shutil.copy2(source, path)", script_source("restore_large_files.py")) def test_scrapers_write_whole_files(self): @@ -95,10 +94,12 @@ class EveryWriterGoesThroughIt(unittest.TestCase): sandbox = {"write_small_list", "Sandbox"} offenders = [] - for path in sorted((REPO_ROOT / "scripts").glob("generate_*.py")): + library = [REPO_ROOT / "scripts" / "installer_build" / name + for name in ("eventschema.py", "installerdoc.py", "launcherindex.py")] + for path in [*sorted((REPO_ROOT / "scripts").glob("generate_*.py")), *library]: tree = ast.parse(path.read_text(encoding="utf-8")) for top in tree.body: - if path.name == "generate_installer_doc.py" and getattr(top, "name", "") in sandbox: + if path.name == "installerdoc.py" and getattr(top, "name", "") in sandbox: continue offenders.extend( f"{path.name}:{node.lineno}" @@ -281,6 +282,7 @@ class RestoreSkipsDownloadsInProgress(unittest.TestCase): def test_a_scratch_promoted_mid_scan_does_not_stop_the_restore(self) -> None: import restore_large_files + from release import restore with tempfile.TemporaryDirectory() as tmp: cache = Path(tmp) @@ -299,7 +301,7 @@ class RestoreSkipsDownloadsInProgress(unittest.TestCase): with mock.patch.object(restore_large_files.os.path, "isfile", side_effect=check_then_promote): - index = restore_large_files.index_cache(str(cache)) + index = restore.index_cache(str(cache)) self.assertNotIn(str(scratch), index.values()) self.assertIn(str(cache / "done.bin"), index.values()) diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index 485277049..8b89c404d 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -2230,7 +2230,7 @@ class CheckoutCompletenessRegressions(unittest.TestCase): self.assertLess(self._index(steps, "refresh_data_dirs.py"), generate) def test_restore_matches_assets_by_content_not_by_name(self): - from scripts.restore_large_files import restore + from scripts.release.restore import restore with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: root = Path(directory) @@ -2265,7 +2265,7 @@ class CheckoutCompletenessRegressions(unittest.TestCase): restore, nothing unsatisfied, exit 0 with every asset absent.""" import subprocess - from scripts.restore_large_files import gitignored_paths + from scripts.release.restore import gitignored_paths with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: missing = str(Path(directory) / "absent") @@ -2284,7 +2284,7 @@ class CheckoutCompletenessRegressions(unittest.TestCase): """The cache is hashed first and copied later: another run that replaced the cached name in between put its bytes at a path the database pins to the old ones.""" - from scripts import restore_large_files + from scripts.release import restore as release_restore with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: root = Path(directory) @@ -2298,7 +2298,7 @@ class CheckoutCompletenessRegressions(unittest.TestCase): json.dumps({"files": {sha1: {"path": "bios/Sony/big.pup"}}}), encoding="utf-8", ) - real_index = restore_large_files.index_cache + real_index = release_restore.index_cache def index_then_replace(cache_dir: str) -> dict[str, str]: index = real_index(cache_dir) @@ -2308,8 +2308,8 @@ class CheckoutCompletenessRegressions(unittest.TestCase): cwd = os.getcwd() os.chdir(root) try: - with mock.patch.object(restore_large_files, "index_cache", index_then_replace): - restored, unsatisfied = restore_large_files.restore( + with mock.patch.object(release_restore, "index_cache", index_then_replace): + restored, unsatisfied = release_restore.restore( str(cache), "database.json", ".gitignore" ) self.assertEqual((restored, unsatisfied), (0, ["bios/Sony/big.pup"])) @@ -2319,7 +2319,7 @@ class CheckoutCompletenessRegressions(unittest.TestCase): os.chdir(cwd) def test_restore_leaves_tracked_paths_alone(self): - from scripts.restore_large_files import restore + from scripts.release.restore import restore with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: root = Path(directory) @@ -2347,7 +2347,7 @@ class CheckoutCompletenessRegressions(unittest.TestCase): def test_restore_without_a_cache_names_what_is_missing(self): """A job that skipped `mkdir .cache/large` exited 0 with every gitignored file absent: the early return ran before the check.""" - from scripts.restore_large_files import restore + from scripts.release.restore import restore with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: root = Path(directory) @@ -2696,7 +2696,7 @@ class ReleaseAssetsMatchTheCollection(unittest.TestCase): """ def test_missing_and_resized_assets_are_reported_and_nothing_else(self): - from scripts import check_release_assets + from scripts.release import assets as release_assets expected = { "bios/Other/fbneo/fbneo/samples/twotiger.zip": 154985212, @@ -2708,7 +2708,7 @@ class ReleaseAssetsMatchTheCollection(unittest.TestCase): "MAME.0.174.Arcade.XML.dat": 53677408, "unrelated.zip": 1, } - findings = check_release_assets.compare(expected, assets) + findings = release_assets.compare(expected, assets) self.assertEqual( findings, [ @@ -2718,7 +2718,7 @@ class ReleaseAssetsMatchTheCollection(unittest.TestCase): ) def test_expected_assets_are_the_gitignored_database_entries(self): - from scripts import check_release_assets + from scripts.release import assets as release_assets db = { "files": { @@ -2728,7 +2728,7 @@ class ReleaseAssetsMatchTheCollection(unittest.TestCase): } gitignore = "# large\nbios/Other/x/big.zip\ntmp/\n" self.assertEqual( - check_release_assets.expected_assets(db, gitignore), + release_assets.expected_assets(db, gitignore), {"bios/Other/x/big.zip": 10}, ) @@ -2741,7 +2741,7 @@ class ReleaseAssetsMatchTheCollection(unittest.TestCase): description from the profile that declares the file, and an asset the collection does not index is listed apart, with its size only. """ - from scripts import check_release_assets + from scripts.release import assets as release_assets db = {"files": { "a" * 40: {"path": "bios/Nintendo/Wii/nand.bin", "size": 553649152}, @@ -2758,7 +2758,7 @@ class ReleaseAssetsMatchTheCollection(unittest.TestCase): ) descriptions = {"nand.bin": "BootMii NAND backup"} bundles = {"sdlpal-data.zip": "SDLPAL Chinese Paladin game data (.mkf archives)"} - body = check_release_assets.render_notes( + body = release_assets.render_notes( db, gitignore, assets, previous, descriptions, bundles, {"sdlpal-data.zip": "d" * 40} ) self.assertIn("| [twotiger.zip](https://github.com/Abdess/retrobios/releases/download/large-files/twotiger.zip) | Two Tigers samples | 148 MB | `" + "b" * 40 + "` |", body) @@ -2774,9 +2774,9 @@ class ReleaseAssetsMatchTheCollection(unittest.TestCase): )) def test_stale_notes_are_a_finding(self): - from scripts import check_release_assets + from scripts.release import assets as release_assets - findings = check_release_assets.compare({}, {}, notes_current=False) + findings = release_assets.compare({}, {}, notes_current=False) self.assertEqual(findings, [("notes", "release description", 0, None)]) def test_pipeline_runs_the_check_online_and_marks_it_skipped_offline(self): @@ -3168,7 +3168,7 @@ class ACheckThatCannotAnswerDoesNotPass(unittest.TestCase): self.assertNotEqual(swept.returncode, 0, swept.stdout + swept.stderr) def test_an_unsatisfiable_declared_path_is_reported(self): - from scripts.restore_large_files import restore + from scripts.release.restore import restore with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: root = Path(directory) @@ -3194,19 +3194,20 @@ class ACheckThatCannotAnswerDoesNotPass(unittest.TestCase): """Every HEAD unanswered printed "16 unknown" and exited 0, so the online pipeline printed check_buildbot OK.""" import check_buildbot_system as cbs + from scraper import buildbot_system registry = str(ROOT / "platforms" / "_data_dirs.yml") - tracked = cbs.load_tracked_entries(registry) + tracked = buildbot_system.load_tracked_entries(registry) self.assertTrue(tracked) cases = { "index unreachable": mock.patch.object( - cbs, "fetch_index", side_effect=OSError("down")), + buildbot_system, "fetch_index", side_effect=OSError("down")), "every HEAD unanswered": mock.patch.object( - cbs, "fetch_index", return_value=set(tracked)), + buildbot_system, "fetch_index", return_value=set(tracked)), } for label, index in cases.items(): with self.subTest(label), index, \ - mock.patch.object(cbs, "get_remote_etag", return_value=None), \ + mock.patch.object(buildbot_system, "get_remote_etag", return_value=None), \ mock.patch.object(sys, "argv", ["check_buildbot_system.py", "--registry", registry]), \ contextlib.redirect_stdout(io.StringIO()), \ diff --git a/tests/test_autorun.py b/tests/test_autorun.py index 9cd467bfe..c3f37fa8a 100644 --- a/tests/test_autorun.py +++ b/tests/test_autorun.py @@ -29,7 +29,7 @@ from core import hostguard from core import statefile import bios_integrity as bib import cleanup_disk as cd -import sync_release_assets as sra +from release import sync REPO_ROOT = Path(__file__).resolve().parents[1] @@ -785,14 +785,14 @@ class AssetSync(Scratch): (self.root / rel).parent.mkdir(parents=True, exist_ok=True) (self.root / rel).write_bytes(data) self.db = {"files": { - sra.sha1_of(self.root / "bios/A/big.bin"): {"path": "bios/A/big.bin", "size": 1}, + sync.sha1_of(self.root / "bios/A/big.bin"): {"path": "bios/A/big.bin", "size": 1}, "0" * 40: {"path": "bios/C/solo.iso", "size": 1}, }} def test_only_a_file_whose_sha1_matches_twice_is_cleared(self): findings = [("missing", "bios/A/big.bin", 1, None), ("size", "bios/C/solo.iso", 1, 5), ("notes", "release description", 0, None)] - plans = sra.plan_uploads(self.root, self.db, self.GITIGNORE, findings) + plans = sync.plan_uploads(self.root, self.db, self.GITIGNORE, findings) self.assertEqual([(p.path, p.asset, p.verdict) for p in plans], [ ("bios/A/big.bin", "A--big.bin", "upload"), ("bios/C/solo.iso", "solo.iso", "refused"), @@ -801,23 +801,23 @@ class AssetSync(Scratch): def test_two_reads_that_disagree_refuse_the_upload(self): reads = iter(["1" * 40, "2" * 40]) - plans = sra.plan_uploads(self.root, self.db, self.GITIGNORE, + plans = sync.plan_uploads(self.root, self.db, self.GITIGNORE, [("content", "bios/A/big.bin", 1, 1)], hasher=lambda _p: next(reads)) self.assertEqual(plans[0].verdict, "refused") self.assertIn("two reads disagree", plans[0].reason) def test_an_upload_goes_under_its_asset_name_and_is_tried_twice(self): - plans = [sra.Upload("bios/A/big.bin", "A--big.bin", "missing", "upload"), - sra.Upload("bios/C/solo.iso", "solo.iso", "size", "refused", "x")] + plans = [sync.Upload("bios/A/big.bin", "A--big.bin", "missing", "upload"), + sync.Upload("bios/C/solo.iso", "solo.iso", "size", "refused", "x")] seen = [] def upload(path: Path) -> int: seen.append(path.name) return 1 - self.assertEqual(sra.upload_all(self.root, plans, upload), ["bios/A/big.bin"]) + self.assertEqual(sync.upload_all(self.root, plans, upload), ["bios/A/big.bin"]) self.assertEqual(seen, ["A--big.bin", "A--big.bin"]) - self.assertFalse((self.root / sra.STAGING / "A--big.bin").exists()) + self.assertFalse((self.root / sync.STAGING / "A--big.bin").exists()) class BiosIntegrity(Scratch): @@ -961,30 +961,30 @@ class SubjectsFollowTheRepositoryRules(unittest.TestCase): calls: a copy in the hook alone let CI check only the shape.""" def test_the_runner_reads_the_tracked_rules(self): - import commit_rules + from devtools import commitrules for subject in ("chore: fix the broken manifests", "update things", "chore: " + "a" * 60): with self.subTest(subject=subject): - self.assertEqual(ar.check_subject(subject), commit_rules.problems(subject)) + self.assertEqual(ar.check_subject(subject), commitrules.problems(subject)) self.assertTrue(ar.check_subject(subject)) self.assertEqual(ar.check_subject("chore: tidy the cache"), []) def test_review_numbers_are_refused(self): """47 pushed subjects pointed at a numbered private review, which no clone can follow. The subject says what the change does.""" - import commit_rules + from devtools import commitrules for subject in ("chore: audit 24 and 17 cases, host kept out", "fix: polish the screens audit 11 named", "chore: merge audit batch, resolver and profiles", "fix: settle the review 3 notes"): with self.subTest(subject=subject): - self.assertTrue(commit_rules.problems(subject)) + self.assertTrue(commitrules.problems(subject)) for subject in ("fix: scroll long messages in the installer", "feat: read regions in region_audit.py", "chore: merge resolver and profile fixes"): with self.subTest(subject=subject): - self.assertEqual(commit_rules.problems(subject), []) + self.assertEqual(commitrules.problems(subject), []) def test_the_rules_run_as_a_hook(self): with tempfile.TemporaryDirectory() as tmp: diff --git a/tests/test_build_installer.py b/tests/test_build_installer.py index 72c0b1db6..01b212f82 100644 --- a/tests/test_build_installer.py +++ b/tests/test_build_installer.py @@ -16,7 +16,7 @@ import textwrap import unittest from pathlib import Path -import build_installer +from installer_build import amalgamate REPO_ROOT = Path(__file__).resolve().parents[1] DOCSTRING = '"""A test installer."""\n' @@ -33,13 +33,13 @@ def _package(root: Path, modules: dict[str, str]) -> Path: class TheCommittedFileIsTheBuiltOne(unittest.TestCase): def test_install_py_is_what_the_package_builds(self): - built = build_installer.build(REPO_ROOT / "installer") + built = amalgamate.build(REPO_ROOT / "installer") self.assertEqual(built, (REPO_ROOT / "install.py").read_text(encoding="utf-8"), - f"install.py differs from installer/: run {build_installer.COMMAND}") + f"install.py differs from installer/: run {amalgamate.COMMAND}") def test_two_builds_give_the_same_bytes(self): - self.assertEqual(build_installer.build(REPO_ROOT / "installer"), - build_installer.build(REPO_ROOT / "installer")) + self.assertEqual(amalgamate.build(REPO_ROOT / "installer"), + amalgamate.build(REPO_ROOT / "installer")) def test_the_file_says_it_is_generated(self): head = (REPO_ROOT / "install.py").read_text(encoding="utf-8").splitlines()[:3] @@ -85,8 +85,8 @@ class JoiningRefusesWhatOneNamespaceCannotHold(unittest.TestCase): def assert_refused(self, modules: dict[str, str], words: str) -> None: package = _package(self.root, modules) - with self.assertRaises(build_installer.BuildError) as caught: - build_installer.build(package) + with self.assertRaises(amalgamate.BuildError) as caught: + amalgamate.build(package) self.assertIn(words, str(caught.exception)) def test_a_package_joins_in_import_order(self): @@ -111,7 +111,7 @@ class JoiningRefusesWhatOneNamespaceCannotHold(unittest.TestCase): A = sys.platform + str(zlib.crc32(b"")) ''', }) - text = build_installer.build(package) + text = amalgamate.build(package) self.assertLess(text.index("A = sys.platform"), text.index("B = A + os.sep")) self.assertIn("import os\nimport sys\n", text) self.assertNotIn("from installer", text) @@ -147,7 +147,7 @@ class JoiningRefusesWhatOneNamespaceCannotHold(unittest.TestCase): 'if TYPE_CHECKING:\n from installer.b import B\n\n\ndef f(b: B) -> None:\n return None\n'), "b": '"""B."""\nfrom __future__ import annotations\n\nfrom installer.a import f\n\n\nclass B:\n pass\n', }) - text = build_installer.build(package) + text = amalgamate.build(package) self.assertNotIn("TYPE_CHECKING", text) self.assertLess(text.index("def f("), text.index("class B:")) diff --git a/tests/test_check_freshness.py b/tests/test_check_freshness.py index 45fe2eba2..499eb0149 100644 --- a/tests/test_check_freshness.py +++ b/tests/test_check_freshness.py @@ -742,19 +742,19 @@ class TheBuildbotIndexIsRead(unittest.TestCase): def test_new_and_dropped_assets_are_stale(self): from unittest import mock - import check_buildbot_system as cbs + from scraper import buildbot_system report = {"entries": [ {"zip": "New.zip", "status": "NEW", "key": None}, {"zip": "Old.zip", "status": "OK", "key": "old"}, ]} - with mock.patch.object(cbs, "check", lambda registry: report): + with mock.patch.object(buildbot_system, "check", lambda registry: report): finding = cf._check_buildbot_system() self.assertEqual(finding.status, cf.STALE) self.assertIn("new New.zip", finding.detail) - with mock.patch.object(cbs, "check", lambda registry: {"error": "x", "entries": []}): + with mock.patch.object(buildbot_system, "check", lambda registry: {"error": "x", "entries": []}): self.assertEqual(cf._check_buildbot_system().status, cf.UNKNOWN) - self.assertEqual([e["zip"] for e in cbs.pending(report)], ["New.zip"]) + self.assertEqual([e["zip"] for e in buildbot_system.pending(report)], ["New.zip"]) diff --git a/tests/test_check_release.py b/tests/test_check_release.py index 416e3fcd1..694eccbf0 100644 --- a/tests/test_check_release.py +++ b/tests/test_check_release.py @@ -11,8 +11,8 @@ import tests import unittest -import build_port -from check_release import SIGNATURE, SUMS, Asset, compare_release, parse_sums +from installer_build import port +from release.check import SIGNATURE, SUMS, Asset, compare_release, parse_sums A = "a" * 64 B = "b" * 64 @@ -97,7 +97,7 @@ class ReleaseMatchesWhatWasBuilt(unittest.TestCase): def test_a_handheld_launcher_is_no_release_file(self): """The site serves the launchers built from its own commit: one in the checksum list or among the assets is refused.""" - for name in build_port.ARCHIVES: + for name in port.ARCHIVES: with self.subTest(name=name): sums = {**SUMS_LIST, name: A} assets = _assets() diff --git a/tests/test_contributing_text.py b/tests/test_contributing_text.py index 5e92583cd..039e741da 100644 --- a/tests/test_contributing_text.py +++ b/tests/test_contributing_text.py @@ -240,28 +240,28 @@ class OneCommandRunsTheChecks(unittest.TestCase): r"|vermin|npm (?:ci|run build)|mypy|ruff check|shellcheck))") def test_every_check_ci_runs_is_a_step(self): - import pr_checks + from devtools import prchecks workflow = (REPO_ROOT / ".github" / "workflows" / "validate.yml").read_text(encoding="utf-8") ran = {m.group(1) for line in workflow.splitlines() if not line.strip().startswith("#") for m in [self.CHECK.search(line)] if m} self.assertGreaterEqual(len(ran), 10) - steps = [step.command for step in pr_checks.STEPS] + steps = [step.command for step in prchecks.STEPS] for check in sorted(ran): with self.subTest(check=check): self.assertTrue(any(command.startswith(check) for command in steps)) def test_a_step_ci_lets_fail_does_not_fail_the_run(self): - import pr_checks + from devtools import prchecks workflow = (REPO_ROOT / ".github" / "workflows" / "validate.yml").read_text(encoding="utf-8") tolerated = set(re.findall(r"continue-on-error: true\n\s*run: (\S+ \S+)", workflow)) - for step in pr_checks.STEPS: + for step in prchecks.STEPS: with self.subTest(step=step.command): self.assertEqual(step.may_fail, " ".join(step.command.split()[:2]) in tolerated) def test_steps_keep_ci_order(self): - import pr_checks + from devtools import prchecks workflow = (REPO_ROOT / ".github" / "workflows" / "validate.yml").read_text(encoding="utf-8") order = [workflow.index(key) for key in ( @@ -269,19 +269,19 @@ class OneCommandRunsTheChecks(unittest.TestCase): "npm run build --prefix website", "python scripts/run_tests.py", "validate_site.py")] self.assertEqual(order, sorted(order)) - commands = [step.command for step in pr_checks.STEPS] + commands = [step.command for step in prchecks.STEPS] positions = [next(i for i, c in enumerate(commands) if key in c) for key in ( "refresh_data_dirs.py", "generate_site.py", "npm run build", "run_tests.py", "validate_site.py")] self.assertEqual(positions, sorted(positions)) def test_the_guide_gives_the_runner_and_what_it_runs(self): - import pr_checks + from devtools import prchecks text = readme.generate_contributing() section = text.split("## Before opening a PR", 1)[1].split("\n## ", 1)[0] self.assertIn("python scripts/pr_checks.py\n", section) - for step in pr_checks.STEPS: + for step in prchecks.STEPS: with self.subTest(step=step.command): self.assertIn(step.command, section) @@ -289,17 +289,17 @@ class OneCommandRunsTheChecks(unittest.TestCase): import contextlib import io - import pr_checks + from devtools import prchecks steps = ( - pr_checks.Step("python -c raise(SystemExit(3))", "fails"), - pr_checks.Step("no-such-tool-here --x", "absent", needs="no-such-tool-here", + prchecks.Step("python -c raise(SystemExit(3))", "fails"), + prchecks.Step("no-such-tool-here --x", "absent", needs="no-such-tool-here", provider="nothing"), - pr_checks.Step("python -c pass", "passes"), + prchecks.Step("python -c pass", "passes"), ) out = io.StringIO() with contextlib.redirect_stdout(out): - code = pr_checks.run(steps) + code = prchecks.run(steps) self.assertEqual(code, 1) self.assertIn("FAILED python -c raise(SystemExit(3)) (exit 3)", out.getvalue()) self.assertIn("NOT RUN no-such-tool-here --x", out.getvalue()) diff --git a/tests/test_doc_pages.py b/tests/test_doc_pages.py index 694468ba6..84ef99c46 100644 --- a/tests/test_doc_pages.py +++ b/tests/test_doc_pages.py @@ -97,17 +97,17 @@ class InstallerOutputExample(unittest.TestCase): prints each one with install.py from the committed list.""" def test_the_samples_are_the_ones_the_installer_prints(self): - import generate_installer_doc + from installer_build import installerdoc page = _page("installer.md") - self.assertEqual(generate_installer_doc.render(page), page, + self.assertEqual(installerdoc.render(page), page, "run python scripts/generate_installer_doc.py") for name in ("dry-run", "run-date", "run-index", "run-download", "run-end", "run-check"): with self.subTest(sample=name): self.assertIn(f"", page) def test_a_retyped_count_fails_the_check(self): - import generate_installer_doc + from installer_build import installerdoc page = _page("installer.md") for name in ("dry-run", "run-end", "bulk-hint"): @@ -116,10 +116,10 @@ class InstallerOutputExample(unittest.TestCase): edited = re.sub(r"\d+", lambda m: str(int(m.group(0)) + 1), body, count=1) stale = page.replace(body, edited) self.assertNotEqual(stale, page) - self.assertEqual(generate_installer_doc.render(stale), page) + self.assertEqual(installerdoc.render(stale), page) def test_a_sample_is_dated_by_its_list_never_by_the_day_it_ran(self): - import generate_installer_doc + from installer_build import installerdoc page = _page("installer.md") for name, platform in (("dry-run", "retroarch"), ("run-date", "batocera")): @@ -128,7 +128,7 @@ class InstallerOutputExample(unittest.TestCase): date = json.loads(listed)["generated"][:10] self.assertIn(f"the list of {date}", _generated(page, name)) self.assertNotIn(str(ROOT), page) - home = f"{generate_installer_doc.SHOWN_HOME}/.config/retroarch" + home = f"{installerdoc.SHOWN_HOME}/.config/retroarch" self.assertIn(home, _generated(page, "dry-run")) def test_run_and_menu_show_one_run_of_the_manifest(self): @@ -222,13 +222,13 @@ class InstallerSamplesSayWhatTheCodePrints(unittest.TestCase): import socket from unittest import mock - import generate_installer_doc + from installer_build import installerdoc def no_lookup(*_args: object) -> str: raise AssertionError("the sandbox asked for a name") with mock.patch.object(socket, "getfqdn", no_lookup), \ - generate_installer_doc.Sandbox() as box: + installerdoc.Sandbox() as box: self.assertEqual(box.server.server_name, "127.0.0.1") @@ -1808,7 +1808,7 @@ class ReportExcerptIsTheRun(unittest.TestCase): def test_every_quoted_line_is_printed(self): import subprocess - from restore_large_files import gitignored_paths + from release.restore import gitignored_paths # The excerpt is a run over the whole collection. A checkout without # the release assets (the PR workflow restores none) prints other @@ -2074,10 +2074,10 @@ class LandingAChangeNamesTheCommitRules(unittest.TestCase): return _section(_page("testing-guide.md"), "Landing a change") def test_every_refusal_is_on_the_page(self): - import commit_rules + from devtools import commitrules section = self._landing() - words = re.search(r"\\b\((.*?)\)", commit_rules.REFUSED_WORDS.pattern).group(1) + words = re.search(r"\\b\((.*?)\)", commitrules.REFUSED_WORDS.pattern).group(1) from tests.test_prose_style import NoMarketingVocabulary for word in words.replace("|", " ").split(): @@ -2099,8 +2099,9 @@ class LandingAChangeNamesTheCommitRules(unittest.TestCase): clone = Path(scratch) (clone / ".git" / "hooks").mkdir(parents=True) (clone / "scripts").mkdir() - (clone / "scripts" / "commit_rules.py").write_bytes( - (ROOT / "scripts" / "commit_rules.py").read_bytes()) + for name in ("commit_rules.py", "devtools/__init__.py", "devtools/commitrules.py"): + (clone / "scripts" / name).parent.mkdir(exist_ok=True) + (clone / "scripts" / name).write_bytes((ROOT / "scripts" / name).read_bytes()) subprocess.run(["sh", "-c", block], cwd=clone, check=True) message = clone / "MSG" message.write_text("fix: address review 3 notes\n", encoding="utf-8") diff --git a/tests/test_doc_surfaces.py b/tests/test_doc_surfaces.py index 65fcfb56c..6d78cfd3c 100644 --- a/tests/test_doc_surfaces.py +++ b/tests/test_doc_surfaces.py @@ -19,7 +19,7 @@ import unittest from functools import cache from pathlib import Path -import release_record +from model import releaserecord from sitegen.readme import ( SITE_URL, asset_links, @@ -31,7 +31,7 @@ from sitegen.readme import ( REPO_ROOT = Path(__file__).resolve().parent.parent -RECORD = release_record.load_record(REPO_ROOT / "release.json") +RECORD = releaserecord.load_record(REPO_ROOT / "release.json") REPO = "https://github.com/Abdess/retrobios" SPLIT_RECORD = { @@ -217,10 +217,10 @@ class DownloadLinksKeepTheirAddress(unittest.TestCase): from model.platforms import load_platform_config from sitegen import install - record = release_record.load_advertised() + record = releaserecord.load_advertised() page = _which_pack() for key in list_registered_platforms("platforms"): - if release_record.pack_for(key, record) is not None: + if releaserecord.pack_for(key, record) is not None: continue label = load_platform_config(key, "platforms").get("platform", key) row = next(line for line in page.splitlines() if line.startswith(f"| [{label}](")) @@ -380,7 +380,7 @@ class SizesComeFromTheRecord(unittest.TestCase): tag, platform, download, extracted = quoted.groups() if tag != RECORD.get("tag"): self.skipTest(f"release.json records {RECORD.get('tag')}, not {tag}") - pack = release_record.pack_for(platform.lower(), RECORD) + pack = releaserecord.pack_for(platform.lower(), RECORD) self.assertEqual(download, format_size(pack["download_size"])) self.assertEqual(extracted, format_size(pack["extracted_size"])) diff --git a/tests/test_game_catalogs.py b/tests/test_game_catalogs.py index bb71d8de6..76c98ffda 100644 --- a/tests/test_game_catalogs.py +++ b/tests/test_game_catalogs.py @@ -132,7 +132,7 @@ class FixtureImport(unittest.TestCase): class Selection(unittest.TestCase): def test_every_system_is_a_repository_system(self) -> None: - from romfolders import SystemResolver + from model.romfolders import SystemResolver ids = SystemResolver.from_repo().ids wanted = [s for s, _ in importer.NOINTRO_DATS.values()] diff --git a/tests/test_game_headers.py b/tests/test_game_headers.py index df1c70c88..3a2bd93e8 100644 --- a/tests/test_game_headers.py +++ b/tests/test_game_headers.py @@ -123,7 +123,7 @@ class HeaderReaders(unittest.TestCase): self.assertIn(core, self.profiles, system) def test_every_system_is_a_repository_system(self) -> None: - from romfolders import SystemResolver + from model.romfolders import SystemResolver ids = SystemResolver.from_repo().ids self.assertEqual([s for s in self.doc["systems"] if s not in ids], []) diff --git a/tests/test_games_index.py b/tests/test_games_index.py index 80a852d23..359d67e52 100644 --- a/tests/test_games_index.py +++ b/tests/test_games_index.py @@ -17,7 +17,7 @@ import unittest from pathlib import Path import generate_games_index as gi -from romfolders import SystemResolver, load_setups +from model.romfolders import SystemResolver, load_setups ROOT = Path(__file__).resolve().parent.parent TMP_ROOT = ROOT / "tmp" / "tests" @@ -237,7 +237,7 @@ class CommittedData(unittest.TestCase): if not setups: self.skipTest("no setup scraped") from model.profiles import load_emulator_profiles - from romfolders import ProfileResolver + from model.romfolders import ProfileResolver resolver = SystemResolver.from_repo(str(ROOT / "emulators"), str(ROOT / "platforms")) cores = ProfileResolver.from_repo(str(ROOT / "emulators")) @@ -258,7 +258,7 @@ class CommittedData(unittest.TestCase): folder run by mednafen_pce_fast, which lists nec-pc-engine, got no System Card.""" from model.profiles import load_emulator_profiles - from romfolders import ProfileResolver, folder_names + from model.romfolders import ProfileResolver, folder_names setups = load_setups(ROOT / "platforms" / "romfolders") if not setups: @@ -345,7 +345,7 @@ KNOWN_UNRESOLVED = { class EveryCoreResolvesOrIsExplained(unittest.TestCase): def setUp(self) -> None: from model.profiles import load_emulator_profiles - from romfolders import ProfileResolver + from model.romfolders import ProfileResolver self.resolver = SystemResolver.from_repo(str(ROOT / "emulators"), str(ROOT / "platforms")) self.cores = ProfileResolver.from_repo(str(ROOT / "emulators")) diff --git a/tests/test_handheld_launchers.py b/tests/test_handheld_launchers.py index 1800a6254..eb332c287 100644 --- a/tests/test_handheld_launchers.py +++ b/tests/test_handheld_launchers.py @@ -33,7 +33,7 @@ from pathlib import Path import yaml -import build_port +from installer_build import port REPO_ROOT = Path(__file__).resolve().parent.parent PORTS = REPO_ROOT / "ports" @@ -275,22 +275,22 @@ class TheSdlModel(unittest.TestCase): class TheArchives(unittest.TestCase): LAYOUT = { - build_port.PORT_ZIP: ("RetroBIOS.sh", "retrobios"), - build_port.BATOCERA_ZIP: ("RetroBIOS.sh", "retrobios"), - build_port.MUOS_APP: (None, "RetroBIOS"), - build_port.TOOLS_ZIP: ("RetroBIOS.sh", "retrobios"), + port.PORT_ZIP: ("RetroBIOS.sh", "retrobios"), + port.BATOCERA_ZIP: ("RetroBIOS.sh", "retrobios"), + port.MUOS_APP: (None, "RetroBIOS"), + port.TOOLS_ZIP: ("RetroBIOS.sh", "retrobios"), } def setUp(self): self.out = _tempdir(self) def test_every_release_archive_is_built(self): - self.assertEqual(set(build_port.ARCHIVES), set(self.LAYOUT)) + self.assertEqual(set(port.ARCHIVES), set(self.LAYOUT)) def test_layout(self): for name, (script, folder) in self.LAYOUT.items(): with self.subTest(archive=name): - with zipfile.ZipFile(build_port.build_archive(name, self.out / name)) as zf: + with zipfile.ZipFile(port.build_archive(name, self.out / name)) as zf: names = zf.namelist() modes = {n: zf.getinfo(n).external_attr >> 16 for n in names} self.assertEqual(names, sorted(names)) @@ -301,7 +301,7 @@ class TheArchives(unittest.TestCase): self.assertIn(f"{folder}/{member}", names) launcher = script or f"{folder}/mux_launch.sh" self.assertTrue(modes[launcher] & 0o111, launcher) - if name == build_port.BATOCERA_ZIP: + if name == port.BATOCERA_ZIP: self.assertEqual(top, ["RetroBIOS.sh", "RetroBIOS.sh.keys"]) self.assertNotIn("retrobios/retrobios.gptk", names) elif script: @@ -316,8 +316,8 @@ class TheArchives(unittest.TestCase): muxapp named an icon it did not carry.""" header = (REPO_ROOT / "ports" / "muos" / "mux_launch.sh").read_text() icon = re.search(r"^# ICON: (\S+)$", header, re.MULTILINE).group(1) - name = build_port.MUOS_APP - with zipfile.ZipFile(build_port.build_archive(name, self.out / name)) as zf: + name = port.MUOS_APP + with zipfile.ZipFile(port.build_archive(name, self.out / name)) as zf: data = zf.read(f"RetroBIOS/glyph/{icon}.png") self.assertEqual(data[:8], b"\x89PNG\r\n\x1a\n") @@ -326,26 +326,26 @@ class TheArchives(unittest.TestCase): system's extension (.sh for Tools and Ports): batocera-emulationstation and EmulationStation-fcamod SystemData.cpp drop a folder with none. The support folders must keep none, or each shows up in the menu.""" - for name in (build_port.TOOLS_ZIP, build_port.PORT_ZIP, build_port.BATOCERA_ZIP): + for name in (port.TOOLS_ZIP, port.PORT_ZIP, port.BATOCERA_ZIP): with self.subTest(archive=name): - with zipfile.ZipFile(build_port.build_archive(name, self.out / name)) as zf: + with zipfile.ZipFile(port.build_archive(name, self.out / name)) as zf: inside = [n for n in zf.namelist() if "/" in n and n.lower().endswith(".sh")] self.assertEqual(inside, []) def test_each_carries_the_pinned_installer(self): - pinned = build_port.pinned_installer_sha256() + pinned = port.pinned_installer_sha256() for name, (_script, folder) in self.LAYOUT.items(): with self.subTest(archive=name): - with zipfile.ZipFile(build_port.build_archive(name, self.out / name)) as zf: + with zipfile.ZipFile(port.build_archive(name, self.out / name)) as zf: bundled = hashlib.sha256(zf.read(f"{folder}/install.py")).hexdigest() self.assertEqual(bundled, pinned) def test_reproducible(self): - for name in build_port.ARCHIVES: + for name in port.ARCHIVES: with self.subTest(archive=name): - first = build_port.build_archive(name, self.out / f"a-{name}").read_bytes() - second = build_port.build_archive(name, self.out / f"b-{name}").read_bytes() + first = port.build_archive(name, self.out / f"a-{name}").read_bytes() + second = port.build_archive(name, self.out / f"b-{name}").read_bytes() self.assertEqual(first, second) def test_each_names_the_release_packs(self): @@ -354,13 +354,13 @@ class TheArchives(unittest.TestCase): registry = yaml.safe_load((REPO_ROOT / "platforms" / "_registry.yml").read_text()) released = {name for name, entry in registry["platforms"].items() if entry.get("release_pack") is True} - labels = build_port.release_pack_labels() + labels = port.release_pack_labels() self.assertEqual(set(labels), released) self.assertEqual(labels["retroarch"], "RetroArch") expected = "".join(f"{p}\t{label}\n" for p, label in sorted(labels.items())) for name, (_script, folder) in self.LAYOUT.items(): with self.subTest(archive=name), \ - zipfile.ZipFile(build_port.build_archive(name, self.out / name)) as zf: + zipfile.ZipFile(port.build_archive(name, self.out / name)) as zf: self.assertEqual(zf.read(f"{folder}/packs.txt").decode(), expected) def test_an_unpinned_installer_is_refused(self): @@ -370,9 +370,9 @@ class TheArchives(unittest.TestCase): shutil.copytree(PORTS, root / "ports") with (root / "install.py").open("a") as fh: fh.write("\n") - for name in build_port.ARCHIVES: + for name in port.ARCHIVES: with self.subTest(archive=name), self.assertRaises(ValueError): - build_port.build_archive(name, self.out / name, root) + port.build_archive(name, self.out / name, root) def test_the_site_serves_each_and_the_release_none(self): """Each archive carries install.py: the site serves it from its own @@ -380,7 +380,7 @@ class TheArchives(unittest.TestCase): text = (REPO_ROOT / "wiki" / "release-process.md").read_text(encoding="utf-8") self.assertNotIn("scripts/build_port.py", text) installer = (REPO_ROOT / "wiki" / "installer.md").read_text(encoding="utf-8") - for name in build_port.ARCHIVES: + for name in port.ARCHIVES: with self.subTest(archive=name): self.assertNotIn(name, text) self.assertIn(f"](../get/handheld/{name})", installer) @@ -763,7 +763,7 @@ class Device: """The launcher archive extracted where the firmware keeps it, with the fake installer in place of install.py.""" into.mkdir(parents=True, exist_ok=True) - built = build_port.build_archive(archive, self.root / "dist" / archive) + built = port.build_archive(archive, self.root / "dist" / archive) with zipfile.ZipFile(built) as zf: zf.extractall(into) for info in zf.infolist(): @@ -946,7 +946,7 @@ class ThePortMasterPort(unittest.TestCase): def device(self, console: str | None = None, **env: str) -> Device: device = Device(self, **env) roms = device.root / "roms" - self.gamedir = device.unpack(build_port.PORT_ZIP, roms / "ports") / "retrobios" + self.gamedir = device.unpack(port.PORT_ZIP, roms / "ports") / "retrobios" control = device.root / "xdg" / "PortMaster" control.mkdir(parents=True) self.control = control @@ -1530,7 +1530,7 @@ class ThePortMasterPort(unittest.TestCase): class TheBatoceraPort(unittest.TestCase): def device(self, **env: str) -> tuple[Device, Path]: device = Device(self, **env) - ports = device.unpack(build_port.BATOCERA_ZIP, device.root / "userdata" / "roms" / "ports") + ports = device.unpack(port.BATOCERA_ZIP, device.root / "userdata" / "roms" / "ports") return device, ports def console_switch(self, device: Device) -> dict[str, str]: @@ -1637,7 +1637,7 @@ class TheBatoceraPort(unittest.TestCase): class TheMuosApp(unittest.TestCase): def device(self, muxterm: bool, gptokeyb2: bool = True) -> tuple[Device, Path]: device = Device(self) - apps = device.unpack(build_port.MUOS_APP, device.root / "mmc" / "MUOS" / "application") + apps = device.unpack(port.MUOS_APP, device.root / "mmc" / "MUOS" / "application") muos = device.root / "opt-muos" (muos / "script" / "var").mkdir(parents=True) (muos / "script" / "var" / "retro.sh").write_text( @@ -1858,7 +1858,7 @@ class TheMuosApp(unittest.TestCase): class TheToolsEntry(unittest.TestCase): def device(self, **env: str) -> tuple[Device, Path]: device = Device(self, **env) - tools = device.unpack(build_port.TOOLS_ZIP, device.root / "tools") + tools = device.unpack(port.TOOLS_ZIP, device.root / "tools") device.env["RB_ROOT"] = str(device.root / "fs") return device, tools @@ -2100,7 +2100,7 @@ class TheDocs(unittest.TestCase): def test_the_offline_packs_named_are_the_ones_that_serve(self): """The wiki names the pack each firmware takes offline: the release pack of the platform install.py detects it as, or none.""" - labels = build_port.release_pack_labels() + labels = port.release_pack_labels() served = {} for rule in install._EMBEDDED_RULES: served.setdefault(rule.name, labels.get(rule.manifest)) diff --git a/tests/test_install.py b/tests/test_install.py index 4721fc9a6..bf00d4c8a 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -2517,7 +2517,7 @@ class TestAvailablePlatforms(unittest.TestCase): def test_pin_script_writes_both_pins(self): """Every edit to install.py meant a sha256sum pasted by hand into two files with two syntaxes, and the failing test named no command.""" - import pin_installer + from installer_build import pins with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp" / "tests") as directory: root = Path(directory) @@ -2525,9 +2525,9 @@ class TestAvailablePlatforms(unittest.TestCase): shutil.copy2(REPO_ROOT / name, root / name) (root / "install.py").write_text("# changed\n", encoding="utf-8") sh_mode = (root / "install.sh").stat().st_mode - self.assertEqual(pin_installer.stale_pins(root), ["install.sh", "install.ps1"]) - self.assertEqual(pin_installer.write_pins(root), ["install.sh", "install.ps1"]) - self.assertEqual(pin_installer.stale_pins(root), []) + self.assertEqual(pins.stale_pins(root), ["install.sh", "install.ps1"]) + self.assertEqual(pins.write_pins(root), ["install.sh", "install.ps1"]) + self.assertEqual(pins.stale_pins(root), []) digest = hashlib.sha256(b"# changed\n").hexdigest() for name in ("install.sh", "install.ps1"): before = (REPO_ROOT / name).read_text(encoding="utf-8").splitlines() @@ -7088,9 +7088,9 @@ class TheEventSchemaFileIsEventKeys(unittest.TestCase): outside Python could check a stream against.""" def _generator(self): - import generate_event_schema + from installer_build import eventschema - return generate_event_schema + return eventschema def test_the_committed_file_is_the_generated_one(self): generator = self._generator() @@ -7117,7 +7117,8 @@ class TheEventSchemaFileIsEventKeys(unittest.TestCase): generator.build_schema() def test_the_check_command_fails_on_a_stale_file(self): - generator = self._generator() + import generate_event_schema as generator + scratch = Path(_tempdir(self)) / "events.schema.json" scratch.write_text("{}\n", encoding="utf-8") with contextlib.redirect_stdout(io.StringIO()), \ @@ -7136,8 +7137,10 @@ class TheInstallerPageIsWrittenFromTheCode(unittest.TestCase): def setUp(self): import generate_installer_doc + from installer_build import installerdoc self.generator = generate_installer_doc + self.doc = installerdoc self.scratch = Path(_tempdir(self)) / "installer.md" self.scratch.write_text(self.PAGE.read_text(encoding="utf-8"), encoding="utf-8") @@ -7175,7 +7178,7 @@ class TheInstallerPageIsWrittenFromTheCode(unittest.TestCase): self.assertEqual(self.run_generator("--check")[0], 0) def test_what_the_code_gains_stops_it_until_the_page_says_it(self): - real = self.generator._install.build_parser + real = self.doc._install.build_parser def gained() -> argparse.ArgumentParser: parser = real() @@ -7183,12 +7186,12 @@ class TheInstallerPageIsWrittenFromTheCode(unittest.TestCase): return parser page = self.scratch.read_text(encoding="utf-8") - events = {**self.generator._install.EVENT_KEYS, "brand_new": ("thing",)} + events = {**self.doc._install.EVENT_KEYS, "brand_new": ("thing",)} for name, patch in ( ("--brand-new", unittest.mock.patch.object( - self.generator._install, "build_parser", gained)), + self.doc._install, "build_parser", gained)), ("brand_new", unittest.mock.patch.object( - self.generator._install, "EVENT_KEYS", events))): + self.doc._install, "EVENT_KEYS", events))): with self.subTest(gained=name), patch: code, said = self.run_generator() self.assertEqual(code, 1) @@ -7200,13 +7203,13 @@ class TheInstallerPageIsWrittenFromTheCode(unittest.TestCase): self.scratch.write_text( page.replace(close, "\n| `--brand-new` | Something new |" + close, 1), encoding="utf-8") - with unittest.mock.patch.object(self.generator._install, "build_parser", gained): + with unittest.mock.patch.object(self.doc._install, "build_parser", gained): self.assertEqual(self.run_generator()[0], 0) self.assertIn('| `--brand-new` | Something new |', self.scratch.read_text(encoding="utf-8")) def test_the_exit_codes_are_the_ones_install_py_exits_with(self): - self.assertEqual(self.generator.exit_codes(), [0, 1, 2, 3, 4, 130, 141]) + self.assertEqual(self.doc.exit_codes(), [0, 1, 2, 3, 4, 130, 141]) def test_a_missing_marker_stops_it(self): page = self.scratch.read_text(encoding="utf-8") diff --git a/tests/test_install_app.py b/tests/test_install_app.py index da29c43f3..02509a143 100644 --- a/tests/test_install_app.py +++ b/tests/test_install_app.py @@ -214,9 +214,9 @@ class TheList(unittest.TestCase): if "repo_path" in entry else entry["content"].encode()) for entry in launcher["members"]] data = install.app_archive(members) - import build_port - built = _tempdir(self) / build_port.MUOS_APP - build_port.build_archive(build_port.MUOS_APP, built) + from installer_build import port + built = _tempdir(self) / port.MUOS_APP + port.build_archive(port.MUOS_APP, built) with zipfile.ZipFile(built) as release, zipfile.ZipFile(io.BytesIO(data)) as ours: self.assertEqual(release.namelist(), ours.namelist()) for name in release.namelist(): diff --git a/tests/test_install_tui.py b/tests/test_install_tui.py index aecf4cfd8..1638bc7e5 100644 --- a/tests/test_install_tui.py +++ b/tests/test_install_tui.py @@ -10,7 +10,7 @@ installs it). from __future__ import annotations import tests -from tests.sources import script_source +from tests.sources import script_paths, script_source import argparse import contextlib @@ -9559,9 +9559,10 @@ class PacksWordingAndDocs(unittest.TestCase): env = page[page.index("## Environment overrides"):] self.assertIn("`TERMINFO`", env) self.assertIn("`TERMINFO_DIRS`", env) - script = (REPO_ROOT / "scripts" / "generate_installer_doc.py").read_text(encoding="utf-8") - self.assertEqual([n for n, line in enumerate(script.splitlines(), 1) if len(line) > 100], - []) + for path in script_paths("generate_installer_doc.py"): + script = path.read_text(encoding="utf-8") + self.assertEqual( + [n for n, line in enumerate(script.splitlines(), 1) if len(line) > 100], []) class OneDeviceRegistry(unittest.TestCase): @@ -10620,7 +10621,7 @@ class CardNamesAndHelp(_CardFixtures, unittest.TestCase): """The table left out the SHARE drives. It is generated: every card rule and SHARE drive file is a row, about.info among them.""" - import generate_installer_doc + from installer_build import installerdoc page = (REPO_ROOT / "wiki" / "installer.md").read_text(encoding="utf-8") block = page[page.index(""): @@ -10631,7 +10632,7 @@ class CardNamesAndHelp(_CardFixtures, unittest.TestCase): self.assertIn(f"`{marker}`", block) self.assertIn(self.ABOUT, block) self.assertIn("Recalbox SHARE drive", block) - self.assertEqual(generate_installer_doc.render(page), page) + self.assertEqual(installerdoc.render(page), page) class TheAndroidResultReadsWhole(unittest.TestCase): """A run on Android 17 under Termux: the result named /sdcard and diff --git a/tests/test_large_file_cache.py b/tests/test_large_file_cache.py index 63771575b..a4ed81961 100644 --- a/tests/test_large_file_cache.py +++ b/tests/test_large_file_cache.py @@ -25,7 +25,7 @@ from unittest import mock from model.composition import GAME_DATA_TOPS, composition_tier from model.profiles import load_emulator_profiles from model import largefiles -import check_release_assets +from release import assets as release_assets REPO_ROOT = Path(__file__).resolve().parent.parent @@ -573,14 +573,14 @@ class ReleaseAssetNames(unittest.TestCase): sizes = {self.ET: 228138631, self.RTCW: 122757192, self.PUP: 10} published = {expected[p]: size for p, size in sizes.items()} self.assertEqual( - check_release_assets.compare( + release_assets.compare( sizes, published, registered=self.REGISTERED ), [], ) # The old basename-only asset must not satisfy either pak. self.assertEqual( - {f[1] for f in check_release_assets.compare( + {f[1] for f in release_assets.compare( sizes, {"pak0.pk3": 228138631, "PS3UPDAT.PUP": 10}, registered=self.REGISTERED, )}, @@ -591,7 +591,7 @@ class ReleaseAssetNames(unittest.TestCase): "b" * 40: {"path": self.RTCW, "size": sizes[self.RTCW]}, "c" * 40: {"path": self.PUP, "size": sizes[self.PUP]}, }} - body = check_release_assets.render_notes( + body = release_assets.render_notes( db, gitignore, published, "", {}, {}, {} ) self.assertIn(f"[{expected[self.ET]}]", body) @@ -740,7 +740,7 @@ class GameDataHasOneDefinition(unittest.TestCase): with self.subTest(path=path): self.assertEqual(composition_tier(path), "game_data") self.assertEqual( - check_release_assets._section_for(path), "Game engine data" + release_assets._section_for(path), "Game engine data" ) def test_a_tree_of_game_data_alone_is_a_game_data_tree(self): @@ -829,21 +829,21 @@ class ASameSizeReuploadIsSeen(unittest.TestCase): assets = {"dsi_nand.bin": 8} ours = {"bios/Nintendo/DSi/dsi_nand.bin": "a" * 64} self.assertEqual( - [f[0] for f in check_release_assets.compare( + [f[0] for f in release_assets.compare( expected, assets, expected_digests=ours, asset_digests={"dsi_nand.bin": "b" * 64}, )], ["content"], ) self.assertEqual( - check_release_assets.compare( + release_assets.compare( expected, assets, expected_digests=ours, asset_digests={"dsi_nand.bin": "a" * 64}, ), [], ) self.assertEqual( - check_release_assets.digests_of( + release_assets.digests_of( [{"name": "x", "digest": "sha256:ABC"}, {"name": "y"}] ), {"x": "abc"}, diff --git a/tests/test_layers.py b/tests/test_layers.py index ff86fe7f6..7b7a15164 100644 --- a/tests/test_layers.py +++ b/tests/test_layers.py @@ -20,7 +20,8 @@ from pathlib import Path SCRIPTS = Path(__file__).resolve().parent.parent / "scripts" PACKAGE_LAYERS = {"core": 0, "model": 1, "resolve": 2, "packs": 3, "scraper": 3, "exporter": 3, - "probes": 3, "profiling": 3, "sitegen": 3, "romrecipes": 3, "acquire": 3} + "probes": 3, "profiling": 3, "sitegen": 3, "romrecipes": 3, "acquire": 3, + "release": 3, "installer_build": 3, "devtools": 3} LIBRARY_LAYER = 3 COMMAND_LAYER = 4 @@ -34,17 +35,20 @@ SIBLING_IMPORTS: dict[str, frozenset[str]] = { "profiling": frozenset(), "romrecipes": frozenset(), # The site prints the recipe counts and the dump-catalog coverage report - # those two packages compute. - "sitegen": frozenset({"acquire", "packs", "romrecipes"}), + # those two packages compute, serves the handheld launchers and prints the + # CI checks. + "sitegen": frozenset({"acquire", "packs", "romrecipes", "installer_build", "devtools"}), + # The record names its packs as the pack builder does. + "release": frozenset({"packs"}), + # The launcher archives are written by the pack member writer. + "installer_build": frozenset({"packs"}), + "devtools": frozenset(), } # Top-level modules other modules of scripts/ import: library code that a # later wave moves into a package. NOT_YET_PACKAGED = frozenset({ - "autorun", "build_port", - "check_buildbot_system", "check_release_assets", "commit_rules", - "generate_event_schema", "pin_installer", "pr_checks", - "release_record", "romfolders", + "autorun", }) # Top-level files that stay whole at their path although packages import them: @@ -60,20 +64,6 @@ PENDING_TOP_LEVEL_IMPORTS = frozenset({ ("probes.gate", "autorun"), ("probes.host", "autorun"), ("probes.packprobe", "autorun"), - ("sitegen.build", "release_record"), - ("sitegen.config", "release_record"), - ("sitegen.decorate", "release_record"), - ("sitegen.descriptions", "release_record"), - ("sitegen.getpages", "release_record"), - ("sitegen.guidepage", "release_record"), - ("sitegen.handheld", "build_port"), - ("sitegen.platformindex", "release_record"), - ("sitegen.publish", "release_record"), - ("sitegen.readme", "pr_checks"), - ("sitegen.readme", "release_record"), - ("sitegen.validate", "release_record"), - ("sitegen.versions", "release_record"), - ("sitegen.whichpack", "release_record"), }) diff --git a/tests/test_pack_counts.py b/tests/test_pack_counts.py index a2ec93b78..9190cede4 100644 --- a/tests/test_pack_counts.py +++ b/tests/test_pack_counts.py @@ -39,7 +39,9 @@ from packs import platformpack from sitegen import readme as sitegen_readme from sitegen import home import release_notes -import release_record +from release import notes +from release import record as release_record +from model import releaserecord from packs import parts HAS_JSONSCHEMA = jsonschema is not None @@ -483,9 +485,9 @@ class ReleaseRecord(unittest.TestCase): record["packs"]["Whole_1.0_BIOS_Pack.zip"], files=99, platforms=["other"] ) self.assertEqual( - release_record.pack_name_for("whole", record), "Whole_1.0_BIOS_Pack.zip" + releaserecord.pack_name_for("whole", record), "Whole_1.0_BIOS_Pack.zip" ) - self.assertEqual(release_record.pack_for("whole", record)["files"], 2) + self.assertEqual(releaserecord.pack_for("whole", record)["files"], 2) def test_the_owners_are_the_full_pack_names_the_builder_writes(self): owners = release_record.release_owners(str(REPO_ROOT / "platforms")) @@ -589,7 +591,7 @@ class TheReleaseNotesReadTheRecord(unittest.TestCase): }} def render(self, record=None): - return release_notes.render(record or self.RECORD, str(REPO_ROOT / "platforms"), + return notes.render(record or self.RECORD, str(REPO_ROOT / "platforms"), "### What changed\n\n- x\n") def test_each_pack_row_carries_the_record(self): @@ -620,11 +622,11 @@ class TheReleaseNotesReadTheRecord(unittest.TestCase): text = self.render().split("### What changed")[0] self.assertNotIn("every file its emulators", text) self.assertIn("https://abdess.github.io/retrobios/gaps/", text) - self.assertEqual(release_notes.refused_words(text), []) + self.assertEqual(notes.refused_words(text), []) def test_a_judging_whats_new_is_refused(self): self.assertEqual( - release_notes.refused_words( + notes.refused_words( "- Every hash comes from the emulator's source, never from a forum list.\n" "- So a game never stops on a missing file."), ["forum", "never stops"]) diff --git a/tests/test_port.py b/tests/test_port.py index e35093b4b..4bd29aaa8 100644 --- a/tests/test_port.py +++ b/tests/test_port.py @@ -24,7 +24,7 @@ import unittest import zipfile from pathlib import Path -import build_port +from installer_build import port as installer_build_port REPO_ROOT = Path(__file__).resolve().parent.parent PORT = REPO_ROOT / "ports" / "RetroBIOS" @@ -80,7 +80,7 @@ class ThePortArchive(unittest.TestCase): self.out = _tempdir(self) def _build(self, name: str = "RetroBIOS.zip") -> Path: - return build_port.build_port(self.out / name) + return installer_build_port.build_port(self.out / name) def test_layout_portmaster_installs(self): """One launch script at the top, one folder holding port.json: what @@ -107,7 +107,7 @@ class ThePortArchive(unittest.TestCase): def test_bundled_installer_is_the_pinned_one(self): with zipfile.ZipFile(self._build()) as zf: bundled = hashlib.sha256(zf.read("retrobios/install.py")).hexdigest() - self.assertEqual(bundled, build_port.pinned_installer_sha256()) + self.assertEqual(bundled, installer_build_port.pinned_installer_sha256()) install_sh = (REPO_ROOT / "install.sh").read_text(encoding="utf-8") self.assertIn(f'DEFAULT_INSTALL_SHA256="{bundled}"', install_sh) @@ -117,11 +117,11 @@ class LauncherIndex(unittest.TestCase): the archives built from the same tree, each with its size and hash.""" def test_the_committed_list_is_current(self): - import generate_launcher_index + from installer_build import launcherindex - text = generate_launcher_index.render(generate_launcher_index.build_index()) + text = launcherindex.render(launcherindex.build_index()) self.assertEqual( - generate_launcher_index.OUTPUT.read_text(encoding="utf-8"), text, + launcherindex.OUTPUT.read_text(encoding="utf-8"), text, "install/launchers/index.json is stale: run " "python scripts/generate_launcher_index.py") @@ -133,31 +133,31 @@ class LauncherIndex(unittest.TestCase): self.assertIn("scripts/generate_launcher_index.py", section) def test_every_member_of_the_archives_is_listed(self): - import generate_launcher_index + from installer_build import launcherindex - index = json.loads(generate_launcher_index.OUTPUT.read_text(encoding="utf-8")) + index = json.loads(launcherindex.OUTPUT.read_text(encoding="utf-8")) places = {place.key: place for place in install.APP_PLACES.values()} - for key, archive in generate_launcher_index.LAUNCHER_ARCHIVES.items(): + for key, archive in launcherindex.LAUNCHER_ARCHIVES.items(): with self.subTest(key=key): launcher = index["launchers"][key] listed = launcher.get("members") or launcher["files"] names = [entry.get("name") or entry["dest"] for entry in listed] prefix = "" if "members" in launcher else places[key].folder + "/" self.assertEqual(sorted(names), sorted( - prefix + name for name, _path in build_port.archive_members(archive))) + prefix + name for name, _path in installer_build_port.archive_members(archive))) for entry in listed: if "repo_path" in entry: data = (REPO_ROOT / entry["repo_path"]).read_bytes() self.assertEqual(hashlib.sha256(data).hexdigest(), entry["sha256"]) def test_the_list_refuses_an_installer_the_bootstraps_do_not_pin(self): - import generate_launcher_index + from installer_build import launcherindex root = _tempdir(self) shutil.copyfile(REPO_ROOT / "install.py", root / "install.py") (root / "install.sh").write_text('DEFAULT_INSTALL_SHA256="' + "0" * 64 + '"\n') with self.assertRaises(ValueError): - generate_launcher_index.build_index(root) + launcherindex.build_index(root) class EventRecords(unittest.TestCase): diff --git a/tests/test_prose_style.py b/tests/test_prose_style.py index 44d51982e..320eabaf4 100644 --- a/tests/test_prose_style.py +++ b/tests/test_prose_style.py @@ -170,7 +170,7 @@ class NoMarketingVocabulary(unittest.TestCase): offenders = [] for path in _tracked(): # This file and the commit rules have to name the words they refuse. - if path.name in {"test_prose_style.py", "commit_rules.py"}: + if path.name in {"test_prose_style.py", "commit_rules.py", "commitrules.py"}: continue text = path.read_text(encoding="utf-8", errors="replace") for number, line in enumerate(text.splitlines(), 1): diff --git a/tests/test_pypi_package.py b/tests/test_pypi_package.py index 496519a65..bf1198d51 100644 --- a/tests/test_pypi_package.py +++ b/tests/test_pypi_package.py @@ -23,7 +23,7 @@ import unittest import zipfile from pathlib import Path -import build_pypi +from installer_build import pypi REPO_ROOT = Path(__file__).resolve().parent.parent @@ -47,7 +47,7 @@ class Built(unittest.TestCase): raise unittest.SkipTest("uv is not installed") cls._scratch = tempfile.TemporaryDirectory(prefix="pypi-") cls.scratch = Path(cls._scratch.name) - cls.wheel, cls.sdist = build_pypi.build(cls.scratch / "dist") + cls.wheel, cls.sdist = pypi.build(cls.scratch / "dist") cls.version = cls.wheel.name.split("-")[1] @classmethod @@ -121,7 +121,7 @@ class TheArchivesHoldTheInstallerAndNothingElse(Built): def test_build_is_reproducible(self): # SOURCE_DATE_EPOCH is install.py's commit time, so the clock moving # between the two builds changes no byte. - again = build_pypi.build(self.scratch / "again") + again = pypi.build(self.scratch / "again") self.assertEqual([path.read_bytes() for path in again], [self.wheel.read_bytes(), self.sdist.read_bytes()]) @@ -132,15 +132,15 @@ class TheVersionIsInstallPyCommitDate(unittest.TestCase): def test_one_change_that_day(self): # 2026-11-09 12:00 UTC, then a change the day before. - self.assertEqual(build_pypi.package_version([1794225600, 1794139200]), "2026.11.9") + self.assertEqual(pypi.package_version([1794225600, 1794139200]), "2026.11.9") def test_the_rank_in_the_day(self): - self.assertEqual(build_pypi.package_version([1794229200, 1794225600, 1794222000]), + self.assertEqual(pypi.package_version([1794229200, 1794225600, 1794222000]), "2026.11.9.3") def test_no_commit_refused(self): with self.assertRaises(ValueError): - build_pypi.package_version([]) + pypi.package_version([]) class AnUnpinnedInstallerIsRefused(unittest.TestCase): @@ -151,13 +151,13 @@ class AnUnpinnedInstallerIsRefused(unittest.TestCase): root = Path(name) (root / "install.py").write_bytes(b"print('another')\n") shutil.copyfile(REPO_ROOT / "install.sh", root / "install.sh") - original = build_pypi.ROOT - build_pypi.ROOT = root + original = pypi.ROOT + pypi.ROOT = root try: with self.assertRaises(ValueError): - build_pypi.installer_bytes() + pypi.installer_bytes() finally: - build_pypi.ROOT = original + pypi.ROOT = original def _python38() -> str | None: diff --git a/tests/test_refresh_failures.py b/tests/test_refresh_failures.py index 33863cf1b..b40827080 100644 --- a/tests/test_refresh_failures.py +++ b/tests/test_refresh_failures.py @@ -21,7 +21,7 @@ import zipfile from pathlib import Path from unittest import mock -import check_buildbot_system +from scraper import buildbot_system from packs import datadirs REPO_ROOT = Path(__file__).resolve().parent.parent @@ -140,10 +140,10 @@ class RefreshFailuresAreFailures(unittest.TestCase): report = {"entries": [{"status": "UPDATED", "key": "dolphin-sys"}, {"status": "OK", "key": "ppsspp-assets"}]} with mock.patch.object( - check_buildbot_system.subprocess, "run", + buildbot_system.subprocess, "run", return_value=subprocess.CompletedProcess([], 1), ): - self.assertEqual(check_buildbot_system.update_changed(report), ["dolphin-sys"]) + self.assertEqual(buildbot_system.update_changed(report), ["dolphin-sys"]) source = (REPO_ROOT / "scripts" / "check_buildbot_system.py").read_text(encoding="utf-8") self.assertIn("failed = update_changed(report)", source) self.assertIn("sys.exit(1)", source[source.index("failed = update_changed(report)"):]) diff --git a/tests/test_release_packs.py b/tests/test_release_packs.py index 5a309760a..f6bdfd54a 100644 --- a/tests/test_release_packs.py +++ b/tests/test_release_packs.py @@ -28,7 +28,8 @@ from unittest import mock import yaml from model.registry import list_registered_platforms, list_release_pack_platforms -import release_record +from release import record as release_record +from model import releaserecord REPO_ROOT = Path(__file__).resolve().parent.parent @@ -225,7 +226,7 @@ class TheReleaseCheckReadsTheField(unittest.TestCase): }} def test_a_missing_and_an_unlisted_pack_are_reported(self): - from check_release import Asset, compare_release + from release.check import Asset, compare_release sums = {"A_BIOS_Pack.zip": "a" * 64, "K_BIOS_Pack.zip": "b" * 64} assets = {name: Asset(1, digest) for name, digest in sums.items()} @@ -245,12 +246,12 @@ class TheTablesFollowTheField(unittest.TestCase): "assets": ["x.zip"]}, "Recalbox_BIOS_Pack.zip": {"platforms": ["recalbox"], "assets": ["y.zip"]}, }} - shown = release_record.advertised(record, PLATFORMS) + shown = releaserecord.advertised(record, PLATFORMS) self.assertEqual(list(shown["packs"]), ["RetroArch_Lakka_BIOS_Pack.zip"]) self.assertEqual(shown["packs"]["RetroArch_Lakka_BIOS_Pack.zip"]["platforms"], ["retroarch"]) - self.assertIsNone(release_record.pack_for("lakka", shown)) - self.assertEqual(release_record.advertised({}, PLATFORMS), {}) + self.assertIsNone(releaserecord.pack_for("lakka", shown)) + self.assertEqual(releaserecord.advertised({}, PLATFORMS), {}) class EverySurfaceSaysWhy(unittest.TestCase): @@ -312,9 +313,9 @@ class TheReleaseNotesNameTheSetupsWithoutAZip(unittest.TestCase): }} def test_the_paragraph_names_them_and_points_to_the_command(self): - import release_notes + from release import notes - text = release_notes.render(self.RECORD, PLATFORMS, "### What changed\n\n- x\n") + text = notes.render(self.RECORD, PLATFORMS, "### What changed\n\n- x\n") paragraph = next(line for line in text.splitlines() if line.startswith("Only the most used setups have a pack")) for name in ("KNULLI", "Recalbox", "RetroPie", "Lakka"): @@ -328,9 +329,9 @@ class TheReleaseNotesNameTheSetupsWithoutAZip(unittest.TestCase): def test_the_rows_link_this_release_files(self): """The files sit right below the notes: a row sends nobody to the site to find them (owner, 2026-11-10).""" - import release_notes + from release import notes - text = release_notes.render(self.RECORD, PLATFORMS, "x") + text = notes.render(self.RECORD, PLATFORMS, "x") self.assertIn( "[Download](https://github.com/Abdess/retrobios/releases/download/" "v2026.10.24/RomM_5_BIOS_Pack.zip)", text) @@ -342,9 +343,9 @@ class TheReleaseNotesNameTheSetupsWithoutAZip(unittest.TestCase): def test_the_command_comes_before_the_packs(self): """Most readers need a few files, not a pack of several GB (owner, 2026-11-10): the command and the handheld app open the notes.""" - import release_notes + from release import notes - text = release_notes.render(self.RECORD, PLATFORMS, "### What changed\n\n- x\n") + text = notes.render(self.RECORD, PLATFORMS, "### What changed\n\n- x\n") command = text.index("```sh") # The installer's handheld section, which opens on every download. handheld = text.index(f"{SITE}wiki/installer/#on-a-handheld-the-retrobios-port") @@ -407,14 +408,14 @@ class TheReleaseNotesThankPeople(unittest.TestCase): self.calls = [] def test_the_base_is_the_previous_release_record(self): - import release_notes + from release import notes - self.assertEqual(release_notes.previous_record_commit("v2026.11.10", self.fake), "c1") + self.assertEqual(notes.previous_record_commit("v2026.11.10", self.fake), "c1") def test_everyone_since_the_start_is_thanked_once(self): - import release_notes + from release import notes - lines = release_notes.gather_thanks(self.fake) + lines = notes.gather_thanks(self.fake) self.assertEqual(lines, [ "- **Code and data**: @closedwithoutmerge, @dajiaohuang, @habib256 and @zed.", "- **Reports**: @72374 and @paperweightorder.", @@ -430,25 +431,26 @@ class TheReleaseNotesThankPeople(unittest.TestCase): self.assertEqual(issues[issues.index("--state") + 1], "all") def test_the_notes_end_with_thanks_then_the_changelog(self): - import release_notes + from release import notes - closing = release_notes.closing_lines( + closing = notes.closing_lines( ["- **Code and data**: @habib256."], - release_notes.changelog_url("55eb95344" + "0" * 31, "v2026.11.10")) - text = release_notes.render(TheReleaseNotesNameTheSetupsWithoutAZip.RECORD, PLATFORMS, + notes.changelog_url("55eb95344" + "0" * 31, "v2026.11.10")) + text = notes.render(TheReleaseNotesNameTheSetupsWithoutAZip.RECORD, PLATFORMS, "### What changed\n\n- x\n", closing) self.assertLess(text.index("### What changed"), text.index("### Thanks")) self.assertIn("### Thanks\n\n
\n" "Everyone who helped since the start\n\n" "- **Code and data**: @habib256.\n\n
\n\n**Full changelog**", text) - self.assertEqual(release_notes.refused_words(text), []) + self.assertEqual(notes.refused_words(text), []) self.assertTrue(text.rstrip().endswith( "**Full changelog**: https://github.com/Abdess/retrobios/compare/" "55eb95344...v2026.11.10")) def test_a_checked_list_replaces_the_one_gh_gives(self): import release_notes + from release import notes with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: tmp = Path(tmp) @@ -461,7 +463,7 @@ class TheReleaseNotesThankPeople(unittest.TestCase): "--whats-new", str(tmp / "whats-new.md"), "--thanks", str(tmp / "thanks.md"), "--platforms-dir", PLATFORMS, "--output", str(tmp / "notes.md")] with mock.patch.object(sys, "argv", argv), \ - mock.patch.object(release_notes, "_run", self.fake), \ + mock.patch.object(notes, "_run", self.fake), \ mock.patch.object(release_notes, "gather_thanks", side_effect=AssertionError("gh read")), \ contextlib.redirect_stdout(io.StringIO()): @@ -475,11 +477,11 @@ class EveryPlatformHasAPermanentPage(unittest.TestCase): def test_a_page_for_every_registered_platform(self): from sitegen import getpages - record = release_record.load_advertised() + record = releaserecord.load_advertised() with contextlib.chdir(REPO_ROOT): for name in list_registered_platforms(PLATFORMS): page = getpages.generate_get_page(name) - pack = release_record.pack_for(name, record) + pack = releaserecord.pack_for(name, record) with self.subTest(platform=name): self.assertRegex(page, r"\n# (.+ )?BIOS (pack|files)( for .+)?\n") if name in RELEASED and pack: @@ -494,13 +496,13 @@ class EveryPlatformHasAPermanentPage(unittest.TestCase): def test_the_generator_writes_and_sweeps_them(self): from sitegen import config - self.assertIn(release_record.GET_DIR, config.GENERATED_DIRS) + self.assertIn(releaserecord.GET_DIR, config.GENERATED_DIRS) source = script_source("generate_site.py") self.assertIn('write_if_changed(str(get_dir / f"{name}.md"), generate_get_page(name))', source) def test_built_pages_exist(self): - docs = REPO_ROOT / "website" / "src" / "content" / "docs" / release_record.GET_DIR + docs = REPO_ROOT / "website" / "src" / "content" / "docs" / releaserecord.GET_DIR if not docs.is_dir(): self.skipTest("the site is not generated") for name in list_registered_platforms(PLATFORMS): diff --git a/tests/test_romfolders_card.py b/tests/test_romfolders_card.py index f3a817f92..bbaa78aa4 100644 --- a/tests/test_romfolders_card.py +++ b/tests/test_romfolders_card.py @@ -13,7 +13,7 @@ import json import unittest from pathlib import Path -from romfolders import split_refs +from model.romfolders import split_refs from model.safeparse import yaml_load from scraper.romfolders import SourceError, load_sources, scrape_setup from scraper.romfolders.__main__ import dump_setup diff --git a/tests/test_romfolders_es.py b/tests/test_romfolders_es.py index e4cd504c7..a50b24ea7 100644 --- a/tests/test_romfolders_es.py +++ b/tests/test_romfolders_es.py @@ -15,7 +15,7 @@ import json import unittest from pathlib import Path -from romfolders import setup_paths, split_refs +from model.romfolders import setup_paths, split_refs from scraper.romfolders import ( Fetcher, SourceError, diff --git a/tests/test_site_agents.py b/tests/test_site_agents.py index b9a962a17..28332f24d 100644 --- a/tests/test_site_agents.py +++ b/tests/test_site_agents.py @@ -54,9 +54,9 @@ class TheGuideDrivesTheInstaller(unittest.TestCase): fact is held to install.py, so the guide cannot drift from it.""" def setUp(self) -> None: - import generate_installer_doc + from installer_build import installerdoc - self.doc = generate_installer_doc + self.doc = installerdoc self.text = siteagents.llms_txt([("retroarch", "RetroArch")]) self.section = self.text.split("\n## Driving the installer for a user\n", 1)[1].split("\n## ", 1)[0] diff --git a/tests/test_site_entry.py b/tests/test_site_entry.py index a4b621f24..28a211170 100644 --- a/tests/test_site_entry.py +++ b/tests/test_site_entry.py @@ -53,7 +53,7 @@ from sitegen import nav as sitegen_nav from sitegen import platformindex from sitegen import reference from sitegen import versions -import release_record +from model import releaserecord from model import guides from sitegen import markup as sitemarkup from model.platforms import load_platform_config @@ -209,9 +209,9 @@ class GetYourFilesOrder(unittest.TestCase): def test_a_setup_after_the_release_says_no_zip_yet(self): text = _page("which-pack.md") self.assertNotIn("Not in v", text) - record = release_record.load_advertised() + record = releaserecord.load_advertised() pending = [k for k in REGISTRY if REGISTRY[k].get("release_pack") - and not release_record.pack_for(k, record)] + and not releaserecord.pack_for(k, record)] if record.get("tag") and pending: self.assertIn("No ZIP yet. [Use the command]", text) self.assertIn("Setups added after the last release have no ZIP until the next one.", @@ -283,8 +283,8 @@ class PackManualReadsThePageFolders(unittest.TestCase): class DownloadNamesTheRelease(unittest.TestCase): def test_tag_date_checksums_and_signature(self): - record = release_record.load_record() - if not release_record.pack_for("batocera", record): + record = releaserecord.load_record() + if not releaserecord.pack_for("batocera", record): self.skipTest("release.json has no Batocera pack") tag = record["tag"] lines = versions.release_line("batocera", record) @@ -461,11 +461,11 @@ class HandheldWayIn(unittest.TestCase): class PackNamesItsVersion(unittest.TestCase): def test_the_line_under_the_release(self): - record = release_record.load_record() - if not release_record.pack_for("batocera", record): + record = releaserecord.load_record() + if not releaserecord.pack_for("batocera", record): self.skipTest("release.json has no Batocera pack") block = guidepage._pack_buttons("batocera") - name = release_record.pack_name_for("batocera", record) + name = releaserecord.pack_name_for("batocera", record) version = versions._pack_version(name, ["batocera"]) self.assertIn(f"Made for Batocera {version}. " + versions.other_version("batocera"), block) @@ -577,12 +577,12 @@ class GetYourFilesListsEachSetupOnce(unittest.TestCase): self.assertNotIn("**Self-hosted game library**", self.text) def test_no_unzip_into_without_a_zip(self): - record = release_record.load_record() + record = releaserecord.load_record() for line in self.text.splitlines(): if "Unzip into" in line: key = re.search(r"/retrobios/platforms/([a-z0-9]+)/", line)[1] with self.subTest(platform=key): - self.assertTrue(release_record.pack_for(key, record)) + self.assertTrue(releaserecord.pack_for(key, record)) def test_parts_are_buttons_with_the_size_after(self): """A row links the setup's get/ page, which lists every part, with the @@ -665,8 +665,8 @@ class TileLogosLoadWhenSeen(unittest.TestCase): class DownloadLine(unittest.TestCase): def test_checksums_and_signature_read_as_two(self): - record = release_record.load_record() - if not release_record.pack_for("batocera", record): + record = releaserecord.load_record() + if not releaserecord.pack_for("batocera", record): self.skipTest("release.json has no Batocera pack") line = versions.release_line("batocera", record)[0] self.assertRegex(line, r"\[SHA256SUMS\.txt\]\([^)]+\) and its \[signature\]\([^)]+\)\.$") @@ -682,7 +682,7 @@ def _plain_page(name: str) -> str: def _with_zip(name: str) -> bool: - pack = release_record.pack_for(name, release_record.load_advertised()) + pack = releaserecord.pack_for(name, releaserecord.load_advertised()) return bool(pack and pack.get("assets")) @@ -1113,10 +1113,10 @@ class TheSiteSaysWhatTheInstallerShows(unittest.TestCase): self.assertNotIn("offers to install everything or to choose systems", readme) source = script_source("generate_readme.py") self.assertIn("_installer_words().TUI_SYSTEMS_ROW", source) - import generate_installer_doc + from installer_build import installerdoc page = (REPO_ROOT / "wiki" / "installer.md").read_text(encoding="utf-8") - self.assertIn(generate_installer_doc.line_menu(), page) + self.assertIn(installerdoc.line_menu(), page) menu = page.split("", 1)[1] outside = page.replace(menu.split("", 1)[0], "") for line in self.MENU_LINES: diff --git a/tests/test_site_handheld.py b/tests/test_site_handheld.py index 05a0e1889..5014b05eb 100644 --- a/tests/test_site_handheld.py +++ b/tests/test_site_handheld.py @@ -21,9 +21,10 @@ import unittest from pathlib import Path from unittest import mock -import build_port +from installer_build import port from model.registry import list_registered_platforms from sitegen import handheld as sitehandheld +from installer_build import handhelds REPO_ROOT = Path(__file__).resolve().parents[1] @@ -36,8 +37,8 @@ def _pages() -> dict[str, str]: with contextlib.chdir(REPO_ROOT): pages = {f"get/{key}.md": getpages.generate_get_page(key) - for key in sorted(set(sitehandheld.PLATFORM_OF.values()))} - pages[f"get/{sitehandheld.GROUP_PAGE}.md"] = sitehandheld.group_page(REPO_ROOT) + for key in sorted(set(handhelds.PLATFORM_OF.values()))} + pages[f"get/{handhelds.GROUP_PAGE}.md"] = sitehandheld.group_page(REPO_ROOT) return pages @@ -50,11 +51,11 @@ class TheSiteServesTheLaunchers(unittest.TestCase): def test_the_written_archives_are_the_ones_build_port_writes(self): written = sitehandheld.write_launchers(self.tmp / "public", REPO_ROOT) - self.assertEqual([path.name for path in written], list(build_port.ARCHIVES)) + self.assertEqual([path.name for path in written], list(port.ARCHIVES)) for path in written: with self.subTest(archive=path.name): self.assertEqual(path.parent, self.tmp / "public" / "get" / "handheld") - built = build_port.build_archive(path.name, self.tmp / "built" / path.name) + built = port.build_archive(path.name, self.tmp / "built" / path.name) self.assertEqual(path.read_bytes(), built.read_bytes()) def test_an_unchanged_archive_is_not_rewritten(self): @@ -67,7 +68,7 @@ class TheSiteServesTheLaunchers(unittest.TestCase): """build_port refuses an install.py the bootstraps do not pin: served, that launcher would refuse its own installer.""" with mock.patch.dict(sitehandheld._built, clear=True), \ - mock.patch.object(build_port, "pinned_installer_sha256", return_value="0" * 64), \ + mock.patch.object(port, "pinned_installer_sha256", return_value="0" * 64), \ self.assertRaisesRegex(ValueError, "re-pin the bootstraps"): sitehandheld.write_launchers(self.tmp / "public", REPO_ROOT) self.assertFalse(list((self.tmp / "public").rglob("RetroBIOS*"))) @@ -76,7 +77,7 @@ class TheSiteServesTheLaunchers(unittest.TestCase): public = self.tmp / "public" written = {path.name: path for path in sitehandheld.write_launchers(public, REPO_ROOT)} pages = _pages() - for name in build_port.ARCHIVES: + for name in port.ARCHIVES: with self.subTest(archive=name): data = written[name].read_bytes() digest = hashlib.sha256(data).hexdigest() @@ -98,8 +99,8 @@ class TheSiteServesTheLaunchers(unittest.TestCase): class WhereEachSystemFindsItsFile(unittest.TestCase): def test_each_platform_page_is_a_registered_platform(self): registered = set(list_registered_platforms(PLATFORMS)) - self.assertLessEqual(set(sitehandheld.PLATFORM_OF.values()), registered) - self.assertNotIn(sitehandheld.GROUP_PAGE, registered) + self.assertLessEqual(set(handhelds.PLATFORM_OF.values()), registered) + self.assertNotIn(handhelds.GROUP_PAGE, registered) def test_the_group_page_sits_with_the_handheld_guide(self): """It shares the guide's name, so the sidebar files it with it, and @@ -109,31 +110,31 @@ class WhereEachSystemFindsItsFile(unittest.TestCase): from sitegen import guidepage guide = guides.HANDHELD_GUIDE - self.assertEqual(sitehandheld.GROUP_PAGE, guide.page) + self.assertEqual(handhelds.GROUP_PAGE, guide.page) with contextlib.chdir(REPO_ROOT): - self.assertIn(f"(../get/{sitehandheld.GROUP_PAGE}.md)", + self.assertIn(f"(../get/{handhelds.GROUP_PAGE}.md)", guidepage.generate_handheld_guide(guide)) - self.assertIn(f"]({sitehandheld.GROUP_PAGE}.md)", getpages.generate_get_index()) + self.assertIn(f"]({handhelds.GROUP_PAGE}.md)", getpages.generate_get_index()) def test_every_system_has_its_launchers_on_its_page(self): pages = _pages() - for system in sitehandheld.systems(): - page = sitehandheld.page_of(system) + for system in handhelds.systems(): + page = handhelds.page_of(system) with self.subTest(system=system): self.assertIn(page, pages) - for launcher in sitehandheld.launchers_for(system): + for launcher in handhelds.launchers_for(system): self.assertIn(f'href="handheld/{launcher.archive}"', pages[page]) self.assertIn(launcher.folder_for(system), pages[page]) self.assertIn(launcher.start, pages[page]) for system in sitehandheld.group_systems(): - self.assertIn(f"\n## {system}\n", pages[f"get/{sitehandheld.GROUP_PAGE}.md"]) + self.assertIn(f"\n## {system}\n", pages[f"get/{handhelds.GROUP_PAGE}.md"]) def test_the_installer_table_is_written_from_the_same_rows(self): text = (REPO_ROOT / "wiki" / "installer.md").read_text(encoding="utf-8") block = re.search(r"\n(.*?)", text, re.S) self.assertIsNotNone(block) - self.assertEqual(block.group(1).strip(), "\n".join(sitehandheld.table_rows())) + self.assertEqual(block.group(1).strip(), "\n".join(handhelds.table_rows())) self.assertNotIn("releases/latest", text.split("## On a handheld", 1)[1].split("\n## ")[0]) def test_the_installer_section_opens_on_the_downloads(self): @@ -145,18 +146,18 @@ class WhereEachSystemFindsItsFile(unittest.TestCase): block = re.search(r"\n(.*?)" r"", section, re.S) self.assertIsNotNone(block) - self.assertEqual(block.group(1).strip(), "\n".join(sitehandheld.download_rows())) + self.assertEqual(block.group(1).strip(), "\n".join(handhelds.download_rows())) self.assertLess(block.start(), section.index("### Where each file goes")) self.assertLess(len(section[:block.start()].split()), 40) - for system in sitehandheld.systems(): + for system in handhelds.systems(): with self.subTest(system=system): row = next(line for line in block.group(1).splitlines() if line.startswith(f"| {system} |")) - for launcher in sitehandheld.launchers_for(system): - self.assertIn(f"](../{sitehandheld.SERVED_DIR}/{launcher.archive})", row) - self.assertIn(f"](../{sitehandheld.page_of(system)}#", row) - for name in build_port.ARCHIVES: - self.assertIn(f"](../{sitehandheld.SERVED_DIR}/{name})", block.group(1)) + for launcher in handhelds.launchers_for(system): + self.assertIn(f"](../{handhelds.SERVED_DIR}/{launcher.archive})", row) + self.assertIn(f"](../{handhelds.page_of(system)}#", row) + for name in port.ARCHIVES: + self.assertIn(f"](../{handhelds.SERVED_DIR}/{name})", block.group(1)) def test_the_generator_writes_them(self): source = script_source("generate_site.py") diff --git a/tests/test_site_pronouns.py b/tests/test_site_pronouns.py index 4eb75e1aa..e0f176f88 100644 --- a/tests/test_site_pronouns.py +++ b/tests/test_site_pronouns.py @@ -189,17 +189,17 @@ class SitePronouns(unittest.TestCase): def test_release_notes(self): """The release page is public text too. Rendered from the committed record, and once more with a pack in parts, its own paragraph.""" - import release_notes - import release_record + from release import notes + from model import releaserecord - record = release_record.load_record(ROOT / "release.json") + record = releaserecord.load_record(ROOT / "release.json") first = next(iter(record["packs"])) parted = {**record, "packs": {**record["packs"], first: { **record["packs"][first], "assets": ["a.part1of2.zip", "a.part2of2.zip"]}}} platforms = str(ROOT / "platforms") hits = [f"release notes:{number}: {line}" for sample in (record, parted) - for number, line in pronouns(release_notes.render(sample, platforms, "x"))] + for number, line in pronouns(notes.render(sample, platforms, "x"))] self.assertEqual(hits, [], "\n".join(hits)) def test_every_allowed_quote_says_why(self): diff --git a/tests/test_site_reference.py b/tests/test_site_reference.py index 554516c02..b76d729af 100644 --- a/tests/test_site_reference.py +++ b/tests/test_site_reference.py @@ -78,7 +78,7 @@ from sitegen.sources import launcher_ref_markdown, list_source import check_platform_folder import core from sitegen import sources -import release_record +from model import releaserecord from core import upstream REPO_ROOT = Path(__file__).resolve().parents[1] @@ -1230,8 +1230,8 @@ class TheReleaseRecordHasAVersion(unittest.TestCase): """8.9.""" def test_the_writer_and_the_committed_record(self): - self.assertEqual(release_record.SCHEMA_VERSION, 1) - source = (REPO_ROOT / "scripts" / "release_record.py").read_text(encoding="utf-8") + self.assertEqual(releaserecord.SCHEMA_VERSION, 1) + source = script_source("release_record.py") self.assertIn('{"schema_version": SCHEMA_VERSION, "tag": tag, "packs": packs}', source) schema = json.loads((REPO_ROOT / "schemas" / "release.schema.json").read_text()) self.assertIn("schema_version", schema["required"]) @@ -1320,13 +1320,13 @@ class OneAnswerOnReleasePacks(unittest.TestCase): else None) as folder: publish.write_release_advertised(Path(folder)) written = json.loads((Path(folder) / "release-advertised.json").read_text()) - self.assertEqual(written, release_record.load_advertised()) + self.assertEqual(written, releaserecord.load_advertised()) served = {p for pack in written.get("packs", {}).values() for p in pack["platforms"]} self.assertLessEqual(served, _released()) def test_the_built_picker_file(self): written = json.loads(_built(GENERATED / "release-advertised.json").read_text()) - self.assertEqual(written, release_record.load_advertised()) + self.assertEqual(written, releaserecord.load_advertised()) def _properties(node: object, path: str = ""): diff --git a/tests/test_site_wiki.py b/tests/test_site_wiki.py index b62649eff..048546ad5 100644 --- a/tests/test_site_wiki.py +++ b/tests/test_site_wiki.py @@ -45,8 +45,8 @@ import importlib.util from sitegen import diagrams from model.guides import INSTALL_SH from tests import sitepages -import build_port -from check_release import SUMS, Asset, compare_release +from installer_build import port +from release.check import SUMS, Asset, compare_release REPO_ROOT = Path(__file__).resolve().parents[1] @@ -880,11 +880,11 @@ class PinnedInstaller(unittest.TestCase): """The handheld launchers carry install.py: the site serves them from its own commit, the release never does.""" record = {"tag": "v1", "packs": {"P.zip": {"download_size": 5, "assets": ["P.zip"]}}} - sums = _sums_with(["P.zip", *build_port.ARCHIVES]) + sums = _sums_with(["P.zip", *port.ARCHIVES]) assets = {name: Asset(5, digest) for name, digest in sums.items()} assets[SUMS] = Asset(1, None) kinds = {(f.kind, f.name) for f in compare_release(record, sums, assets, "v1")} - self.assertEqual(kinds, {("unrecorded", name) for name in build_port.ARCHIVES}) + self.assertEqual(kinds, {("unrecorded", name) for name in port.ARCHIVES}) def test_the_release_steps_ship_none(self): text = _wiki("release-process.md") @@ -897,7 +897,7 @@ class PinnedInstaller(unittest.TestCase): self.assertNotIn(name, sums) self.assertNotIn(name, upload) # A launcher built into dist/ is never caught by the glob either. - for archive in build_port.ARCHIVES: + for archive in port.ARCHIVES: with self.subTest(archive=archive): self.assertFalse(fnmatch.fnmatch(archive, "*_BIOS_Pack*.zip")) self.assertIn("*_BIOS_Pack*.zip", sums) diff --git a/tests/test_which_pack.py b/tests/test_which_pack.py index 039bff564..20631f288 100644 --- a/tests/test_which_pack.py +++ b/tests/test_which_pack.py @@ -27,16 +27,16 @@ class WhichPackRows(unittest.TestCase): release asset: the asset URL dies with its tag.""" from sitegen import install from sitegen import whichpack - import release_record + from model import releaserecord - record = release_record.load_advertised() + record = releaserecord.load_advertised() page = whichpack.generate_which_pack() row = re.compile(r"^\| \[[^\]]+\]\(platforms/([a-z0-9]+)\.md\) \|(.*)$", re.M) get = re.compile(r'href="get/([a-z0-9]+)\.md"') checked = 0 for key, rest in row.findall(page): linked = set(get.findall(rest)) - pack = release_record.pack_for(key, record) + pack = releaserecord.pack_for(key, record) with self.subTest(platform=key): self.assertNotIn("/releases/download/", rest) self.assertLessEqual(linked, {key})