refactor: build platform packs without printing

build_platform_pack and build_split_packs return what the build came to and print nothing. print_platform_pack holds the report lines, and generate_pack and generate_split_packs compose the two. The variant choice, the plan and the data directory pass return their notices instead of printing them. The callers that silenced stdout to get a record now call the builder.
This commit is contained in:
Abdessamad Derraz committed 2026-11-22 02:26:45 +01:00
1 parent 977d3f6874
commit d8570c6480
15 files changed
+295 -205

No files matched your search

+3 -4
View File
@@ -117,9 +117,8 @@ def check_narrowed_packs(
load_target_config(platform, target, platforms_dir) if target else None
)
record = archive.PackRecord()
with contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()):
built = platformpack.generate_pack(
with contextlib.redirect_stderr(io.StringIO()):
built = platformpack.build_platform_pack(
platform, platforms_dir, db, "bios", "",
emulators_dir=emulators_dir, zip_contents=zip_contents,
data_registry=registry, emu_profiles=profiles,
@@ -131,7 +130,7 @@ def check_narrowed_packs(
emulators_dir, profiles, target_cores=target_cores,
data_dir_registry=registry,
**{k: v for k, v in narrowing.items() if k != "target_name"},
) if built else None
) if built.zip_path else None
compared += 1
name = f"{platform} {label}"
if report is None:
+3 -4
View File
@@ -68,12 +68,11 @@ def check_split_packs(
)
full = archive.PackRecord()
parts: dict[str, archive.PackRecord] = {}
with contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()):
platformpack.generate_pack(
with contextlib.redirect_stderr(io.StringIO()):
platformpack.build_platform_pack(
platform, platforms_dir, db, "bios", "", record=full, **args,
)
platformpack.generate_split_packs(
platformpack.build_split_packs(
platform, platforms_dir, db, "bios", "", records=parts, **args,
)
lines = split_differences(full, parts, archive.same_bytes)
+140 -118
View File
@@ -3,7 +3,6 @@
from __future__ import annotations
import contextlib
import io
import os
import tempfile
import zipfile
@@ -37,7 +36,6 @@ from packs.datatrees import (
core_data_trees,
data_directory_members,
pack_markers,
uncached_warning,
)
from packs.naming import system_display_name
from packs.extras import (
@@ -53,6 +51,7 @@ from packs.extras import (
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.platformreport import print_platform_pack, print_split_packs
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
from resolve.contentlayout import TARGET_KEY
@@ -93,51 +92,6 @@ def _case_twin_pairs(
return sorted({(twin, held[twin.lower()]) for twin in twins if twin.lower() in held})
def _report_pack_counts(
zip_path: str,
file_status: dict,
total_files: int,
core_count: int,
source: str,
verification_mode: str,
tree_count: int = 0,
) -> None:
"""Print the pack's counts line.
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")
files_excluded = sum(1 for s in file_status.values() if s == "excluded")
files_miss = sum(1 for s in file_status.values() if s == "missing")
total_checked = len(file_status)
parts = [f"{files_ok}/{total_checked} files OK"]
if files_untested:
parts.append(f"{files_untested} untested")
if files_excluded:
parts.append(f"{files_excluded} unsafe excluded")
if files_miss:
parts.append(f"{files_miss} missing")
if source == "platform":
print(
f" {zip_path}: {total_files} files packed (platform baseline only), "
f"{', '.join(parts)} [{verification_mode}]"
)
elif source == "truth":
print(
f" {zip_path}: {total_files} files packed (ground truth only), "
f"{core_count} from emulator profiles [{verification_mode}]"
)
else:
baseline = total_files - core_count - tree_count
trees = f"{tree_count} in core data trees + " if tree_count else ""
print(
f" {zip_path}: {total_files} files packed ({baseline} baseline + "
f"{trees}{core_count} from cores), {', '.join(parts)} [{verification_mode}]"
)
class _VariantOptions(TypedDict, total=False):
"""The keyword options of _select_variants."""
@@ -213,11 +167,6 @@ def _select_variants(
config, emu_profiles, target_cores, region_groups, region_drops, held
)
region_drops = region_drops | slot_drops
if slot_undecidable:
print(
f" {len(slot_undecidable)} slot(s) with no declared order: "
f"every candidate kept"
)
return region_drops, region_fallbacks, slot_undecidable
@@ -267,8 +216,8 @@ def _matches_an_alternative(fe: dict, local_path: str, profiles: dict) -> bool:
return False
def _report_left_out(cut: GameDataCut, systems: set[str], cores: bool) -> None:
"""Name the game data a --no-game-data build left out, and why.
def _left_out_lines(cut: GameDataCut, systems: set[str], cores: bool) -> list[str]:
"""The game data a --no-game-data build left out, and why, one line each.
``systems`` limits the platform layer to the systems this pack covers,
and ``cores`` says whether this pack collected the core files itself:
@@ -279,8 +228,7 @@ def _report_left_out(cut: GameDataCut, systems: set[str], cores: bool) -> None:
if (item.layer == "platform" and item.system in systems)
or (item.layer == "core" and cores)
]
for line in GameDataCut(cut.config, cut.profiles, kept).report_lines():
print(f" {line}")
return GameDataCut(cut.config, cut.profiles, kept).report_lines()
class PackNarrowing(TypedDict, total=False):
@@ -399,9 +347,9 @@ def _plan_platform_pack(
bios_dir: str,
output_dir: str,
opts: _PackSettings,
) -> _PlatformPlan | None:
"""The configuration, scope and checks a platform pack reads, or None
when the systems asked for leave nothing to build."""
) -> _PlatformPlan | str:
"""The configuration, scope and checks a platform pack reads, or the
reason the systems asked for leave nothing to build."""
config = load_platform_config(platform_name, platforms_dir)
if opts.target_name:
config = {**config, TARGET_KEY: opts.target_name}
@@ -455,9 +403,7 @@ def _plan_platform_pack(
config, emu_profiles or {}, opts.target_cores, opts.system_filter
)
if opts.system_filter and not pack_systems:
reason = system_scope_error(config, platform_name, opts.system_filter, opts.target_name)
print(f" WARNING: {reason}")
return None
return system_scope_error(config, platform_name, opts.system_filter, opts.target_name)
if opts.extras_only:
# The part of a split that carries the core extras no platform system
# owns: the platform's own files and trees went to the other parts.
@@ -510,15 +456,35 @@ def _settle_pack_choices(plan: _PlatformPlan) -> None:
)
_STATUS_LABELS = {"untested": "UNTESTED", "excluded": "EXCLUDED", "missing": "MISSING"}
@dataclass
class PlatformPackOutcome:
"""What one platform pack build came to, as print_platform_pack reports it.
``refusal`` is set, and ``zip_path`` None, when the systems asked for
leave nothing to build.
"""
zip_path: str | None
refusal: str = ""
source: str = "full"
verification_mode: str = ""
total_files: int = 0
core_count: int = 0
tree_count: int = 0
file_status: dict[str, str] = field(default_factory=dict)
file_reasons: dict[str, str] = field(default_factory=dict)
core_discrepancies: list[str] = field(default_factory=list)
slot_undecidable: list[str] = field(default_factory=list)
uncached: list[tuple[str, str]] = field(default_factory=list)
left_out: list[str] = field(default_factory=list)
@dataclass
class _PlatformPackBuild:
"""One platform pack being written: its members and what each slot came to.
The four lookups are bound by generate_pack, the one place that says how
a platform file and a core extra are found and judged.
The four lookups are bound by build_platform_pack, the one place that
says how a platform file and a core extra are found and judged.
"""
plan: _PlatformPlan
@@ -542,6 +508,8 @@ class _PlatformPackBuild:
core_discrepancies: list[str] = field(default_factory=list)
# Spellings left out as case twins of a packed file, for the README.
case_twins: list[str] = field(default_factory=list)
# (registry key, cache path) of each data directory the cache lacks.
uncached: list[tuple[str, str]] = field(default_factory=list)
def __post_init__(self) -> None:
self.placed = Placed(self.plan.case_insensitive)
@@ -974,8 +942,7 @@ class _PlatformPackBuild:
if isinstance(self.zf, PackRecord):
self.zf.trees.append(self._flat(full))
added += 1
for ref_key, local_path in uncached:
print(uncached_warning(ref_key, local_path))
self.uncached.extend(uncached)
if plan.opts.uncached_out is not None:
plan.opts.uncached_out.update(ref_key for ref_key, _path in uncached)
return added
@@ -1055,23 +1022,29 @@ class _PlatformPackBuild:
"",
)
def report(self) -> None:
def outcome(self) -> PlatformPackOutcome:
plan, opts = self.plan, self.plan.opts
_report_pack_counts(
plan.zip_path, self.file_status, self.total_files, self.core_count, opts.source,
plan.verification_mode, tree_count=self.tree_count,
return PlatformPackOutcome(
zip_path=plan.zip_path,
source=opts.source,
verification_mode=plan.verification_mode,
total_files=self.total_files,
core_count=self.core_count,
tree_count=self.tree_count,
file_status=self.file_status,
file_reasons=self.file_reasons,
core_discrepancies=self.core_discrepancies,
slot_undecidable=plan.slot_undecidable,
uncached=self.uncached,
left_out=(
_left_out_lines(
plan.cut,
systems=set(plan.pack_systems) if opts.source != "truth" else set(),
cores=opts.source != "platform" and opts.precomputed_extras is None,
)
if plan.cut is not None else []
),
)
if plan.cut is not None:
_report_left_out(
plan.cut,
systems=set(plan.pack_systems) if opts.source != "truth" else set(),
cores=opts.source != "platform" and opts.precomputed_extras is None,
)
for key, reason in sorted(self.file_reasons.items()):
label = _STATUS_LABELS.get(self.file_status.get(key, ""), "DISCREPANCY")
print(f" {label}: {key}: {reason}")
for note in sorted(self.core_discrepancies):
print(f" DISCREPANCY: {note}")
def _platform_registry(platforms_dir: str) -> dict:
@@ -1079,15 +1052,15 @@ def _platform_registry(platforms_dir: str) -> dict:
return load_platform_registry(platforms_dir)
def generate_pack(
def build_platform_pack(
platform_name: str,
platforms_dir: str,
db: dict,
bios_dir: str,
output_dir: str,
**options: Unpack[PackOptions],
) -> str | None:
"""Generate a ZIP pack for a platform.
) -> PlatformPackOutcome:
"""Build a ZIP pack for a platform. Its report is print_platform_pack's.
``no_game_data`` leaves out the platform's entries categorized as game
data and the cores' ``category: game_data`` files, and names each one.
@@ -1110,13 +1083,14 @@ def generate_pack(
``uncached_out`` receives the data directories the pack carries and the
cache does not hold: the pack is written without them.
Returns the path to the generated ZIP, or None on failure.
The outcome carries the ZIP path, or the refusal when the systems asked
for leave nothing to build.
"""
reject_unknown("generate_pack", options, PackOptions.__optional_keys__)
opts = _PackSettings(**options)
plan = _plan_platform_pack(platform_name, platforms_dir, db, bios_dir, output_dir, opts)
if plan is None:
return None
if isinstance(plan, str):
return PlatformPackOutcome(zip_path=None, refusal=plan)
def resolve(file_entry: dict, full_dest: str) -> tuple[str | None, str]:
return resolve_declaration(
@@ -1155,10 +1129,26 @@ def generate_pack(
) as zf:
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
return build.outcome()
def generate_pack(
platform_name: str,
platforms_dir: str,
db: dict,
bios_dir: str,
output_dir: str,
**options: Unpack[PackOptions],
) -> str | None:
"""Build a platform pack (build_platform_pack) and print its report.
Returns the path to the generated ZIP, or None when nothing was built.
"""
outcome = build_platform_pack(platform_name, platforms_dir, db, bios_dir, output_dir, **options)
print_platform_pack(outcome)
return outcome.zip_path
def _group_systems_by_manufacturer(
@@ -1183,9 +1173,12 @@ class SplitOptions(PackNarrowing, total=False):
uncached_out: set[str] | None
def _split_extras(config: dict, db: dict, narrowing: PackNarrowing) -> list[dict]:
def _split_extras(
config: dict, db: dict, narrowing: PackNarrowing,
) -> tuple[list[dict], list[str]]:
"""The core extras of every part, collected once (expensive: scans 260+
emulator profiles), then distributed per group by system overlap."""
emulator profiles), then distributed per group by system overlap, and
the core game data the run leaves out, named once for all parts."""
emu_profiles = narrowing["emu_profiles"] or {}
source = narrowing["source"]
target_cores = narrowing["target_cores"]
@@ -1206,12 +1199,26 @@ def _split_extras(config: dict, db: dict, narrowing: PackNarrowing) -> list[dict
)
else:
all_extras = []
if cut is not None and source != "platform":
_report_left_out(cut, systems=set(), cores=True)
return all_extras
left_out = (
_left_out_lines(cut, systems=set(), cores=True)
if cut is not None and source != "platform" else []
)
return all_extras, left_out
def generate_split_packs(
@dataclass
class SplitOutcome:
"""What a --split build came to: the core game data left out, then each part."""
left_out: list[str] = field(default_factory=list)
parts: list[PlatformPackOutcome] = field(default_factory=list)
@property
def zip_paths(self) -> list[str]:
return [part.zip_path for part in self.parts if part.zip_path]
def build_split_packs(
platform_name: str,
platforms_dir: str,
db: dict,
@@ -1219,8 +1226,8 @@ def generate_split_packs(
output_dir: str,
group_by: str = "system",
**options: Unpack[SplitOptions],
) -> list[str]:
"""Generate split packs (one ZIP per system or manufacturer).
) -> SplitOutcome:
"""Build split packs (one ZIP per system or manufacturer), printing nothing.
The parts add up to the full pack: each is built against the full pack's
own placement (``within``). ``records`` builds the parts in memory, keyed
@@ -1274,22 +1281,21 @@ def generate_split_packs(
narrowing["emu_profiles"] = emu_profiles
full = PackRecord()
# The parts add up to the full pack: its trees are the run's account.
with contextlib.redirect_stdout(io.StringIO()):
generate_pack(
platform_name, platforms_dir, db, bios_dir, split_dir,
record=full, uncached_out=options.get("uncached_out"), **narrowing,
)
build_platform_pack(
platform_name, platforms_dir, db, bios_dir, split_dir,
record=full, uncached_out=options.get("uncached_out"), **narrowing,
)
def part(pack_name: str, scope: _PartScope) -> str | None:
def part(pack_name: str, scope: _PartScope) -> PlatformPackOutcome:
record = PackRecord() if records is not None else None
zip_path = generate_pack(
built = build_platform_pack(
platform_name, platforms_dir, db, bios_dir, split_dir,
pack_name=pack_name, record=record, within=full.sources,
**scope, **narrowing,
)
if records is not None and record is not None and zip_path:
if records is not None and record is not None and built.zip_path:
records[pack_name] = record
return zip_path
return built
# The systems a core of the target runs: a part per declared system sent
# each one the target drops to a refusal naming it as unknown.
systems = platform_scope_systems(config, emu_profiles, narrowing["target_cores"])
@@ -1299,16 +1305,14 @@ def generate_split_packs(
else:
groups = {system_display_name(sid): [sid] for sid in systems}
all_extras = _split_extras(config, db, narrowing)
results = []
all_extras, left_out = _split_extras(config, db, narrowing)
outcome = SplitOutcome(left_out=left_out)
for group_name, group_system_ids in sorted(groups.items()):
group_extras = _extras_for_systems(all_extras, group_system_ids)
zip_path = part(
outcome.parts.append(part(
f"{part_prefix}_{file_name_part(group_name, '_')}{PACK_SUFFIX}",
{"system_filter": group_system_ids, "precomputed_extras": group_extras},
)
if zip_path:
results.append(zip_path)
))
# Extras whose system the platform does not declare, or that name none,
# belong to no group: they go in a part of their own, or the parts would
@@ -1321,11 +1325,29 @@ def generate_split_packs(
}
undistributed = [fe for fe in all_extras if id(fe) not in distributed]
if undistributed:
zip_path = part(
outcome.parts.append(part(
f"{part_prefix}_Other_Cores{PACK_SUFFIX}",
{"precomputed_extras": undistributed, "extras_only": True},
)
if zip_path:
results.append(zip_path)
))
return results
return outcome
def generate_split_packs(
platform_name: str,
platforms_dir: str,
db: dict,
bios_dir: str,
output_dir: str,
group_by: str = "system",
**options: Unpack[SplitOptions],
) -> list[str]:
"""Build split packs (build_split_packs) and print each part's report.
Returns the path of each part written.
"""
outcome = build_split_packs(
platform_name, platforms_dir, db, bios_dir, output_dir, group_by, **options,
)
print_split_packs(outcome)
return outcome.zip_paths
+83
View File
@@ -0,0 +1,83 @@
"""The lines a platform pack build prints: its counts, its notices and each file it could not serve."""
from __future__ import annotations
from typing import TYPE_CHECKING
from packs.datatrees import uncached_warning
if TYPE_CHECKING:
from packs.platformpack import PlatformPackOutcome, SplitOutcome
_STATUS_LABELS = {"untested": "UNTESTED", "excluded": "EXCLUDED", "missing": "MISSING"}
def _print_pack_counts(outcome: PlatformPackOutcome) -> None:
"""Print the pack's counts line.
The pipeline's consistency check reads the same counts as data
(packs.packcounts), never this line.
"""
statuses = list(outcome.file_status.values())
files_ok = statuses.count("ok")
files_untested = statuses.count("untested")
files_excluded = statuses.count("excluded")
files_miss = statuses.count("missing")
parts = [f"{files_ok}/{len(statuses)} files OK"]
if files_untested:
parts.append(f"{files_untested} untested")
if files_excluded:
parts.append(f"{files_excluded} unsafe excluded")
if files_miss:
parts.append(f"{files_miss} missing")
zip_path, total_files, core_count = outcome.zip_path, outcome.total_files, outcome.core_count
mode = outcome.verification_mode
if outcome.source == "platform":
print(
f" {zip_path}: {total_files} files packed (platform baseline only), "
f"{', '.join(parts)} [{mode}]"
)
elif outcome.source == "truth":
print(
f" {zip_path}: {total_files} files packed (ground truth only), "
f"{core_count} from emulator profiles [{mode}]"
)
else:
tree_count = outcome.tree_count
baseline = total_files - core_count - tree_count
trees = f"{tree_count} in core data trees + " if tree_count else ""
print(
f" {zip_path}: {total_files} files packed ({baseline} baseline + "
f"{trees}{core_count} from cores), {', '.join(parts)} [{mode}]"
)
def print_platform_pack(outcome: PlatformPackOutcome) -> None:
"""Print what build_platform_pack came to, or why it built nothing."""
if outcome.refusal:
print(f" WARNING: {outcome.refusal}")
return
if outcome.slot_undecidable:
print(
f" {len(outcome.slot_undecidable)} slot(s) with no declared order: "
f"every candidate kept"
)
for ref_key, local_path in outcome.uncached:
print(uncached_warning(ref_key, local_path))
_print_pack_counts(outcome)
for line in outcome.left_out:
print(f" {line}")
for key, reason in sorted(outcome.file_reasons.items()):
label = _STATUS_LABELS.get(outcome.file_status.get(key, ""), "DISCREPANCY")
print(f" {label}: {key}: {reason}")
for note in sorted(outcome.core_discrepancies):
print(f" DISCREPANCY: {note}")
def print_split_packs(outcome: SplitOutcome) -> None:
"""Print the core game data a --split run left out, then each part."""
for line in outcome.left_out:
print(f" {line}")
for part in outcome.parts:
print_platform_pack(part)
+2 -1
View File
@@ -17,7 +17,8 @@ SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"
COMMANDS = {
"generate_pack.py": (
"packs/archive.py", "packs/naming.py", "packs/scope.py", "packs/datatrees.py",
"packs/platformpack.py", "packs/emulatorpack.py", "packs/md5pack.py", "packs/targets.py",
"packs/platformpack.py", "packs/platformreport.py", "packs/emulatorpack.py",
"packs/md5pack.py", "packs/targets.py",
"packs/manifestentry.py", "packs/manifestcores.py", "packs/standalone.py",
"packs/manifest.py", "packs/finalize.py", "packs/outputdir.py", "packs/variants.py",
"packs/manifestrun.py", "packs/packcheck.py", "packs/runscope.py", "packs/platformrun.py",
+1 -1
View File
@@ -1558,7 +1558,7 @@ class OneBaselineVerdict(unittest.TestCase):
def test_the_builder_and_the_manifest_read_the_same_rules(self):
source = script_source("generate_pack.py")
tree = ast.parse(source)
for name in ("generate_pack", "generate_manifest"):
for name in ("build_platform_pack", "generate_manifest"):
function = next(
node for node in tree.body
if isinstance(node, ast.FunctionDef) and node.name == name
+4 -7
View File
@@ -9,9 +9,7 @@ from __future__ import annotations
import tests
import contextlib
import hashlib
import io
import os
import tempfile
import unittest
@@ -95,11 +93,10 @@ class ThePackReadmeNamesTheSpellingsItLeavesOut(unittest.TestCase):
platformpack.write_generated_member = capture
self.addCleanup(setattr, platformpack, "write_generated_member", real)
with contextlib.redirect_stdout(io.StringIO()):
platformpack.generate_pack(
"p", "platforms", self.db, "bios", "", emulators_dir="emulators",
offline=True, record=archive.PackRecord(),
)
platformpack.build_platform_pack(
"p", "platforms", self.db, "bios", "", emulators_dir="emulators",
offline=True, record=archive.PackRecord(),
)
return texts["README.txt"]
def test_a_platform_also_on_linux_names_them(self):
+9 -11
View File
@@ -26,7 +26,7 @@ import yaml
from model.profiles import emulator_profiles_cache
from model.platforms import load_platform_config
from packs.platformpack import generate_pack
from packs.platformpack import build_platform_pack, generate_pack
from packs.coverage import verify_platform
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -83,11 +83,10 @@ class ACoreFileFillsAFreeDeclaration(unittest.TestCase):
self.config, self.db, str(self.emulators),
)
out = self.root / "out"
with redirect_stdout(io.StringIO()):
zip_path = generate_pack(
"fakeplat", str(self.platforms), self.db, str(self.root / "bios"),
str(out), emulators_dir=str(self.emulators), offline=True,
)
zip_path = build_platform_pack(
"fakeplat", str(self.platforms), self.db, str(self.root / "bios"),
str(out), emulators_dir=str(self.emulators), offline=True,
).zip_path
with zipfile.ZipFile(zip_path) as zf:
self.assertIn("zzz_absent.bin", zf.namelist())
self.assertEqual(result["status_counts"], {"ok": 1})
@@ -133,11 +132,10 @@ class AFileDeclaredUnderAnotherName(unittest.TestCase):
}))
config = load_platform_config("fakeplat", str(root / "platforms"))
result = verify_platform(config, db, str(root / "emulators"))
with redirect_stdout(io.StringIO()):
zip_path = generate_pack(
"fakeplat", str(root / "platforms"), db, str(root / "bios"),
str(root / "out"), emulators_dir=str(root / "emulators"), offline=True,
)
zip_path = build_platform_pack(
"fakeplat", str(root / "platforms"), db, str(root / "bios"),
str(root / "out"), emulators_dir=str(root / "emulators"), offline=True,
).zip_path
with zipfile.ZipFile(zip_path) as zf:
self.assertIn("gs/ROM", zf.namelist())
reported = [(u["name"], u["in_repo"]) for u in result["undeclared_files"]]
+5 -6
View File
@@ -2343,7 +2343,7 @@ class TestE2E(unittest.TestCase):
"""
from orchestrate.consistency import check_consistency
from packs.packcounts import PackCounts, write_pack_counts
from packs.platformpack import generate_pack
from packs.platformpack import build_platform_pack
from packs.verifyoutput import write_pack_destinations
profiles = load_emulator_profiles(self.emulators_dir)
@@ -2352,11 +2352,10 @@ class TestE2E(unittest.TestCase):
groups, group_results = [], []
for platform in ("test_existence", "test_md5"):
sink: list[PackCounts] = []
with contextlib.redirect_stdout(io.StringIO()):
generate_pack(
platform, self.platforms_dir, self.db, self.bios_dir, output_dir,
emulators_dir=self.emulators_dir, emu_profiles=profiles, counts=sink,
)
build_platform_pack(
platform, self.platforms_dir, self.db, self.bios_dir, output_dir,
emulators_dir=self.emulators_dir, emu_profiles=profiles, counts=sink,
)
self.assertEqual(len(sink), 1)
packs.append((platform, [platform], sink[0]))
config = load_platform_config(platform, self.platforms_dir)
+2 -3
View File
@@ -89,9 +89,8 @@ class RealListParity(unittest.TestCase):
the list serves from the collection is no choice of either option."""
base = self.config(plat).get("base_destination", "")
record = archive.PackRecord()
with contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()):
platformpack.generate_pack(
with contextlib.redirect_stderr(io.StringIO()):
platformpack.build_platform_pack(
plat, str(REPO_ROOT / "platforms"), self.db, str(REPO_ROOT / "bios"),
tempfile.gettempdir(), emulators_dir=str(REPO_ROOT / "emulators"),
zip_contents=self.zip_contents, emu_profiles=self.profiles,
+3 -6
View File
@@ -1445,18 +1445,15 @@ class ANativeNameSelectsOneSetEverywhere(unittest.TestCase):
cls.profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"))
def _packed(self, platform: str, systems: list[str]) -> set[str]:
import contextlib
import io
import zipfile
with tempfile.TemporaryDirectory() as out, \
contextlib.redirect_stdout(io.StringIO()):
zip_path = platformpack.generate_pack(
with tempfile.TemporaryDirectory() as out:
zip_path = platformpack.build_platform_pack(
platform, str(REPO_ROOT / "platforms"), self.db,
str(REPO_ROOT / "bios"), out,
emulators_dir=str(REPO_ROOT / "emulators"),
emu_profiles=self.profiles, system_filter=systems, offline=True,
)
).zip_path
with zipfile.ZipFile(zip_path) as zf:
infos = [i for i in zf.infolist() if not i.is_dir()]
return {i.filename: i.file_size for i in infos}
+16 -19
View File
@@ -27,7 +27,7 @@ from model.profiles import emulator_profiles_cache, load_emulator_profiles
from model.platforms import load_platform_config
from resolve.standalone import platform_layouts, standalone_set
from packs.manifest import generate_manifest
from packs.platformpack import generate_pack
from packs.platformpack import build_platform_pack
from packs.coverage import verify_platform
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -94,12 +94,11 @@ class ALinkMovesTheDestination(unittest.TestCase):
}))
def pack_names(self, platform: str, name: str = "kick13.rom") -> list[str]:
with redirect_stdout(io.StringIO()):
zip_path = generate_pack(
platform, str(self.platforms), self.db, str(self.root / "bios"),
str(self.root / "out" / platform), emulators_dir=str(self.emulators),
offline=True,
)
zip_path = build_platform_pack(
platform, str(self.platforms), self.db, str(self.root / "bios"),
str(self.root / "out" / platform), emulators_dir=str(self.emulators),
offline=True,
).zip_path
with zipfile.ZipFile(zip_path) as zf:
return [n for n in zf.namelist() if n.rsplit("/", 1)[-1] == name]
@@ -387,12 +386,11 @@ class AProgramRunFromItsFolder(unittest.TestCase):
}))
def pack(self, platform: str) -> list[str]:
with redirect_stdout(io.StringIO()):
zip_path = generate_pack(
platform, str(self.platforms), self.db, str(self.root / "bios"),
str(self.root / "out" / platform), emulators_dir=str(self.emulators),
offline=True,
)
zip_path = build_platform_pack(
platform, str(self.platforms), self.db, str(self.root / "bios"),
str(self.root / "out" / platform), emulators_dir=str(self.emulators),
offline=True,
).zip_path
with zipfile.ZipFile(zip_path) as zf:
return sorted(n for n in zf.namelist() if n.split("/")[-1].startswith("prog"))
@@ -626,12 +624,11 @@ class ASettingSetsTheBiosFolder(unittest.TestCase):
}))
def pack_names(self, platform: str) -> list[str]:
with redirect_stdout(io.StringIO()):
zip_path = generate_pack(
platform, str(self.platforms), self.db, str(self.root / "bios"),
str(self.root / "out" / platform), emulators_dir=str(self.emulators),
offline=True,
)
zip_path = build_platform_pack(
platform, str(self.platforms), self.db, str(self.root / "bios"),
str(self.root / "out" / platform), emulators_dir=str(self.emulators),
offline=True,
).zip_path
with zipfile.ZipFile(zip_path) as zf:
return sorted(n for n in zf.namelist() if n.endswith((".bin", ".zip")))
+17 -19
View File
@@ -64,7 +64,7 @@ class _Fixture(unittest.TestCase):
def _both(self) -> tuple[dict, set[str]]:
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from packs.platformpack import generate_pack
from packs.platformpack import build_platform_pack
from packs.coverage import verify_platform
profiles = load_emulator_profiles(str(self.emulators))
@@ -72,12 +72,11 @@ class _Fixture(unittest.TestCase):
load_platform_config("paths", str(self.platforms)), self.db,
str(self.emulators), profiles,
)
with contextlib.redirect_stdout(io.StringIO()):
zip_path = generate_pack(
"paths", str(self.platforms), self.db, str(self.bios),
str(self.root / "out"), emulators_dir=str(self.emulators),
emu_profiles=profiles, offline=True,
)
zip_path = build_platform_pack(
"paths", str(self.platforms), self.db, str(self.bios),
str(self.root / "out"), emulators_dir=str(self.emulators),
emu_profiles=profiles, offline=True,
).zip_path
with zipfile.ZipFile(zip_path) as zf:
members = {n for n in zf.namelist() if n != "README.txt"}
return report, members
@@ -131,7 +130,7 @@ class ARequiredOnlyPack(_Fixture):
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from packs.archive import PackRecord
from packs.platformpack import generate_pack
from packs.platformpack import build_platform_pack
from packs.coverage import verify_platform
(self.emulators / "coreemu.yml").write_text(yaml.safe_dump({
@@ -145,17 +144,16 @@ class ARequiredOnlyPack(_Fixture):
)
profiles = load_emulator_profiles(str(self.emulators))
record = PackRecord()
with contextlib.redirect_stdout(io.StringIO()):
zip_path = generate_pack(
"paths", str(self.platforms), self.db, str(self.bios),
str(self.root / "out"), emulators_dir=str(self.emulators),
emu_profiles=profiles, offline=True, required_only=True,
)
generate_pack(
"paths", str(self.platforms), self.db, str(self.bios), "",
emulators_dir=str(self.emulators), emu_profiles=profiles,
offline=True, required_only=True, record=record,
)
zip_path = build_platform_pack(
"paths", str(self.platforms), self.db, str(self.bios),
str(self.root / "out"), emulators_dir=str(self.emulators),
emu_profiles=profiles, offline=True, required_only=True,
).zip_path
build_platform_pack(
"paths", str(self.platforms), self.db, str(self.bios), "",
emulators_dir=str(self.emulators), emu_profiles=profiles,
offline=True, required_only=True, record=record,
)
with zipfile.ZipFile(zip_path) as zf:
members = set(zf.namelist())
# The record names what the archive holds, nothing more or less.
+3 -2
View File
@@ -149,10 +149,11 @@ class ASplitBuildsOnlyTheTargetsSystems(unittest.TestCase):
def record(*_a, **kw):
if kw.get("system_filter"):
asked.append(kw["system_filter"])
return
return platformpack.PlatformPackOutcome(zip_path=None)
with tempfile.TemporaryDirectory() as out, \
mock.patch.object(platformpack, "generate_pack", record), \
mock.patch.object(platformpack, "build_platform_pack", record), \
mock.patch.object(platformpack, "print_split_packs"), \
mock.patch.object(platformpack, "collect_emulator_extras", return_value=[]), \
mock.patch.object(manifest, "collect_emulator_extras", return_value=[]):
packs_platformpack.generate_split_packs(
+4 -4
View File
@@ -94,7 +94,7 @@ class ValidatedChoice(unittest.TestCase):
for call in ast.walk(node)
)
}
self.assertLessEqual({"generate_pack", "generate_manifest"}, callers)
self.assertLessEqual({"build_platform_pack", "generate_manifest"}, callers)
# The manifest's core extras go through the builder's own lookup,
# which reads validated_choice (packextras.ExtraResolver).
resolvers = {
@@ -106,7 +106,7 @@ class ValidatedChoice(unittest.TestCase):
for call in ast.walk(node)
)
}
self.assertLessEqual({"generate_pack", "manifest_core_entries"}, resolvers)
self.assertLessEqual({"build_platform_pack", "manifest_core_entries"}, resolvers)
extras = ast.parse((REPO_ROOT / "scripts" / "packs" / "extras.py").read_text(encoding="utf-8"))
resolve = next(
node for node in ast.walk(extras)
@@ -119,11 +119,11 @@ class ValidatedChoice(unittest.TestCase):
def test_core_extras_are_judged_too(self):
"""The baseline loop judged a platform's own files while the core-extras loop
shipped whatever the name found. Both loops live in generate_pack."""
shipped whatever the name found. Both loops live in build_platform_pack."""
tree = ast.parse(script_source("generate_pack.py"))
builder = next(
node for node in ast.walk(tree)
if isinstance(node, ast.FunctionDef) and node.name == "generate_pack"
if isinstance(node, ast.FunctionDef) and node.name == "build_platform_pack"
)
calls = [
call for call in ast.walk(builder)