Coverage for src/romfarmer/farmhand/optimizer/merge.py: 0%
86 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-03 11:31 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-03 11:31 -0700
1"""Pool merge utility — combine pool manifests from multiple builds.
3When a full deployment spans multiple builds (e.g., nointro + redump +
4nintendo-disc), the optimizer needs a single combined pool so it can reason
5about total size across all content. This module merges per-build pools into
6one directory the optimizer can consume via ``--pool-root``.
8If the same platform appears in more than one source (unusual, but possible
9if you accidentally include overlapping builds), entries are merged by game
10name — the first source wins for duplicate names.
11"""
13from __future__ import annotations
15import json
16import logging
17import shutil
18from dataclasses import dataclass
19from pathlib import Path
21logger = logging.getLogger(__name__)
24@dataclass
25class MergeResult:
26 """Summary of a pool merge operation."""
28 output_root: Path
29 platforms_merged: int
30 platforms_total: int
31 games_total: int
32 conflicts_resolved: int # platforms that appeared in >1 source
33 source_breakdown: dict[str, list[str]] # source_build → [platform, ...]
36def merge_pools(
37 sources: list[Path],
38 output: Path,
39 *,
40 overwrite: bool = True,
41) -> MergeResult:
42 """Merge pool manifests from multiple source directories into *output*.
44 Args:
45 sources: Paths to ``.pool`` directories (each produced by
46 ``collect_pool`` or ``farmhand collect-pool``).
47 output: Destination directory for the merged pool. Will be created
48 if it does not exist. If it already contains manifests and
49 *overwrite* is True (default), they are replaced.
50 overwrite: When True, existing manifests in *output* are replaced by
51 fresher data from the sources. When False, existing
52 manifests are preserved and only new platforms are added.
54 Returns:
55 :class:`MergeResult` with stats.
56 """
57 output.mkdir(parents=True, exist_ok=True)
59 # Track which source each platform came from (for conflict reporting)
60 seen: dict[str, str] = {} # platform → first source label
61 conflicts_resolved = 0
62 source_breakdown: dict[str, list[str]] = {}
63 games_total = 0
65 for source_dir in sources:
66 if not source_dir.exists():
67 logger.warning(f"Pool source not found, skipping: {source_dir}")
68 continue
70 source_label = source_dir.parent.name # e.g. "nointro-1g1r-eng-7z-batocera-v2"
71 source_breakdown[source_label] = []
73 manifests = sorted(source_dir.glob("*.json"))
74 if not manifests:
75 logger.warning(f"No manifests found in {source_dir}")
76 continue
78 for manifest_path in manifests:
79 platform = manifest_path.stem
80 dest_path = output / manifest_path.name
82 if platform in seen:
83 conflicts_resolved += 1
84 logger.info(
85 f" Platform '{platform}' from '{source_label}' conflicts with "
86 f"'{seen[platform]}' — merging entries"
87 )
88 # Merge: load both, combine by name (first seen wins for dupes)
89 existing = _load_raw_entries(dest_path)
90 incoming = _load_raw_entries(manifest_path)
91 merged = _merge_entries(existing, incoming)
92 _write_raw_entries(dest_path, merged)
93 games_total += len(merged)
94 else:
95 # First time we see this platform
96 if not dest_path.exists() or overwrite:
97 shutil.copy2(manifest_path, dest_path)
98 entries = _load_raw_entries(dest_path)
99 games_total += len(entries)
100 else:
101 # overwrite=False and file already exists — preserve
102 entries = _load_raw_entries(dest_path)
103 games_total += len(entries)
104 logger.debug(f" Preserving existing manifest for '{platform}'")
106 seen[platform] = source_label
107 source_breakdown[source_label].append(platform)
109 logger.info(f" Source '{source_label}': {len(source_breakdown[source_label])} platforms")
111 result = MergeResult(
112 output_root=output,
113 platforms_merged=len(seen),
114 platforms_total=sum(len(v) for v in source_breakdown.values()),
115 games_total=games_total,
116 conflicts_resolved=conflicts_resolved,
117 source_breakdown=source_breakdown,
118 )
120 logger.info(
121 f"Merge complete: {result.platforms_merged} platforms, "
122 f"{result.games_total} games → {output}"
123 )
124 return result
127def merge_pools_from_builds(
128 build_names: list[str],
129 output: Path,
130 output_base: Path | None = None,
131 *,
132 overwrite: bool = True,
133) -> MergeResult:
134 """Convenience wrapper: merge pools from named builds under *output_base*.
136 Looks for pools at ``output_base / build_name / .pool`` for each name.
138 Args:
139 build_names: Build names whose pools should be merged.
140 output: Destination directory.
141 output_base: Root of all build outputs. Defaults to ``output/``
142 relative to the workspace root (resolved via
143 :func:`romfarmer.core.paths.get_paths`).
144 overwrite: Passed through to :func:`merge_pools`.
145 """
146 if output_base is None:
147 from romfarmer.core.paths import get_paths
149 output_base = get_paths().workspace_root / "output"
151 sources: list[Path] = []
152 for name in build_names:
153 pool_dir = output_base / name / ".pool"
154 if pool_dir.exists():
155 sources.append(pool_dir)
156 else:
157 logger.warning(
158 f"No pool found for build '{name}' at {pool_dir}. "
159 "Run 'farmhand collect-pool' first."
160 )
162 if not sources:
163 raise FileNotFoundError(
164 f"No pool manifests found for any of the specified builds: "
165 f"{', '.join(build_names)}\n"
166 "Run 'romfarmer farmhand collect-pool <build-name>' for each build first."
167 )
169 return merge_pools(sources, output, overwrite=overwrite)
172# ---------------------------------------------------------------------------
173# Internal helpers
174# ---------------------------------------------------------------------------
177def _load_raw_entries(path: Path) -> list[dict]:
178 """Load a manifest as a list of raw dicts."""
179 try:
180 with open(path) as f:
181 return json.load(f)
182 except Exception as e:
183 logger.warning(f"Could not load manifest {path}: {e}")
184 return []
187def _write_raw_entries(path: Path, entries: list[dict]) -> None:
188 """Write a list of raw dicts to a manifest file."""
189 with open(path, "w") as f:
190 json.dump(entries, f, indent=2)
193def _merge_entries(existing: list[dict], incoming: list[dict]) -> list[dict]:
194 """Merge two lists of pool entries, deduplicating by game name.
196 The existing list takes precedence for duplicate names (first-seen wins).
197 New entries from *incoming* that aren't in *existing* are appended.
198 """
199 names_seen = {e["name"] for e in existing}
200 merged = list(existing)
201 for entry in incoming:
202 if entry["name"] not in names_seen:
203 merged.append(entry)
204 names_seen.add(entry["name"])
205 return merged