Coverage for src/romfarmer/mcp/clonelist.py: 0%

111 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-01 23:08 -0700

1"""MCP tools for clone list maintenance: diff, validate, patch, metadata.""" 

2 

3import json 

4import tempfile 

5import zipfile 

6from pathlib import Path 

7from typing import Any 

8 

9from romfarmer.core.paths import get_paths 

10 

11WORKSPACE_ROOT = get_paths().workspace_root 

12 

13 

14async def tool_clonelist_diff( 

15 old_dat: str, 

16 new_dat: str, 

17) -> dict[str, Any]: 

18 """Diff two DAT versions by hash — detect renames, adds, removes.""" 

19 from romfarmer.dat_parser.clonelist import dat_diff 

20 from romfarmer.dat_parser.parser import DATParser 

21 

22 parser = DATParser() 

23 old_path = _resolve_dat_path(old_dat) 

24 new_path = _resolve_dat_path(new_dat) 

25 

26 if not old_path or not old_path.exists(): 

27 return {"error": f"Old DAT not found: {old_dat}"} 

28 if not new_path or not new_path.exists(): 

29 return {"error": f"New DAT not found: {new_dat}"} 

30 

31 old_parsed = _parse_dat_file(parser, old_path) 

32 new_parsed = _parse_dat_file(parser, new_path) 

33 

34 result = dat_diff(old_parsed, new_parsed) 

35 

36 return { 

37 "old_dat": result.old_dat_name, 

38 "new_dat": result.new_dat_name, 

39 "old_count": result.old_count, 

40 "new_count": result.new_count, 

41 "has_changes": result.has_changes, 

42 "renames": [{"old_name": r.old_name, "new_name": r.new_name} for r in result.renames], 

43 "additions": result.additions[:50], # Cap output size 

44 "additions_total": len(result.additions), 

45 "removals": result.removals[:50], 

46 "removals_total": len(result.removals), 

47 "summary": ( 

48 f"{len(result.renames)} renames, " 

49 f"{len(result.additions)} additions, " 

50 f"{len(result.removals)} removals" 

51 ), 

52 } 

53 

54 

55async def tool_clonelist_validate( 

56 clonelist: str, 

57 dat_file: str, 

58) -> dict[str, Any]: 

59 """Validate clone list searchTerms against a DAT — find broken references.""" 

60 from romfarmer.dat_parser.clonelist import clonelist_validate 

61 from romfarmer.dat_parser.parser import DATParser 

62 

63 cl_path = _resolve_clonelist_path(clonelist) 

64 if not cl_path or not cl_path.exists(): 

65 return {"error": f"Clone list not found: {clonelist}"} 

66 

67 dat_path = _resolve_dat_path(dat_file) 

68 if not dat_path or not dat_path.exists(): 

69 return {"error": f"DAT not found: {dat_file}"} 

70 

71 parser = DATParser() 

72 dat = _parse_dat_file(parser, dat_path) 

73 result = clonelist_validate(cl_path, dat) 

74 

75 return { 

76 "clonelist": result.clonelist_name, 

77 "dat": result.dat_name, 

78 "total_search_terms": result.total_search_terms, 

79 "matched": result.matched, 

80 "match_rate": f"{result.match_rate:.1%}", 

81 "unmatched": [ 

82 { 

83 "group": u.group, 

84 "search_term": u.search_term, 

85 "suggestion": u.suggestion, 

86 "similarity": round(u.similarity, 2), 

87 } 

88 for u in result.unmatched[:50] 

89 ], 

90 "unmatched_total": len(result.unmatched), 

91 } 

92 

93 

94async def tool_clonelist_patch( 

95 clonelist: str, 

96 old_dat: str, 

97 new_dat: str, 

98 output: str | None = None, 

99 dry_run: bool = True, 

100) -> dict[str, Any]: 

101 """Auto-patch clone list searchTerms from DAT renames. Dry-run by default.""" 

102 from romfarmer.dat_parser.clonelist import clonelist_patch, dat_diff 

103 from romfarmer.dat_parser.parser import DATParser 

104 

105 cl_path = _resolve_clonelist_path(clonelist) 

106 if not cl_path or not cl_path.exists(): 

107 return {"error": f"Clone list not found: {clonelist}"} 

108 

109 parser = DATParser() 

110 old_path = _resolve_dat_path(old_dat) 

111 new_path = _resolve_dat_path(new_dat) 

112 

113 if not old_path or not old_path.exists(): 

114 return {"error": f"Old DAT not found: {old_dat}"} 

115 if not new_path or not new_path.exists(): 

116 return {"error": f"New DAT not found: {new_dat}"} 

117 

118 old_parsed = _parse_dat_file(parser, old_path) 

119 new_parsed = _parse_dat_file(parser, new_path) 

120 

121 diff_result = dat_diff(old_parsed, new_parsed) 

122 

123 out_path = Path(output) if output else None 

124 result = clonelist_patch(cl_path, diff_result, output_path=out_path, dry_run=dry_run) 

125 

126 applied_or_proposed = result.patches_applied if not dry_run else result.patches_skipped 

127 return { 

128 "clonelist": result.clonelist_name, 

129 "dry_run": dry_run, 

130 "patches": [ 

131 { 

132 "group": p.group, 

133 "old": p.old_search_term, 

134 "new": p.new_search_term, 

135 "reason": p.reason, 

136 } 

137 for p in applied_or_proposed 

138 ], 

139 "patch_count": len(applied_or_proposed), 

140 "output": str(out_path) if out_path else "in-place", 

141 } 

142 

143 

144async def tool_clonelist_metadata_generate( 

145 dat_file: str, 

146 output: str | None = None, 

147) -> dict[str, Any]: 

148 """Auto-generate Retool metadata JSON from DAT filenames.""" 

149 from romfarmer.dat_parser.clonelist import metadata_generate, metadata_to_retool_json 

150 from romfarmer.dat_parser.parser import DATParser 

151 

152 dat_path = _resolve_dat_path(dat_file) 

153 if not dat_path or not dat_path.exists(): 

154 return {"error": f"DAT not found: {dat_file}"} 

155 

156 parser = DATParser() 

157 dat = _parse_dat_file(parser, dat_path) 

158 

159 entries = metadata_generate(dat) 

160 retool_json = metadata_to_retool_json(entries) 

161 

162 # Count language coverage 

163 with_langs = sum(1 for e in entries if e.languages) 

164 

165 if output: 

166 out_path = Path(output) 

167 out_path.parent.mkdir(parents=True, exist_ok=True) 

168 with open(out_path, "w", encoding="utf-8") as f: 

169 json.dump(retool_json, f, indent=2, ensure_ascii=False) 

170 f.write("\n") 

171 

172 # Return sample + stats (full JSON could be huge) 

173 sample_keys = list(retool_json.keys())[:10] 

174 sample = {k: retool_json[k] for k in sample_keys} 

175 

176 return { 

177 "dat": dat.name, 

178 "total_entries": len(retool_json), 

179 "with_languages": with_langs, 

180 "language_coverage": f"{with_langs / len(entries):.1%}" if entries else "0%", 

181 "output": str(output) if output else "not saved", 

182 "sample": sample, 

183 } 

184 

185 

186# ── Helpers ────────────────────────────────────────────────────────────── 

187 

188 

189def _resolve_dat_path(dat_ref: str) -> Path | None: 

190 """Resolve a DAT file reference to a path. 

191 

192 Accepts: absolute path, relative path, or just a name (searches dats/). 

193 """ 

194 p = Path(dat_ref) 

195 if p.is_absolute(): 

196 return p 

197 

198 # Try relative to workspace 

199 ws_path = WORKSPACE_ROOT / p 

200 if ws_path.exists(): 

201 return ws_path 

202 

203 # Search in dats/ directories 

204 for dats_dir in [ 

205 WORKSPACE_ROOT / "dats", 

206 WORKSPACE_ROOT / "dats" / "generated", 

207 WORKSPACE_ROOT / "dats" / "retool-1g1r-eng", 

208 ]: 

209 if dats_dir.exists(): 

210 for f in dats_dir.rglob(f"*{dat_ref}*"): 

211 if f.suffix in (".dat", ".xml", ".zip"): 

212 return f 

213 

214 return p # Return as-is, caller checks .exists() 

215 

216 

217def _resolve_clonelist_path(cl_ref: str) -> Path | None: 

218 """Resolve a clone list reference to a path. 

219 

220 Searches in the retool-clonelists-metadata repo. 

221 """ 

222 p = Path(cl_ref) 

223 if p.is_absolute(): 

224 return p 

225 

226 # Try relative to workspace 

227 ws_path = WORKSPACE_ROOT / p 

228 if ws_path.exists(): 

229 return ws_path 

230 

231 # Search in retool repos relative to workspace 

232 from romfarmer.core.paths import paths as _paths 

233 

234 for search_dir in [ 

235 _paths.workspace_root.parent / "retool-clonelists-metadata", 

236 _paths.workspace_root.parent / "retool" / "clonelists", 

237 ]: 

238 if search_dir.exists(): 

239 for f in search_dir.rglob(f"*{cl_ref}*"): 

240 if f.suffix == ".json": 

241 return f 

242 

243 return p 

244 

245 

246def _parse_dat_file(parser, path: Path): 

247 """Parse a DAT file, handling ZIP-compressed DATs.""" 

248 if path.suffix.lower() == ".zip": 

249 with tempfile.TemporaryDirectory() as tmpdir: 

250 with zipfile.ZipFile(path, "r") as zf: 

251 dat_files = [f for f in zf.namelist() if f.endswith(".dat")] 

252 if not dat_files: 

253 raise ValueError(f"No .dat file in {path.name}") 

254 zf.extract(dat_files[0], tmpdir) 

255 return parser.parse(Path(tmpdir) / dat_files[0]) 

256 return parser.parse(path)