mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-24 02:27:52 -06:00
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:
1 parent
5b3b3f19e8
commit
c4fdf12874
91 files changed
+3508
-3277
No files matched your search
+1
-1
@@ -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)
|
||||
|
||||
|
||||
+1
-315
@@ -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}.<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)
|
||||
from installer_build.amalgamate import BuildError, COMMAND, OUTPUT, PACKAGE, ROOT, build
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
|
||||
+1
-158
@@ -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/<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)
|
||||
from installer_build.port import ARCHIVES, build_archive
|
||||
|
||||
|
||||
def main() -> int:
|
||||
|
||||
+1
-97
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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"
|
||||
),
|
||||
)
|
||||
|
||||
+10
-137
@@ -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:
|
||||
|
||||
+10
-298
@@ -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<name>[^\]]+)\]\([^)]*\) \| (?P<desc>[^|]*?) \| [^|]* \|"
|
||||
r"(?: `(?P<sha1>[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 <file>`.", ""]
|
||||
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:
|
||||
|
||||
+1
-35
@@ -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:
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""The repository's own rules: commit messages and the checks CI runs on a pull request."""
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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<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'); 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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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."""
|
||||
@@ -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)
|
||||
@@ -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"
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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"
|
||||
@@ -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),
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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/<platform>/ 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
|
||||
File renamed without changes.
@@ -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:
|
||||
|
||||
+1
-93
@@ -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:
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Release artifacts: what the packs of a release hold, its notes, and the checks of its assets."""
|
||||
@@ -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<name>[^\]]+)\]\([^)]*\) \| (?P<desc>[^|]*?) \| [^|]* \|"
|
||||
r"(?: `(?P<sha1>[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 <file>`.", ""]
|
||||
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"]}
|
||||
@@ -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
|
||||
@@ -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", "", "<details>",
|
||||
"<summary>Everyone who helped since the start</summary>", "",
|
||||
*thanks, "", "</details>", ""]
|
||||
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)
|
||||
@@ -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"
|
||||
@@ -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 `<asset>.<random>.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
|
||||
@@ -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,
|
||||
)
|
||||
+11
-250
@@ -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", "", "<details>",
|
||||
"<summary>Everyone who helped since the start</summary>", "",
|
||||
*thanks, "", "</details>", ""]
|
||||
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
|
||||
|
||||
+9
-175
@@ -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/<platform>/ 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:
|
||||
|
||||
@@ -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 `<asset>.<random>.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:
|
||||
|
||||
@@ -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"]
|
||||
@@ -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
|
||||
|
||||
@@ -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())
|
||||
|
||||
|
||||
@@ -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")
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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])}. "
|
||||
|
||||
@@ -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)
|
||||
@@ -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 }",
|
||||
"",
|
||||
|
||||
+12
-119
@@ -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/<platform>/ 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/<platform>/ 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"
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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",
|
||||
)
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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 ""
|
||||
|
||||
@@ -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 "
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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"]
|
||||
|
||||
Reference in new issue
Block a user