Coverage for src/romfarmer/planner/lowering/base.py: 86%

64 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-05 02:19 -0700

1"""Base types and dispatcher for the lowering layer. 

2 

3``FormatChain`` and ``LoweringRule`` are the two load-bearing contracts; 

4everything else in this package is concrete implementations. 

5 

6The ``lower()`` dispatcher is the single entry point used by the 

7orchestrator — it chooses the right rule based on the chain. 

8""" 

9 

10from __future__ import annotations 

11 

12import hashlib 

13import re 

14import subprocess 

15from pathlib import Path 

16from typing import Any, Protocol 

17 

18from romfarmer.ir.actions import ( 

19 Action, 

20 ActionId, 

21 ArtifactDecl, 

22 ContentRef, 

23 Retention, 

24 SizePrediction, 

25 UnitPlan, 

26) 

27from romfarmer.ir.catalog import GameUnit 

28from romfarmer.ir.chain import FormatChain as FormatChain # re-exported for lowering rules 

29from romfarmer.ir.manifest import BuildManifest 

30from romfarmer.ir.tool_impl import impl_version_suffix 

31 

32# ``FormatChain`` is defined in ``romfarmer.ir.chain``; re-exported here for 

33# the lowering rules. Examples: 

34# ("chd",) — disc → chdman 

35# ("xiso", "squashfs") — xbox iso → extract-xiso → mksquashfs 

36# ("7z",) — cartridge → unzip → 7z 

37# ("passthrough",) — copy as-is 

38 

39 

40class LoweringRule(Protocol): 

41 """Protocol for a platform-specific lowering rule. 

42 

43 Implementations are in the sibling modules 

44 (disc.py, cartridge.py, etc.). 

45 """ 

46 

47 def lower( 

48 self, 

49 unit: GameUnit, 

50 chain: FormatChain, 

51 manifest: BuildManifest, 

52 ) -> UnitPlan: 

53 """Translate *unit* into a ``UnitPlan`` for the given *chain*.""" 

54 ... 

55 

56 

57# --------------------------------------------------------------------------- 

58# Action-ID helper 

59# --------------------------------------------------------------------------- 

60 

61 

62def make_action_id(unit_id: str, step_idx: int, tool: str) -> ActionId: 

63 """Stable ActionId = sha1(f"{unit_id}:{step_idx}:{tool}").""" 

64 raw = f"{unit_id}:{step_idx}:{tool}" 

65 return ActionId(hashlib.sha1(raw.encode()).hexdigest()) 

66 

67 

68# --------------------------------------------------------------------------- 

69# Source-copy action helper 

70# --------------------------------------------------------------------------- 

71 

72 

73def source_action( 

74 unit: GameUnit, 

75 step_idx: int, 

76 source_path: Path, 

77 logical_name: str, 

78 kind: str = "source", 

79 tool_version: str | None = None, 

80) -> Action: 

81 """Return an Action that copies *source_path* into the CAS. 

82 

83 The executor's ``SourceCopyTransform`` handles this tool. It is the 

84 bridge between the filesystem source files and the CAS-aware executor. 

85 """ 

86 return Action( 

87 action_id=make_action_id(str(unit.unit_id), step_idx, "source-copy"), 

88 tool="source-copy", 

89 tool_version=tool_version 

90 if tool_version is not None 

91 else static_tool_version("source-copy"), 

92 params={"path": str(source_path)}, 

93 inputs=(), # source file is NOT from CAS — it's a filesystem path 

94 outputs=( 

95 ArtifactDecl( 

96 logical_name=logical_name, 

97 kind=kind, 

98 retention=Retention.INTERMEDIATE, 

99 ), 

100 ), 

101 ) 

102 

103 

104def source_ref( 

105 unit: GameUnit, 

106 action_cache: Any | None, 

107) -> tuple[ContentRef | None, str | None]: 

108 """Return ``(ContentRef, sha256)`` if the unit's first disc sha256 is known. 

109 

110 Returns ``(None, None)`` when sha256 is not yet in the CAS. 

111 """ 

112 disc0 = unit.discs[0] 

113 if disc0.identity.sha256 is not None: 

114 return ContentRef(disc0.identity.sha256), disc0.identity.sha256 

115 # Try MD5 alias lookup 

116 if action_cache is not None and disc0.identity.md5 is not None: 

117 try: 

118 ident = action_cache.lookup_by_md5(disc0.identity.md5) 

119 if ident is not None and ident.sha256 is not None: 

120 return ContentRef(ident.sha256), ident.sha256 

121 except Exception: 

122 pass 

123 return None, None 

124 

125 

126# --------------------------------------------------------------------------- 

127# Tool version probing 

128# --------------------------------------------------------------------------- 

129 

130_VERSION_CACHE: dict[str, str] = {} 

131 

132# Not every tool understands --version; these print a banner on stdout/stderr. 

133_VERSION_ARGS: dict[str, tuple[str, ...]] = { 

134 "7z": ("i",), 

135 "7zz": ("i",), 

136 "7za": ("i",), 

137 "chdman": (), 

138 "extract-xiso": ("-h",), 

139 "mksquashfs": ("-version",), 

140} 

141_VERSION_TOKEN = re.compile(r"\d+(?:\.\d+)+") 

142 

143 

144def probe_tool_version(tool: str, *args: str) -> str: 

145 """Return a stable version string for *tool*, cached per process. 

146 

147 Runs the tool's banner command (``--version`` unless overridden in 

148 ``_VERSION_ARGS``) and keeps the first dotted version token found in the 

149 first non-empty output line (falling back to the sanitised line itself). 

150 The impl-version suffix from ``IMPL_VERSIONS`` is appended when the entry 

151 is ≥ 2. Falls back to ``"unknown"`` if the tool is not found or fails. 

152 """ 

153 cache_key = tool 

154 if cache_key in _VERSION_CACHE: 

155 return _VERSION_CACHE[cache_key] 

156 banner_args = args or _VERSION_ARGS.get(Path(tool).name, ("--version",)) 

157 try: 

158 result = subprocess.run( 

159 [tool, *banner_args], 

160 capture_output=True, 

161 text=True, 

162 timeout=5, 

163 ) 

164 lines = [ln.strip() for ln in (result.stdout + "\n" + result.stderr).splitlines()] 

165 line = next((ln for ln in lines if ln), "") 

166 token = _VERSION_TOKEN.search(line) 

167 version = token.group(0) if token else re.sub(r"[^\w.\-+]", "", line)[:40] 

168 version = version or "unknown" 

169 except Exception: 

170 version = "unknown" 

171 version = version + impl_version_suffix(Path(tool).name) 

172 _VERSION_CACHE[cache_key] = version 

173 return version 

174 

175 

176def static_tool_version(tool: str) -> str: 

177 """Return the ``tool_version`` string for a synthetic (no-subprocess) tool. 

178 

179 Synthetic tools (source-copy, passthrough, m3u-create) have no external 

180 binary to probe, so their base version is always ``"1"``. The impl-version 

181 suffix is appended using the same ``IMPL_VERSIONS`` registry so bumping 

182 IMPL_VERSIONS["m3u-create"] to 2 automatically changes the emitted 

183 ``tool_version`` from ``"1"`` to ``"1+i2"`` and invalidates cache rows. 

184 """ 

185 return "1" + impl_version_suffix(tool) 

186 

187 

188# --------------------------------------------------------------------------- 

189# Size-prediction helper 

190# --------------------------------------------------------------------------- 

191 

192 

193def zero_prediction() -> SizePrediction: 

194 return SizePrediction(ratio=1.0, source="prior:passthrough", confidence=0.5) 

195 

196 

197# --------------------------------------------------------------------------- 

198# Dispatcher 

199# --------------------------------------------------------------------------- 

200 

201 

202def lower( 

203 unit: GameUnit, 

204 chain: FormatChain, 

205 manifest: BuildManifest, 

206 action_cache: Any | None = None, 

207) -> UnitPlan: 

208 """Dispatch to the right lowering rule based on *chain[0]*. 

209 

210 ``action_cache`` is optional; when provided it is used to resolve sha256 

211 from MD5 aliases so that ``ContentRef`` can be used instead of a 

212 source-copy action. 

213 """ 

214 from . import ( 

215 arcade, 

216 cartridge, 

217 disc, 

218 passthrough, 

219 ps3, 

220 rvz, 

221 wux, 

222 xiso, 

223 ) 

224 

225 if not chain: 

226 raise ValueError(f"Empty FormatChain for unit {unit.canonical_name!r}") 

227 

228 primary = chain[0].lower() 

229 rule_map: dict[str, LoweringRule] = { 

230 "chd": disc.DiscLoweringRule(action_cache=action_cache), 

231 "cue_bin": disc.DiscLoweringRule(action_cache=action_cache, no_chd=True), 

232 "iso": disc.DiscLoweringRule(action_cache=action_cache, no_chd=True), 

233 "rvz": rvz.RVZLoweringRule(action_cache=action_cache), 

234 "wux": wux.WUXLoweringRule(action_cache=action_cache), 

235 "xiso": xiso.XisoLoweringRule(action_cache=action_cache), 

236 "squashfs": xiso.XisoLoweringRule(action_cache=action_cache), 

237 "ps3": ps3.PS3LoweringRule(action_cache=action_cache), 

238 "ps3_dec": ps3.PS3LoweringRule(action_cache=action_cache), 

239 "arcade": arcade.ArcadeLoweringRule(action_cache=action_cache), 

240 "zip": cartridge.CartridgeLoweringRule(action_cache=action_cache), 

241 "7z": cartridge.CartridgeLoweringRule(action_cache=action_cache, fmt="7z"), 

242 "passthrough": passthrough.PassthroughLoweringRule(action_cache=action_cache), 

243 } 

244 

245 rule = rule_map.get(primary) 

246 if rule is None: 

247 raise ValueError( 

248 f"No lowering rule for chain primary={primary!r}. " 

249 f"Register one in planner/lowering/base.py:lower()." 

250 ) 

251 return rule.lower(unit, chain, manifest)