codegraphcontext-rust 0.9.24__cp314-cp314-win_amd64.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.
- codegraphcontext/__init__.py +2 -0
- codegraphcontext/__main__.py +5 -0
- codegraphcontext/_cgc_rust.cp314-win_amd64.pyd +4 -0
- codegraphcontext/cli/__init__.py +1 -0
- codegraphcontext/cli/cli_helpers.py +774 -0
- codegraphcontext/cli/config_manager.py +1051 -0
- codegraphcontext/cli/entry.py +21 -0
- codegraphcontext/cli/main.py +2386 -0
- codegraphcontext/cli/registry_commands.py +404 -0
- codegraphcontext/cli/setup_macos.py +93 -0
- codegraphcontext/cli/setup_wizard.py +991 -0
- codegraphcontext/cli/visualizer.py +50 -0
- codegraphcontext/core/__init__.py +165 -0
- codegraphcontext/core/bundle_registry.py +181 -0
- codegraphcontext/core/cgc_bundle.py +858 -0
- codegraphcontext/core/cgcignore.py +118 -0
- codegraphcontext/core/database.py +273 -0
- codegraphcontext/core/database_falkordb.py +480 -0
- codegraphcontext/core/database_falkordb_remote.py +199 -0
- codegraphcontext/core/database_kuzu.py +636 -0
- codegraphcontext/core/falkor_worker.py +132 -0
- codegraphcontext/core/jobs.py +132 -0
- codegraphcontext/core/watcher.py +260 -0
- codegraphcontext/prompts.py +125 -0
- codegraphcontext/server.py +471 -0
- codegraphcontext/tool_definitions.py +220 -0
- codegraphcontext/tools/__init__.py +0 -0
- codegraphcontext/tools/advanced_language_query_tool.py +103 -0
- codegraphcontext/tools/code_finder.py +1160 -0
- codegraphcontext/tools/graph_builder.py +337 -0
- codegraphcontext/tools/handlers/analysis_handlers.py +114 -0
- codegraphcontext/tools/handlers/indexing_handlers.py +116 -0
- codegraphcontext/tools/handlers/management_handlers.py +339 -0
- codegraphcontext/tools/handlers/query_handlers.py +83 -0
- codegraphcontext/tools/handlers/watcher_handlers.py +83 -0
- codegraphcontext/tools/indexing/__init__.py +1 -0
- codegraphcontext/tools/indexing/angular_routes.py +396 -0
- codegraphcontext/tools/indexing/cgc_wiki_cli.py +1334 -0
- codegraphcontext/tools/indexing/constants.py +70 -0
- codegraphcontext/tools/indexing/context_generator.py +461 -0
- codegraphcontext/tools/indexing/discovery.py +64 -0
- codegraphcontext/tools/indexing/engine.py +114 -0
- codegraphcontext/tools/indexing/execution_flows.py +355 -0
- codegraphcontext/tools/indexing/module_grouping.py +551 -0
- codegraphcontext/tools/indexing/noise_filter.py +131 -0
- codegraphcontext/tools/indexing/op_param_extraction.py +287 -0
- codegraphcontext/tools/indexing/persistence/__init__.py +3 -0
- codegraphcontext/tools/indexing/persistence/duckdb_writer.py +1116 -0
- codegraphcontext/tools/indexing/persistence/parquet_loader.py +643 -0
- codegraphcontext/tools/indexing/persistence/writer.py +1562 -0
- codegraphcontext/tools/indexing/pipeline.py +171 -0
- codegraphcontext/tools/indexing/pre_scan.py +105 -0
- codegraphcontext/tools/indexing/rationale_extraction.py +154 -0
- codegraphcontext/tools/indexing/resolution/__init__.py +8 -0
- codegraphcontext/tools/indexing/resolution/calls.py +253 -0
- codegraphcontext/tools/indexing/resolution/inheritance.py +91 -0
- codegraphcontext/tools/indexing/route_extraction.py +659 -0
- codegraphcontext/tools/indexing/sanitize.py +41 -0
- codegraphcontext/tools/indexing/schema.py +79 -0
- codegraphcontext/tools/indexing/schema_contract.py +44 -0
- codegraphcontext/tools/indexing/scip_pipeline.py +140 -0
- codegraphcontext/tools/languages/c.py +563 -0
- codegraphcontext/tools/languages/cpp.py +616 -0
- codegraphcontext/tools/languages/csharp.py +551 -0
- codegraphcontext/tools/languages/dart.py +378 -0
- codegraphcontext/tools/languages/elixir.py +460 -0
- codegraphcontext/tools/languages/go.py +499 -0
- codegraphcontext/tools/languages/haskell.py +426 -0
- codegraphcontext/tools/languages/java.py +500 -0
- codegraphcontext/tools/languages/javascript.py +589 -0
- codegraphcontext/tools/languages/kotlin.py +640 -0
- codegraphcontext/tools/languages/perl.py +260 -0
- codegraphcontext/tools/languages/php.py +519 -0
- codegraphcontext/tools/languages/python.py +578 -0
- codegraphcontext/tools/languages/ruby.py +537 -0
- codegraphcontext/tools/languages/rust.py +295 -0
- codegraphcontext/tools/languages/scala.py +519 -0
- codegraphcontext/tools/languages/swift.py +491 -0
- codegraphcontext/tools/languages/typescript.py +606 -0
- codegraphcontext/tools/languages/typescriptjsx.py +151 -0
- codegraphcontext/tools/package_resolver.py +472 -0
- codegraphcontext/tools/query_tool_languages/c_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/cpp_toolkit.py +87 -0
- codegraphcontext/tools/query_tool_languages/csharp_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/dart_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/go_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/haskell_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/java_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/javascript_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/perl_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/python_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/ruby_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/rust_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/scala_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/swift_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/typescript_toolkit.py +5 -0
- codegraphcontext/tools/scip_indexer.py +467 -0
- codegraphcontext/tools/scip_pb2.py +2455 -0
- codegraphcontext/tools/system.py +133 -0
- codegraphcontext/tools/tree_sitter_parser.py +103 -0
- codegraphcontext/utils/debug_log.py +90 -0
- codegraphcontext/utils/path_ignore.py +55 -0
- codegraphcontext/utils/repo_path.py +27 -0
- codegraphcontext/utils/tree_sitter_manager.py +285 -0
- codegraphcontext/utils/visualize_graph.py +0 -0
- codegraphcontext/viz/server.py +282 -0
- codegraphcontext_rust-0.9.24.dist-info/METADATA +543 -0
- codegraphcontext_rust-0.9.24.dist-info/RECORD +112 -0
- codegraphcontext_rust-0.9.24.dist-info/WHEEL +4 -0
- codegraphcontext_rust-0.9.24.dist-info/entry_points.txt +4 -0
- codegraphcontext_rust-0.9.24.dist-info/licenses/LICENSE +21 -0
- codegraphcontext_rust-0.9.24.dist-info/sboms/cgc-python.cyclonedx.json +2302 -0
|
@@ -0,0 +1,1562 @@
|
|
|
1
|
+
"""All graph DB writes for indexing (single persistence entry point)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple
|
|
8
|
+
|
|
9
|
+
from ....utils.debug_log import info_logger, warning_logger
|
|
10
|
+
from ..sanitize import sanitize_props
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class GraphWriter:
|
|
14
|
+
"""Persists repository/file/symbol nodes and relationships via the Neo4j-like driver API."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, driver: Any):
|
|
17
|
+
self.driver = driver
|
|
18
|
+
|
|
19
|
+
def add_repository_to_graph(self, repo_path: Path, is_dependency: bool = False) -> None:
|
|
20
|
+
repo_name = repo_path.name
|
|
21
|
+
repo_path_str = str(repo_path.resolve())
|
|
22
|
+
with self.driver.session() as session:
|
|
23
|
+
session.run(
|
|
24
|
+
"""
|
|
25
|
+
MERGE (r:Repository {path: $path})
|
|
26
|
+
SET r.name = $name, r.is_dependency = $is_dependency
|
|
27
|
+
""",
|
|
28
|
+
path=repo_path_str,
|
|
29
|
+
name=repo_name,
|
|
30
|
+
is_dependency=is_dependency,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
def add_file_to_graph(
|
|
34
|
+
self,
|
|
35
|
+
file_data: Dict[str, Any],
|
|
36
|
+
repo_name: str,
|
|
37
|
+
imports_map: dict,
|
|
38
|
+
repo_path_str: Optional[str] = None,
|
|
39
|
+
) -> None:
|
|
40
|
+
file_path_str = str(Path(file_data["path"]).resolve())
|
|
41
|
+
file_name = Path(file_path_str).name
|
|
42
|
+
is_dependency = file_data.get("is_dependency", False)
|
|
43
|
+
lang = file_data.get("lang")
|
|
44
|
+
|
|
45
|
+
with self.driver.session() as session:
|
|
46
|
+
if repo_path_str:
|
|
47
|
+
resolved_repo_str = repo_path_str
|
|
48
|
+
else:
|
|
49
|
+
repo_result = session.run(
|
|
50
|
+
"MATCH (r:Repository {path: $repo_path}) RETURN r.path as path",
|
|
51
|
+
repo_path=str(Path(file_data["repo_path"]).resolve()),
|
|
52
|
+
).single()
|
|
53
|
+
resolved_repo_str = (
|
|
54
|
+
repo_result["path"] if repo_result else str(Path(file_data["repo_path"]).resolve())
|
|
55
|
+
)
|
|
56
|
+
if not repo_result:
|
|
57
|
+
warning_logger(
|
|
58
|
+
f"Repository node not found for {file_data['repo_path']} during indexing of {file_name}."
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
try:
|
|
62
|
+
relative_path = str(Path(file_path_str).relative_to(Path(resolved_repo_str)))
|
|
63
|
+
except ValueError:
|
|
64
|
+
relative_path = file_name
|
|
65
|
+
|
|
66
|
+
session.run(
|
|
67
|
+
"""
|
|
68
|
+
MERGE (f:File {path: $path})
|
|
69
|
+
SET f.name = $name, f.relative_path = $relative_path, f.is_dependency = $is_dependency
|
|
70
|
+
""",
|
|
71
|
+
path=file_path_str,
|
|
72
|
+
name=file_name,
|
|
73
|
+
relative_path=relative_path,
|
|
74
|
+
is_dependency=is_dependency,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
file_path_obj = Path(file_path_str)
|
|
78
|
+
repo_path_obj = Path(resolved_repo_str)
|
|
79
|
+
relative_path_to_file = file_path_obj.relative_to(repo_path_obj)
|
|
80
|
+
parent_path = resolved_repo_str
|
|
81
|
+
parent_label = "Repository"
|
|
82
|
+
for part in relative_path_to_file.parts[:-1]:
|
|
83
|
+
current_path_str = str(Path(parent_path) / part)
|
|
84
|
+
session.run(
|
|
85
|
+
f"""
|
|
86
|
+
MATCH (p:{parent_label} {{path: $parent_path}})
|
|
87
|
+
MERGE (d:Directory {{path: $current_path}})
|
|
88
|
+
SET d.name = $part
|
|
89
|
+
MERGE (p)-[:CONTAINS]->(d)
|
|
90
|
+
""",
|
|
91
|
+
parent_path=parent_path,
|
|
92
|
+
current_path=current_path_str,
|
|
93
|
+
part=part,
|
|
94
|
+
)
|
|
95
|
+
parent_path = current_path_str
|
|
96
|
+
parent_label = "Directory"
|
|
97
|
+
session.run(
|
|
98
|
+
f"""
|
|
99
|
+
MATCH (p:{parent_label} {{path: $parent_path}})
|
|
100
|
+
MATCH (f:File {{path: $path}})
|
|
101
|
+
MERGE (p)-[:CONTAINS]->(f)
|
|
102
|
+
""",
|
|
103
|
+
parent_path=parent_path,
|
|
104
|
+
path=file_path_str,
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
item_mappings = [
|
|
108
|
+
(file_data.get("functions", []), "Function"),
|
|
109
|
+
(file_data.get("classes", []), "Class"),
|
|
110
|
+
(file_data.get("traits", []), "Trait"),
|
|
111
|
+
(file_data.get("variables", []), "Variable"),
|
|
112
|
+
(file_data.get("interfaces", []), "Interface"),
|
|
113
|
+
(file_data.get("macros", []), "Macro"),
|
|
114
|
+
(file_data.get("structs", []), "Struct"),
|
|
115
|
+
(file_data.get("enums", []), "Enum"),
|
|
116
|
+
(file_data.get("unions", []), "Union"),
|
|
117
|
+
(file_data.get("records", []), "Record"),
|
|
118
|
+
(file_data.get("properties", []), "Property"),
|
|
119
|
+
]
|
|
120
|
+
params_batch: List[Dict[str, Any]] = []
|
|
121
|
+
class_fn_batch: List[Dict[str, Any]] = []
|
|
122
|
+
nested_fn_batch: List[Dict[str, Any]] = []
|
|
123
|
+
|
|
124
|
+
for item_list, label in item_mappings:
|
|
125
|
+
if not item_list:
|
|
126
|
+
continue
|
|
127
|
+
batch: List[Dict[str, Any]] = []
|
|
128
|
+
for item in item_list:
|
|
129
|
+
row = dict(item)
|
|
130
|
+
if label == "Function" and "cyclomatic_complexity" not in row:
|
|
131
|
+
row["cyclomatic_complexity"] = 1
|
|
132
|
+
batch.append(sanitize_props(row))
|
|
133
|
+
if label == "Function":
|
|
134
|
+
for arg_name in item.get("args", []):
|
|
135
|
+
params_batch.append(
|
|
136
|
+
{
|
|
137
|
+
"func_name": item["name"],
|
|
138
|
+
"line_number": item["line_number"],
|
|
139
|
+
"arg_name": arg_name,
|
|
140
|
+
}
|
|
141
|
+
)
|
|
142
|
+
if item.get("class_context"):
|
|
143
|
+
class_fn_batch.append(
|
|
144
|
+
{
|
|
145
|
+
"class_name": item["class_context"],
|
|
146
|
+
"func_name": item["name"],
|
|
147
|
+
"func_line": item["line_number"],
|
|
148
|
+
}
|
|
149
|
+
)
|
|
150
|
+
if item.get("context_type") == "function_definition":
|
|
151
|
+
nested_fn_batch.append(
|
|
152
|
+
{
|
|
153
|
+
"outer": item["context"],
|
|
154
|
+
"inner_name": item["name"],
|
|
155
|
+
"inner_line": item["line_number"],
|
|
156
|
+
}
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
if batch:
|
|
160
|
+
import json as _json
|
|
161
|
+
|
|
162
|
+
all_keys = set()
|
|
163
|
+
for b in batch:
|
|
164
|
+
all_keys.update(b.keys())
|
|
165
|
+
|
|
166
|
+
for k in all_keys:
|
|
167
|
+
counts: Dict[str, int] = {}
|
|
168
|
+
for b in batch:
|
|
169
|
+
v = b.get(k)
|
|
170
|
+
if v is not None:
|
|
171
|
+
tname = type(v).__name__
|
|
172
|
+
counts[tname] = counts.get(tname, 0) + 1
|
|
173
|
+
|
|
174
|
+
dominant = max(counts, key=counts.get) if counts else "str"
|
|
175
|
+
|
|
176
|
+
for b in batch:
|
|
177
|
+
v = b.get(k)
|
|
178
|
+
if dominant == "list":
|
|
179
|
+
if isinstance(v, list):
|
|
180
|
+
b[k] = [str(x) for x in v] if v else [""]
|
|
181
|
+
elif isinstance(v, str) and v:
|
|
182
|
+
try:
|
|
183
|
+
p = _json.loads(v)
|
|
184
|
+
b[k] = [str(x) for x in p] if isinstance(p, list) and p else [""]
|
|
185
|
+
except Exception:
|
|
186
|
+
b[k] = [v]
|
|
187
|
+
else:
|
|
188
|
+
b[k] = [""]
|
|
189
|
+
elif dominant == "int":
|
|
190
|
+
if v is None or v == "":
|
|
191
|
+
b[k] = 0
|
|
192
|
+
elif not isinstance(v, int):
|
|
193
|
+
try:
|
|
194
|
+
b[k] = int(v)
|
|
195
|
+
except Exception:
|
|
196
|
+
b[k] = 0
|
|
197
|
+
elif dominant == "bool":
|
|
198
|
+
b[k] = bool(v) if v is not None else False
|
|
199
|
+
else:
|
|
200
|
+
if v is None:
|
|
201
|
+
b[k] = ""
|
|
202
|
+
elif isinstance(v, list):
|
|
203
|
+
b[k] = _json.dumps(v)
|
|
204
|
+
elif not isinstance(v, str):
|
|
205
|
+
b[k] = str(v)
|
|
206
|
+
|
|
207
|
+
key_order = sorted(all_keys)
|
|
208
|
+
batch[:] = [{k: b[k] for k in key_order} for b in batch]
|
|
209
|
+
|
|
210
|
+
session.run(
|
|
211
|
+
f"""
|
|
212
|
+
UNWIND $batch AS row
|
|
213
|
+
MERGE (n:{label} {{name: row.name, path: $file_path, line_number: row.line_number}})
|
|
214
|
+
SET n += row
|
|
215
|
+
""",
|
|
216
|
+
batch=batch,
|
|
217
|
+
file_path=file_path_str,
|
|
218
|
+
)
|
|
219
|
+
session.run(
|
|
220
|
+
f"""
|
|
221
|
+
UNWIND $batch AS row
|
|
222
|
+
MATCH (f:File {{path: $file_path}})
|
|
223
|
+
MATCH (n:{label} {{name: row.name, path: $file_path, line_number: row.line_number}})
|
|
224
|
+
MERGE (f)-[:CONTAINS]->(n)
|
|
225
|
+
""",
|
|
226
|
+
batch=batch,
|
|
227
|
+
file_path=file_path_str,
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
if params_batch:
|
|
231
|
+
session.run(
|
|
232
|
+
"""
|
|
233
|
+
UNWIND $batch AS row
|
|
234
|
+
MATCH (fn:Function {name: row.func_name, path: $file_path, line_number: row.line_number})
|
|
235
|
+
MERGE (p:Parameter {name: row.arg_name, path: $file_path, function_line_number: row.line_number})
|
|
236
|
+
MERGE (fn)-[:HAS_PARAMETER]->(p)
|
|
237
|
+
""",
|
|
238
|
+
batch=params_batch,
|
|
239
|
+
file_path=file_path_str,
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
if class_fn_batch:
|
|
243
|
+
session.run(
|
|
244
|
+
"""
|
|
245
|
+
UNWIND $batch AS row
|
|
246
|
+
MATCH (c:Class {name: row.class_name, path: $file_path})
|
|
247
|
+
MATCH (fn:Function {name: row.func_name, path: $file_path, line_number: row.func_line})
|
|
248
|
+
MERGE (c)-[:CONTAINS]->(fn)
|
|
249
|
+
""",
|
|
250
|
+
batch=class_fn_batch,
|
|
251
|
+
file_path=file_path_str,
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
if nested_fn_batch:
|
|
255
|
+
session.run(
|
|
256
|
+
"""
|
|
257
|
+
UNWIND $batch AS row
|
|
258
|
+
MATCH (outer:Function {name: row.outer, path: $file_path})
|
|
259
|
+
MATCH (inner:Function {name: row.inner_name, path: $file_path, line_number: row.inner_line})
|
|
260
|
+
MERGE (outer)-[:CONTAINS]->(inner)
|
|
261
|
+
""",
|
|
262
|
+
batch=nested_fn_batch,
|
|
263
|
+
file_path=file_path_str,
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
ruby_modules = file_data.get("modules", [])
|
|
267
|
+
if ruby_modules:
|
|
268
|
+
session.run(
|
|
269
|
+
"""
|
|
270
|
+
UNWIND $batch AS row
|
|
271
|
+
MERGE (mod:Module {name: row.name})
|
|
272
|
+
ON CREATE SET mod.lang = row.lang
|
|
273
|
+
ON MATCH SET mod.lang = coalesce(mod.lang, row.lang)
|
|
274
|
+
""",
|
|
275
|
+
batch=[{"name": m["name"], "lang": lang} for m in ruby_modules],
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
js_imports = []
|
|
279
|
+
other_imports = []
|
|
280
|
+
for imp in file_data.get("imports", []):
|
|
281
|
+
if lang == "javascript":
|
|
282
|
+
module_name = imp.get("source")
|
|
283
|
+
if module_name:
|
|
284
|
+
js_imports.append(
|
|
285
|
+
{
|
|
286
|
+
"module_name": module_name,
|
|
287
|
+
"imported_name": imp.get("name", "*"),
|
|
288
|
+
"alias": imp.get("alias"),
|
|
289
|
+
"line_number": imp.get("line_number"),
|
|
290
|
+
}
|
|
291
|
+
)
|
|
292
|
+
else:
|
|
293
|
+
other_imports.append(imp)
|
|
294
|
+
|
|
295
|
+
if js_imports:
|
|
296
|
+
session.run(
|
|
297
|
+
"""
|
|
298
|
+
UNWIND $batch AS row
|
|
299
|
+
MATCH (f:File {path: $file_path})
|
|
300
|
+
MERGE (m:Module {name: row.module_name})
|
|
301
|
+
MERGE (f)-[r:IMPORTS]->(m)
|
|
302
|
+
SET r.imported_name = row.imported_name,
|
|
303
|
+
r.alias = row.alias,
|
|
304
|
+
r.line_number = row.line_number
|
|
305
|
+
""",
|
|
306
|
+
batch=js_imports,
|
|
307
|
+
file_path=file_path_str,
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
if other_imports:
|
|
311
|
+
session.run(
|
|
312
|
+
"""
|
|
313
|
+
UNWIND $batch AS row
|
|
314
|
+
MATCH (f:File {path: $file_path})
|
|
315
|
+
MERGE (m:Module {name: row.name})
|
|
316
|
+
SET m.alias = row.alias,
|
|
317
|
+
m.full_import_name = coalesce(row.full_import_name, m.full_import_name)
|
|
318
|
+
MERGE (f)-[r:IMPORTS]->(m)
|
|
319
|
+
SET r.line_number = row.line_number,
|
|
320
|
+
r.alias = row.alias
|
|
321
|
+
""",
|
|
322
|
+
batch=other_imports,
|
|
323
|
+
file_path=file_path_str,
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
module_inclusions = file_data.get("module_inclusions", [])
|
|
327
|
+
if module_inclusions:
|
|
328
|
+
session.run(
|
|
329
|
+
"""
|
|
330
|
+
UNWIND $batch AS row
|
|
331
|
+
MATCH (c:Class {name: row.class_name, path: $file_path})
|
|
332
|
+
MERGE (m:Module {name: row.module_name})
|
|
333
|
+
MERGE (c)-[:INCLUDES]->(m)
|
|
334
|
+
""",
|
|
335
|
+
batch=[
|
|
336
|
+
{"class_name": i["class"], "module_name": i["module"]} for i in module_inclusions
|
|
337
|
+
],
|
|
338
|
+
file_path=file_path_str,
|
|
339
|
+
)
|
|
340
|
+
|
|
341
|
+
# ── Batch write (10-20x faster than per-file add_file_to_graph) ──────────
|
|
342
|
+
|
|
343
|
+
def add_files_batch_to_graph(
|
|
344
|
+
self,
|
|
345
|
+
all_file_data: List[Dict[str, Any]],
|
|
346
|
+
repo_name: str,
|
|
347
|
+
imports_map: dict,
|
|
348
|
+
repo_path_str: str,
|
|
349
|
+
on_progress: Optional[Callable] = None,
|
|
350
|
+
) -> int:
|
|
351
|
+
"""Write all parsed files to graph in batched queries.
|
|
352
|
+
|
|
353
|
+
Instead of N×12 individual queries, this runs ~12 batched UNWIND
|
|
354
|
+
queries total, reducing KuzuDB transaction overhead dramatically.
|
|
355
|
+
|
|
356
|
+
Returns the number of files successfully written.
|
|
357
|
+
"""
|
|
358
|
+
import json as _json
|
|
359
|
+
|
|
360
|
+
repo_path_obj = Path(repo_path_str)
|
|
361
|
+
total = len(all_file_data)
|
|
362
|
+
|
|
363
|
+
# ── Collect all data into flat batches ──────────────────────────
|
|
364
|
+
file_batch = []
|
|
365
|
+
dir_batch = [] # (parent_path, parent_label, dir_path, dir_name)
|
|
366
|
+
file_parent_batch = [] # (parent_path, parent_label, file_path)
|
|
367
|
+
symbol_batches: Dict[str, List[Dict]] = {} # label → [rows]
|
|
368
|
+
symbol_file_batches: Dict[str, List[Dict]] = {} # label → [(file_path, name, line)]
|
|
369
|
+
params_batch = []
|
|
370
|
+
class_fn_batch = []
|
|
371
|
+
nested_fn_batch = []
|
|
372
|
+
js_imports_batch = []
|
|
373
|
+
other_imports_batch = []
|
|
374
|
+
|
|
375
|
+
for idx, file_data in enumerate(all_file_data):
|
|
376
|
+
file_path_str = str(Path(file_data["path"]).resolve())
|
|
377
|
+
file_name = Path(file_path_str).name
|
|
378
|
+
is_dep = file_data.get("is_dependency", False)
|
|
379
|
+
lang = file_data.get("lang")
|
|
380
|
+
|
|
381
|
+
try:
|
|
382
|
+
rel_path = str(Path(file_path_str).relative_to(repo_path_obj))
|
|
383
|
+
except ValueError:
|
|
384
|
+
rel_path = file_name
|
|
385
|
+
|
|
386
|
+
file_batch.append({
|
|
387
|
+
"path": file_path_str, "name": file_name,
|
|
388
|
+
"relative_path": rel_path, "is_dependency": is_dep,
|
|
389
|
+
})
|
|
390
|
+
|
|
391
|
+
# Directory chain
|
|
392
|
+
try:
|
|
393
|
+
rel_to_file = Path(file_path_str).relative_to(repo_path_obj)
|
|
394
|
+
except ValueError:
|
|
395
|
+
rel_to_file = Path(file_name)
|
|
396
|
+
|
|
397
|
+
parent_path = repo_path_str
|
|
398
|
+
parent_label = "Repository"
|
|
399
|
+
for part in rel_to_file.parts[:-1]:
|
|
400
|
+
cur = str(Path(parent_path) / part)
|
|
401
|
+
dir_batch.append({
|
|
402
|
+
"parent_path": parent_path, "parent_label": parent_label,
|
|
403
|
+
"dir_path": cur, "dir_name": part,
|
|
404
|
+
})
|
|
405
|
+
parent_path = cur
|
|
406
|
+
parent_label = "Directory"
|
|
407
|
+
file_parent_batch.append({
|
|
408
|
+
"parent_path": parent_path, "parent_label": parent_label,
|
|
409
|
+
"file_path": file_path_str,
|
|
410
|
+
})
|
|
411
|
+
|
|
412
|
+
# Symbols
|
|
413
|
+
item_mappings = [
|
|
414
|
+
(file_data.get("functions", []), "Function"),
|
|
415
|
+
(file_data.get("classes", []), "Class"),
|
|
416
|
+
(file_data.get("traits", []), "Trait"),
|
|
417
|
+
(file_data.get("variables", []), "Variable"),
|
|
418
|
+
(file_data.get("interfaces", []), "Interface"),
|
|
419
|
+
(file_data.get("macros", []), "Macro"),
|
|
420
|
+
(file_data.get("structs", []), "Struct"),
|
|
421
|
+
(file_data.get("enums", []), "Enum"),
|
|
422
|
+
(file_data.get("unions", []), "Union"),
|
|
423
|
+
(file_data.get("records", []), "Record"),
|
|
424
|
+
(file_data.get("properties", []), "Property"),
|
|
425
|
+
]
|
|
426
|
+
|
|
427
|
+
for item_list, label in item_mappings:
|
|
428
|
+
if not item_list:
|
|
429
|
+
continue
|
|
430
|
+
if label not in symbol_batches:
|
|
431
|
+
symbol_batches[label] = []
|
|
432
|
+
symbol_file_batches[label] = []
|
|
433
|
+
for item in item_list:
|
|
434
|
+
row = dict(item)
|
|
435
|
+
row["_file_path"] = file_path_str
|
|
436
|
+
if label == "Function" and "cyclomatic_complexity" not in row:
|
|
437
|
+
row["cyclomatic_complexity"] = 1
|
|
438
|
+
symbol_batches[label].append(sanitize_props(row))
|
|
439
|
+
symbol_file_batches[label].append({
|
|
440
|
+
"file_path": file_path_str,
|
|
441
|
+
"name": item["name"],
|
|
442
|
+
"line_number": item["line_number"],
|
|
443
|
+
})
|
|
444
|
+
|
|
445
|
+
if label == "Function":
|
|
446
|
+
for arg_name in item.get("args", []):
|
|
447
|
+
params_batch.append({
|
|
448
|
+
"func_name": item["name"],
|
|
449
|
+
"line_number": item["line_number"],
|
|
450
|
+
"arg_name": arg_name,
|
|
451
|
+
"file_path": file_path_str,
|
|
452
|
+
})
|
|
453
|
+
if item.get("class_context"):
|
|
454
|
+
class_fn_batch.append({
|
|
455
|
+
"class_name": item["class_context"],
|
|
456
|
+
"func_name": item["name"],
|
|
457
|
+
"func_line": item["line_number"],
|
|
458
|
+
"file_path": file_path_str,
|
|
459
|
+
})
|
|
460
|
+
if item.get("context_type") == "function_definition":
|
|
461
|
+
nested_fn_batch.append({
|
|
462
|
+
"outer": item["context"],
|
|
463
|
+
"inner_name": item["name"],
|
|
464
|
+
"inner_line": item["line_number"],
|
|
465
|
+
"file_path": file_path_str,
|
|
466
|
+
})
|
|
467
|
+
|
|
468
|
+
# Imports
|
|
469
|
+
for imp in file_data.get("imports", []):
|
|
470
|
+
if lang == "javascript":
|
|
471
|
+
module_name = imp.get("source")
|
|
472
|
+
if module_name:
|
|
473
|
+
js_imports_batch.append({
|
|
474
|
+
"module_name": module_name,
|
|
475
|
+
"imported_name": imp.get("name", "*"),
|
|
476
|
+
"alias": imp.get("alias"),
|
|
477
|
+
"line_number": imp.get("line_number"),
|
|
478
|
+
"file_path": file_path_str,
|
|
479
|
+
})
|
|
480
|
+
else:
|
|
481
|
+
other_imports_batch.append({
|
|
482
|
+
"name": imp.get("name", ""),
|
|
483
|
+
"alias": imp.get("alias"),
|
|
484
|
+
"full_import_name": imp.get("full_import_name", imp.get("name", "")),
|
|
485
|
+
"line_number": imp.get("line_number"),
|
|
486
|
+
"file_path": file_path_str,
|
|
487
|
+
})
|
|
488
|
+
|
|
489
|
+
# ── Execute batched queries ─────────────────────────────────────
|
|
490
|
+
if on_progress:
|
|
491
|
+
on_progress(0, total, "Writing files to graph...")
|
|
492
|
+
|
|
493
|
+
batch_size = 500
|
|
494
|
+
|
|
495
|
+
with self.driver.session() as session:
|
|
496
|
+
# 1. Files
|
|
497
|
+
for i in range(0, len(file_batch), batch_size):
|
|
498
|
+
session.run(
|
|
499
|
+
"UNWIND $batch AS row "
|
|
500
|
+
"MERGE (f:File {path: row.path}) "
|
|
501
|
+
"SET f.name = row.name, f.relative_path = row.relative_path, "
|
|
502
|
+
" f.is_dependency = row.is_dependency",
|
|
503
|
+
batch=file_batch[i:i + batch_size],
|
|
504
|
+
)
|
|
505
|
+
|
|
506
|
+
if on_progress:
|
|
507
|
+
on_progress(total // 4, total, "Writing directories...")
|
|
508
|
+
|
|
509
|
+
# 2. Directories (grouped by parent_label to avoid dynamic labels)
|
|
510
|
+
for plabel in ("Repository", "Directory"):
|
|
511
|
+
subset = [d for d in dir_batch if d["parent_label"] == plabel]
|
|
512
|
+
for i in range(0, len(subset), batch_size):
|
|
513
|
+
chunk = [{k: v for k, v in d.items() if k != "parent_label"} for d in subset[i:i + batch_size]]
|
|
514
|
+
session.run(
|
|
515
|
+
f"UNWIND $batch AS row "
|
|
516
|
+
f"MATCH (p:{plabel} {{path: row.parent_path}}) "
|
|
517
|
+
f"MERGE (d:Directory {{path: row.dir_path}}) "
|
|
518
|
+
f"SET d.name = row.dir_name "
|
|
519
|
+
f"MERGE (p)-[:CONTAINS]->(d)",
|
|
520
|
+
batch=chunk,
|
|
521
|
+
)
|
|
522
|
+
|
|
523
|
+
# 3. File-parent CONTAINS
|
|
524
|
+
for plabel in ("Repository", "Directory"):
|
|
525
|
+
subset = [d for d in file_parent_batch if d["parent_label"] == plabel]
|
|
526
|
+
for i in range(0, len(subset), batch_size):
|
|
527
|
+
chunk = [{k: v for k, v in d.items() if k != "parent_label"} for d in subset[i:i + batch_size]]
|
|
528
|
+
session.run(
|
|
529
|
+
f"UNWIND $batch AS row "
|
|
530
|
+
f"MATCH (p:{plabel} {{path: row.parent_path}}) "
|
|
531
|
+
f"MATCH (f:File {{path: row.file_path}}) "
|
|
532
|
+
f"MERGE (p)-[:CONTAINS]->(f)",
|
|
533
|
+
batch=chunk,
|
|
534
|
+
)
|
|
535
|
+
|
|
536
|
+
if on_progress:
|
|
537
|
+
on_progress(total // 2, total, "Writing symbols...")
|
|
538
|
+
|
|
539
|
+
# 4. Symbols (per label)
|
|
540
|
+
for label, batch in symbol_batches.items():
|
|
541
|
+
# Normalize types across batch
|
|
542
|
+
all_keys = set()
|
|
543
|
+
for b in batch:
|
|
544
|
+
all_keys.update(b.keys())
|
|
545
|
+
all_keys.discard("_file_path")
|
|
546
|
+
|
|
547
|
+
for k in all_keys:
|
|
548
|
+
counts: Dict[str, int] = {}
|
|
549
|
+
for b in batch:
|
|
550
|
+
v = b.get(k)
|
|
551
|
+
if v is not None:
|
|
552
|
+
tname = type(v).__name__
|
|
553
|
+
counts[tname] = counts.get(tname, 0) + 1
|
|
554
|
+
dominant = max(counts, key=counts.get) if counts else "str"
|
|
555
|
+
|
|
556
|
+
for b in batch:
|
|
557
|
+
v = b.get(k)
|
|
558
|
+
if dominant == "list":
|
|
559
|
+
if isinstance(v, list):
|
|
560
|
+
b[k] = [str(x) for x in v] if v else [""]
|
|
561
|
+
elif isinstance(v, str) and v:
|
|
562
|
+
try:
|
|
563
|
+
p = _json.loads(v)
|
|
564
|
+
b[k] = [str(x) for x in p] if isinstance(p, list) and p else [""]
|
|
565
|
+
except Exception:
|
|
566
|
+
b[k] = [v]
|
|
567
|
+
else:
|
|
568
|
+
b[k] = [""]
|
|
569
|
+
elif dominant == "int":
|
|
570
|
+
if v is None or v == "":
|
|
571
|
+
b[k] = 0
|
|
572
|
+
elif not isinstance(v, int):
|
|
573
|
+
try:
|
|
574
|
+
b[k] = int(v)
|
|
575
|
+
except Exception:
|
|
576
|
+
b[k] = 0
|
|
577
|
+
elif dominant == "bool":
|
|
578
|
+
b[k] = bool(v) if v is not None else False
|
|
579
|
+
else:
|
|
580
|
+
if v is None:
|
|
581
|
+
b[k] = ""
|
|
582
|
+
elif isinstance(v, list):
|
|
583
|
+
b[k] = _json.dumps(v)
|
|
584
|
+
elif not isinstance(v, str):
|
|
585
|
+
b[k] = str(v)
|
|
586
|
+
|
|
587
|
+
key_order = sorted(all_keys)
|
|
588
|
+
normalized = []
|
|
589
|
+
file_paths_for_batch = []
|
|
590
|
+
for b in batch:
|
|
591
|
+
fp = b.pop("_file_path", "")
|
|
592
|
+
normalized.append({k: b[k] for k in key_order if k in b})
|
|
593
|
+
file_paths_for_batch.append(fp)
|
|
594
|
+
|
|
595
|
+
# Deduplicate by (name, path, line_number) — minified JS can
|
|
596
|
+
# produce duplicates which violate KuzuDB primary key constraint
|
|
597
|
+
seen_keys = set()
|
|
598
|
+
deduped = []
|
|
599
|
+
deduped_fps = []
|
|
600
|
+
for row, fp in zip(normalized, file_paths_for_batch):
|
|
601
|
+
key = (row.get("name", ""), fp, row.get("line_number", 0))
|
|
602
|
+
if key not in seen_keys:
|
|
603
|
+
seen_keys.add(key)
|
|
604
|
+
deduped.append(row)
|
|
605
|
+
deduped_fps.append(fp)
|
|
606
|
+
normalized = deduped
|
|
607
|
+
file_paths_for_batch = deduped_fps
|
|
608
|
+
|
|
609
|
+
# Write symbols in chunks
|
|
610
|
+
for i in range(0, len(normalized), batch_size):
|
|
611
|
+
chunk = normalized[i:i + batch_size]
|
|
612
|
+
fps = file_paths_for_batch[i:i + batch_size]
|
|
613
|
+
# Add file_path back for MERGE key
|
|
614
|
+
for row, fp in zip(chunk, fps):
|
|
615
|
+
row["_fp"] = fp
|
|
616
|
+
|
|
617
|
+
session.run(
|
|
618
|
+
f"UNWIND $batch AS row "
|
|
619
|
+
f"MERGE (n:{label} {{name: row.name, path: row._fp, line_number: row.line_number}}) "
|
|
620
|
+
f"SET n += row",
|
|
621
|
+
batch=chunk,
|
|
622
|
+
)
|
|
623
|
+
session.run(
|
|
624
|
+
f"UNWIND $batch AS row "
|
|
625
|
+
f"MATCH (f:File {{path: row._fp}}) "
|
|
626
|
+
f"MATCH (n:{label} {{name: row.name, path: row._fp, line_number: row.line_number}}) "
|
|
627
|
+
f"MERGE (f)-[:CONTAINS]->(n)",
|
|
628
|
+
batch=chunk,
|
|
629
|
+
)
|
|
630
|
+
|
|
631
|
+
if on_progress:
|
|
632
|
+
on_progress(total * 3 // 4, total, "Writing relationships...")
|
|
633
|
+
|
|
634
|
+
# 5. Parameters
|
|
635
|
+
if params_batch:
|
|
636
|
+
for i in range(0, len(params_batch), batch_size):
|
|
637
|
+
session.run(
|
|
638
|
+
"UNWIND $batch AS row "
|
|
639
|
+
"MATCH (fn:Function {name: row.func_name, path: row.file_path, line_number: row.line_number}) "
|
|
640
|
+
"MERGE (p:Parameter {name: row.arg_name, path: row.file_path, function_line_number: row.line_number}) "
|
|
641
|
+
"MERGE (fn)-[:HAS_PARAMETER]->(p)",
|
|
642
|
+
batch=params_batch[i:i + batch_size],
|
|
643
|
+
)
|
|
644
|
+
|
|
645
|
+
# 6. Class-function containment
|
|
646
|
+
if class_fn_batch:
|
|
647
|
+
for i in range(0, len(class_fn_batch), batch_size):
|
|
648
|
+
session.run(
|
|
649
|
+
"UNWIND $batch AS row "
|
|
650
|
+
"MATCH (c:Class {name: row.class_name, path: row.file_path}) "
|
|
651
|
+
"MATCH (fn:Function {name: row.func_name, path: row.file_path, line_number: row.func_line}) "
|
|
652
|
+
"MERGE (c)-[:CONTAINS]->(fn)",
|
|
653
|
+
batch=class_fn_batch[i:i + batch_size],
|
|
654
|
+
)
|
|
655
|
+
|
|
656
|
+
# 7. Nested functions
|
|
657
|
+
if nested_fn_batch:
|
|
658
|
+
for i in range(0, len(nested_fn_batch), batch_size):
|
|
659
|
+
session.run(
|
|
660
|
+
"UNWIND $batch AS row "
|
|
661
|
+
"MATCH (outer:Function {name: row.outer, path: row.file_path}) "
|
|
662
|
+
"MATCH (inner:Function {name: row.inner_name, path: row.file_path, line_number: row.inner_line}) "
|
|
663
|
+
"MERGE (outer)-[:CONTAINS]->(inner)",
|
|
664
|
+
batch=nested_fn_batch[i:i + batch_size],
|
|
665
|
+
)
|
|
666
|
+
|
|
667
|
+
# 8. JS imports
|
|
668
|
+
if js_imports_batch:
|
|
669
|
+
for i in range(0, len(js_imports_batch), batch_size):
|
|
670
|
+
session.run(
|
|
671
|
+
"UNWIND $batch AS row "
|
|
672
|
+
"MATCH (f:File {path: row.file_path}) "
|
|
673
|
+
"MERGE (m:Module {name: row.module_name}) "
|
|
674
|
+
"MERGE (f)-[r:IMPORTS]->(m) "
|
|
675
|
+
"SET r.imported_name = row.imported_name, r.alias = row.alias, r.line_number = row.line_number",
|
|
676
|
+
batch=js_imports_batch[i:i + batch_size],
|
|
677
|
+
)
|
|
678
|
+
|
|
679
|
+
# 9. Other imports
|
|
680
|
+
if other_imports_batch:
|
|
681
|
+
for i in range(0, len(other_imports_batch), batch_size):
|
|
682
|
+
session.run(
|
|
683
|
+
"UNWIND $batch AS row "
|
|
684
|
+
"MATCH (f:File {path: row.file_path}) "
|
|
685
|
+
"MERGE (m:Module {name: row.name}) "
|
|
686
|
+
"SET m.alias = row.alias, m.full_import_name = coalesce(row.full_import_name, m.full_import_name) "
|
|
687
|
+
"MERGE (f)-[r:IMPORTS]->(m) "
|
|
688
|
+
"SET r.line_number = row.line_number, r.alias = row.alias",
|
|
689
|
+
batch=other_imports_batch[i:i + batch_size],
|
|
690
|
+
)
|
|
691
|
+
|
|
692
|
+
if on_progress:
|
|
693
|
+
on_progress(total, total, "Graph write complete")
|
|
694
|
+
|
|
695
|
+
return len(file_batch)
|
|
696
|
+
|
|
697
|
+
# ── Fast batch write using CREATE (for initial indexing on empty DB) ──────
|
|
698
|
+
|
|
699
|
+
def add_files_batch_to_graph_fast(
|
|
700
|
+
self,
|
|
701
|
+
all_file_data: List[Dict[str, Any]],
|
|
702
|
+
repo_name: str,
|
|
703
|
+
imports_map: dict,
|
|
704
|
+
repo_path_str: str,
|
|
705
|
+
on_progress: Optional[Callable] = None,
|
|
706
|
+
) -> int:
|
|
707
|
+
"""Write all parsed files using CREATE instead of MERGE.
|
|
708
|
+
|
|
709
|
+
~5-10x faster than MERGE-based batch writer because CREATE skips
|
|
710
|
+
the index lookup that MERGE needs. Only safe on an empty DB
|
|
711
|
+
(initial indexing, not incremental updates).
|
|
712
|
+
|
|
713
|
+
Falls back to add_files_batch_to_graph on any error.
|
|
714
|
+
"""
|
|
715
|
+
import json as _json
|
|
716
|
+
|
|
717
|
+
repo_path_obj = Path(repo_path_str)
|
|
718
|
+
total = len(all_file_data)
|
|
719
|
+
batch_size = 2000 # larger batches safe for CREATE (no scan)
|
|
720
|
+
|
|
721
|
+
# ── Collect ──────────────────────────────────────────────────
|
|
722
|
+
file_batch = []
|
|
723
|
+
dir_set: Dict[str, Dict] = {} # path → {name, parent_path, parent_label}
|
|
724
|
+
symbol_batches: Dict[str, List[Dict]] = {}
|
|
725
|
+
params_batch = []
|
|
726
|
+
class_fn_batch = []
|
|
727
|
+
nested_fn_batch = []
|
|
728
|
+
js_imports_batch = []
|
|
729
|
+
other_imports_batch = []
|
|
730
|
+
|
|
731
|
+
for idx, file_data in enumerate(all_file_data):
|
|
732
|
+
file_path_str = str(Path(file_data["path"]).resolve())
|
|
733
|
+
file_name = Path(file_path_str).name
|
|
734
|
+
is_dep = file_data.get("is_dependency", False)
|
|
735
|
+
lang = file_data.get("lang")
|
|
736
|
+
|
|
737
|
+
try:
|
|
738
|
+
rel_path = str(Path(file_path_str).relative_to(repo_path_obj))
|
|
739
|
+
except ValueError:
|
|
740
|
+
rel_path = file_name
|
|
741
|
+
|
|
742
|
+
file_batch.append({
|
|
743
|
+
"path": file_path_str, "name": file_name,
|
|
744
|
+
"relative_path": rel_path, "is_dependency": is_dep,
|
|
745
|
+
})
|
|
746
|
+
|
|
747
|
+
# Directory chain (deduplicated via dict)
|
|
748
|
+
try:
|
|
749
|
+
rel_to_file = Path(file_path_str).relative_to(repo_path_obj)
|
|
750
|
+
except ValueError:
|
|
751
|
+
rel_to_file = Path(file_name)
|
|
752
|
+
|
|
753
|
+
parent_path = repo_path_str
|
|
754
|
+
parent_label = "Repository"
|
|
755
|
+
for part in rel_to_file.parts[:-1]:
|
|
756
|
+
dir_path = str(Path(parent_path) / part)
|
|
757
|
+
if dir_path not in dir_set:
|
|
758
|
+
dir_set[dir_path] = {
|
|
759
|
+
"dir_path": dir_path, "dir_name": part,
|
|
760
|
+
"parent_path": parent_path, "parent_label": parent_label,
|
|
761
|
+
"file_path": file_path_str,
|
|
762
|
+
}
|
|
763
|
+
parent_path = dir_path
|
|
764
|
+
parent_label = "Directory"
|
|
765
|
+
|
|
766
|
+
# Symbols
|
|
767
|
+
for label, items_key in [
|
|
768
|
+
("Function", "functions"), ("Class", "classes"),
|
|
769
|
+
("Variable", "variables"),
|
|
770
|
+
]:
|
|
771
|
+
for sym in file_data.get(items_key, []):
|
|
772
|
+
row = {
|
|
773
|
+
"name": sym.get("name", ""),
|
|
774
|
+
"path": file_path_str,
|
|
775
|
+
"line_number": sym.get("line_number", 0),
|
|
776
|
+
"_fp": file_path_str,
|
|
777
|
+
}
|
|
778
|
+
# Copy known props
|
|
779
|
+
for k in ("decorators", "complexity", "return_type",
|
|
780
|
+
"docstring", "class_context", "bases",
|
|
781
|
+
"is_async", "is_generator", "body_start_line",
|
|
782
|
+
"body_end_line", "type"):
|
|
783
|
+
v = sym.get(k)
|
|
784
|
+
if v is not None:
|
|
785
|
+
if isinstance(v, list):
|
|
786
|
+
row[k] = [str(x) for x in v] if v else [""]
|
|
787
|
+
elif isinstance(v, bool):
|
|
788
|
+
row[k] = v
|
|
789
|
+
elif isinstance(v, int):
|
|
790
|
+
row[k] = v
|
|
791
|
+
else:
|
|
792
|
+
row[k] = str(v)
|
|
793
|
+
symbol_batches.setdefault(label, []).append(row)
|
|
794
|
+
|
|
795
|
+
# Parameters for functions
|
|
796
|
+
if label == "Function":
|
|
797
|
+
for arg in sym.get("args", []):
|
|
798
|
+
arg_name = arg if isinstance(arg, str) else str(arg)
|
|
799
|
+
if arg_name:
|
|
800
|
+
params_batch.append({
|
|
801
|
+
"arg_name": arg_name,
|
|
802
|
+
"file_path": file_path_str,
|
|
803
|
+
"func_name": sym.get("name", ""),
|
|
804
|
+
"line_number": sym.get("line_number", 0),
|
|
805
|
+
})
|
|
806
|
+
|
|
807
|
+
# Class-function containment
|
|
808
|
+
ctx = sym.get("class_context")
|
|
809
|
+
if ctx:
|
|
810
|
+
class_fn_batch.append({
|
|
811
|
+
"class_name": ctx,
|
|
812
|
+
"func_name": sym.get("name", ""),
|
|
813
|
+
"file_path": file_path_str,
|
|
814
|
+
"func_line": sym.get("line_number", 0),
|
|
815
|
+
})
|
|
816
|
+
|
|
817
|
+
# Nested functions
|
|
818
|
+
parent_ctx = sym.get("parent_function")
|
|
819
|
+
if parent_ctx:
|
|
820
|
+
nested_fn_batch.append({
|
|
821
|
+
"outer": parent_ctx,
|
|
822
|
+
"inner_name": sym.get("name", ""),
|
|
823
|
+
"inner_line": sym.get("line_number", 0),
|
|
824
|
+
"file_path": file_path_str,
|
|
825
|
+
})
|
|
826
|
+
|
|
827
|
+
# Imports
|
|
828
|
+
for imp in file_data.get("imports", []):
|
|
829
|
+
imp_name = imp.get("name", "")
|
|
830
|
+
source = imp.get("source", "")
|
|
831
|
+
alias = imp.get("alias", "")
|
|
832
|
+
full_name = imp.get("full_import_name", "") or source or imp_name
|
|
833
|
+
line_no = imp.get("line_number", 0)
|
|
834
|
+
if lang in ("javascript", "typescript", "tsx", "jsx"):
|
|
835
|
+
js_imports_batch.append({
|
|
836
|
+
"file_path": file_path_str,
|
|
837
|
+
"module_name": source or imp_name,
|
|
838
|
+
"imported_name": imp_name,
|
|
839
|
+
"alias": alias or "",
|
|
840
|
+
"line_number": line_no,
|
|
841
|
+
})
|
|
842
|
+
else:
|
|
843
|
+
other_imports_batch.append({
|
|
844
|
+
"file_path": file_path_str,
|
|
845
|
+
"name": full_name or imp_name,
|
|
846
|
+
"alias": alias or "",
|
|
847
|
+
"full_import_name": full_name or "",
|
|
848
|
+
"line_number": line_no,
|
|
849
|
+
})
|
|
850
|
+
|
|
851
|
+
# ── Write with CREATE ────────────────────────────────────────
|
|
852
|
+
if on_progress:
|
|
853
|
+
on_progress(0, total, "Fast writing files...")
|
|
854
|
+
|
|
855
|
+
try:
|
|
856
|
+
with self.driver.session() as session:
|
|
857
|
+
# 1. Files — CREATE (no MERGE needed, DB is empty)
|
|
858
|
+
for i in range(0, len(file_batch), batch_size):
|
|
859
|
+
session.run(
|
|
860
|
+
"UNWIND $batch AS row "
|
|
861
|
+
"CREATE (f:File {path: row.path, name: row.name, "
|
|
862
|
+
"relative_path: row.relative_path, is_dependency: row.is_dependency})",
|
|
863
|
+
batch=file_batch[i:i + batch_size],
|
|
864
|
+
)
|
|
865
|
+
|
|
866
|
+
if on_progress:
|
|
867
|
+
on_progress(total // 4, total, "Fast writing directories...")
|
|
868
|
+
|
|
869
|
+
# 2. Directories — CREATE + CONTAINS in one query
|
|
870
|
+
dir_list = list(dir_set.values())
|
|
871
|
+
for plabel in ("Repository", "Directory"):
|
|
872
|
+
subset = [d for d in dir_list if d["parent_label"] == plabel]
|
|
873
|
+
for i in range(0, len(subset), batch_size):
|
|
874
|
+
chunk = subset[i:i + batch_size]
|
|
875
|
+
session.run(
|
|
876
|
+
f"UNWIND $batch AS row "
|
|
877
|
+
f"MATCH (p:{plabel} {{path: row.parent_path}}) "
|
|
878
|
+
f"CREATE (d:Directory {{path: row.dir_path, name: row.dir_name}}) "
|
|
879
|
+
f"CREATE (p)-[:CONTAINS]->(d)",
|
|
880
|
+
batch=chunk,
|
|
881
|
+
)
|
|
882
|
+
|
|
883
|
+
# 3. File→parent CONTAINS
|
|
884
|
+
file_parent = []
|
|
885
|
+
for fd in file_batch:
|
|
886
|
+
fp = fd["path"]
|
|
887
|
+
try:
|
|
888
|
+
rel = Path(fp).relative_to(repo_path_obj)
|
|
889
|
+
parts = rel.parts[:-1]
|
|
890
|
+
except ValueError:
|
|
891
|
+
parts = ()
|
|
892
|
+
if parts:
|
|
893
|
+
parent_p = str(repo_path_obj / Path(*parts))
|
|
894
|
+
file_parent.append({"parent_path": parent_p, "file_path": fp, "plabel": "Directory"})
|
|
895
|
+
else:
|
|
896
|
+
file_parent.append({"parent_path": repo_path_str, "file_path": fp, "plabel": "Repository"})
|
|
897
|
+
|
|
898
|
+
for plabel in ("Repository", "Directory"):
|
|
899
|
+
subset = [d for d in file_parent if d["plabel"] == plabel]
|
|
900
|
+
for i in range(0, len(subset), batch_size):
|
|
901
|
+
session.run(
|
|
902
|
+
f"UNWIND $batch AS row "
|
|
903
|
+
f"MATCH (p:{plabel} {{path: row.parent_path}}) "
|
|
904
|
+
f"MATCH (f:File {{path: row.file_path}}) "
|
|
905
|
+
f"CREATE (p)-[:CONTAINS]->(f)",
|
|
906
|
+
batch=subset[i:i + batch_size],
|
|
907
|
+
)
|
|
908
|
+
|
|
909
|
+
if on_progress:
|
|
910
|
+
on_progress(total // 2, total, "Fast writing symbols...")
|
|
911
|
+
|
|
912
|
+
# 4. Symbols — CREATE symbol + CONTAINS in single query
|
|
913
|
+
for label, batch in symbol_batches.items():
|
|
914
|
+
# Deduplicate by (name, path, line_number)
|
|
915
|
+
seen = set()
|
|
916
|
+
deduped = []
|
|
917
|
+
for row in batch:
|
|
918
|
+
key = (row.get("name", ""), row.get("path", ""), row.get("line_number", 0))
|
|
919
|
+
if key not in seen:
|
|
920
|
+
seen.add(key)
|
|
921
|
+
deduped.append(row)
|
|
922
|
+
|
|
923
|
+
# Normalize types
|
|
924
|
+
if deduped:
|
|
925
|
+
all_keys = set()
|
|
926
|
+
for b in deduped:
|
|
927
|
+
all_keys.update(k for k in b.keys() if k != "_fp")
|
|
928
|
+
|
|
929
|
+
for k in all_keys:
|
|
930
|
+
counts: Dict[str, int] = {}
|
|
931
|
+
for b in deduped:
|
|
932
|
+
v = b.get(k)
|
|
933
|
+
if v is not None:
|
|
934
|
+
tname = type(v).__name__
|
|
935
|
+
counts[tname] = counts.get(tname, 0) + 1
|
|
936
|
+
dominant = max(counts, key=counts.get) if counts else "str"
|
|
937
|
+
|
|
938
|
+
for b in deduped:
|
|
939
|
+
v = b.get(k)
|
|
940
|
+
if dominant == "list":
|
|
941
|
+
if isinstance(v, list):
|
|
942
|
+
b[k] = [str(x) for x in v] if v else [""]
|
|
943
|
+
elif isinstance(v, str) and v:
|
|
944
|
+
try:
|
|
945
|
+
p = _json.loads(v)
|
|
946
|
+
b[k] = [str(x) for x in p] if isinstance(p, list) and p else [""]
|
|
947
|
+
except Exception:
|
|
948
|
+
b[k] = [v]
|
|
949
|
+
else:
|
|
950
|
+
b[k] = [""]
|
|
951
|
+
elif dominant == "int":
|
|
952
|
+
b[k] = int(v) if v not in (None, "") else 0
|
|
953
|
+
elif dominant == "bool":
|
|
954
|
+
b[k] = bool(v) if v is not None else False
|
|
955
|
+
else:
|
|
956
|
+
if v is None:
|
|
957
|
+
b[k] = ""
|
|
958
|
+
elif isinstance(v, list):
|
|
959
|
+
b[k] = _json.dumps(v)
|
|
960
|
+
elif not isinstance(v, str):
|
|
961
|
+
b[k] = str(v)
|
|
962
|
+
|
|
963
|
+
# Combined CREATE symbol + CONTAINS in one query
|
|
964
|
+
for i in range(0, len(deduped), batch_size):
|
|
965
|
+
chunk = deduped[i:i + batch_size]
|
|
966
|
+
session.run(
|
|
967
|
+
f"UNWIND $batch AS row "
|
|
968
|
+
f"MATCH (f:File {{path: row._fp}}) "
|
|
969
|
+
f"CREATE (n:{label} {{name: row.name, path: row._fp, line_number: row.line_number}}) "
|
|
970
|
+
f"SET n += row "
|
|
971
|
+
f"CREATE (f)-[:CONTAINS]->(n)",
|
|
972
|
+
batch=chunk,
|
|
973
|
+
)
|
|
974
|
+
|
|
975
|
+
if on_progress:
|
|
976
|
+
on_progress(total * 3 // 4, total, "Fast writing relationships...")
|
|
977
|
+
|
|
978
|
+
# 5. Parameters — combined CREATE
|
|
979
|
+
if params_batch:
|
|
980
|
+
for i in range(0, len(params_batch), batch_size):
|
|
981
|
+
session.run(
|
|
982
|
+
"UNWIND $batch AS row "
|
|
983
|
+
"MATCH (fn:Function {name: row.func_name, path: row.file_path, line_number: row.line_number}) "
|
|
984
|
+
"CREATE (p:Parameter {name: row.arg_name, path: row.file_path, function_line_number: row.line_number}) "
|
|
985
|
+
"CREATE (fn)-[:HAS_PARAMETER]->(p)",
|
|
986
|
+
batch=params_batch[i:i + batch_size],
|
|
987
|
+
)
|
|
988
|
+
|
|
989
|
+
# 6. Class→function CONTAINS
|
|
990
|
+
if class_fn_batch:
|
|
991
|
+
for i in range(0, len(class_fn_batch), batch_size):
|
|
992
|
+
session.run(
|
|
993
|
+
"UNWIND $batch AS row "
|
|
994
|
+
"MATCH (c:Class {name: row.class_name, path: row.file_path}) "
|
|
995
|
+
"MATCH (fn:Function {name: row.func_name, path: row.file_path, line_number: row.func_line}) "
|
|
996
|
+
"CREATE (c)-[:CONTAINS]->(fn)",
|
|
997
|
+
batch=class_fn_batch[i:i + batch_size],
|
|
998
|
+
)
|
|
999
|
+
|
|
1000
|
+
# 7. Nested functions
|
|
1001
|
+
if nested_fn_batch:
|
|
1002
|
+
for i in range(0, len(nested_fn_batch), batch_size):
|
|
1003
|
+
session.run(
|
|
1004
|
+
"UNWIND $batch AS row "
|
|
1005
|
+
"MATCH (outer:Function {name: row.outer, path: row.file_path}) "
|
|
1006
|
+
"MATCH (inner:Function {name: row.inner_name, path: row.file_path, line_number: row.inner_line}) "
|
|
1007
|
+
"CREATE (outer)-[:CONTAINS]->(inner)",
|
|
1008
|
+
batch=nested_fn_batch[i:i + batch_size],
|
|
1009
|
+
)
|
|
1010
|
+
|
|
1011
|
+
# 8. JS imports — combined MODULE CREATE + IMPORTS
|
|
1012
|
+
if js_imports_batch:
|
|
1013
|
+
# Deduplicate modules
|
|
1014
|
+
module_set = set()
|
|
1015
|
+
module_list = []
|
|
1016
|
+
for imp in js_imports_batch:
|
|
1017
|
+
mn = imp["module_name"]
|
|
1018
|
+
if mn not in module_set:
|
|
1019
|
+
module_set.add(mn)
|
|
1020
|
+
module_list.append({"name": mn})
|
|
1021
|
+
for i in range(0, len(module_list), batch_size):
|
|
1022
|
+
session.run(
|
|
1023
|
+
"UNWIND $batch AS row "
|
|
1024
|
+
"MERGE (m:Module {name: row.name})",
|
|
1025
|
+
batch=module_list[i:i + batch_size],
|
|
1026
|
+
)
|
|
1027
|
+
for i in range(0, len(js_imports_batch), batch_size):
|
|
1028
|
+
session.run(
|
|
1029
|
+
"UNWIND $batch AS row "
|
|
1030
|
+
"MATCH (f:File {path: row.file_path}) "
|
|
1031
|
+
"MATCH (m:Module {name: row.module_name}) "
|
|
1032
|
+
"CREATE (f)-[:IMPORTS {imported_name: row.imported_name, alias: row.alias, line_number: row.line_number}]->(m)",
|
|
1033
|
+
batch=js_imports_batch[i:i + batch_size],
|
|
1034
|
+
)
|
|
1035
|
+
|
|
1036
|
+
# 9. Other imports
|
|
1037
|
+
if other_imports_batch:
|
|
1038
|
+
module_set2 = set()
|
|
1039
|
+
module_list2 = []
|
|
1040
|
+
for imp in other_imports_batch:
|
|
1041
|
+
mn = imp["name"]
|
|
1042
|
+
if mn not in module_set2:
|
|
1043
|
+
module_set2.add(mn)
|
|
1044
|
+
module_list2.append({"name": mn, "alias": imp.get("alias", ""), "full_import_name": imp.get("full_import_name", "")})
|
|
1045
|
+
for i in range(0, len(module_list2), batch_size):
|
|
1046
|
+
session.run(
|
|
1047
|
+
"UNWIND $batch AS row "
|
|
1048
|
+
"MERGE (m:Module {name: row.name}) "
|
|
1049
|
+
"SET m.alias = row.alias, m.full_import_name = coalesce(row.full_import_name, m.full_import_name)",
|
|
1050
|
+
batch=module_list2[i:i + batch_size],
|
|
1051
|
+
)
|
|
1052
|
+
for i in range(0, len(other_imports_batch), batch_size):
|
|
1053
|
+
session.run(
|
|
1054
|
+
"UNWIND $batch AS row "
|
|
1055
|
+
"MATCH (f:File {path: row.file_path}) "
|
|
1056
|
+
"MATCH (m:Module {name: row.name}) "
|
|
1057
|
+
"CREATE (f)-[:IMPORTS {line_number: row.line_number, alias: row.alias}]->(m)",
|
|
1058
|
+
batch=other_imports_batch[i:i + batch_size],
|
|
1059
|
+
)
|
|
1060
|
+
|
|
1061
|
+
if on_progress:
|
|
1062
|
+
on_progress(total, total, "Fast graph write complete")
|
|
1063
|
+
|
|
1064
|
+
return len(file_batch)
|
|
1065
|
+
|
|
1066
|
+
except Exception as e:
|
|
1067
|
+
info_logger(f"[FAST WRITE] Failed ({e}), falling back to MERGE writer")
|
|
1068
|
+
return self.add_files_batch_to_graph(
|
|
1069
|
+
all_file_data, repo_name, imports_map, repo_path_str, on_progress
|
|
1070
|
+
)
|
|
1071
|
+
|
|
1072
|
+
# ── Fast CALLS writer using CREATE ───────────────────────────────────
|
|
1073
|
+
|
|
1074
|
+
def write_function_call_groups_fast(
|
|
1075
|
+
self,
|
|
1076
|
+
fn_to_fn: List[Dict],
|
|
1077
|
+
fn_to_cls: List[Dict],
|
|
1078
|
+
cls_to_fn: List[Dict],
|
|
1079
|
+
cls_to_cls: List[Dict],
|
|
1080
|
+
file_to_fn: List[Dict],
|
|
1081
|
+
file_to_cls: List[Dict],
|
|
1082
|
+
) -> None:
|
|
1083
|
+
"""Write CALLS edges using CREATE instead of MERGE (for initial index)."""
|
|
1084
|
+
batch_size = 2000
|
|
1085
|
+
q_fn_to_fn = """
|
|
1086
|
+
UNWIND $batch AS row
|
|
1087
|
+
MATCH (caller:Function {name: row.caller_name, path: row.caller_file_path, line_number: row.caller_line_number})
|
|
1088
|
+
MATCH (called:Function {name: row.called_name, path: row.called_file_path})
|
|
1089
|
+
CREATE (caller)-[:CALLS {line_number: row.line_number, args: row.args, full_call_name: row.full_call_name}]->(called)
|
|
1090
|
+
"""
|
|
1091
|
+
q_fn_to_cls = """
|
|
1092
|
+
UNWIND $batch AS row
|
|
1093
|
+
MATCH (caller:Function {name: row.caller_name, path: row.caller_file_path, line_number: row.caller_line_number})
|
|
1094
|
+
MATCH (called:Class {name: row.called_name, path: row.called_file_path})
|
|
1095
|
+
CREATE (caller)-[:CALLS {line_number: row.line_number, args: row.args, full_call_name: row.full_call_name}]->(called)
|
|
1096
|
+
"""
|
|
1097
|
+
q_cls_to_fn = """
|
|
1098
|
+
UNWIND $batch AS row
|
|
1099
|
+
MATCH (caller:Class {name: row.caller_name, path: row.caller_file_path, line_number: row.caller_line_number})
|
|
1100
|
+
MATCH (called:Function {name: row.called_name, path: row.called_file_path})
|
|
1101
|
+
CREATE (caller)-[:CALLS {line_number: row.line_number, args: row.args, full_call_name: row.full_call_name}]->(called)
|
|
1102
|
+
"""
|
|
1103
|
+
q_cls_to_cls = """
|
|
1104
|
+
UNWIND $batch AS row
|
|
1105
|
+
MATCH (caller:Class {name: row.caller_name, path: row.caller_file_path, line_number: row.caller_line_number})
|
|
1106
|
+
MATCH (called:Class {name: row.called_name, path: row.called_file_path})
|
|
1107
|
+
CREATE (caller)-[:CALLS {line_number: row.line_number, args: row.args, full_call_name: row.full_call_name}]->(called)
|
|
1108
|
+
"""
|
|
1109
|
+
q_file_to_fn = """
|
|
1110
|
+
UNWIND $batch AS row
|
|
1111
|
+
MATCH (caller:File {path: row.caller_file_path})
|
|
1112
|
+
MATCH (called:Function {name: row.called_name, path: row.called_file_path})
|
|
1113
|
+
CREATE (caller)-[:CALLS {line_number: row.line_number, args: row.args, full_call_name: row.full_call_name}]->(called)
|
|
1114
|
+
"""
|
|
1115
|
+
q_file_to_cls = """
|
|
1116
|
+
UNWIND $batch AS row
|
|
1117
|
+
MATCH (caller:File {path: row.caller_file_path})
|
|
1118
|
+
MATCH (called:Class {name: row.called_name, path: row.called_file_path})
|
|
1119
|
+
CREATE (caller)-[:CALLS {line_number: row.line_number, args: row.args, full_call_name: row.full_call_name}]->(called)
|
|
1120
|
+
"""
|
|
1121
|
+
groups: List[Tuple[str, List[Dict], str]] = [
|
|
1122
|
+
("fn→fn", fn_to_fn, q_fn_to_fn),
|
|
1123
|
+
("fn→cls", fn_to_cls, q_fn_to_cls),
|
|
1124
|
+
("cls→fn", cls_to_fn, q_cls_to_fn),
|
|
1125
|
+
("cls→cls", cls_to_cls, q_cls_to_cls),
|
|
1126
|
+
("file→fn", file_to_fn, q_file_to_fn),
|
|
1127
|
+
("file→cls", file_to_cls, q_file_to_cls),
|
|
1128
|
+
]
|
|
1129
|
+
try:
|
|
1130
|
+
with self.driver.session() as session:
|
|
1131
|
+
for label, calls, query in groups:
|
|
1132
|
+
if not calls:
|
|
1133
|
+
continue
|
|
1134
|
+
t0 = time.time()
|
|
1135
|
+
for i in range(0, len(calls), batch_size):
|
|
1136
|
+
session.run(query, batch=calls[i:i + batch_size])
|
|
1137
|
+
elapsed = time.time() - t0
|
|
1138
|
+
info_logger(f"[CALLS-FAST] {label}: {len(calls)} in {elapsed:.1f}s")
|
|
1139
|
+
except Exception as e:
|
|
1140
|
+
info_logger(f"[CALLS-FAST] Failed ({e}), falling back to MERGE writer")
|
|
1141
|
+
self.write_function_call_groups(
|
|
1142
|
+
fn_to_fn, fn_to_cls, cls_to_fn, cls_to_cls, file_to_fn, file_to_cls
|
|
1143
|
+
)
|
|
1144
|
+
|
|
1145
|
+
def add_minimal_file_node(
|
|
1146
|
+
self, file_path: Path, repo_path: Path, is_dependency: bool = False
|
|
1147
|
+
) -> None:
|
|
1148
|
+
file_path_str = str(file_path.resolve())
|
|
1149
|
+
file_name = file_path.name
|
|
1150
|
+
repo_name = repo_path.name
|
|
1151
|
+
repo_path_str = str(repo_path.resolve())
|
|
1152
|
+
|
|
1153
|
+
with self.driver.session() as session:
|
|
1154
|
+
session.run(
|
|
1155
|
+
"""
|
|
1156
|
+
MERGE (r:Repository {path: $repo_path})
|
|
1157
|
+
SET r.name = $repo_name
|
|
1158
|
+
""",
|
|
1159
|
+
repo_path=repo_path_str,
|
|
1160
|
+
repo_name=repo_name,
|
|
1161
|
+
)
|
|
1162
|
+
|
|
1163
|
+
session.run(
|
|
1164
|
+
"""
|
|
1165
|
+
MERGE (f:File {path: $file_path})
|
|
1166
|
+
SET f.name = $file_name,
|
|
1167
|
+
f.is_dependency = $is_dependency
|
|
1168
|
+
""",
|
|
1169
|
+
file_path=file_path_str,
|
|
1170
|
+
file_name=file_name,
|
|
1171
|
+
is_dependency=is_dependency,
|
|
1172
|
+
)
|
|
1173
|
+
|
|
1174
|
+
file_path_obj = Path(file_path_str)
|
|
1175
|
+
repo_path_obj = Path(repo_path_str)
|
|
1176
|
+
try:
|
|
1177
|
+
relative_path_to_file = file_path_obj.relative_to(repo_path_obj)
|
|
1178
|
+
except ValueError:
|
|
1179
|
+
relative_path_to_file = Path(file_path_obj.name)
|
|
1180
|
+
|
|
1181
|
+
parent_path = repo_path_str
|
|
1182
|
+
parent_label = "Repository"
|
|
1183
|
+
|
|
1184
|
+
for part in relative_path_to_file.parts[:-1]:
|
|
1185
|
+
current_path = Path(parent_path) / part
|
|
1186
|
+
current_path_str = str(current_path)
|
|
1187
|
+
|
|
1188
|
+
session.run(
|
|
1189
|
+
f"""
|
|
1190
|
+
MATCH (p:{parent_label} {{path: $parent_path}})
|
|
1191
|
+
MERGE (d:Directory {{path: $current_path}})
|
|
1192
|
+
SET d.name = $part
|
|
1193
|
+
MERGE (p)-[:CONTAINS]->(d)
|
|
1194
|
+
""",
|
|
1195
|
+
parent_path=parent_path,
|
|
1196
|
+
current_path=current_path_str,
|
|
1197
|
+
part=part,
|
|
1198
|
+
)
|
|
1199
|
+
|
|
1200
|
+
parent_path = current_path_str
|
|
1201
|
+
parent_label = "Directory"
|
|
1202
|
+
|
|
1203
|
+
session.run(
|
|
1204
|
+
f"""
|
|
1205
|
+
MATCH (p:{parent_label} {{path: $parent_path}})
|
|
1206
|
+
MATCH (f:File {{path: $file_path}})
|
|
1207
|
+
MERGE (p)-[:CONTAINS]->(f)
|
|
1208
|
+
""",
|
|
1209
|
+
parent_path=parent_path,
|
|
1210
|
+
file_path=file_path_str,
|
|
1211
|
+
)
|
|
1212
|
+
|
|
1213
|
+
def write_function_call_groups(
|
|
1214
|
+
self,
|
|
1215
|
+
fn_to_fn: List[Dict],
|
|
1216
|
+
fn_to_cls: List[Dict],
|
|
1217
|
+
cls_to_fn: List[Dict],
|
|
1218
|
+
cls_to_cls: List[Dict],
|
|
1219
|
+
file_to_fn: List[Dict],
|
|
1220
|
+
file_to_cls: List[Dict],
|
|
1221
|
+
) -> None:
|
|
1222
|
+
batch_size = 1000
|
|
1223
|
+
q_fn_to_fn = """
|
|
1224
|
+
UNWIND $batch AS row
|
|
1225
|
+
MATCH (caller:Function {name: row.caller_name, path: row.caller_file_path, line_number: row.caller_line_number})
|
|
1226
|
+
MATCH (called:Function {name: row.called_name, path: row.called_file_path})
|
|
1227
|
+
MERGE (caller)-[:CALLS {line_number: row.line_number, args: row.args, full_call_name: row.full_call_name}]->(called)
|
|
1228
|
+
"""
|
|
1229
|
+
q_fn_to_cls = """
|
|
1230
|
+
UNWIND $batch AS row
|
|
1231
|
+
MATCH (caller:Function {name: row.caller_name, path: row.caller_file_path, line_number: row.caller_line_number})
|
|
1232
|
+
MATCH (called:Class {name: row.called_name, path: row.called_file_path})
|
|
1233
|
+
MERGE (caller)-[:CALLS {line_number: row.line_number, args: row.args, full_call_name: row.full_call_name}]->(called)
|
|
1234
|
+
"""
|
|
1235
|
+
q_cls_to_fn = """
|
|
1236
|
+
UNWIND $batch AS row
|
|
1237
|
+
MATCH (caller:Class {name: row.caller_name, path: row.caller_file_path, line_number: row.caller_line_number})
|
|
1238
|
+
MATCH (called:Function {name: row.called_name, path: row.called_file_path})
|
|
1239
|
+
MERGE (caller)-[:CALLS {line_number: row.line_number, args: row.args, full_call_name: row.full_call_name}]->(called)
|
|
1240
|
+
"""
|
|
1241
|
+
q_cls_to_cls = """
|
|
1242
|
+
UNWIND $batch AS row
|
|
1243
|
+
MATCH (caller:Class {name: row.caller_name, path: row.caller_file_path, line_number: row.caller_line_number})
|
|
1244
|
+
MATCH (called:Class {name: row.called_name, path: row.called_file_path})
|
|
1245
|
+
MERGE (caller)-[:CALLS {line_number: row.line_number, args: row.args, full_call_name: row.full_call_name}]->(called)
|
|
1246
|
+
"""
|
|
1247
|
+
q_file_to_fn = """
|
|
1248
|
+
UNWIND $batch AS row
|
|
1249
|
+
MATCH (caller:File {path: row.caller_file_path})
|
|
1250
|
+
MATCH (called:Function {name: row.called_name, path: row.called_file_path})
|
|
1251
|
+
MERGE (caller)-[:CALLS {line_number: row.line_number, args: row.args, full_call_name: row.full_call_name}]->(called)
|
|
1252
|
+
"""
|
|
1253
|
+
q_file_to_cls = """
|
|
1254
|
+
UNWIND $batch AS row
|
|
1255
|
+
MATCH (caller:File {path: row.caller_file_path})
|
|
1256
|
+
MATCH (called:Class {name: row.called_name, path: row.called_file_path})
|
|
1257
|
+
MERGE (caller)-[:CALLS {line_number: row.line_number, args: row.args, full_call_name: row.full_call_name}]->(called)
|
|
1258
|
+
"""
|
|
1259
|
+
groups: List[Tuple[str, List[Dict], str]] = [
|
|
1260
|
+
("fn→fn", fn_to_fn, q_fn_to_fn),
|
|
1261
|
+
("fn→cls", fn_to_cls, q_fn_to_cls),
|
|
1262
|
+
("cls→fn", cls_to_fn, q_cls_to_fn),
|
|
1263
|
+
("cls→cls", cls_to_cls, q_cls_to_cls),
|
|
1264
|
+
("file→fn", file_to_fn, q_file_to_fn),
|
|
1265
|
+
("file→cls", file_to_cls, q_file_to_cls),
|
|
1266
|
+
]
|
|
1267
|
+
total_all = sum(len(g[1]) for g in groups)
|
|
1268
|
+
with self.driver.session() as session:
|
|
1269
|
+
for label, calls, query in groups:
|
|
1270
|
+
if not calls:
|
|
1271
|
+
info_logger(f"[CALLS] {label}: 0 (skipped)")
|
|
1272
|
+
continue
|
|
1273
|
+
t0 = time.time()
|
|
1274
|
+
for i in range(0, len(calls), batch_size):
|
|
1275
|
+
batch = calls[i : i + batch_size]
|
|
1276
|
+
session.run(query, batch=batch)
|
|
1277
|
+
written = min(i + batch_size, len(calls))
|
|
1278
|
+
if written % 5000 < batch_size or written == len(calls):
|
|
1279
|
+
elapsed = time.time() - t0
|
|
1280
|
+
info_logger(f"[CALLS] {label}: {written}/{len(calls)} ({elapsed:.1f}s)")
|
|
1281
|
+
elapsed = time.time() - t0
|
|
1282
|
+
info_logger(f"[CALLS] {label} done: {len(calls)} in {elapsed:.1f}s")
|
|
1283
|
+
info_logger(f"[CALLS] All complete: {total_all} CALLS relationships processed.")
|
|
1284
|
+
|
|
1285
|
+
def _create_csharp_inheritance_and_interfaces(
|
|
1286
|
+
self, session: Any, file_data: Dict[str, Any], imports_map: dict
|
|
1287
|
+
) -> None:
|
|
1288
|
+
if file_data.get("lang") != "c_sharp":
|
|
1289
|
+
return
|
|
1290
|
+
|
|
1291
|
+
caller_file_path = str(Path(file_data["path"]).resolve())
|
|
1292
|
+
|
|
1293
|
+
for type_list_name, type_label in [
|
|
1294
|
+
("classes", "Class"),
|
|
1295
|
+
("structs", "Struct"),
|
|
1296
|
+
("records", "Record"),
|
|
1297
|
+
("interfaces", "Interface"),
|
|
1298
|
+
]:
|
|
1299
|
+
for type_item in file_data.get(type_list_name, []):
|
|
1300
|
+
if not type_item.get("bases"):
|
|
1301
|
+
continue
|
|
1302
|
+
|
|
1303
|
+
for base_str in type_item["bases"]:
|
|
1304
|
+
base_name = base_str.split("<")[0].strip()
|
|
1305
|
+
|
|
1306
|
+
is_interface = False
|
|
1307
|
+
resolved_path = caller_file_path
|
|
1308
|
+
|
|
1309
|
+
for iface in file_data.get("interfaces", []):
|
|
1310
|
+
if iface["name"] == base_name:
|
|
1311
|
+
is_interface = True
|
|
1312
|
+
break
|
|
1313
|
+
|
|
1314
|
+
if base_name in imports_map:
|
|
1315
|
+
possible_paths = imports_map[base_name]
|
|
1316
|
+
if len(possible_paths) > 0:
|
|
1317
|
+
resolved_path = possible_paths[0]
|
|
1318
|
+
|
|
1319
|
+
base_index = type_item["bases"].index(base_str)
|
|
1320
|
+
|
|
1321
|
+
if is_interface or (base_index > 0 and type_label == "Class"):
|
|
1322
|
+
session.run(
|
|
1323
|
+
"""
|
|
1324
|
+
MATCH (child {name: $child_name, path: $path})
|
|
1325
|
+
WHERE child:Class OR child:Struct OR child:Record
|
|
1326
|
+
MATCH (iface:Interface {name: $interface_name})
|
|
1327
|
+
MERGE (child)-[:IMPLEMENTS]->(iface)
|
|
1328
|
+
""",
|
|
1329
|
+
child_name=type_item["name"],
|
|
1330
|
+
path=caller_file_path,
|
|
1331
|
+
interface_name=base_name,
|
|
1332
|
+
)
|
|
1333
|
+
else:
|
|
1334
|
+
session.run(
|
|
1335
|
+
"""
|
|
1336
|
+
MATCH (child {name: $child_name, path: $path})
|
|
1337
|
+
WHERE child:Class OR child:Record OR child:Interface
|
|
1338
|
+
MATCH (parent {name: $parent_name})
|
|
1339
|
+
WHERE parent:Class OR parent:Record OR parent:Interface
|
|
1340
|
+
MERGE (child)-[:INHERITS]->(parent)
|
|
1341
|
+
""",
|
|
1342
|
+
child_name=type_item["name"],
|
|
1343
|
+
path=caller_file_path,
|
|
1344
|
+
parent_name=base_name,
|
|
1345
|
+
)
|
|
1346
|
+
|
|
1347
|
+
def write_inheritance_links(
|
|
1348
|
+
self,
|
|
1349
|
+
inheritance_batch: List[Dict[str, Any]],
|
|
1350
|
+
csharp_files: List[Dict[str, Any]],
|
|
1351
|
+
imports_map: dict,
|
|
1352
|
+
) -> None:
|
|
1353
|
+
info_logger(
|
|
1354
|
+
f"[INHERITS] Resolved {len(inheritance_batch)} inheritance links, "
|
|
1355
|
+
f"{len(csharp_files)} C# files. Writing to Neo4j..."
|
|
1356
|
+
)
|
|
1357
|
+
batch_size = 500
|
|
1358
|
+
with self.driver.session() as session:
|
|
1359
|
+
for i in range(0, len(inheritance_batch), batch_size):
|
|
1360
|
+
batch = inheritance_batch[i : i + batch_size]
|
|
1361
|
+
session.run(
|
|
1362
|
+
"""
|
|
1363
|
+
UNWIND $batch AS row
|
|
1364
|
+
MATCH (child:Class {name: row.child_name, path: row.path})
|
|
1365
|
+
MATCH (parent:Class {name: row.parent_name, path: row.resolved_parent_file_path})
|
|
1366
|
+
MERGE (child)-[:INHERITS]->(parent)
|
|
1367
|
+
""",
|
|
1368
|
+
batch=batch,
|
|
1369
|
+
)
|
|
1370
|
+
|
|
1371
|
+
for file_data in csharp_files:
|
|
1372
|
+
self._create_csharp_inheritance_and_interfaces(session, file_data, imports_map)
|
|
1373
|
+
|
|
1374
|
+
info_logger(f"[INHERITS] Complete: {len(inheritance_batch)} inheritance links processed.")
|
|
1375
|
+
|
|
1376
|
+
def write_scip_call_edges(
|
|
1377
|
+
self, files_data: Dict[str, Any], name_from_symbol: Callable[[str], str]
|
|
1378
|
+
) -> None:
|
|
1379
|
+
with self.driver.session() as session:
|
|
1380
|
+
for file_data in files_data.values():
|
|
1381
|
+
for edge in file_data.get("function_calls_scip", []):
|
|
1382
|
+
try:
|
|
1383
|
+
session.run(
|
|
1384
|
+
"""
|
|
1385
|
+
MATCH (caller:Function {name: $caller_name, path: $caller_file, line_number: $caller_line})
|
|
1386
|
+
MATCH (callee:Function {name: $callee_name, path: $callee_file, line_number: $callee_line})
|
|
1387
|
+
MERGE (caller)-[:CALLS {line_number: $ref_line, source: 'scip'}]->(callee)
|
|
1388
|
+
""",
|
|
1389
|
+
caller_name=name_from_symbol(edge["caller_symbol"]),
|
|
1390
|
+
caller_file=edge["caller_file"],
|
|
1391
|
+
caller_line=edge["caller_line"],
|
|
1392
|
+
callee_name=edge["callee_name"],
|
|
1393
|
+
callee_file=edge["callee_file"],
|
|
1394
|
+
callee_line=edge["callee_line"],
|
|
1395
|
+
ref_line=edge["ref_line"],
|
|
1396
|
+
)
|
|
1397
|
+
except Exception as e:
|
|
1398
|
+
warning_logger(f"Failed to write SCIP call edge: {e}")
|
|
1399
|
+
|
|
1400
|
+
def delete_file_from_graph(self, path: str) -> None:
|
|
1401
|
+
file_path_str = str(Path(path).resolve())
|
|
1402
|
+
with self.driver.session() as session:
|
|
1403
|
+
parents_res = session.run(
|
|
1404
|
+
"""
|
|
1405
|
+
MATCH (f:File {path: $path})<-[:CONTAINS*]-(d:Directory)
|
|
1406
|
+
RETURN d.path as path ORDER BY d.path DESC
|
|
1407
|
+
""",
|
|
1408
|
+
path=file_path_str,
|
|
1409
|
+
)
|
|
1410
|
+
parent_paths = [record["path"] for record in parents_res]
|
|
1411
|
+
|
|
1412
|
+
session.run(
|
|
1413
|
+
"""
|
|
1414
|
+
MATCH (f:File {path: $path})
|
|
1415
|
+
OPTIONAL MATCH (f)-[:CONTAINS]->(element)
|
|
1416
|
+
DETACH DELETE f, element
|
|
1417
|
+
""",
|
|
1418
|
+
path=file_path_str,
|
|
1419
|
+
)
|
|
1420
|
+
info_logger(f"Deleted file and its elements from graph: {file_path_str}")
|
|
1421
|
+
|
|
1422
|
+
for p in parent_paths:
|
|
1423
|
+
session.run(
|
|
1424
|
+
"""
|
|
1425
|
+
MATCH (d:Directory {path: $path})
|
|
1426
|
+
WHERE NOT (d)-[:CONTAINS]->()
|
|
1427
|
+
DETACH DELETE d
|
|
1428
|
+
""",
|
|
1429
|
+
path=p,
|
|
1430
|
+
)
|
|
1431
|
+
|
|
1432
|
+
def delete_repository_from_graph(self, repo_path: str) -> bool:
|
|
1433
|
+
repo_path_str = str(Path(repo_path).resolve())
|
|
1434
|
+
path_prefix = repo_path_str + "/"
|
|
1435
|
+
with self.driver.session() as session:
|
|
1436
|
+
result = session.run(
|
|
1437
|
+
"MATCH (r:Repository {path: $path}) RETURN count(r) as cnt", path=repo_path_str
|
|
1438
|
+
).single()
|
|
1439
|
+
if not result or result["cnt"] == 0:
|
|
1440
|
+
warning_logger(f"Attempted to delete non-existent repository: {repo_path_str}")
|
|
1441
|
+
return False
|
|
1442
|
+
|
|
1443
|
+
for rel_type in ("CALLS", "INHERITS", "IMPORTS"):
|
|
1444
|
+
while True:
|
|
1445
|
+
with self.driver.session() as session:
|
|
1446
|
+
result = session.run(
|
|
1447
|
+
f"MATCH (a)-[r:{rel_type}]->(b) "
|
|
1448
|
+
"WHERE a.path STARTS WITH $prefix OR b.path STARTS WITH $prefix "
|
|
1449
|
+
"WITH r LIMIT 5000 DELETE r RETURN count(r) AS deleted",
|
|
1450
|
+
prefix=path_prefix,
|
|
1451
|
+
).single()
|
|
1452
|
+
deleted = result["deleted"] if result else 0
|
|
1453
|
+
if deleted == 0:
|
|
1454
|
+
break
|
|
1455
|
+
info_logger(f"[DELETE] Removed {deleted} {rel_type} rels for {repo_path_str}")
|
|
1456
|
+
|
|
1457
|
+
while True:
|
|
1458
|
+
with self.driver.session() as session:
|
|
1459
|
+
result = session.run(
|
|
1460
|
+
"MATCH (a)-[r:CONTAINS]->(b) "
|
|
1461
|
+
"WHERE a.path STARTS WITH $prefix OR a.path = $path "
|
|
1462
|
+
"WITH r LIMIT 10000 DELETE r RETURN count(r) AS deleted",
|
|
1463
|
+
prefix=path_prefix,
|
|
1464
|
+
path=repo_path_str,
|
|
1465
|
+
).single()
|
|
1466
|
+
deleted = result["deleted"] if result else 0
|
|
1467
|
+
if deleted == 0:
|
|
1468
|
+
break
|
|
1469
|
+
info_logger(f"[DELETE] Removed {deleted} CONTAINS rels for {repo_path_str}")
|
|
1470
|
+
|
|
1471
|
+
for label in ("Function", "Class", "File"):
|
|
1472
|
+
while True:
|
|
1473
|
+
with self.driver.session() as session:
|
|
1474
|
+
result = session.run(
|
|
1475
|
+
f"MATCH (n:{label}) WHERE n.path STARTS WITH $prefix "
|
|
1476
|
+
"WITH n LIMIT 10000 DETACH DELETE n RETURN count(n) AS deleted",
|
|
1477
|
+
prefix=path_prefix,
|
|
1478
|
+
).single()
|
|
1479
|
+
deleted = result["deleted"] if result else 0
|
|
1480
|
+
if deleted == 0:
|
|
1481
|
+
break
|
|
1482
|
+
info_logger(f"[DELETE] Removed {deleted} {label} nodes for {repo_path_str}")
|
|
1483
|
+
|
|
1484
|
+
with self.driver.session() as session:
|
|
1485
|
+
session.run("MATCH (r:Repository {path: $path}) DETACH DELETE r", path=repo_path_str)
|
|
1486
|
+
|
|
1487
|
+
info_logger(f"Deleted repository and its contents from graph: {repo_path_str}")
|
|
1488
|
+
return True
|
|
1489
|
+
|
|
1490
|
+
def get_caller_file_paths(self, file_path_str: str) -> set:
|
|
1491
|
+
with self.driver.session() as session:
|
|
1492
|
+
result = session.run(
|
|
1493
|
+
"MATCH (caller)-[:CALLS]->(callee) "
|
|
1494
|
+
"WHERE callee.path = $path "
|
|
1495
|
+
"RETURN DISTINCT coalesce(caller.path, '') AS p",
|
|
1496
|
+
path=file_path_str,
|
|
1497
|
+
)
|
|
1498
|
+
return {r["p"] for r in result if r["p"] and r["p"] != file_path_str}
|
|
1499
|
+
|
|
1500
|
+
def get_inheritance_neighbor_paths(self, file_path_str: str) -> set:
|
|
1501
|
+
with self.driver.session() as session:
|
|
1502
|
+
result = session.run(
|
|
1503
|
+
"MATCH (a)-[:INHERITS]->(b) "
|
|
1504
|
+
"WHERE a.path = $path OR b.path = $path "
|
|
1505
|
+
"RETURN DISTINCT CASE WHEN a.path = $path THEN b.path ELSE a.path END AS p",
|
|
1506
|
+
path=file_path_str,
|
|
1507
|
+
)
|
|
1508
|
+
return {r["p"] for r in result if r["p"] and r["p"] != file_path_str}
|
|
1509
|
+
|
|
1510
|
+
def delete_outgoing_calls_from_files(self, file_paths: List[str]) -> None:
|
|
1511
|
+
with self.driver.session() as session:
|
|
1512
|
+
result = session.run(
|
|
1513
|
+
"MATCH (a)-[r:CALLS]->(b) WHERE a.path IN $paths DELETE r RETURN count(r) AS cnt",
|
|
1514
|
+
paths=file_paths,
|
|
1515
|
+
).single()
|
|
1516
|
+
cnt = result["cnt"] if result else 0
|
|
1517
|
+
info_logger(f"[RELINK] Deleted {cnt} outgoing CALLS from {len(file_paths)} caller files")
|
|
1518
|
+
|
|
1519
|
+
def delete_inherits_for_files(self, file_paths: List[str]) -> None:
|
|
1520
|
+
with self.driver.session() as session:
|
|
1521
|
+
result = session.run(
|
|
1522
|
+
"MATCH (a)-[r:INHERITS]->(b) WHERE a.path IN $paths OR b.path IN $paths "
|
|
1523
|
+
"DELETE r RETURN count(r) AS cnt",
|
|
1524
|
+
paths=file_paths,
|
|
1525
|
+
).single()
|
|
1526
|
+
cnt = result["cnt"] if result else 0
|
|
1527
|
+
info_logger(f"[RELINK] Deleted {cnt} INHERITS for {len(file_paths)} affected files")
|
|
1528
|
+
|
|
1529
|
+
def get_repo_class_lookup(self, repo_path: Path) -> Dict[str, set]:
|
|
1530
|
+
prefix = str(repo_path.resolve()) + "/"
|
|
1531
|
+
result_map: Dict[str, set] = {}
|
|
1532
|
+
with self.driver.session() as session:
|
|
1533
|
+
result = session.run(
|
|
1534
|
+
"MATCH (c:Class) WHERE c.path STARTS WITH $prefix "
|
|
1535
|
+
"RETURN c.name AS name, c.path AS path",
|
|
1536
|
+
prefix=prefix,
|
|
1537
|
+
)
|
|
1538
|
+
for record in result:
|
|
1539
|
+
path = record["path"]
|
|
1540
|
+
if path not in result_map:
|
|
1541
|
+
result_map[path] = set()
|
|
1542
|
+
result_map[path].add(record["name"])
|
|
1543
|
+
return result_map
|
|
1544
|
+
|
|
1545
|
+
def delete_relationship_links(self, repo_path: Path) -> None:
|
|
1546
|
+
repo_path_str = str(repo_path.resolve()) + "/"
|
|
1547
|
+
with self.driver.session() as session:
|
|
1548
|
+
result = session.run(
|
|
1549
|
+
"MATCH (a)-[r:CALLS]->(b) WHERE a.path STARTS WITH $prefix DELETE r RETURN count(r) AS cnt",
|
|
1550
|
+
prefix=repo_path_str,
|
|
1551
|
+
).single()
|
|
1552
|
+
calls_deleted = result["cnt"] if result else 0
|
|
1553
|
+
|
|
1554
|
+
result = session.run(
|
|
1555
|
+
"MATCH (a)-[r:INHERITS]->(b) WHERE a.path STARTS WITH $prefix DELETE r RETURN count(r) AS cnt",
|
|
1556
|
+
prefix=repo_path_str,
|
|
1557
|
+
).single()
|
|
1558
|
+
inherits_deleted = result["cnt"] if result else 0
|
|
1559
|
+
|
|
1560
|
+
info_logger(
|
|
1561
|
+
f"[RELINK] Cleared {calls_deleted} CALLS and {inherits_deleted} INHERITS before re-linking: {repo_path}"
|
|
1562
|
+
)
|