refactor: release, installer_build, devtools pkgs

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

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Release artifacts: what the packs of a release hold, its notes, and the checks of its assets."""
+306
View File
@@ -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"]}
+145
View File
@@ -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
+255
View File
@@ -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)
+122
View File
@@ -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"
+114
View File
@@ -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
+126
View File
@@ -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,
)