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,178 @@
1
+ """Python-specific call resolver.
2
+
3
+ PythonCallResolver extends BaseCallResolver with:
4
+ - C3 MRO linearisation (Python's multiple-inheritance algorithm)
5
+ - super().__init__() resolution with parent self-call inlining
6
+ - cls.xxx() / cls() resolution for classmethods
7
+
8
+ The module-level resolve_internal_calls() function is kept for
9
+ backward compatibility and uses PythonCallResolver.
10
+ """
11
+
12
+ from typing import Dict, List
13
+
14
+ from codiff.languages.resolver import BaseCallResolver
15
+
16
+
17
+ class PythonCallResolver(BaseCallResolver):
18
+ # ------------------------------------------------------------------
19
+ # BaseCallResolver abstract interface
20
+ # ------------------------------------------------------------------
21
+
22
+ @property
23
+ def instance_keyword(self) -> str:
24
+ return "self"
25
+
26
+ @property
27
+ def constructor_method_name(self) -> str:
28
+ return "__init__"
29
+
30
+ # ------------------------------------------------------------------
31
+ # MRO (C3 linearisation)
32
+ # ------------------------------------------------------------------
33
+
34
+ def _compute_mro(self, class_name: str) -> List[str]:
35
+ if class_name in self._mro_cache:
36
+ return self._mro_cache[class_name]
37
+
38
+ in_progress = self._mro_tls.__dict__.setdefault("in_progress", set())
39
+ if class_name in in_progress:
40
+ return [class_name]
41
+
42
+ if class_name not in self.class_id_map:
43
+ return [class_name]
44
+
45
+ class_obj = next((c for c in self.classes if c.name == class_name), None)
46
+ if not class_obj or not class_obj.superclasses:
47
+ mro = [class_name]
48
+ self._mro_cache[class_name] = mro
49
+ return mro
50
+
51
+ parents = [
52
+ n for s in class_obj.superclasses if (n := self._clean_superclass_name(s)) is not None
53
+ ]
54
+
55
+ in_progress.add(class_name)
56
+ try:
57
+ parent_mros = [self._compute_mro(p) for p in parents]
58
+ finally:
59
+ in_progress.discard(class_name)
60
+
61
+ filtered_parent_mros = [[c for c in mro if c != class_name] for mro in parent_mros]
62
+ filtered_parent_mros = [mro for mro in filtered_parent_mros if mro]
63
+
64
+ try:
65
+ mro = self._c3_merge([[class_name]] + filtered_parent_mros + [parents])
66
+ except ValueError:
67
+ mro = [class_name] + parents
68
+
69
+ self._mro_cache[class_name] = mro
70
+ return mro
71
+
72
+ def _c3_merge(self, sequences: List[List[str]]) -> List[str]:
73
+ result: list[str] = []
74
+ sequences = [list(s) for s in sequences]
75
+ while True:
76
+ sequences = [s for s in sequences if s]
77
+ if not sequences:
78
+ return result
79
+ candidate = None
80
+ for seq in sequences:
81
+ head = seq[0]
82
+ if not any(head in s[1:] for s in sequences):
83
+ candidate = head
84
+ break
85
+ if candidate is None:
86
+ raise ValueError("Inconsistent hierarchy")
87
+ result.append(candidate)
88
+ for seq in sequences:
89
+ if seq and seq[0] == candidate:
90
+ seq.pop(0)
91
+
92
+ # ------------------------------------------------------------------
93
+ # super() resolution with parent self-call inlining
94
+ # ------------------------------------------------------------------
95
+
96
+ def _resolve_super_call(self, parts: List[str], function) -> List[str]:
97
+ """Resolve super().__init__() / super().method() calls.
98
+
99
+ Also inlines the parent's self.xxx() calls re-resolved from the
100
+ child's MRO so that the child gets direct edges to overriding methods.
101
+ """
102
+ if not function.class_name or len(parts) < 2:
103
+ return []
104
+
105
+ method_name = parts[1]
106
+ class_obj = next((c for c in self.classes if c.name == function.class_name), None)
107
+ if not class_obj or not class_obj.superclasses:
108
+ return []
109
+
110
+ resolved = None
111
+ for superclass_name in class_obj.superclasses:
112
+ clean_name = self._clean_superclass_name(superclass_name)
113
+ if not clean_name:
114
+ continue
115
+ resolved = self._find_method_in_mro(clean_name, method_name)
116
+ if resolved:
117
+ break
118
+
119
+ if not resolved:
120
+ return []
121
+
122
+ results = [resolved]
123
+
124
+ parent_class = resolved.rsplit(".", 1)[0]
125
+ parent_self_methods = self.self_calls_by_func_id.get(resolved, [])
126
+ for method in parent_self_methods:
127
+ child_resolved = self._find_method_in_mro(function.class_name, method)
128
+ if not child_resolved or child_resolved in results:
129
+ continue
130
+ parent_resolved = self._find_method_in_mro(parent_class.rsplit(".", 1)[-1], method)
131
+ if child_resolved != parent_resolved:
132
+ results.append(child_resolved)
133
+
134
+ return results
135
+
136
+ # ------------------------------------------------------------------
137
+ # cls.xxx() / cls() resolution (Python classmethod pattern)
138
+ # ------------------------------------------------------------------
139
+
140
+ def _resolve_cls_call(self, parts: List[str], function) -> str | None:
141
+ if not function.class_name:
142
+ return None
143
+
144
+ if parts[0].startswith("cls("):
145
+ if len(parts) >= 2:
146
+ resolved = self._find_method_in_mro(function.class_name, parts[1])
147
+ if resolved:
148
+ return resolved
149
+ return self._find_init_for_class(function.class_name)
150
+
151
+ if len(parts) == 1:
152
+ return self._find_init_for_class(function.class_name)
153
+ else:
154
+ method_name = parts[1]
155
+ resolved = self._find_method_in_mro(function.class_name, method_name)
156
+ if resolved:
157
+ return resolved
158
+ file_path_key = self._file_path_to_module_key(function.file_path)
159
+ if file_path_key in self.modules_dict:
160
+ module_path = self.modules_dict[file_path_key]
161
+ return f"{module_path}.{function.class_name}.{method_name}"
162
+ return None
163
+
164
+
165
+ # Backward-compatible alias
166
+ CallResolver = PythonCallResolver
167
+
168
+
169
+ def resolve_internal_calls(
170
+ functions: List,
171
+ classes: List,
172
+ imports: Dict[str, str],
173
+ modules_dict: Dict[str, str],
174
+ package_exports: Dict[str, str] | None = None,
175
+ max_workers: int = 10,
176
+ ) -> List:
177
+ resolver = PythonCallResolver(functions, classes, imports, modules_dict, package_exports)
178
+ return resolver.resolve_all_calls(max_workers=max_workers)
@@ -0,0 +1,245 @@
1
+ """Language-agnostic entry point for parsing a repository.
2
+
3
+ parse_repository() is the single function callers use. It:
4
+ 1. Asks each registered parser to build its module-resolution dict
5
+ 2. Walks the repo and dispatches each file to the right parser by extension
6
+ 3. Resolves inter-file call references using each parser's own resolver
7
+ 4. Returns a ParsedRepository with all results
8
+
9
+ Adding a new language means creating a new LanguageParser subclass and
10
+ appending it to _PARSERS — no other file changes required.
11
+ """
12
+
13
+ import logging
14
+ import os
15
+ import time
16
+ from concurrent.futures import ProcessPoolExecutor
17
+ from pathlib import Path
18
+ from typing import NamedTuple
19
+
20
+ from codiff.languages.parser import LanguageParser
21
+ from codiff.languages.python.parser import PythonParser
22
+ from codiff.languages.typescript.parser import TypeScriptParser, TypeScriptXParser
23
+ from codiff.schema.parsing import ClassChunk, FunctionChunk
24
+ from codiff.utils.files import is_venv_dir
25
+ from codiff.utils.git import is_dir_ignored, load_gitignore
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ # Registry: add new LanguageParser subclasses here to support more languages
30
+ _PARSERS: list[LanguageParser] = [PythonParser(), TypeScriptParser(), TypeScriptXParser()]
31
+
32
+ # Worker-process globals — set once per process by _init_mp_worker().
33
+ # Using module-level globals avoids pickling modules_dict (130k entries) on
34
+ # every task; the initializer sends it once when the worker process starts.
35
+ _mp_ext_map: dict | None = None
36
+ _mp_modules_dict: dict | None = None
37
+
38
+
39
+ def _init_mp_worker(modules_dict: dict) -> None:
40
+ """Run once in each worker process: create per-process parsers and stash modules_dict."""
41
+ global _mp_ext_map, _mp_modules_dict
42
+ _mp_modules_dict = modules_dict
43
+ _mp_ext_map = {
44
+ p.extension: p for p in [PythonParser(), TypeScriptParser(), TypeScriptXParser()]
45
+ }
46
+
47
+
48
+ def _parse_file_mp(args: tuple) -> tuple | None:
49
+ """Parse one file in a worker process.
50
+
51
+ Returns (ext, rel, funcs, classes, imports, mod_doc) or None on error.
52
+ Reads modules_dict from the process-local global set by _init_mp_worker.
53
+ """
54
+ fpath, rel, ext = args
55
+ file_parser = _mp_ext_map.get(ext) # type: ignore[union-attr]
56
+ if file_parser is None:
57
+ return None
58
+ try:
59
+ src = Path(fpath).read_text(encoding="utf-8", errors="ignore")
60
+ funcs, classes, imports, mod_doc = file_parser.parse_code(src, rel, _mp_modules_dict)
61
+ return (ext, rel, funcs, classes, imports, mod_doc)
62
+ except Exception as exc:
63
+ logging.getLogger(__name__).warning("Parse error %s: %s", rel, exc)
64
+ return None
65
+
66
+
67
+ class ParsedRepository(NamedTuple):
68
+ """All parsed data for a repository — returned by parse_repository()."""
69
+
70
+ functions: list[FunctionChunk]
71
+ classes: list[ClassChunk]
72
+ module_docstrings: dict[str, str] # rel_path → docstring
73
+ class_docstrings: dict[str, str] # class_name → docstring
74
+ modules_dict: dict[str, str] # module alias → full module path
75
+ package_exports: dict[str, str] # re-exported name → real path
76
+
77
+
78
+ def parse_repository(
79
+ repo_path: str | Path,
80
+ gitignore=None,
81
+ max_workers: int = 4,
82
+ files_to_parse: set[str] | None = None,
83
+ extra_index_functions=None,
84
+ extra_index_classes=None,
85
+ ) -> ParsedRepository:
86
+ """Walk *repo_path*, parse every source file, resolve internal calls.
87
+
88
+ Each registered parser handles its own file extension. Call resolution
89
+ runs per-language so that imports from different languages do not bleed
90
+ into each other's resolution context. modules_dict and package_exports
91
+ are merged across languages (they are keyed by module path, which is
92
+ unique per file).
93
+
94
+ If *files_to_parse* is given, only those relative paths are parsed for
95
+ content (the module/export dicts are still built from the full walk).
96
+ *extra_index_functions* and *extra_index_classes* are duck-typed objects
97
+ that augment the resolver's lookup index without being re-resolved; only
98
+ the freshly parsed functions are resolved and returned.
99
+ """
100
+ repo = Path(repo_path)
101
+ if gitignore is None:
102
+ gitignore = load_gitignore(str(repo))
103
+
104
+ # Build combined module context and package exports from all parsers.
105
+ # Merging is safe because each parser only registers its own file extensions.
106
+ t0 = time.perf_counter()
107
+ modules_dict: dict[str, str] = {}
108
+ package_exports: dict[str, str] = {}
109
+ for parser in _PARSERS:
110
+ modules_dict.update(parser.build_modules_dict(repo, gitignore))
111
+ package_exports.update(parser.build_package_exports(repo, gitignore))
112
+ logger.debug(
113
+ "[timing] build module dict: %.2fs (%d entries)",
114
+ time.perf_counter() - t0,
115
+ len(modules_dict),
116
+ )
117
+
118
+ ext_map: dict[str, LanguageParser] = {p.extension: p for p in _PARSERS}
119
+
120
+ all_exclude_dirs: set[str] = set()
121
+ for parser in _PARSERS:
122
+ all_exclude_dirs.update(parser.exclude_dirs)
123
+
124
+ # Bucket by resolver class, not by file extension.
125
+ # .ts and .tsx share the same TypeScriptCallResolver so they must be grouped
126
+ # together — otherwise a .tsx component that instantiates a .ts class won't
127
+ # find the class in the resolver's all_class_names and loses the edge.
128
+ # Imports are still kept per-language (not per-extension) to prevent Python
129
+ # alias names from bleeding into the TypeScript resolution context.
130
+ resolver_cls_map: dict[type, type] = {p.resolver_class: p.resolver_class for p in _PARSERS}
131
+ ext_to_resolver: dict[str, type] = {p.extension: p.resolver_class for p in _PARSERS}
132
+ resolver_funcs: dict[type, list[FunctionChunk]] = {rc: [] for rc in resolver_cls_map}
133
+ resolver_classes: dict[type, list[ClassChunk]] = {rc: [] for rc in resolver_cls_map}
134
+ resolver_imports: dict[type, dict[str, str]] = {rc: {} for rc in resolver_cls_map}
135
+
136
+ # Map each resolver class to its set of file extensions (for index filtering).
137
+ resolver_cls_to_exts: dict[type, set[str]] = {}
138
+ for p in _PARSERS:
139
+ resolver_cls_to_exts.setdefault(p.resolver_class, set()).add(p.extension)
140
+
141
+ module_docstrings: dict[str, str] = {}
142
+ class_docstrings: dict[str, str] = {}
143
+ supported_exts = set(ext_map)
144
+
145
+ # Phase 1: walk the directory tree to collect files to parse (sequential, fast).
146
+ t0 = time.perf_counter()
147
+ pending: list[tuple] = []
148
+ for root, dirs, files in os.walk(str(repo)):
149
+ dirs[:] = sorted(
150
+ d
151
+ for d in dirs
152
+ if d not in all_exclude_dirs
153
+ and not is_venv_dir(root, d)
154
+ and not is_dir_ignored(gitignore, str(repo), root, d)
155
+ )
156
+ for fname in sorted(files):
157
+ ext = Path(fname).suffix
158
+ if ext not in supported_exts:
159
+ continue
160
+ fpath = Path(root) / fname
161
+ rel = str(fpath.relative_to(repo))
162
+ if files_to_parse is not None and rel not in files_to_parse:
163
+ continue
164
+ pending.append((fpath, rel, ext))
165
+ logger.debug(
166
+ "[timing] file walk (collect): %.2fs (%d files)", time.perf_counter() - t0, len(pending)
167
+ )
168
+
169
+ # Phase 2: parse files across worker processes for true CPU parallelism.
170
+ # modules_dict is sent once per worker via the initializer — not once per task.
171
+ # chunksize batches multiple files per IPC round-trip to reduce pickle overhead.
172
+ t0 = time.perf_counter()
173
+ chunksize = max(1, len(pending) // (max_workers * 8))
174
+ with ProcessPoolExecutor(
175
+ max_workers=max_workers,
176
+ initializer=_init_mp_worker,
177
+ initargs=(modules_dict,),
178
+ ) as pool:
179
+ for result in pool.map(_parse_file_mp, pending, chunksize=chunksize):
180
+ if result is None:
181
+ continue
182
+ ext, rel, funcs, classes, imports, mod_doc = result
183
+ resolver_cls = ext_to_resolver[ext]
184
+ if mod_doc:
185
+ module_docstrings[rel] = mod_doc
186
+ resolver_funcs[resolver_cls].extend(funcs)
187
+ resolver_classes[resolver_cls].extend(classes)
188
+ resolver_imports[resolver_cls].update(imports)
189
+ for cls in classes:
190
+ if cls.docstring:
191
+ class_docstrings[cls.name] = cls.docstring
192
+
193
+ n_fresh = sum(len(f) for f in resolver_funcs.values())
194
+ logger.debug(
195
+ "[timing] parse files (parallel, %d workers): %.2fs (%d functions, %d classes)",
196
+ max_workers,
197
+ time.perf_counter() - t0,
198
+ n_fresh,
199
+ sum(len(c) for c in resolver_classes.values()),
200
+ )
201
+
202
+ # Resolve calls per resolver class (groups all extensions that share a resolver).
203
+ all_resolved_functions: list[FunctionChunk] = []
204
+ for resolver_cls, funcs in resolver_funcs.items():
205
+ if not funcs and not extra_index_functions:
206
+ continue
207
+ classes = resolver_classes[resolver_cls]
208
+ imports = resolver_imports[resolver_cls]
209
+
210
+ t0 = time.perf_counter()
211
+ if extra_index_functions is not None:
212
+ # Incremental mode: augment the resolver's index with stubs from the
213
+ # base snapshot so that fresh functions can resolve calls to unchanged
214
+ # functions. Stubs have calls=[] so they are never re-resolved.
215
+ my_exts = resolver_cls_to_exts.get(resolver_cls, set())
216
+ index_funcs = [f for f in extra_index_functions if Path(f.file_path).suffix in my_exts]
217
+ # Class stubs have no file_path so pass all of them to every resolver;
218
+ # cross-language contamination is harmless in practice.
219
+ index_cls = list(extra_index_classes or [])
220
+ resolver = resolver_cls(
221
+ index_funcs + funcs, index_cls + classes, imports, modules_dict, package_exports
222
+ )
223
+ resolved = resolver.resolve_all_calls(max_workers=max_workers, resolve_subset=funcs)
224
+ else:
225
+ resolver = resolver_cls(funcs, classes, imports, modules_dict, package_exports)
226
+ resolved = resolver.resolve_all_calls(max_workers=max_workers)
227
+
228
+ logger.debug(
229
+ "[timing] resolve %s: %.2fs (%d functions)",
230
+ resolver_cls.__name__,
231
+ time.perf_counter() - t0,
232
+ len(resolved),
233
+ )
234
+ all_resolved_functions.extend(resolved)
235
+
236
+ all_classes = [cls for ext_classes in resolver_classes.values() for cls in ext_classes]
237
+
238
+ return ParsedRepository(
239
+ functions=all_resolved_functions,
240
+ classes=all_classes,
241
+ module_docstrings=module_docstrings,
242
+ class_docstrings=class_docstrings,
243
+ modules_dict=modules_dict,
244
+ package_exports=package_exports,
245
+ )