refactor: step 5 reads counts both tools record

This commit is contained in:
Abdessamad Derraz committed 2026-11-21 19:50:42 +01:00
1 parent cf7e13808f
commit 9814bb1234
21 files changed
+428 -432

No files matched your search

+4
View File
@@ -166,6 +166,10 @@ def build_parser() -> argparse.ArgumentParser:
action="store_true",
help="Extract and verify pack integrity (path + hash)",
)
parser.add_argument(
"--counts", metavar="FILE",
help="Also write each full pack's counts as JSON (the pipeline's consistency check)",
)
return parser
+28 -20
View File
@@ -19,13 +19,23 @@ from orchestrate.results import SKIPPED
from packs.datadirs import hold_data_dirs
def scratch_file(prefix: str) -> str:
"""An empty JSON file in the repository's tmp/, removed when the run ends."""
scratch = REPO_ROOT / "tmp"
scratch.mkdir(exist_ok=True)
fd, path = tempfile.mkstemp(prefix=prefix, suffix=".json", dir=scratch)
os.close(fd)
atexit.register(Path(path).unlink, missing_ok=True)
return path
def verify_steps(
args: argparse.Namespace, results: dict, held: contextlib.ExitStack
) -> tuple[bool, str, str]:
) -> tuple[bool, str]:
"""Steps 3 to 3b: verify, identities, slots.
Returns whether they passed, verify's output and the file of the paths
each pack holds by its report.
Returns whether they passed and the file of what each pack holds by
verify's report: its counts and paths.
"""
all_ok = True
# Every step from here reads the data directory trees: verify, the packs,
@@ -36,15 +46,9 @@ def verify_steps(
# exclusive.
hold_data_dirs(held, load_data_dir_registry(PLATFORMS_DIR))
# Step 3: Verify. The paths each pack holds by this report go to a file
# step 5 compares with the archives.
scratch = REPO_ROOT / "tmp"
scratch.mkdir(exist_ok=True)
fd, destinations_file = tempfile.mkstemp(
prefix="verify-destinations.", suffix=".json", dir=scratch
)
os.close(fd)
atexit.register(Path(destinations_file).unlink, missing_ok=True)
# Step 3: Verify. The counts and paths each pack holds by this report go
# to a file step 5 compares with the build's own counts and archives.
destinations_file = scratch_file("verify-destinations.")
verify_cmd = [
sys.executable, "scripts/verify.py", "--all", "--strict",
"--destinations", destinations_file,
@@ -55,7 +59,7 @@ def verify_steps(
# The packs of step 4 fetch no release asset: a missing one is
# missing on both sides.
verify_cmd.append("--offline")
ok, verify_output = runner.run(verify_cmd, STEP_LABELS["verify"])
ok, _ = runner.run(verify_cmd, STEP_LABELS["verify"])
results["verify"] = ok
all_ok = all_ok and ok
@@ -82,7 +86,7 @@ def verify_steps(
ok, _ = runner.run(slots_cmd, "3b slot arbitration")
results["slots"] = ok
all_ok &= ok
return all_ok, verify_output, destinations_file
return all_ok, destinations_file
def purge_stale_packs(output_dir: str) -> None:
@@ -111,14 +115,16 @@ def purge_stale_packs(output_dir: str) -> None:
sys.exit(1)
def pack_command(args: argparse.Namespace) -> list[str]:
"""The step 4 command: every platform's pack."""
def pack_command(args: argparse.Namespace, counts_file: str) -> list[str]:
"""The step 4 command: every platform's pack, its counts to *counts_file*."""
pack_cmd = [
sys.executable,
"scripts/generate_pack.py",
"--all",
"--output-dir",
args.output_dir,
"--counts",
counts_file,
]
if args.offline:
pack_cmd.append("--offline")
@@ -138,14 +144,16 @@ def pack_command(args: argparse.Namespace) -> list[str]:
def pack_steps(args: argparse.Namespace, results: dict) -> tuple[bool, str]:
"""Steps 4 to 4c: packs, install manifests, target manifests.
Returns whether they passed and the pack build's output.
Returns whether they passed and the file of the full packs' counts,
empty when no pack was built.
"""
all_ok = True
# Step 4: Generate packs
pack_output = ""
pack_counts_file = ""
if not args.skip_packs:
purge_stale_packs(args.output_dir)
ok, pack_output = runner.run(pack_command(args), STEP_LABELS["generate_packs"])
pack_counts_file = scratch_file("pack-counts.")
ok, _ = runner.run(pack_command(args, pack_counts_file), STEP_LABELS["generate_packs"])
results["generate_packs"] = ok
all_ok = all_ok and ok
else:
@@ -193,7 +201,7 @@ def pack_steps(args: argparse.Namespace, results: dict) -> tuple[bool, str]:
else:
skip_notice("generate_target_manifests", "--skip-packs")
results["generate_target_manifests"] = SKIPPED
return all_ok, pack_output
return all_ok, pack_counts_file
def index_steps(results: dict) -> bool:
+8 -8
View File
@@ -5,12 +5,13 @@ from __future__ import annotations
import argparse
import sys
from core.paths import PLATFORMS_DIR
from model.registry import list_release_pack_platforms
from orchestrate import runner
from orchestrate.consistency import check_consistency, check_pack_destinations
from orchestrate.emulatorpacks import check_emulator_packs
from orchestrate.labels import STEP_LABELS, skip_notice, step_title
from orchestrate.narrowed import check_narrowed_packs
from orchestrate.reports import release_pack_keys
from orchestrate.results import SKIPPED
from orchestrate.splitcheck import check_split_packs
@@ -36,8 +37,7 @@ def check_steps(
args: argparse.Namespace,
results: dict,
*,
pack_output: str,
verify_output: str,
pack_counts_file: str,
destinations_file: str,
) -> bool:
"""Steps 5 and 6: verify against the packs, then the packs' integrity."""
@@ -46,16 +46,16 @@ def check_steps(
# built only a reduced one (--source platform or truth) has nothing to
# compare it with, and says so instead of failing on an empty parse.
full_pack_built = args.source == "full" or args.all_variants
if pack_output and verify_output and not full_pack_built:
if pack_counts_file and not full_pack_built:
skip_notice("consistency", "no full pack built")
results["consistency"] = SKIPPED
elif pack_output and verify_output:
elif pack_counts_file:
ok = check_consistency(
verify_output, pack_output,
release_pack_keys(),
destinations_file, pack_counts_file,
set(list_release_pack_platforms(PLATFORMS_DIR)),
)
# Counts can agree while the paths differ, both ways at once.
ok = check_pack_destinations(destinations_file, pack_output) and ok
ok = check_pack_destinations(destinations_file, pack_counts_file) and ok
ok = check_emulator_packs(full=args.full_narrowings) and ok
ok = check_narrowed_packs(full=args.full_narrowings) and ok
ok = check_split_packs() and ok
+94 -97
View File
@@ -2,108 +2,107 @@
from __future__ import annotations
import json
from pathlib import Path
from core.paths import PLATFORMS_DIR
from orchestrate import compare
from packs.archive import is_pack_note
from orchestrate.labels import STEP_LABELS, step_title
from orchestrate.reports import (
match_key,
parse_pack_counts,
parse_pack_exclusions,
parse_pack_extras,
parse_pack_paths,
parse_verify_counts,
parse_verify_extras,
)
from packs.archive import is_pack_note
from packs.packcounts import read_pack_counts
def read_records(destinations_file: str, counts_file: str) -> tuple[dict, list[dict]] | None:
"""verify's records by registry id and the build's full packs, or None
when either file cannot be read (the step that writes it failed)."""
try:
verify = json.loads(Path(destinations_file).read_text())
packs = read_pack_counts(counts_file)
except (OSError, ValueError) as exc:
print(f" unreadable counts ({exc})")
return None
if not isinstance(verify, dict):
print(f" unreadable counts ({destinations_file} holds no record per platform)")
return None
return verify, packs
def _platform_agrees(record: dict, pack: dict) -> bool:
"""One platform's verify record against the pack built for it, printed."""
label, ok = record["label"], True
if record["core_files"] != pack["core_files"]:
# The cores' share: the base check passed RomM while verify
# counted 412 core files and game data and the pack held 60.
print(
f" {label}: MISMATCH core files verify "
f"{record['core_files']} != pack {pack['core_files']}"
)
ok = False
v_ok, v_total, p_ok, p_total = record["ok"], record["total"], pack["ok"], pack["total"]
if v_total != p_total:
print(f" {label}: MISMATCH total verify {v_total} != pack {p_total}")
return False
if p_ok == v_ok:
print(f" {label}: verify {v_ok}/{v_total} == pack {p_ok}/{p_total} OK")
return ok
# Both ways are a disagreement. A pack exclusion never covers a file
# verify counts OK: an existence platform ships a file whose hash
# disagrees, and a hash platform's verify reports it untested, so the
# counts can only differ by a defect.
print(
f" {label}: MISMATCH pack {p_ok}/{p_total} OK "
f"({pack['unsafe_excluded']} unsafe excluded) != verify {v_ok}/{v_total}"
)
return False
def compare_counts(verify: dict, packs: list[dict], released: set[str] | None = None) -> bool:
"""Each platform's verify record against the full pack built for it.
Both sides are keyed by registry id: *verify* as verify.py --destinations
writes it, *packs* as generate_pack.py --counts does. *released* holds
the registry ids of the platforms with a release pack. verify judges
every platform, the build only those: a platform outside it has no pack
to compare, which is no failure.
"""
all_ok = True
if not verify or not packs:
# Nothing read is nothing compared: a build that recorded no pack
# would otherwise pass the check without a single platform in it.
print(f" parsed {len(verify)} verify and {len(packs)} pack results: nothing to compare")
all_ok = False
pack_of = {platform: pack for pack in packs for platform in pack["platforms"]}
for pack in sorted(packs, key=lambda p: p["label"]):
if not any(platform in verify for platform in pack["platforms"]):
print(f" {pack['label']}: pack with no verify result")
all_ok = False
for platform, record in sorted(verify.items(), key=lambda item: (item[1]["label"], item[0])):
if platform in pack_of:
all_ok = _platform_agrees(record, pack_of[platform]) and all_ok
elif released is not None and platform not in released:
print(f" {record['label']}: {record['ok']}/{record['total']} "
"(no release pack, served by the installer)")
else:
print(f" {record['label']}: MISSING pack: verify judged "
f"{record['ok']}/{record['total']} but the build wrote no pack for it")
all_ok = False
return all_ok
def check_consistency(
verify_output: str, pack_output: str, released: set[str] | None = None,
destinations_file: str, counts_file: str, released: set[str] | None = None,
) -> bool:
"""Verify that check counts match between verify and pack for each platform.
*released* holds the identities of the platforms with a release pack
(release_pack_keys). verify judges every platform, the build only those:
a platform outside it has no pack to compare, which is no failure.
"""
v = parse_verify_counts(verify_output)
p = parse_pack_counts(pack_output)
excluded = parse_pack_exclusions(pack_output)
verify_extras = parse_verify_extras(verify_output)
pack_extras = parse_pack_extras(pack_output)
"""Verify that check counts match between verify and pack for each platform."""
print(f"\n--- {step_title(STEP_LABELS['consistency'])} ---")
all_ok = True
if not v or not p:
# Nothing parsed is nothing compared: a changed output format would
# otherwise pass the check without a single platform in it.
print(f" parsed {len(v)} verify and {len(p)} pack results: nothing to compare")
all_ok = False
for p_label in sorted(p):
if not any(match_key(p_label) & match_key(v_label) for v_label in v):
print(f" {p_label}: pack with no verify result")
all_ok = False
for v_label, (v_ok, v_total) in sorted(v.items()):
# Match by normalized name overlap. Platform display labels and
# registry IDs legitimately differ in punctuation and spacing
# (notably ``MiSTer FPGA`` vs ``misterfpga``).
p_match = None
v_names = match_key(v_label)
for p_label in p:
if v_names & match_key(p_label):
p_match = p_label
break
if (
p_match
and p_match in pack_extras
and v_label in verify_extras
and verify_extras[v_label] != pack_extras[p_match]
):
# The cores' share: the base check passed RomM while verify
# counted 412 core files and game data and the pack held 60.
print(
f" {v_label}: MISMATCH core files verify "
f"{verify_extras[v_label]} != pack {pack_extras[p_match]}"
)
all_ok = False
if p_match:
p_ok, p_total = p[p_match]
p_excluded = excluded.get(p_match, 0)
if v_total != p_total:
print(f" {v_label}: MISMATCH total verify {v_total} != pack {p_total}")
all_ok = False
elif p_ok == v_ok:
print(
f" {v_label}: verify {v_ok}/{v_total} == pack {p_ok}/{p_total} OK"
)
else:
# Both ways are a disagreement. A pack exclusion never covers
# a file verify counts OK: an existence platform ships a file
# whose hash disagrees, and a hash platform's verify reports
# it untested, so the counts can only differ by a defect.
print(
f" {v_label}: MISMATCH pack {p_ok}/{p_total} OK "
f"({p_excluded} unsafe excluded) != verify {v_ok}/{v_total}"
)
all_ok = False
elif released is not None and not (v_names & released):
print(f" {v_label}: {v_ok}/{v_total} (no release pack, served by the installer)")
else:
print(f" {v_label}: MISSING pack: verify judged {v_ok}/{v_total} "
"but the build wrote no pack for it")
all_ok = False
records = read_records(destinations_file, counts_file)
all_ok = records is not None and compare_counts(*records, released)
status = "OK" if all_ok else "FAILED"
print(f"--- {step_title(STEP_LABELS['consistency'])}, counts: {status} ---")
return all_ok
def check_pack_destinations(
destinations_file: str, pack_output: str, platforms_dir: str = PLATFORMS_DIR,
destinations_file: str, counts_file: str, platforms_dir: str = PLATFORMS_DIR,
) -> bool:
"""Compare the paths verify credits with the members of each archive.
@@ -112,22 +111,20 @@ def check_pack_destinations(
set aside when its path and size are the cached file's and verify does
not credit the path.
"""
import json
import zipfile
print(f"\n--- {step_title(STEP_LABELS['consistency'])}, destinations ---")
try:
credited_by = json.loads(Path(destinations_file).read_text())
except (OSError, ValueError) as exc:
print(f" no destinations from verify ({exc})")
records = read_records(destinations_file, counts_file)
if records is None:
return False
paths = parse_pack_paths(pack_output)
if not paths:
print(" no archive named in the pack output")
credited_by, packs = records
if not packs:
print(" no archive in the pack counts")
return False
all_ok = True
for label, zip_path in sorted(paths.items()):
names = [n for n in credited_by if match_key(n) & match_key(label)]
for pack in sorted(packs, key=lambda p: p["label"]):
label = pack["label"]
names = [platform for platform in pack["platforms"] if platform in credited_by]
if not names:
print(f" {label}: no verify destinations")
all_ok = False
@@ -135,7 +132,7 @@ def check_pack_destinations(
entry = credited_by[names[0]]
credited = set(entry["pack_destinations"])
trees = compare.tree_members(entry["platform"], platforms_dir)
with zipfile.ZipFile(zip_path) as zf:
with zipfile.ZipFile(pack["archive"]) as zf:
written = {
info.filename for info in zf.infolist()
if not info.is_dir()
-143
View File
@@ -1,143 +0,0 @@
"""What verify and the pack build print, read back as counts, paths and platform identities."""
from __future__ import annotations
import re
from collections.abc import Iterator
from core.paths import PLATFORMS_DIR
# "Label: X/Y OK ..." or "Label: X/Y present ...", the summary line verify
# prints for each group of identical platforms.
_VERIFY_SUMMARY = re.compile(r"^(.+?):\s+(\d+)/(\d+)\s+(OK|present)")
_PACK_HEADER = re.compile(r"Generating (?:shared )?pack for (.+)\.\.\.")
def _verify_groups(output: str) -> Iterator[tuple[list[str] | None, str, re.Match[str] | None]]:
"""Each verify line with the platforms of the summary it falls under,
and its own summary match when it is one."""
names: list[str] | None = None
for line in output.splitlines():
m = _VERIFY_SUMMARY.match(line)
if m:
names = [name.strip() for name in m.group(1).split(" / ")]
yield names, line, m
def _pack_lines(output: str) -> Iterator[tuple[str, str]]:
"""Each generate_pack line under a full pack's header, with its label.
Labels carry execution metadata such as ``[source=full]``. Only the
full, unreduced pack is what verify describes: with --all-variants the
six variants shared one label and the last (platform, required) was
compared to the full report.
"""
label = ""
for line in output.splitlines():
m = _PACK_HEADER.match(line)
if m:
label = _full_pack_label(m.group(1).strip())
elif label:
yield label, line
def parse_verify_counts(output: str) -> dict[str, tuple[int, int]]:
"""Per-platform OK/total from verify output."""
return {
name: (int(m.group(2)), int(m.group(3)))
for names, _line, m in _verify_groups(output) if m and names
for name in names
}
def parse_verify_extras(output: str) -> dict[str, int]:
"""Core files and game data verify says each pack carries, per platform.
Read from the "Core files: N in pack" and "Game data: N in pack" lines
that follow a platform's summary line.
"""
extras: dict[str, int] = {}
for names, line, m in _verify_groups(output):
if m and names:
extras.update(dict.fromkeys(names, 0))
continue
packed = re.match(r"^\s+(?:Core files|Game data): (\d+) in pack", line)
if packed and names:
for name in names:
extras[name] += int(packed.group(1))
return extras
def parse_pack_extras(output: str) -> dict[str, int]:
"""Files each full pack takes from the cores, per pack label."""
extras: dict[str, int] = {}
for label, line in _pack_lines(output):
cores = re.search(r"\+ (\d+) from cores\)", line)
if "files packed" in line and cores:
extras[label] = int(cores.group(1))
return extras
def _full_pack_label(label: str) -> str:
"""The pack name, or "" for a reduced variant such as [source=platform]."""
meta = re.search(r"\s+\[([^\]]+)\]$", label)
if meta is None:
return label
return label[: meta.start()] if meta.group(1) == "source=full" else ""
def parse_pack_counts(output: str) -> dict[str, tuple[int, int]]:
"""Per-pack OK/total from generate_pack output: {pack_label: (ok, total)}."""
counts = {}
for label, line in _pack_lines(output):
# "622 files packed (359 baseline + 263 from cores), 358/359 files OK"
ok_m = re.search(r"(\d+)/(\d+) files OK", line) if "files packed" in line else None
if ok_m:
counts[label] = (int(ok_m.group(1)), int(ok_m.group(2)))
return counts
def parse_pack_exclusions(output: str) -> dict[str, int]:
"""Intentional unsafe-omission counts from pack output, per pack label."""
exclusions: dict[str, int] = {}
for label, line in _pack_lines(output):
if "files packed" in line:
excluded = re.search(r"(\d+) unsafe excluded", line)
exclusions[label] = int(excluded.group(1)) if excluded else 0
return exclusions
def parse_pack_paths(output: str) -> dict[str, str]:
"""The archive each full pack was written to, per pack label."""
paths: dict[str, str] = {}
for label, line in _pack_lines(output):
written = re.match(r"^\s+(\S.*?\.zip): \d+ files packed", line)
if written:
paths[label] = written.group(1)
return paths
def match_key(label: str) -> set[str]:
"""Comparable identity for a platform label.
Display labels and registry ids differ in punctuation and spacing
(``MiSTer FPGA`` against ``misterfpga``), and grouped packs join their
members with either separator.
"""
return {
re.sub(r"[^a-z0-9]+", "", part.strip().lower())
for part in label.replace("+", "/").split("/")
} - {""}
def release_pack_keys(platforms_dir: str = PLATFORMS_DIR) -> set[str]:
"""Comparable identities of the platforms --all builds a pack for: their
registry ids and display names, normalized as match_key does."""
from model.registry import list_release_pack_platforms
from model.platforms import load_platform_config
keys: set[str] = set()
for name in list_release_pack_platforms(platforms_dir):
keys |= match_key(name)
keys |= match_key(str(load_platform_config(name, platforms_dir).get("platform", name)))
return keys
+53
View File
@@ -0,0 +1,53 @@
"""The counts each full platform pack hands the pipeline's consistency check."""
from __future__ import annotations
import json
from dataclasses import asdict, dataclass
from pathlib import Path
@dataclass(frozen=True)
class PackCounts:
"""What a built pack holds, by the builder's own count.
``ok`` and ``total`` are the platform's declared files judged in the
pack's verification mode, ``core_files`` what the pack takes from the
cores' profiles, and ``unsafe_excluded`` the files left out because the
frontend would reject their hash.
"""
archive: str
ok: int
total: int
core_files: int
unsafe_excluded: int
def pack_counts(archive: str, file_status: dict[str, str], core_files: int) -> PackCounts:
"""A pack's counts from the verdict of each declared file."""
statuses = list(file_status.values())
return PackCounts(
archive=archive,
ok=statuses.count("ok"),
total=len(statuses),
core_files=core_files,
unsafe_excluded=statuses.count("excluded"),
)
def write_pack_counts(path: str, packs: list[tuple[str, list[str], PackCounts]]) -> None:
"""Each pack's printed label, registry ids and counts, as a JSON list."""
Path(path).write_text(json.dumps(
[{"label": label, "platforms": platforms, **asdict(counts)}
for label, platforms, counts in packs],
indent=1, sort_keys=True,
))
def read_pack_counts(path: str) -> list[dict]:
"""The packs a build recorded with write_pack_counts."""
packs = json.loads(Path(path).read_text())
if not isinstance(packs, list):
raise ValueError(f"{path} is not a list of packs")
return packs
+16
View File
@@ -81,6 +81,21 @@ def _argument_conflicts(args: argparse.Namespace) -> list[tuple[bool, str]]:
(one_per_slot and args.manifest, "--one-per-slot is incompatible with --manifest"),
(one_per_slot and has_emulator, "--one-per-slot is incompatible with --emulator"),
(one_per_slot and has_system, "--one-per-slot is incompatible with --system"),
*_counts_conflicts(args, has_platform or has_all, has_system or has_from_md5),
]
def _counts_conflicts(
args: argparse.Namespace, platform_run: bool, narrowed: bool,
) -> list[tuple[bool, str]]:
"""--counts describes the full platform packs: another mode refuses it."""
counts = bool(getattr(args, "counts", None))
return [
(counts and not platform_run, "--counts requires --platform or --all"),
(counts and args.manifest, "--counts is incompatible with --manifest"),
(counts and args.split, "--counts is incompatible with --split"),
(counts and narrowed,
"--counts describes the full pack and is incompatible with --system and --from-md5"),
]
@@ -204,6 +219,7 @@ def _given_flags(args: argparse.Namespace) -> set[str]:
"--list-emulators": args.list_emulators,
"--list-systems": args.list_systems,
"--list-targets": args.list_targets,
"--counts": getattr(args, "counts", None),
"--refresh-data": args.refresh_data,
"--no-refresh-data": args.no_refresh_data,
}
+10 -4
View File
@@ -51,6 +51,7 @@ from packs.extras import (
undeclared_report,
)
from packs.naming import file_name_part, pack_narrowings, platform_pack_name, platform_pack_stem
from packs.packcounts import PackCounts, pack_counts
from packs.paths import flat_arcname, save_layout
from packs.readme import build_agnostic_rename_readme, build_readme, save_place
from resolve import packfiles as packresolve, regions as resolve_regions, slot as slot_mod
@@ -101,11 +102,10 @@ def _report_pack_counts(
verification_mode: str,
tree_count: int = 0,
) -> None:
"""Print the line the pipeline's consistency check reads.
"""Print the pack's counts line.
The check compares these counts against what verify.py reports for
the same platform, so the wording is a contract: parse_pack_counts
in orchestrate/reports.py matches on it.
The pipeline's consistency check reads the same counts as data
(packs.packcounts), never this line.
"""
files_ok = sum(1 for s in file_status.values() if s == "ok")
files_untested = sum(1 for s in file_status.values() if s == "untested")
@@ -316,6 +316,7 @@ class PackOptions(PackNarrowing, _PartScope, total=False):
record: PackRecord | None
within: dict[str, str] | None
uncached_out: set[str] | None
counts: list[PackCounts] | None
@dataclass(frozen=True)
@@ -342,6 +343,7 @@ class _PackSettings:
record: PackRecord | None = None
within: dict[str, str] | None = None
uncached_out: set[str] | None = None
counts: list[PackCounts] | None = None
@dataclass
@@ -1093,6 +1095,8 @@ def generate_pack(
its group, and a name built from every system of a hundred-system group
is longer than a file name can be.
``counts``, when given, receives the pack's PackCounts once it is built.
``record`` builds the pack in memory (PackRecord): no archive is written,
no external file fetched, and the paths are kept on it.
@@ -1151,6 +1155,8 @@ def generate_pack(
build = _PlatformPackBuild(plan, zf, resolve, verdict, judge, resolve_extra)
build.run()
build.report()
if opts.counts is not None:
opts.counts.append(pack_counts(plan.zip_path, build.file_status, build.core_count))
return plan.zip_path
+18 -9
View File
@@ -24,6 +24,7 @@ from packs.manifest import generate_manifest
from packs.manifestrun import run_manifest_mode
from packs.naming import pack_narrowings, platform_pack_name, platform_target
from packs.outputdir import holds_other_kind, pack_output_lock
from packs.packcounts import PackCounts, write_pack_counts
from packs.packcheck import run_verify_packs
from packs.platformpack import generate_pack, generate_split_packs
from packs.runscope import settle_scope
@@ -60,19 +61,23 @@ def run_platform_packs(
# The packs this run writes, the only ones it verifies and rewrites.
built: set[str] = set()
# The full packs' counts, for --counts: the pipeline compares them with
# verify's.
recorded: list[tuple[str, list[str], PackCounts]] = []
record_counts = getattr(args, "counts", None)
failed: list[str] = []
for source, required_only in run_variants(args):
for group_platforms, representative in groups:
aliases = [p for p in group_platforms if p != representative]
if aliases:
all_names = [
load_platform_config(p, args.platforms_dir).get("platform", p)
for p in group_platforms
]
label = " / ".join(all_names)
print(f"\nGenerating pack for {label} {pack_label(source, required_only)}...")
else:
print(f"\nGenerating pack for {representative} {pack_label(source, required_only)}...")
label = " / ".join(
load_platform_config(p, args.platforms_dir).get("platform", p)
for p in group_platforms
) if aliases else representative
print(f"\nGenerating pack for {label} {pack_label(source, required_only)}...")
counts: list[PackCounts] | None = (
[] if record_counts and (source, required_only) == ("full", False) else None
)
zip_path = None
zip_paths: list = []
@@ -138,6 +143,7 @@ def run_platform_packs(
pack_name=group_name,
no_game_data=getattr(args, "no_game_data", False),
uncached_out=getattr(args, "uncached_trees", None),
counts=counts,
)
except (FileNotFoundError, OSError, yaml.YAMLError) as e:
print(f" ERROR: {e}", file=sys.stderr)
@@ -153,6 +159,7 @@ def run_platform_packs(
os.path.relpath(path, args.output_dir)
for path in ([zip_path] if zip_path else zip_paths)
)
recorded.extend((label, group_platforms, c) for c in counts or ())
if zip_path and not system_filter:
# The install list of the same choices names each file's
# systems: the pack records them, so a pack alone (a
@@ -170,6 +177,8 @@ def run_platform_packs(
uncached_out=getattr(args, "uncached_trees", None),
), target_list(board_list) if board_list.is_file() else None)
if record_counts:
write_pack_counts(record_counts, recorded)
all_ok = finalize_platform_packs(args, db, data_registry, built, systems_for, system_filter)
if failed:
# Verification only sees the ZIPs that exist, so a pack that was never
+18 -12
View File
@@ -243,6 +243,23 @@ def split_undeclared(undeclared: list[dict]) -> tuple[list[dict], list[dict], li
return game_data, placed, unplaced
def pack_shares(result: dict) -> tuple[int, int]:
"""The core files and the game data a platform's pack carries, by the report.
The builder's count, one file per pack path, when the platform pass
replayed it. Counting entries said 1130 for RetroArch, 48 more than the
pack holds: rom.key alone was claimed by three Amiga cores.
"""
packed = result.get("packed_extras")
if packed is not None:
return packed["bios"], packed["game_data"]
game_data, bios_files, _unplaced = split_undeclared(result.get("undeclared_files", []))
return (
sum(1 for u in bios_files if u["in_repo"]),
sum(1 for u in game_data if u["in_repo"] and u.get("in_pack", True)),
)
def core_required_missing(bios_files: list[dict]) -> list[dict]:
"""Core files a core cannot run without, absent from the collection.
@@ -303,15 +320,8 @@ def _print_undeclared_section(result: dict, verbose: bool) -> None:
for u in bios_files
if u["required"] and not u["in_repo"] and u.get("hle_fallback")
]
req_in_repo = [u for u in bios_files if u["required"] and u["in_repo"]]
opt_in_repo = [u for u in bios_files if not u["required"] and u["in_repo"]]
opt_not_in_repo = [u for u in bios_files if not u["required"] and not u["in_repo"]]
# The builder's count, one file per pack path, when the platform pass
# replayed it. Counting entries said 1130 for RetroArch, 48 more than the
# pack holds: rom.key alone was claimed by three Amiga cores.
core_in_pack = (
packed["bios"] if packed is not None else len(req_in_repo) + len(opt_in_repo)
)
core_in_pack, gd_packed = pack_shares(result)
core_missing_req = len(req_not_in_repo) + len(req_hle_not_in_repo)
core_missing_opt = len(opt_not_in_repo)
@@ -354,10 +364,6 @@ def _print_undeclared_section(result: dict, verbose: bool) -> None:
if game_data or (packed and packed.get("game_data")):
gd_missing = [u for u in game_data if not u["in_repo"]]
gd_packed = (
packed["game_data"] if packed is not None
else sum(1 for u in game_data if u["in_repo"] and u.get("in_pack", True))
)
gd_unplaced = [u for u in game_data if u["in_repo"] and not u.get("in_pack", True)]
if gd_missing or gd_packed or gd_unplaced:
listed = "" if verbose or not gd_missing else " (--verbose lists them)"
+1 -1
View File
@@ -22,7 +22,7 @@ def run_variants(args: argparse.Namespace) -> tuple[tuple[str, bool], ...]:
def pack_label(source: str, required_only: bool) -> str:
"""The variant tag orchestrate.reports.parse_pack_counts reads after a pack name."""
"""The variant tag printed after a pack name."""
return f"[source={source}, required]" if required_only else f"[source={source}]"
+17 -4
View File
@@ -5,7 +5,8 @@ from __future__ import annotations
import json
from pathlib import Path
from packs.verdicts import Status
from packs.report import pack_shares
from packs.verdicts import Severity, Status
def json_details(details: list[dict], verbose: bool) -> list[dict]:
@@ -25,11 +26,23 @@ def write_pack_destinations(
groups: list[tuple[list[str], str]],
group_results: list[tuple[dict, list[str]]],
) -> None:
"""The paths each pack holds according to the report, per platform, as JSON."""
"""What each platform's pack holds according to the report, as JSON.
Keyed by registry id: the name verify prints, its OK and total counts,
the core files and game data the pack takes from the cores, and the
paths it credits. The pipeline's consistency check reads them here
rather than from the printed report.
"""
destinations = {}
for (result, names), (group, _rep) in zip(group_results, groups):
core_files, game_data = pack_shares(result)
for name, key in zip(names, group):
destinations[name] = {
"platform": key, "pack_destinations": result["pack_destinations"],
destinations[key] = {
"platform": key,
"label": name,
"ok": result["severity_counts"][Severity.OK],
"total": result["total_files"],
"core_files": core_files + game_data,
"pack_destinations": result["pack_destinations"],
}
Path(path).write_text(json.dumps(destinations, indent=1, sort_keys=True))
+3 -3
View File
@@ -150,13 +150,13 @@ def main() -> None:
all_ok = database_steps(args, results)
all_ok = refresh_steps(args, results) and all_ok
all_ok = truth_steps(args, results) and all_ok
ok, verify_output, destinations_file = verify_steps(args, results, held)
ok, destinations_file = verify_steps(args, results, held)
all_ok = all_ok and ok
ok, pack_output = pack_steps(args, results)
ok, pack_counts_file = pack_steps(args, results)
all_ok = all_ok and ok
all_ok = index_steps(results) and all_ok
all_ok = check_steps(
args, results, pack_output=pack_output, verify_output=verify_output,
args, results, pack_counts_file=pack_counts_file,
destinations_file=destinations_file,
) and all_ok
all_ok = docs_steps(args, results) and all_ok
+2 -2
View File
@@ -89,8 +89,8 @@ def build_parser() -> argparse.ArgumentParser:
)
parser.add_argument(
"--destinations", metavar="FILE",
help="With --platform or --all, also write the paths each pack holds "
"according to this report to FILE (JSON), for comparison with the archive",
help="With --platform or --all, also write the counts and paths each pack "
"holds according to this report to FILE (JSON), for comparison with the archive",
)
parser.add_argument(
"--strict",