refactor: release, installer_build, devtools pkgs

The release tools, the installer build tools and the repository's
commit and PR checks keep their commands and move their code into
three packages. The release record readers move to model.releaserecord,
romfolders to model, the buildbot check to scraper. The site reads the
handheld launchers and the bootstrap pin from installer_build.
This commit is contained in:
Abdessamad Derraz committed 2026-11-18 20:44:12 +01:00
1 parent 5b3b3f19e8
commit c4fdf12874
91 files changed
+3508 -3277

No files matched your search

+1
View File
@@ -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."""
+322
View File
@@ -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}.<module> 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)
+92
View File
@@ -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"
+126
View File
@@ -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/<platform>/ 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
+645
View File
@@ -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<open><!-- generated: (?P<name>[a-z-]+) -->\n)(?P<body>.*?)"
r"(?P<close><!-- /generated: (?P=name) -->)", re.S)
_CELL = re.compile(r"(?<!\\)\|")
# The help screen's actions, as the page names them.
ACTIONS = {
"move": "Move",
"page": "Page",
"ok": "Continue, open, choose",
"tick": "Tick, untick",
"options": "Change",
"back": "Back, and quit on the first screen",
"stop": "Stop an install",
"kill": "Quit at once",
"enter": "Use the folder typed",
"esc": "Clear a filter, leave the folder typed",
}
# The two routes no launcher names, as the page heads their columns.
ROUTE_HEADINGS = {"keys": "Computer (`keys`)", "both": "Unknown (`both`)"}
class MissingProse(Exception):
"""Rows install.py has that the page does not describe yet."""
def _cells(line: str) -> 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'<span id="option-{flags[0][2:]}"></span>{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/<platform>.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
+89
View File
@@ -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"
+58
View File
@@ -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),
}
+167
View File
@@ -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/<ICON>.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)
+104
View File
@@ -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