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,145 @@
1
+ """Derive structural facts from a GraphDiff.
2
+
3
+ Pure: takes GraphDiff + base/head GraphSnapshots, returns AnalysisResult.
4
+ No I/O, no DB access. Every fact is computed deterministically.
5
+ """
6
+
7
+ from collections import defaultdict
8
+
9
+ from codiff.schema.diff import (
10
+ AddedFunctionInfo,
11
+ AnalysisResult,
12
+ GraphDiff,
13
+ GraphSnapshot,
14
+ ModifiedFunctionInfo,
15
+ RemovedFunctionInfo,
16
+ SummaryStats,
17
+ )
18
+
19
+
20
+ def analyze(
21
+ diff: GraphDiff,
22
+ base: GraphSnapshot,
23
+ head: GraphSnapshot,
24
+ ) -> AnalysisResult:
25
+ added_ids = set(diff.added_nodes)
26
+
27
+ base_reverse = _reverse_index(base)
28
+ head_reverse = _reverse_index(head)
29
+
30
+ return AnalysisResult(
31
+ summary=_summary(diff),
32
+ added=_added(diff, added_ids, head, head_reverse),
33
+ modified=_modified(diff, added_ids, base, head, head_reverse),
34
+ removed=_removed(diff, base_reverse),
35
+ class_parents=head.class_parents,
36
+ )
37
+
38
+
39
+ def _reverse_index(snapshot: GraphSnapshot) -> dict[str, set[str]]:
40
+ """Build callee_id → {caller_ids}."""
41
+ rev: dict[str, set[str]] = defaultdict(set)
42
+ for caller_id, callee_id in snapshot.edges:
43
+ rev[callee_id].add(caller_id)
44
+ return dict(rev)
45
+
46
+
47
+ def _summary(diff: GraphDiff) -> SummaryStats:
48
+ touched: set[str] = set()
49
+ for node in diff.added_nodes.values():
50
+ touched.add(node.file_path)
51
+ for node in diff.removed_nodes.values():
52
+ touched.add(node.file_path)
53
+ for old, new in diff.modified_nodes.values():
54
+ touched.add(old.file_path)
55
+ touched.add(new.file_path)
56
+
57
+ return SummaryStats(
58
+ added_functions=len(diff.added_nodes),
59
+ removed_functions=len(diff.removed_nodes),
60
+ modified_functions=len(diff.modified_nodes),
61
+ modules_touched=sorted(touched),
62
+ )
63
+
64
+
65
+ def _added(
66
+ diff: GraphDiff,
67
+ added_ids: set[str],
68
+ head: GraphSnapshot,
69
+ head_reverse: dict[str, set[str]],
70
+ ) -> list[AddedFunctionInfo]:
71
+ result: list[AddedFunctionInfo] = []
72
+ for fid, node in sorted(diff.added_nodes.items()):
73
+ all_callers = sorted(head_reverse.get(fid, set()))
74
+ existing_callers = [c for c in all_callers if c not in added_ids]
75
+ new_callers = [c for c in all_callers if c in added_ids]
76
+
77
+ resolved_calls = [c for c in node.calls if c in head.nodes]
78
+ existing_calls = sorted(c for c in resolved_calls if c not in added_ids)
79
+ new_calls = sorted(c for c in resolved_calls if c in added_ids)
80
+
81
+ result.append(
82
+ AddedFunctionInfo(
83
+ function_id=fid,
84
+ file_path=node.file_path,
85
+ class_name=node.class_name,
86
+ existing_callers=existing_callers,
87
+ new_callers=new_callers,
88
+ existing_calls=existing_calls,
89
+ new_calls=new_calls,
90
+ is_entry_point=len(all_callers) == 0,
91
+ )
92
+ )
93
+ return result
94
+
95
+
96
+ def _modified(
97
+ diff: GraphDiff,
98
+ added_ids: set[str],
99
+ base: GraphSnapshot,
100
+ head: GraphSnapshot,
101
+ head_reverse: dict[str, set[str]],
102
+ ) -> list[ModifiedFunctionInfo]:
103
+ result: list[ModifiedFunctionInfo] = []
104
+ for fid, (old, new) in sorted(diff.modified_nodes.items()):
105
+ sig_changed = old.parameters != new.parameters or old.return_type != new.return_type
106
+
107
+ old_calls = set(old.calls)
108
+ new_calls_set = set(new.calls)
109
+ added_calls = sorted(c for c in (new_calls_set - old_calls) if c in head.nodes)
110
+ removed_calls = sorted(c for c in (old_calls - new_calls_set) if c in base.nodes)
111
+
112
+ result.append(
113
+ ModifiedFunctionInfo(
114
+ function_id=fid,
115
+ file_path=new.file_path,
116
+ class_name=new.class_name,
117
+ signature_changed=sig_changed,
118
+ old_params=old.parameters,
119
+ new_params=new.parameters,
120
+ old_return_type=old.return_type,
121
+ new_return_type=new.return_type,
122
+ calls_added_new=[c for c in added_calls if c in added_ids],
123
+ calls_added_existing=[c for c in added_calls if c not in added_ids],
124
+ calls_removed=removed_calls,
125
+ callers=sorted(head_reverse.get(fid, set())),
126
+ )
127
+ )
128
+ return result
129
+
130
+
131
+ def _removed(
132
+ diff: GraphDiff,
133
+ base_reverse: dict[str, set[str]],
134
+ ) -> list[RemovedFunctionInfo]:
135
+ result: list[RemovedFunctionInfo] = []
136
+ for fid, node in sorted(diff.removed_nodes.items()):
137
+ result.append(
138
+ RemovedFunctionInfo(
139
+ function_id=fid,
140
+ file_path=node.file_path,
141
+ class_name=node.class_name,
142
+ was_called_by=sorted(base_reverse.get(fid, set())),
143
+ )
144
+ )
145
+ return result
codiff/diff/differ.py ADDED
@@ -0,0 +1,45 @@
1
+ """Pure graph diff: diff two GraphSnapshots into a GraphDiff.
2
+
3
+ No I/O. Takes two GraphSnapshot objects and returns a GraphDiff describing
4
+ exactly what changed between them: added/removed/modified nodes and edges.
5
+
6
+ A node is "modified" if any of: code, parameters, return_type, calls, or
7
+ file_path changed. This includes pure implementation changes (same signature,
8
+ same call list) so blast-radius analysis sees the full change set.
9
+ """
10
+
11
+ from codiff.schema.diff import GraphDiff, GraphSnapshot, NodeInfo
12
+
13
+
14
+ def diff_snapshots(base: GraphSnapshot, head: GraphSnapshot) -> GraphDiff:
15
+ """Compute the structural delta between *base* and *head*."""
16
+ base_ids = set(base.nodes)
17
+ head_ids = set(head.nodes)
18
+
19
+ added_ids = head_ids - base_ids
20
+ removed_ids = base_ids - head_ids
21
+ common_ids = base_ids & head_ids
22
+
23
+ modified: dict[str, tuple[NodeInfo, NodeInfo]] = {}
24
+ for fid in common_ids:
25
+ b, h = base.nodes[fid], head.nodes[fid]
26
+ if _node_changed(b, h):
27
+ modified[fid] = (b, h)
28
+
29
+ return GraphDiff(
30
+ added_nodes={fid: head.nodes[fid] for fid in added_ids},
31
+ removed_nodes={fid: base.nodes[fid] for fid in removed_ids},
32
+ modified_nodes=modified,
33
+ added_edges=head.edges - base.edges,
34
+ removed_edges=base.edges - head.edges,
35
+ )
36
+
37
+
38
+ def _node_changed(base: NodeInfo, head: NodeInfo) -> bool:
39
+ return (
40
+ base.code != head.code
41
+ or base.parameters != head.parameters
42
+ or base.return_type != head.return_type
43
+ or base.calls != head.calls
44
+ or base.file_path != head.file_path
45
+ )
codiff/diff/engine.py ADDED
@@ -0,0 +1,80 @@
1
+ """Core diff computation — shared between CLI and MCP server."""
2
+
3
+ import logging
4
+ import os
5
+ import time
6
+
7
+ from codiff.utils.args import DEFAULT_WORKERS
8
+
9
+ log = logging.getLogger(__name__)
10
+
11
+
12
+ def compute_diff(
13
+ repo_path: str,
14
+ base_ref: str = "HEAD",
15
+ head_ref: str | None = None,
16
+ include_tests: bool = False,
17
+ include_deleted: bool = False,
18
+ max_workers: int = DEFAULT_WORKERS,
19
+ ):
20
+ from codiff.db import get_db_path
21
+ from codiff.diff.analysis import analyze
22
+ from codiff.diff.differ import diff_snapshots
23
+ from codiff.diff.indexer import ensure_indexed
24
+ from codiff.diff.snapshot import build_snapshot_incremental, load_from_db
25
+
26
+ repo_path = os.path.abspath(repo_path)
27
+ log.info("Diffing %s → %s", base_ref, head_ref or "working tree")
28
+
29
+ t = time.perf_counter()
30
+ db_sha = ensure_indexed(repo_path, "HEAD", max_workers=max_workers)
31
+ log.debug("[timing] ensure_indexed: %.2fs", time.perf_counter() - t)
32
+
33
+ db = get_db_path(repo_path)
34
+ t = time.perf_counter()
35
+ db_snapshot = load_from_db(db)
36
+ log.debug(
37
+ "[timing] load_from_db: %.2fs (%d nodes)", time.perf_counter() - t, len(db_snapshot.nodes)
38
+ )
39
+
40
+ t = time.perf_counter()
41
+ base = build_snapshot_incremental(
42
+ repo_path, db_snapshot, db_sha, base_ref, max_workers=max_workers
43
+ )
44
+ log.debug(
45
+ "[timing] build base snapshot: %.2fs (%d nodes)", time.perf_counter() - t, len(base.nodes)
46
+ )
47
+
48
+ t = time.perf_counter()
49
+ head = build_snapshot_incremental(
50
+ repo_path, db_snapshot, db_sha, head_ref, max_workers=max_workers
51
+ )
52
+ log.debug(
53
+ "[timing] build head snapshot: %.2fs (%d nodes)", time.perf_counter() - t, len(head.nodes)
54
+ )
55
+
56
+ t = time.perf_counter()
57
+ graph_diff = diff_snapshots(base, head)
58
+ log.debug(
59
+ "[timing] diff_snapshots: %.2fs (+%d -%d ~%d)",
60
+ time.perf_counter() - t,
61
+ len(graph_diff.added_nodes),
62
+ len(graph_diff.removed_nodes),
63
+ len(graph_diff.modified_nodes),
64
+ )
65
+
66
+ t = time.perf_counter()
67
+ result = analyze(graph_diff, base, head)
68
+ log.debug("[timing] analyze: %.2fs", time.perf_counter() - t)
69
+
70
+ if not include_tests:
71
+ from codiff.utils.files import is_test_file
72
+
73
+ result.added = [fn for fn in result.added if not is_test_file(fn.file_path)]
74
+ result.modified = [fn for fn in result.modified if not is_test_file(fn.file_path)]
75
+ result.removed = [fn for fn in result.removed if not is_test_file(fn.file_path)]
76
+
77
+ if not include_deleted:
78
+ result.removed = []
79
+
80
+ return result
codiff/diff/indexer.py ADDED
@@ -0,0 +1,134 @@
1
+ """Orchestrate git operations and DB indexing.
2
+
3
+ The only responsibilities here are:
4
+ - resolving git refs to SHAs
5
+ - extracting git archives to tmp directories
6
+ - deciding whether a full or incremental index is needed
7
+ - invoking parsers and delegating all DB writes to codiff.db.operations
8
+ """
9
+
10
+ import logging
11
+ import os
12
+ import tarfile
13
+ import tempfile
14
+
15
+ from codiff.db import get_db_path
16
+ from codiff.db.operations import (
17
+ get_indexed_sha,
18
+ load_snapshot,
19
+ update_sha,
20
+ write_full_snapshot,
21
+ write_incremental,
22
+ )
23
+ from codiff.utils.git import changed_files_between, git_archive, resolve_sha
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+ # Re-exports for backward compatibility with callers/tests that imported from here.
28
+ current_indexed_sha = get_indexed_sha
29
+
30
+
31
+ def ensure_indexed(repo_path: str, ref: str = "HEAD", max_workers: int = 4) -> str:
32
+ """Ensure .codiff.db is indexed at *ref*.
33
+
34
+ - Empty DB: full parse and index.
35
+ - SHA changed: incremental update (re-parse changed files + stale callers).
36
+ - Same SHA: no-op.
37
+
38
+ Returns the resolved commit SHA.
39
+ """
40
+ repo_path = os.path.abspath(repo_path)
41
+ db_path = get_db_path(repo_path)
42
+ sha = resolve_sha(repo_path, ref)
43
+ current = get_indexed_sha(db_path)
44
+ if current == sha:
45
+ logger.info("DB already at %s — skipping re-index", sha[:8])
46
+ return sha
47
+
48
+ if current is None:
49
+ logger.info("DB empty — full index of %s at %s", repo_path, sha[:8])
50
+ _full_index(repo_path, db_path, ref, sha, max_workers=max_workers)
51
+ else:
52
+ logger.info("DB at %s — incremental update to %s", current[:8], sha[:8])
53
+ _incremental_update_db(repo_path, db_path, current, sha, max_workers=max_workers)
54
+
55
+ return sha
56
+
57
+
58
+ # ---------------------------------------------------------------------------
59
+ # Internal helpers
60
+ # ---------------------------------------------------------------------------
61
+
62
+
63
+ def _full_index(repo_path: str, db_path: str, ref: str, sha: str, max_workers: int = 4) -> None:
64
+ """Extract the git ref to a tmpdir, parse it, write to DB."""
65
+ from codiff.languages import parse_repository
66
+
67
+ tar_archive = git_archive(repo_path, ref)
68
+ with tempfile.TemporaryDirectory(prefix="codiff_base_") as tmpdir:
69
+ with tarfile.open(fileobj=tar_archive) as tf:
70
+ tf.extractall(tmpdir, filter="data")
71
+ parsed = parse_repository(tmpdir, max_workers=max_workers)
72
+
73
+ write_full_snapshot(db_path, parsed, sha)
74
+ logger.info(
75
+ "Indexed %d functions, %d classes at %s",
76
+ len(parsed.functions),
77
+ len(parsed.classes),
78
+ sha[:8],
79
+ )
80
+
81
+
82
+ def _incremental_update_db(
83
+ repo_path: str, db_path: str, db_sha: str, new_sha: str, max_workers: int = 4
84
+ ) -> None:
85
+ """Update the DB from db_sha to HEAD incrementally.
86
+
87
+ Re-parses files changed between db_sha and HEAD. If function IDs were deleted
88
+ or renamed, also re-parses files whose call references became stale.
89
+ """
90
+ from codiff.diff.snapshot import _ClassStub, _NodeStub, _parse_and_expand_stale
91
+
92
+ changed_files = changed_files_between(repo_path, db_sha, "HEAD")
93
+ if not changed_files:
94
+ update_sha(db_path, new_sha)
95
+ return
96
+
97
+ logger.info(
98
+ "Incremental DB update: %d changed file(s) (%s → %s)",
99
+ len(changed_files),
100
+ db_sha[:8],
101
+ new_sha[:8],
102
+ )
103
+
104
+ db_snapshot = load_snapshot(db_path)
105
+ node_stubs = [_NodeStub(n) for n in db_snapshot.nodes.values()]
106
+ class_stubs = [_ClassStub(cid, supers) for cid, supers in db_snapshot.class_parents.items()]
107
+ old_ids_in_changed: set[str] = {
108
+ nid for nid, node in db_snapshot.nodes.items() if node.file_path in changed_files
109
+ }
110
+
111
+ tar_archive = git_archive(repo_path, "HEAD")
112
+ with tempfile.TemporaryDirectory(prefix="codiff_inc_") as tmpdir:
113
+ with tarfile.open(fileobj=tar_archive) as tf:
114
+ tf.extractall(tmpdir, filter="data")
115
+ fresh, files_to_update = _parse_and_expand_stale(
116
+ tmpdir,
117
+ set(changed_files),
118
+ old_ids_in_changed,
119
+ db_snapshot,
120
+ node_stubs,
121
+ class_stubs,
122
+ max_workers,
123
+ )
124
+
125
+ old_func_ids: set[str] = {
126
+ nid for nid, node in db_snapshot.nodes.items() if node.file_path in files_to_update
127
+ }
128
+ write_incremental(db_path, fresh, files_to_update, old_func_ids, new_sha)
129
+ logger.info(
130
+ "Incremental update done: %d functions across %d file(s), sha %s",
131
+ len(fresh.functions),
132
+ len(files_to_update),
133
+ new_sha[:8],
134
+ )