Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
588 lines (505 loc) · 17.7 KB
/
Copy pathcli.py
File metadata and controls
588 lines (505 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
import asyncio
from collections.abc import Callable
from pathlib import Path
import typer
from loguru import logger
from rich.panel import Panel
from rich.table import Table
from . import cli_help as ch
from . import constants as cs
from . import logs as ls
from .config import load_cgrignore_patterns, settings
from .graph_updater import GraphUpdater
from .main import (
app_context,
connect_memgraph,
export_graph_to_file,
main_async,
main_optimize_async,
prompt_for_unignored_directories,
style,
update_model_settings,
)
from .parser_loader import load_parsers
from .services.protobuf_service import ProtobufFileIngestor
from .tools.health_checker import HealthChecker
from .tools.language import cli as language_cli
from .types_defs import ResultRow
app = typer.Typer(
name="code-graph-rag",
help=ch.APP_DESCRIPTION,
no_args_is_help=True,
add_completion=False,
)
def validate_models_early() -> None:
try:
orchestrator_config = settings.active_orchestrator_config
orchestrator_config.validate_api_key(cs.ModelRole.ORCHESTRATOR)
cypher_config = settings.active_cypher_config
cypher_config.validate_api_key(cs.ModelRole.CYPHER)
except ValueError as e:
app_context.console.print(style(str(e), cs.Color.RED))
raise typer.Exit(1) from e
def _update_and_validate_models(orchestrator: str | None, cypher: str | None) -> None:
try:
update_model_settings(orchestrator, cypher)
except ValueError as e:
app_context.console.print(style(str(e), cs.Color.RED))
raise typer.Exit(1) from e
validate_models_early()
@app.callback()
def _global_options(
quiet: bool = typer.Option(
False,
"--quiet",
"-q",
help="Suppress non-essential output (progress messages, banners, informational logs).",
is_eager=True,
),
) -> None:
settings.QUIET = quiet
if quiet:
logger.remove()
logger.add(lambda msg: app_context.console.print(msg, end=""), level="ERROR")
def _info(msg: str) -> None:
if not settings.QUIET:
app_context.console.print(msg)
def _delete_hash_cache(repo_path: Path) -> None:
cache_path = repo_path / cs.HASH_CACHE_FILENAME
if cache_path.exists():
_info(
style(
cs.CLI_MSG_CLEANING_HASH_CACHE.format(path=cache_path),
cs.Color.YELLOW,
)
)
cache_path.unlink(missing_ok=True)
@app.command(help=ch.CMD_START)
def start(
repo_path: str | None = typer.Option(
None, "--repo-path", help=ch.HELP_REPO_PATH_RETRIEVAL
),
update_graph: bool = typer.Option(
False,
"--update-graph",
help=ch.HELP_UPDATE_GRAPH,
),
clean: bool = typer.Option(
False,
"--clean",
help=ch.HELP_CLEAN_DB,
),
output: str | None = typer.Option(
None,
"-o",
"--output",
help=ch.HELP_OUTPUT_GRAPH,
),
orchestrator: str | None = typer.Option(
None,
"--orchestrator",
help=ch.HELP_ORCHESTRATOR,
),
cypher: str | None = typer.Option(
None,
"--cypher",
help=ch.HELP_CYPHER_MODEL,
),
no_confirm: bool = typer.Option(
False,
"--no-confirm",
help=ch.HELP_NO_CONFIRM,
),
batch_size: int | None = typer.Option(
None,
"--batch-size",
min=1,
help=ch.HELP_BATCH_SIZE,
),
project_name: str | None = typer.Option(
None,
"--project-name",
help=ch.HELP_PROJECT_NAME,
),
exclude: list[str] | None = typer.Option(
None,
"--exclude",
help=ch.HELP_EXCLUDE_PATTERNS,
),
interactive_setup: bool = typer.Option(
False,
"--interactive-setup",
help=ch.HELP_INTERACTIVE_SETUP,
),
) -> None:
app_context.session.confirm_edits = not no_confirm
target_repo_path = repo_path or settings.TARGET_REPO_PATH
if output and not update_graph:
app_context.console.print(
style(cs.CLI_ERR_OUTPUT_REQUIRES_UPDATE, cs.Color.RED)
)
raise typer.Exit(1)
effective_batch_size = settings.resolve_batch_size(batch_size)
if clean and not update_graph:
repo_to_clean = Path(target_repo_path)
with connect_memgraph(effective_batch_size) as ingestor:
_info(style(cs.CLI_MSG_CLEANING_DB, cs.Color.YELLOW))
ingestor.clean_database()
_delete_hash_cache(repo_to_clean)
_info(style(cs.CLI_MSG_CLEAN_DONE, cs.Color.GREEN))
return
_update_and_validate_models(orchestrator, cypher)
if update_graph:
repo_to_update = Path(target_repo_path)
_info(
style(cs.CLI_MSG_UPDATING_GRAPH.format(path=repo_to_update), cs.Color.GREEN)
)
cgrignore = load_cgrignore_patterns(repo_to_update)
cli_excludes = frozenset(exclude) if exclude else frozenset()
exclude_paths = cli_excludes | cgrignore.exclude or None
unignore_paths: frozenset[str] | None = None
if interactive_setup:
unignore_paths = prompt_for_unignored_directories(repo_to_update, exclude)
else:
_info(style(cs.CLI_MSG_AUTO_EXCLUDE, cs.Color.YELLOW))
unignore_paths = cgrignore.unignore or None
with connect_memgraph(effective_batch_size) as ingestor:
if clean:
_info(style(cs.CLI_MSG_CLEANING_DB, cs.Color.YELLOW))
ingestor.clean_database()
_delete_hash_cache(repo_to_update)
ingestor.ensure_constraints()
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=ingestor,
repo_path=repo_to_update,
parsers=parsers,
queries=queries,
unignore_paths=unignore_paths,
exclude_paths=exclude_paths,
project_name=project_name,
)
updater.run()
if output:
_info(style(cs.CLI_MSG_EXPORTING_TO.format(path=output), cs.Color.CYAN))
if not export_graph_to_file(ingestor, output):
raise typer.Exit(1)
_info(style(cs.CLI_MSG_GRAPH_UPDATED, cs.Color.GREEN))
return
try:
asyncio.run(main_async(target_repo_path, effective_batch_size))
except KeyboardInterrupt:
app_context.console.print(style(cs.CLI_MSG_APP_TERMINATED, cs.Color.RED))
except ValueError as e:
app_context.console.print(
style(cs.CLI_ERR_STARTUP.format(error=e), cs.Color.RED)
)
@app.command(help=ch.CMD_INDEX)
def index(
repo_path: str | None = typer.Option(
None, "--repo-path", help=ch.HELP_REPO_PATH_INDEX
),
output_proto_dir: str = typer.Option(
...,
"-o",
"--output-proto-dir",
help=ch.HELP_OUTPUT_PROTO_DIR,
),
split_index: bool = typer.Option(
False,
"--split-index",
help=ch.HELP_SPLIT_INDEX,
),
exclude: list[str] | None = typer.Option(
None,
"--exclude",
help=ch.HELP_EXCLUDE_PATTERNS,
),
interactive_setup: bool = typer.Option(
False,
"--interactive-setup",
help=ch.HELP_INTERACTIVE_SETUP,
),
) -> None:
target_repo_path = repo_path or settings.TARGET_REPO_PATH
repo_to_index = Path(target_repo_path)
_info(style(cs.CLI_MSG_INDEXING_AT.format(path=repo_to_index), cs.Color.GREEN))
_info(style(cs.CLI_MSG_OUTPUT_TO.format(path=output_proto_dir), cs.Color.CYAN))
cgrignore = load_cgrignore_patterns(repo_to_index)
cli_excludes = frozenset(exclude) if exclude else frozenset()
exclude_paths = cli_excludes | cgrignore.exclude or None
unignore_paths: frozenset[str] | None = None
if interactive_setup:
unignore_paths = prompt_for_unignored_directories(repo_to_index, exclude)
else:
_info(style(cs.CLI_MSG_AUTO_EXCLUDE, cs.Color.YELLOW))
unignore_paths = cgrignore.unignore or None
try:
ingestor = ProtobufFileIngestor(
output_path=output_proto_dir, split_index=split_index
)
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=ingestor,
repo_path=repo_to_index,
parsers=parsers,
queries=queries,
unignore_paths=unignore_paths,
exclude_paths=exclude_paths,
)
updater.run()
_info(style(cs.CLI_MSG_INDEXING_DONE, cs.Color.GREEN))
except Exception as e:
app_context.console.print(
style(cs.CLI_ERR_INDEXING.format(error=e), cs.Color.RED)
)
logger.exception(ls.INDEXING_FAILED)
raise typer.Exit(1) from e
@app.command(help=ch.CMD_EXPORT)
def export(
output: str = typer.Option(..., "-o", "--output", help=ch.HELP_OUTPUT_PATH),
format_json: bool = typer.Option(
True, "--json/--no-json", help=ch.HELP_FORMAT_JSON
),
batch_size: int | None = typer.Option(
None,
"--batch-size",
min=1,
help=ch.HELP_BATCH_SIZE,
),
) -> None:
if not format_json:
app_context.console.print(style(cs.CLI_ERR_ONLY_JSON, cs.Color.RED))
raise typer.Exit(1)
_info(style(cs.CLI_MSG_CONNECTING_MEMGRAPH, cs.Color.CYAN))
effective_batch_size = settings.resolve_batch_size(batch_size)
try:
with connect_memgraph(effective_batch_size) as ingestor:
_info(style(cs.CLI_MSG_EXPORTING_DATA, cs.Color.CYAN))
if not export_graph_to_file(ingestor, output):
raise typer.Exit(1)
except Exception as e:
app_context.console.print(
style(cs.CLI_ERR_EXPORT_FAILED.format(error=e), cs.Color.RED)
)
logger.exception(ls.EXPORT_ERROR.format(error=e))
raise typer.Exit(1) from e
@app.command(help=ch.CMD_OPTIMIZE)
def optimize(
language: str = typer.Argument(
...,
help=ch.HELP_LANGUAGE_ARG,
),
repo_path: str | None = typer.Option(
None, "--repo-path", help=ch.HELP_REPO_PATH_OPTIMIZE
),
reference_document: str | None = typer.Option(
None,
"--reference-document",
help=ch.HELP_REFERENCE_DOC,
),
orchestrator: str | None = typer.Option(
None,
"--orchestrator",
help=ch.HELP_ORCHESTRATOR,
),
cypher: str | None = typer.Option(
None,
"--cypher",
help=ch.HELP_CYPHER_MODEL,
),
no_confirm: bool = typer.Option(
False,
"--no-confirm",
help=ch.HELP_NO_CONFIRM,
),
batch_size: int | None = typer.Option(
None,
"--batch-size",
min=1,
help=ch.HELP_BATCH_SIZE,
),
) -> None:
app_context.session.confirm_edits = not no_confirm
target_repo_path = repo_path or settings.TARGET_REPO_PATH
_update_and_validate_models(orchestrator, cypher)
try:
asyncio.run(
main_optimize_async(
language,
target_repo_path,
reference_document,
orchestrator,
cypher,
batch_size,
)
)
except KeyboardInterrupt:
app_context.console.print(style(cs.CLI_MSG_APP_TERMINATED, cs.Color.RED))
except ValueError as e:
app_context.console.print(
style(cs.CLI_ERR_STARTUP.format(error=e), cs.Color.RED)
)
@app.command(name=ch.CLICommandName.MCP_SERVER, help=ch.CMD_MCP_SERVER)
def mcp_server(
transport: cs.MCPTransport = typer.Option(
cs.MCPTransport.STDIO, help=ch.HELP_MCP_TRANSPORT
),
host: str = typer.Option(None, help=ch.HELP_MCP_HTTP_HOST),
port: int = typer.Option(None, help=ch.HELP_MCP_HTTP_PORT),
) -> None:
try:
if transport == cs.MCPTransport.HTTP:
from codebase_rag.mcp import serve_http
resolved_host = host or settings.MCP_HTTP_HOST
resolved_port = port or settings.MCP_HTTP_PORT
asyncio.run(serve_http(host=resolved_host, port=resolved_port))
else:
from codebase_rag.mcp import serve_stdio
asyncio.run(serve_stdio())
except KeyboardInterrupt:
app_context.console.print(style(cs.CLI_MSG_APP_TERMINATED, cs.Color.RED))
except ValueError as e:
app_context.console.print(
style(cs.CLI_ERR_CONFIG.format(error=e), cs.Color.RED)
)
_info(style(cs.CLI_MSG_HINT_TARGET_REPO, cs.Color.YELLOW))
except Exception as e:
app_context.console.print(
style(cs.CLI_ERR_MCP_SERVER.format(error=e), cs.Color.RED)
)
@app.command(name=ch.CLICommandName.GRAPH_LOADER, help=ch.CMD_GRAPH_LOADER)
def graph_loader_command(
graph_file: str = typer.Argument(..., help=ch.HELP_GRAPH_FILE),
) -> None:
from .graph_loader import load_graph
try:
graph = load_graph(graph_file)
summary = graph.summary()
app_context.console.print(style(cs.CLI_MSG_GRAPH_SUMMARY, cs.Color.GREEN))
app_context.console.print(f" Total nodes: {summary['total_nodes']}")
app_context.console.print(
f" Total relationships: {summary['total_relationships']}"
)
app_context.console.print(
f" Node types: {list(summary['node_labels'].keys())}"
)
app_context.console.print(
f" Relationship types: {list(summary['relationship_types'].keys())}"
)
app_context.console.print(
f" Exported at: {summary['metadata']['exported_at']}"
)
except Exception as e:
app_context.console.print(
style(cs.CLI_ERR_LOAD_GRAPH.format(error=e), cs.Color.RED)
)
raise typer.Exit(1) from e
@app.command(
name=ch.CLICommandName.LANGUAGE,
help=ch.CMD_LANGUAGE,
context_settings={"allow_extra_args": True, "allow_interspersed_args": False},
)
def language_command(ctx: typer.Context) -> None:
language_cli(ctx.args, standalone_mode=False)
@app.command(name=ch.CLICommandName.DOCTOR, help=ch.CMD_DOCTOR)
def doctor() -> None:
checker = HealthChecker()
results = checker.run_all_checks()
passed, total = checker.get_summary()
table = Table(show_header=False, box=None, padding=(0, 2))
table.add_column(style="cyan", no_wrap=False)
for result in results:
status = "✓" if result.passed else "✗"
status_color = cs.Color.GREEN if result.passed else cs.Color.RED
status_text = style(status, status_color, cs.StyleModifier.NONE)
check_name = f"{status_text} {result.name}"
table.add_row(check_name)
panel = Panel(
table,
title="Health Check",
border_style="dim",
padding=(1, 2),
)
app_context.console.print(panel)
app_context.console.print()
summary_text = f"{passed}/{total} checks passed"
if passed == total:
app_context.console.print(style(summary_text, cs.Color.GREEN))
else:
app_context.console.print(style(summary_text, cs.Color.YELLOW))
failed_checks = [r for r in results if not r.passed and r.error]
if failed_checks:
app_context.console.print()
app_context.console.print(style("Failed checks details:", cs.Color.YELLOW))
for result in failed_checks:
error_msg = f" {result.name}: {result.error}"
app_context.console.print(
style(error_msg, cs.Color.YELLOW, cs.StyleModifier.NONE)
)
if passed < total:
raise typer.Exit(1)
def _build_stats_table(
title: str,
col_label: str,
rows: list[ResultRow],
get_label: Callable[[ResultRow], str],
total_label: str,
) -> Table:
table = Table(
title=style(title, cs.Color.GREEN),
show_header=True,
header_style=f"{cs.StyleModifier.BOLD} {cs.Color.MAGENTA}",
)
table.add_column(col_label, style=cs.Color.CYAN)
table.add_column(cs.CLI_STATS_COL_COUNT, style=cs.Color.YELLOW, justify="right")
total = 0
for row in rows:
raw_count = row.get("count", 0)
count = int(raw_count) if isinstance(raw_count, (int, float)) else 0
total += count
table.add_row(get_label(row), f"{count:,}")
table.add_section()
table.add_row(
style(total_label, cs.Color.GREEN),
style(f"{total:,}", cs.Color.GREEN),
)
return table
@app.command(name=ch.CLICommandName.STATS, help=ch.CMD_STATS)
def stats() -> None:
from .cypher_queries import (
CYPHER_STATS_NODE_COUNTS,
CYPHER_STATS_RELATIONSHIP_COUNTS,
)
app_context.console.print(style(cs.CLI_MSG_CONNECTING_STATS, cs.Color.CYAN))
try:
with connect_memgraph(batch_size=1) as ingestor:
node_results = ingestor.fetch_all(CYPHER_STATS_NODE_COUNTS)
rel_results = ingestor.fetch_all(CYPHER_STATS_RELATIONSHIP_COUNTS)
app_context.console.print(
_build_stats_table(
cs.CLI_STATS_NODE_TITLE,
cs.CLI_STATS_COL_NODE_TYPE,
node_results,
lambda r: ":".join(r.get("labels", [])) or cs.CLI_STATS_UNKNOWN,
cs.CLI_STATS_TOTAL_NODES,
)
)
app_context.console.print()
app_context.console.print(
_build_stats_table(
cs.CLI_STATS_REL_TITLE,
cs.CLI_STATS_COL_REL_TYPE,
rel_results,
lambda r: str(r.get("type", cs.CLI_STATS_UNKNOWN)),
cs.CLI_STATS_TOTAL_RELS,
)
)
except Exception as e:
app_context.console.print(
style(cs.CLI_ERR_STATS_FAILED.format(error=e), cs.Color.RED)
)
logger.exception(ls.STATS_ERROR.format(error=e))
raise typer.Exit(1) from e
if __name__ == "__main__":
app()