codiff 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. codiff/__init__.py +1 -0
  2. codiff/__main__.py +5 -0
  3. codiff/cli.py +247 -0
  4. codiff/db/__init__.py +16 -0
  5. codiff/db/engine.py +31 -0
  6. codiff/db/models.py +119 -0
  7. codiff/db/operations.py +238 -0
  8. codiff/diff/__init__.py +1 -0
  9. codiff/diff/analysis.py +145 -0
  10. codiff/diff/differ.py +45 -0
  11. codiff/diff/engine.py +80 -0
  12. codiff/diff/indexer.py +134 -0
  13. codiff/diff/snapshot.py +325 -0
  14. codiff/export/__init__.py +5 -0
  15. codiff/export/json.py +43 -0
  16. codiff/export/mermaid.py +475 -0
  17. codiff/export/terminal.py +866 -0
  18. codiff/languages/__init__.py +29 -0
  19. codiff/languages/parser.py +214 -0
  20. codiff/languages/python/__init__.py +0 -0
  21. codiff/languages/python/parser.py +927 -0
  22. codiff/languages/python/resolver.py +178 -0
  23. codiff/languages/repository.py +245 -0
  24. codiff/languages/resolver.py +582 -0
  25. codiff/languages/typescript/__init__.py +0 -0
  26. codiff/languages/typescript/parser.py +612 -0
  27. codiff/languages/typescript/resolver.py +95 -0
  28. codiff/mcp_server.py +83 -0
  29. codiff/schema/__init__.py +25 -0
  30. codiff/schema/diff.py +110 -0
  31. codiff/schema/parsing.py +76 -0
  32. codiff/setup.py +103 -0
  33. codiff/utils/__init__.py +0 -0
  34. codiff/utils/args.py +114 -0
  35. codiff/utils/files.py +62 -0
  36. codiff/utils/git.py +101 -0
  37. codiff/utils/instructions.py +14 -0
  38. codiff/utils/instructions.yaml +50 -0
  39. codiff/utils/terminal.py +10 -0
  40. codiff-0.1.0.dist-info/METADATA +487 -0
  41. codiff-0.1.0.dist-info/RECORD +45 -0
  42. codiff-0.1.0.dist-info/WHEEL +5 -0
  43. codiff-0.1.0.dist-info/entry_points.txt +3 -0
  44. codiff-0.1.0.dist-info/licenses/LICENSE +201 -0
  45. codiff-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,475 @@
1
+ """Generate a genuine UML class diagram from an AnalysisResult.
2
+
3
+ Uses Mermaid's native classDiagram syntax:
4
+
5
+ namespace ns_file_stem { ← one sanitised namespace per file
6
+ class hdr__path["πŸ“„ path/to/file.py"] { ← dark header showing real path
7
+ <<file>>
8
+ }
9
+ class ClassName["ClassName"] { ← Python class
10
+ + added_method()
11
+ ~ modified_method() sig changed
12
+ - removed_method()
13
+ }
14
+ class standalone["Β«standaloneΒ»"] { ← module-level functions
15
+ <<module>>
16
+ + func()
17
+ }
18
+ }
19
+
20
+ Styles applied via `style ID fill:...` (separate from class definition so
21
+ that Mermaid's parser accepts both a display-name AND colouring β€” combining
22
+ them on one line is not supported in all Mermaid versions).
23
+
24
+ Visibility prefix reused for change type (happy UML coincidence):
25
+ + added (public)
26
+ ~ modified (package)
27
+ - removed (private)
28
+
29
+ Relationships: solid --> for active calls, dashed ..> for removed calls.
30
+ """
31
+
32
+ import re
33
+ from collections import defaultdict
34
+
35
+ from codiff.schema.diff import (
36
+ AddedFunctionInfo,
37
+ AnalysisResult,
38
+ ModifiedFunctionInfo,
39
+ RemovedFunctionInfo,
40
+ )
41
+
42
+ # ── Style constants ───────────────────────────────────────────────────────────
43
+
44
+ # Tinted fill + vivid border: colour at a glance, still readable
45
+ _S = {
46
+ "added": "fill:#f0fdf4,color:#166534,stroke:#22c55e,stroke-width:3px",
47
+ "modified": "fill:#fefce8,color:#854d0e,stroke:#f59e0b,stroke-width:3px",
48
+ "removed": "fill:#fff1f2,color:#991b1b,stroke:#f87171,stroke-width:3px",
49
+ }
50
+
51
+
52
+ _THEME = (
53
+ "'maxTextSize': 999999, "
54
+ "'theme': 'base', "
55
+ "'themeVariables': {"
56
+ "'background': '#ffffff', "
57
+ "'clusterBkg': '#f8fafc', "
58
+ "'clusterBorder': '#94a3b8', "
59
+ "'primaryColor': '#f8fafc', "
60
+ "'primaryBorderColor': '#94a3b8', "
61
+ "'primaryTextColor': '#1e293b', "
62
+ "'lineColor': '#64748b', "
63
+ "'fontSize': '13px', "
64
+ "'fontFamily': 'ui-monospace, SFMono-Regular, Menlo, monospace'"
65
+ "}"
66
+ )
67
+
68
+ # Connected diagram: ELK layered algorithm, left-to-right
69
+ _INIT = f"%%{{init: {{'layout': 'elk', 'elk': {{'direction': 'RIGHT'}}, {_THEME}}}}}%%"
70
+
71
+ # Isolated diagram: Dagre with direction LR β€” namespace blocks (one per
72
+ # folder) arranged left-to-right, files within each folder stack vertically.
73
+ _INIT_GRID = f"%%{{init: {{{_THEME}}}}}%%"
74
+
75
+
76
+ # ── ID / name helpers ─────────────────────────────────────────────────────────
77
+
78
+
79
+ def _san(s: str) -> str:
80
+ return re.sub(r"[^a-zA-Z0-9_]", "_", s)
81
+
82
+
83
+ def _class_id(file_path: str, class_name: str) -> str:
84
+ return _san(f"cls__{file_path}__{class_name}")
85
+
86
+
87
+ def _mod_id(file_path: str) -> str:
88
+ return _san(f"mod__{file_path}")
89
+
90
+
91
+ # ── Member label helpers ──────────────────────────────────────────────────────
92
+
93
+
94
+ def _method(fid: str) -> str:
95
+ return fid.split(".")[-1]
96
+
97
+
98
+ def _added_line(fn: AddedFunctionInfo) -> str:
99
+ return f"+ {_method(fn.function_id)}()"
100
+
101
+
102
+ def _modified_line(fn: ModifiedFunctionInfo) -> str:
103
+ name = _method(fn.function_id)
104
+ if fn.signature_changed:
105
+ return f"~ {name}() sig"
106
+ added = len(fn.calls_added_new) + len(fn.calls_added_existing)
107
+ removed = len(fn.calls_removed)
108
+ if added or removed:
109
+ parts = ([f"+{added}"] if added else []) + ([f"βˆ’{removed}"] if removed else [])
110
+ return f"~ {name}() calls {''.join(parts)}"
111
+ return f"~ {name}()"
112
+
113
+
114
+ def _removed_line(fn: RemovedFunctionInfo) -> str:
115
+ return f"- {_method(fn.function_id)}()"
116
+
117
+
118
+ def _topo_sort(nodes: list[str], edges: set[tuple[str, str]]) -> list[str]:
119
+ """Kahn's algorithm: nodes with no incoming edges (callers) come first."""
120
+ from collections import deque
121
+
122
+ node_set = set(nodes)
123
+ in_deg = {n: 0 for n in nodes}
124
+ adj: dict[str, list[str]] = {n: [] for n in nodes}
125
+ for src, dst in edges:
126
+ if src in node_set and dst in node_set:
127
+ adj[src].append(dst)
128
+ in_deg[dst] += 1
129
+ queue = deque(sorted(n for n, d in in_deg.items() if d == 0))
130
+ result: list[str] = []
131
+ while queue:
132
+ node = queue.popleft()
133
+ result.append(node)
134
+ for nb in sorted(adj[node]):
135
+ in_deg[nb] -= 1
136
+ if in_deg[nb] == 0:
137
+ queue.append(nb)
138
+ # append anything left (cycles)
139
+ result.extend(sorted(n for n in nodes if n not in result))
140
+ return result
141
+
142
+
143
+ def _class_style(change_type: str) -> str:
144
+ """Always use change-type color β€” green/yellow/red is unambiguous at a glance.
145
+ Chain membership is already communicated by the relationship arrows."""
146
+ return _S[change_type]
147
+
148
+
149
+ def _dominant(added: list, modified: list, removed: list) -> str:
150
+ if removed and not added and not modified:
151
+ return "removed"
152
+ if added and not modified and not removed:
153
+ return "added"
154
+ return "modified"
155
+
156
+
157
+ _MAX_METHODS = 12 # max method lines per class box to keep diagram size in check
158
+
159
+
160
+ def _emit_methods(
161
+ lines: list[str],
162
+ added: list,
163
+ modified: list,
164
+ removed: list,
165
+ indent: str = " ",
166
+ ) -> None:
167
+ """Append method lines to *lines*, truncating if the total exceeds _MAX_METHODS."""
168
+ all_lines: list[str] = (
169
+ [_added_line(fn) for fn in added]
170
+ + [_modified_line(fn) for fn in modified]
171
+ + [_removed_line(fn) for fn in removed]
172
+ )
173
+ shown = all_lines[:_MAX_METHODS]
174
+ rest = len(all_lines) - len(shown)
175
+ for ln in shown:
176
+ lines.append(f"{indent}{ln}")
177
+ if rest:
178
+ lines.append(f"{indent}... {rest} more")
179
+
180
+
181
+ # ── Renderer ──────────────────────────────────────────────────────────────────
182
+
183
+
184
+ def render_mermaid(result: AnalysisResult) -> str:
185
+
186
+ # ── Group changed functions by file β†’ class ───────────────────────────────
187
+ files: dict[str, dict] = defaultdict(
188
+ lambda: defaultdict(lambda: {"added": [], "modified": [], "removed": []})
189
+ )
190
+ for a_fn in result.added:
191
+ files[a_fn.file_path][a_fn.class_name]["added"].append(a_fn)
192
+ for m_fn in result.modified:
193
+ files[m_fn.file_path][m_fn.class_name]["modified"].append(m_fn)
194
+ for r_fn in result.removed:
195
+ files[r_fn.file_path][r_fn.class_name]["removed"].append(r_fn)
196
+
197
+ # ── Build fn_id β†’ diagram class ID (for edges) ───────────────────────────
198
+ fn_to_cid: dict[str, str] = {}
199
+ for a_fn in result.added:
200
+ fn_to_cid[a_fn.function_id] = (
201
+ _class_id(a_fn.file_path, a_fn.class_name)
202
+ if a_fn.class_name
203
+ else _mod_id(a_fn.file_path)
204
+ )
205
+ for m_fn in result.modified:
206
+ fn_to_cid[m_fn.function_id] = (
207
+ _class_id(m_fn.file_path, m_fn.class_name)
208
+ if m_fn.class_name
209
+ else _mod_id(m_fn.file_path)
210
+ )
211
+ for r_fn in result.removed:
212
+ fn_to_cid[r_fn.function_id] = (
213
+ _class_id(r_fn.file_path, r_fn.class_name)
214
+ if r_fn.class_name
215
+ else _mod_id(r_fn.file_path)
216
+ )
217
+ # ── Assign short sequential IDs to keep diagram size manageable ──────────
218
+ # Long sanitised IDs (e.g. cls__very__long__path__ClassName) are repeated
219
+ # in class defs, style commands, and every edge. Replacing them with n0,
220
+ # n1, … cuts 60-70 % off diagram size on large diffs, staying within
221
+ # GitHub's hard rendering limit.
222
+ _all_long_ids: list[str] = sorted(
223
+ {_mod_id(fp) for fp in files}
224
+ | {_class_id(fp, cn) for fp, classes in files.items() for cn in classes if cn is not None}
225
+ )
226
+ _short: dict[str, str] = {lid: f"n{i}" for i, lid in enumerate(_all_long_ids)}
227
+
228
+ def _sid(long_id: str) -> str:
229
+ return _short.get(long_id, long_id)
230
+
231
+ # Remap fn_to_cid to short IDs
232
+ fn_to_cid = {fid: _sid(cid) for fid, cid in fn_to_cid.items()}
233
+
234
+ # ── Build class-level edges first (needed for topo sort) ─────────────────
235
+ cid_to_fp: dict[str, str] = {}
236
+ for fp, classes in files.items():
237
+ for cn in classes:
238
+ long = _mod_id(fp) if cn is None else _class_id(fp, cn)
239
+ cid_to_fp[_sid(long)] = fp
240
+
241
+ edges: set[tuple[str, str]] = set()
242
+ removed_edges: set[tuple[str, str]] = set()
243
+
244
+ for a_fn in result.added:
245
+ src = fn_to_cid.get(a_fn.function_id)
246
+ for fid in a_fn.new_calls:
247
+ dst = fn_to_cid.get(fid)
248
+ if src and dst and src != dst:
249
+ edges.add((src, dst))
250
+ for fid in a_fn.new_callers:
251
+ caller = fn_to_cid.get(fid)
252
+ if caller and src and caller != src:
253
+ edges.add((caller, src))
254
+ for m_fn in result.modified:
255
+ src = fn_to_cid.get(m_fn.function_id)
256
+ for fid in m_fn.calls_added_new:
257
+ dst = fn_to_cid.get(fid)
258
+ if src and dst and src != dst:
259
+ edges.add((src, dst))
260
+ for fid in m_fn.calls_removed:
261
+ dst = fn_to_cid.get(fid)
262
+ if src and dst and src != dst:
263
+ removed_edges.add((src, dst))
264
+ for r_fn in result.removed:
265
+ src = fn_to_cid.get(r_fn.function_id)
266
+ for fid in r_fn.was_called_by:
267
+ caller = fn_to_cid.get(fid)
268
+ if caller and src and caller != src:
269
+ edges.add((caller, src))
270
+
271
+ # ── Build inheritance edges from class_parents ───────────────────────────
272
+ # Map class_name β†’ cid for all changed classes (to look up by name)
273
+ class_name_to_cid: dict[str, str] = {}
274
+ for fp, classes in files.items():
275
+ for cn in classes:
276
+ if cn is not None:
277
+ class_name_to_cid[cn] = _sid(_class_id(fp, cn))
278
+
279
+ inherit_edges: set[tuple[str, str]] = set()
280
+ if result.class_parents:
281
+ for class_id, parents in result.class_parents.items():
282
+ child_name = class_id.split(".")[-1]
283
+ child_cid = class_name_to_cid.get(child_name)
284
+ if not child_cid:
285
+ continue
286
+ for parent_name in parents:
287
+ parent_name = parent_name.split("[")[0].strip()
288
+ parent_cid = class_name_to_cid.get(parent_name)
289
+ if parent_cid and parent_cid != child_cid:
290
+ # Use short IDs β€” must match the remapped fn_to_cid/cid_to_fp
291
+ inherit_edges.add((_sid(child_cid), _sid(parent_cid)))
292
+
293
+ # ── Topo-sort namespaces (callers before callees) ────────────────────────
294
+ ns_edges: set[tuple[str, str]] = set()
295
+ for src, dst in edges:
296
+ sfp, dfp = cid_to_fp.get(src), cid_to_fp.get(dst)
297
+ if sfp and dfp and sfp != dfp:
298
+ ns_edges.add((sfp, dfp))
299
+
300
+ # Also propagate namespace ordering from inheritance
301
+ for src, dst in inherit_edges:
302
+ sfp, dfp = cid_to_fp.get(src), cid_to_fp.get(dst)
303
+ if sfp and dfp and sfp != dfp:
304
+ ns_edges.add((sfp, dfp))
305
+
306
+ # Split files into connected (appear in at least one cross-file edge) and
307
+ # isolated (no call/inheritance relationship with any other changed file).
308
+ fps_in_edges: set[str] = set()
309
+ for src, dst in edges | inherit_edges | removed_edges:
310
+ sfp, dfp = cid_to_fp.get(src), cid_to_fp.get(dst)
311
+ if sfp and dfp and sfp != dfp:
312
+ fps_in_edges.add(sfp)
313
+ fps_in_edges.add(dfp)
314
+
315
+ connected_fps = {fp for fp in files if fp in fps_in_edges}
316
+ isolated_fps = {fp for fp in files if fp not in fps_in_edges}
317
+
318
+ # Topo-sort the connected files by call direction
319
+ sorted_connected = _topo_sort(sorted(connected_fps), ns_edges)
320
+
321
+ # Group isolated files by immediate parent directory so related modules
322
+ # (e.g. migration versions) are emitted together in a namespace block.
323
+ isolated_by_dir: dict[str, list[str]] = defaultdict(list)
324
+ for fp in sorted(isolated_fps):
325
+ dirs = fp.split("/")[:-1] # path components excluding the filename
326
+ # Group by first 2 folder levels β€” the first folder is usually the
327
+ # top-level source root (backend/, src/, …), the second gives meaning.
328
+ key = "/".join(dirs[:2]) if len(dirs) >= 2 else (dirs[0] if dirs else ".")
329
+ isolated_by_dir[key].append(fp)
330
+
331
+ # ── Helper: emit one file's class boxes into caller-supplied lists ────────
332
+ emitted_ids: set[str] = set()
333
+
334
+ def _emit_file(
335
+ file_path: str,
336
+ out: list[str],
337
+ out_styles: list[str],
338
+ out_del: list[str],
339
+ out_del_styles: list[str],
340
+ indent: str = " ",
341
+ ) -> None:
342
+ changed = files[file_path]
343
+ file_cids = (
344
+ [_sid(_mod_id(file_path))]
345
+ if None in changed
346
+ and (changed[None]["added"] or changed[None]["modified"] or changed[None]["removed"])
347
+ else []
348
+ ) + [_sid(_class_id(file_path, cn)) for cn in changed if cn is not None]
349
+ intra = {
350
+ (s, d)
351
+ for s, d in edges
352
+ if cid_to_fp.get(s) == file_path and cid_to_fp.get(d) == file_path
353
+ }
354
+ for cid in _topo_sort(file_cids, intra):
355
+ if cid == _sid(_mod_id(file_path)):
356
+ sa = changed.get(None, {"added": [], "modified": [], "removed": []})
357
+ cs = _class_style(_dominant(sa["added"], sa["modified"], sa["removed"]))
358
+ if sa["added"] or sa["modified"]:
359
+ out.append(f'{indent}class {cid}["{file_path}"] {{')
360
+ _emit_methods(out, sa["added"], sa["modified"], [], indent + " ")
361
+ out.append(f"{indent}}}")
362
+ out_styles.append(f" style {cid} {cs}")
363
+ emitted_ids.add(cid)
364
+ if sa["removed"]:
365
+ del_cid = f"{cid}_d"
366
+ out_del.append(f' class {del_cid}["{file_path} (deleted)"] {{')
367
+ _emit_methods(out_del, [], [], sa["removed"])
368
+ out_del.append(" }")
369
+ out_del_styles.append(f" style {del_cid} {_S['removed']}")
370
+ emitted_ids.add(del_cid)
371
+ else:
372
+ class_name = next(
373
+ cn for cn in changed if cn is not None and _sid(_class_id(file_path, cn)) == cid
374
+ )
375
+ members = changed[class_name]
376
+ cs = _class_style(
377
+ _dominant(members["added"], members["modified"], members["removed"])
378
+ )
379
+ if members["added"] or members["modified"]:
380
+ out.append(f'{indent}class {cid}["{class_name}"] {{')
381
+ out.append(f"{indent} <<{file_path}>>")
382
+ _emit_methods(out, members["added"], members["modified"], [], indent + " ")
383
+ out.append(f"{indent}}}")
384
+ out_styles.append(f" style {cid} {cs}")
385
+ emitted_ids.add(cid)
386
+ if members["removed"]:
387
+ del_cid = f"{cid}_d"
388
+ out_del.append(f' class {del_cid}["{class_name} (deleted)"] {{')
389
+ out_del.append(f" <<{file_path}>>")
390
+ _emit_methods(out_del, [], [], members["removed"])
391
+ out_del.append(" }")
392
+ out_del_styles.append(f" style {del_cid} {_S['removed']}")
393
+ emitted_ids.add(del_cid)
394
+
395
+ # ── Diagram 1: connected modules β€” direction TB, with relationships ────────
396
+ d1_body: list[str] = []
397
+ d1_styles: list[str] = []
398
+ d1_del: list[str] = []
399
+ d1_del_styles: list[str] = []
400
+
401
+ for file_path in sorted_connected:
402
+ d1_body.append("")
403
+ _emit_file(file_path, d1_body, d1_styles, d1_del, d1_del_styles)
404
+
405
+ # Snapshot before isolated files add their IDs β€” edges must only reference
406
+ # nodes that appear in diagram 1.
407
+ d1_emitted_ids = set(emitted_ids)
408
+
409
+ # ── Diagram 2: isolated modules β€” direction TB, namespace-grouped ──────────
410
+ d2_body: list[str] = []
411
+ d2_styles: list[str] = []
412
+ d2_del: list[str] = []
413
+ d2_del_styles: list[str] = []
414
+
415
+ for dir_path, fps in sorted(isolated_by_dir.items()):
416
+ ns_id = dir_path.replace("/", "-").replace(".", "-") if dir_path != "." else "root"
417
+ d2_body.append("")
418
+ d2_body.append(f" namespace {ns_id} {{")
419
+ for file_path in fps:
420
+ _emit_file(file_path, d2_body, d2_styles, d2_del, d2_del_styles, indent=" ")
421
+ d2_body.append(" }")
422
+
423
+ # ── Build edge section (only for diagram 1 β€” isolated have no edges) ──────
424
+ def _valid(s: str, d: str) -> bool:
425
+ return s in d1_emitted_ids and d in d1_emitted_ids
426
+
427
+ call_edges = {
428
+ (s, d)
429
+ for s, d in edges
430
+ if _valid(s, d) and (s, d) not in inherit_edges and (d, s) not in inherit_edges
431
+ }
432
+ inherit_edges = {(s, d) for s, d in inherit_edges if _valid(s, d)}
433
+ removed_edges = {(s, d) for s, d in removed_edges if _valid(s, d)}
434
+
435
+ edge_lines: list[str] = []
436
+ if call_edges or removed_edges or inherit_edges:
437
+ edge_lines.append("")
438
+ edge_lines.append(" %% Relationships")
439
+ for src, dst in sorted(inherit_edges):
440
+ edge_lines.append(f" {src} --|> {dst}")
441
+ for src, dst in sorted(call_edges):
442
+ edge_lines.append(f" {src} --> {dst} : calls")
443
+ for src, dst in sorted(removed_edges - edges):
444
+ edge_lines.append(f" {src} ..> {dst} : removed")
445
+
446
+ # ── Assemble final output ─────────────────────────────────────────────────
447
+ def _build_diagram(
448
+ body: list[str],
449
+ styles: list[str],
450
+ del_body: list[str],
451
+ del_styles: list[str],
452
+ extra: list[str] | None = None,
453
+ init: str = _INIT,
454
+ ) -> str | None:
455
+ if not body and not del_body:
456
+ return None
457
+ out = ["```mermaid", init, "classDiagram", " direction LR"]
458
+ out.extend(body)
459
+ if del_body:
460
+ out.append("")
461
+ out.extend(del_body)
462
+ if styles or del_styles:
463
+ out.append("")
464
+ out.extend(styles)
465
+ out.extend(del_styles)
466
+ if extra:
467
+ out.extend(extra)
468
+ out.append("```")
469
+ return "\n".join(out)
470
+
471
+ diagrams = [
472
+ _build_diagram(d1_body, d1_styles, d1_del, d1_del_styles, edge_lines),
473
+ _build_diagram(d2_body, d2_styles, d2_del, d2_del_styles, init=_INIT_GRID),
474
+ ]
475
+ return "\n\n".join(d for d in diagrams if d is not None)