-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcli.py
More file actions
1410 lines (1120 loc) * 50.6 KB
/
cli.py
File metadata and controls
1410 lines (1120 loc) * 50.6 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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Lyra Intel CLI - Command-line interface for the intelligence engine.
Usage:
lyra-intel analyze [--output ] [--mode ]
lyra-intel scan
lyra-intel search
lyra-intel query
lyra-intel report [--type ] [--format ]
lyra-intel serve [--port ] [--host ]
lyra-intel worker [--coordinator ]
lyra-intel status
"""
import asyncio
import argparse
import json
import logging
import sys
from pathlib import Path
# Ensure src is importable when running directly
if __name__ == "__main__":
sys.path.insert(0, str(Path(__file__).parent))
from src.core.engine import LyraIntelEngine, EngineConfig, ProcessingMode
from src.collectors.file_crawler import FileCrawler
from src.collectors.git_collector import GitCollector
from src.analyzers.ast_analyzer import ASTAnalyzer
from src.analyzers.pattern_detector import PatternDetector
from src.storage.database import Database, DatabaseConfig
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger("lyra-intel")
async def cmd_analyze(args):
"""Analyze a repository."""
repo_path = Path(args.repo_path).resolve()
if not repo_path.exists():
logger.error(f"Repository not found: {repo_path}")
return 1
logger.info(f"Analyzing repository: {repo_path}")
# Determine mode
mode = ProcessingMode.LOCAL
if args.mode:
mode = ProcessingMode(args.mode)
# Create engine config
config = EngineConfig(
mode=mode,
output_dir=Path(args.output) if args.output else Path("./lyra-output"),
)
# Initialize engine
engine = LyraIntelEngine(config)
# Run analysis
result = await engine.analyze_repository(str(repo_path))
# Output results
if args.json:
print(json.dumps(result.metrics, indent=2))
else:
print("\n" + "="*60)
print("ANALYSIS COMPLETE")
print("="*60)
print(f"Target: {result.target}")
print(f"Success: {result.success}")
print(f"Duration: {result.duration_seconds:.2f}s")
print("\nMetrics:")
for key, value in result.metrics.items():
print(f" {key}: {value}")
if result.errors:
print("\nErrors:")
for error in result.errors:
print(f" - {error}")
return 0 if result.success else 1
async def cmd_quick_scan(args):
"""Quick scan of a repository."""
repo_path = Path(args.repo_path).resolve()
if not repo_path.exists():
logger.error(f"Repository not found: {repo_path}")
return 1
print(f"\nScanning: {repo_path}\n")
# File collection
print(" Collecting files...")
crawler = FileCrawler()
files = await crawler.collect_all(str(repo_path))
stats = await crawler.get_stats(files)
print(f" Total files: {stats['total_files']}")
print(f" Total size: {stats['total_size_bytes'] / 1024 / 1024:.2f} MB")
print(f" Total lines: {stats['total_lines']:,}")
# Git history
print("\n Analyzing git history...")
try:
git = GitCollector()
commits = await git.get_all_commits(str(repo_path))
git_stats = await git.get_stats(commits)
print(f" Total commits: {git_stats['total_commits']}")
print(f" Unique authors: {git_stats['unique_authors']}")
print(f" Total insertions: {git_stats['total_insertions']:,}")
print(f" Total deletions: {git_stats['total_deletions']:,}")
except Exception as e:
print(f" (Git analysis skipped: {e})")
# AST analysis (sample)
print("\n Analyzing code structure...")
analyzer = ASTAnalyzer()
source_files = [f for f in files if f.extension in [".py", ".js", ".ts", ".tsx"]][:100]
ast_results = await analyzer.analyze_files([f.path for f in source_files])
summary = analyzer.get_summary(ast_results)
print(f" Files analyzed: {summary['total_files']}")
print(f" Code units found: {summary['total_code_units']}")
print(f" Imports tracked: {summary['total_imports']}")
# Pattern detection (sample)
print("\n Detecting patterns...")
detector = PatternDetector()
pattern_count = 0
critical_count = 0
for result in ast_results:
if "error" not in result:
matches = await detector.detect_patterns(
result["file_path"],
ast_result=result
)
pattern_count += len(matches)
critical_count += sum(1 for m in matches if m.severity.value == "critical")
print(f" Patterns found: {pattern_count}")
print(f" Critical issues: {critical_count}")
print("\n" + "="*60)
print("Quick scan complete!")
print("="*60)
return 0
async def cmd_serve(args):
"""Start the API server."""
from src.api.server import APIServer, APIConfig
config = APIConfig(
host=args.host,
port=args.port,
)
server = APIServer(config)
print(f"\n Starting Lyra Intel API Server")
print(f" Host: {args.host}")
print(f" Port: {args.port}")
print(f"\nEndpoints:")
print(f" GET /health - Health check")
print(f" GET /status - System status")
print(f" POST /api/v1/analyze - Start analysis")
print(f" POST /api/v1/query - Query codebase")
print(f" POST /api/v1/search - Search code")
print(f" GET /api/v1/reports - List reports")
print(f"\nPress Ctrl+C to stop...")
try:
server.start(blocking=True)
except KeyboardInterrupt:
print("\nShutting down...")
server.stop()
return 0
async def cmd_search(args):
"""Search code in repository."""
from src.search.code_search import CodeSearch, SearchOptions
repo_path = Path(args.repo_path).resolve()
if not repo_path.exists():
logger.error(f"Repository not found: {repo_path}")
return 1
print(f"\n Searching for: {args.query}")
print(f" In: {repo_path}\n")
options = SearchOptions(
case_sensitive=args.case_sensitive if hasattr(args, 'case_sensitive') else False,
regex=args.regex if hasattr(args, 'regex') else False,
max_results=args.max_results if hasattr(args, 'max_results') else 50,
)
search = CodeSearch(options)
matches = search.search(args.query, str(repo_path))
if not matches:
print("No matches found.")
return 0
print(f"Found {len(matches)} matches:\n")
for match in matches[:20]: # Show first 20
print(f" {match.file_path}:{match.line_number}")
print(f" {match.line_content.strip()}")
print()
if len(matches) > 20:
print(f"... and {len(matches) - 20} more matches")
return 0
async def cmd_query(args):
"""Query the codebase with natural language."""
from src.query.query_engine import QueryEngine
repo_path = Path(args.repo_path).resolve()
if not repo_path.exists():
logger.error(f"Repository not found: {repo_path}")
return 1
print(f"\n Query: {args.question}")
print(f" Repository: {repo_path}\n")
# Build index first
print("Building index...")
crawler = FileCrawler()
files = await crawler.collect_all(str(repo_path))
analyzer = ASTAnalyzer()
source_files = [f for f in files if f.extension in [".py", ".js", ".ts", ".tsx"]][:200]
ast_results = await analyzer.analyze_files([f.path for f in source_files])
# Prepare data for query engine
analysis_data = {
"files": [f.to_dict() for f in files],
"ast_results": ast_results,
}
engine = QueryEngine()
engine.build_index(analysis_data)
# Execute query
result = engine.query(args.question)
print(f"Query type: {result.query_type.value}")
print(f"Execution time: {result.execution_time_ms:.2f}ms")
print(f"Results: {result.total}\n")
for item in result.results[:10]:
print(f" * {item.get('type', 'unknown')}: {item.get('name', item.get('path', 'unknown'))}")
if item.get('file_path'):
print(f" Location: {item['file_path']}")
print()
if result.suggestions:
print("Suggestions:")
for suggestion in result.suggestions:
print(f" {suggestion}")
return 0
async def cmd_report(args):
"""Generate analysis report."""
from src.reports.generator import ReportGenerator, ReportOptions, ReportType
repo_path = Path(args.repo_path).resolve()
if not repo_path.exists():
logger.error(f"Repository not found: {repo_path}")
return 1
print(f"\n Generating report for: {repo_path}")
print(f" Type: {args.type}")
print(f" Format: {args.format}\n")
# Collect data
print("Collecting data...")
crawler = FileCrawler()
files = await crawler.collect_all(str(repo_path))
file_stats = await crawler.get_stats(files)
print("Analyzing code...")
analyzer = ASTAnalyzer()
source_files = [f for f in files if f.extension in [".py", ".js", ".ts", ".tsx"]][:200]
ast_results = await analyzer.analyze_files([f.path for f in source_files])
ast_summary = analyzer.get_summary(ast_results)
print("Detecting patterns...")
detector = PatternDetector()
patterns_by_severity = {"critical": 0, "warning": 0, "info": 0}
patterns_by_category = {}
for result in ast_results:
if "error" not in result:
matches = await detector.detect_patterns(result["file_path"], ast_result=result)
for m in matches:
sev = m.severity.value
patterns_by_severity[sev] = patterns_by_severity.get(sev, 0) + 1
cat = m.category.value
patterns_by_category[cat] = patterns_by_category.get(cat, 0) + 1
print("Collecting git history...")
commits_data = {}
try:
git = GitCollector()
commits = await git.get_all_commits(str(repo_path))
commits_data = await git.get_stats(commits)
except Exception:
commits_data = {"total": 0, "authors": 0}
# Prepare analysis data
analysis_data = {
"repository": {"name": repo_path.name, "path": str(repo_path)},
"files": {
"total": file_stats.get("total_files", 0),
"total_lines": file_stats.get("total_lines", 0),
"total_size_bytes": file_stats.get("total_size_bytes", 0),
"by_extension": file_stats.get("by_extension", {}),
},
"code_units": {
"functions": ast_summary.get("by_type", {}).get("function", 0),
"classes": ast_summary.get("by_type", {}).get("class", 0),
"total_imports": ast_summary.get("total_imports", 0),
},
"patterns": {
"by_severity": patterns_by_severity,
"by_category": patterns_by_category,
},
"dependencies": {"internal": 0, "external": 0, "circular": []},
"commits": commits_data,
}
# Generate report
report_type_map = {
"executive": ReportType.EXECUTIVE,
"technical": ReportType.TECHNICAL,
"security": ReportType.SECURITY,
"architecture": ReportType.ARCHITECTURE,
"full": ReportType.FULL,
}
options = ReportOptions(
report_type=report_type_map.get(args.type, ReportType.FULL),
output_format=args.format,
)
generator = ReportGenerator(options)
output_file = None
if args.output:
output_file = args.output
else:
ext = "html" if args.format == "html" else "json" if args.format == "json" else "md"
output_file = f"report_{repo_path.name}_{args.type}.{ext}"
report = generator.generate(analysis_data, output_file)
print(f"\n Report generated: {output_file}")
print(f" Size: {len(report):,} characters")
return 0
async def cmd_worker(args):
"""Start a worker agent."""
from src.agents.worker import AnalysisWorker, WorkerConfig
config = WorkerConfig(
coordinator_url=args.coordinator,
)
worker = AnalysisWorker(config)
logger.info("Worker ready for tasks")
# Keep running
while True:
await asyncio.sleep(1)
async def cmd_forensic(args):
"""Run forensic analysis."""
from src.forensics.forensic_analyzer import ForensicAnalyzer, ForensicConfig
repo_path = Path(args.repo_path).resolve()
if not repo_path.exists():
logger.error(f"Repository not found: {repo_path}")
return 1
print(f"\n Running forensic analysis on: {repo_path}\n")
config = ForensicConfig(
enable_git_analysis=True,
parallel_workers=4,
)
analyzer = ForensicAnalyzer(config)
report = await analyzer.analyze_repository(str(repo_path))
print("\n" + "="*60)
print("FORENSIC ANALYSIS RESULTS")
print("="*60)
summary = report.get("summary", {})
print(f"\n Summary:")
print(f" Code entities: {summary.get('total_code_entities', 0):,}")
print(f" Doc entities: {summary.get('total_doc_entities', 0)}")
print(f" Relationships: {summary.get('total_relationships', 0)}")
print(f" Orphan code: {summary.get('orphan_code_count', 0)}")
print(f" Orphan docs: {summary.get('orphan_doc_count', 0)}")
print(f" Discrepancies: {summary.get('discrepancy_count', 0)}")
# Output to file if requested
if args.output:
import json
Path(args.output).write_text(json.dumps(report, indent=2))
print(f"\n Full report saved to: {args.output}")
return 0
async def cmd_complexity(args):
"""Analyze code complexity."""
from src.forensics.complexity_analyzer import ComplexityAnalyzer
repo_path = Path(args.repo_path).resolve()
if not repo_path.exists():
logger.error(f"Repository not found: {repo_path}")
return 1
print(f"\n Analyzing complexity of: {repo_path}\n")
analyzer = ComplexityAnalyzer()
results = analyzer.analyze_directory(str(repo_path))
summary = analyzer.get_summary(results)
print("=" * 60)
print("COMPLEXITY ANALYSIS")
print("=" * 60)
print(f"\nFiles analyzed: {summary['files_analyzed']}")
print(f"Total functions: {summary['total_entities']}")
print(f"Average complexity: {summary['average_cyclomatic']:.2f}")
print(f"Max complexity: {summary['max_cyclomatic']}")
print(f"Maintainability: {summary['average_maintainability']:.1f}%")
print("\n By Rating:")
for rating, count in summary.get('by_rating', {}).items():
if count > 0:
print(f" {rating}: {count}")
if summary.get('most_complex'):
print("\n Most Complex Functions:")
for entity in summary['most_complex'][:5]:
print(f" {entity.entity_name} ({entity.file_path}) - CC: {entity.cyclomatic_complexity}")
return 0
async def cmd_dead_code(args):
"""Detect dead/unused code."""
from src.forensics.dead_code_detector import DeadCodeDetector, DeadCodeConfig
repo_path = Path(args.repo_path).resolve()
if not repo_path.exists():
logger.error(f"Repository not found: {repo_path}")
return 1
print(f"\n Detecting dead code in: {repo_path}\n")
config = DeadCodeConfig(
check_functions=True,
check_classes=True,
check_imports=True,
min_confidence=0.7,
)
detector = DeadCodeDetector(config)
results = detector.analyze(str(repo_path))
summary = detector.get_summary(results)
print("=" * 60)
print("DEAD CODE ANALYSIS")
print("=" * 60)
print(f"\nPotential dead code: {summary['total_dead_code']}")
print(f"High confidence: {summary['high_confidence_count']}")
print(f"Files affected: {summary['files_affected']}")
print("\n By Type:")
for type_name, data in summary.get('by_type', {}).items():
print(f" {type_name}: {data['count']} ({data['high_confidence']} high confidence)")
if results[:10]:
print("\n Top Candidates:")
for r in results[:10]:
conf_bar = "*" * int(r.confidence * 5) + "*" * (5 - int(r.confidence * 5))
print(f" [{conf_bar}] {r.entity_name} ({r.entity_type}) - {r.file_path}:{r.line_number}")
return 0
async def cmd_dashboard(args):
"""Start visualization dashboard."""
from src.web.visualization_server import VisualizationServer, ServerConfig
from src.web.dashboard import Dashboard, DashboardConfig
print(f"\n Starting visualization dashboard...")
print(f" Host: {args.host}")
print(f" Port: {args.port}")
config = ServerConfig(
host=args.host,
port=args.port,
)
server = VisualizationServer(config)
# Set some sample data
server.set_dashboard_data({
"files": {"total": 0, "total_lines": 0},
"code_units": {"functions": 0, "classes": 0},
"patterns": {"by_severity": {}},
})
print(f"\n Dashboard available at: http://{args.host}:{args.port}/")
print(" Press Ctrl+C to stop...")
try:
server.start(blocking=True)
except KeyboardInterrupt:
print("\nShutting down...")
server.stop()
return 0
async def cmd_test(args):
"""Run test suite."""
from src.testing.test_runner import TestRunner, TestConfig
print("\n Running test suite...\n")
config = TestConfig(
parallel=not args.sequential,
verbose=args.verbose,
output_format=args.format,
)
runner = TestRunner(config)
# Add some basic tests
@runner.test("import_core")
def test_import_core():
from src.core.engine import LyraIntelEngine
assert LyraIntelEngine is not None
@runner.test("import_collectors")
def test_import_collectors():
from src.collectors.file_crawler import FileCrawler
from src.collectors.git_collector import GitCollector
assert FileCrawler is not None
assert GitCollector is not None
@runner.test("import_analyzers")
def test_import_analyzers():
from src.analyzers.ast_analyzer import ASTAnalyzer
from src.analyzers.pattern_detector import PatternDetector
assert ASTAnalyzer is not None
assert PatternDetector is not None
@runner.test("import_forensics")
def test_import_forensics():
from src.forensics.forensic_analyzer import ForensicAnalyzer
from src.forensics.complexity_analyzer import ComplexityAnalyzer
from src.forensics.dead_code_detector import DeadCodeDetector
assert ForensicAnalyzer is not None
assert ComplexityAnalyzer is not None
assert DeadCodeDetector is not None
@runner.test("import_auth")
def test_import_auth():
from src.auth.api_key_auth import APIKeyAuth
from src.auth.jwt_auth import JWTAuth
from src.auth.rate_limiter import RateLimiter
assert APIKeyAuth is not None
assert JWTAuth is not None
assert RateLimiter is not None
@runner.test("import_notifications")
def test_import_notifications():
from src.notifications.webhook_manager import WebhookManager
from src.notifications.notification_service import NotificationService
from src.notifications.alert_manager import AlertManager
assert WebhookManager is not None
assert NotificationService is not None
assert AlertManager is not None
results = await runner.run_all()
print(runner.format_results(results))
total_failed = sum(r.failed for r in results.values())
return 1 if total_failed > 0 else 0
async def cmd_benchmark(args):
"""Run performance benchmarks."""
from src.testing.benchmark_runner import BenchmarkRunner
print("\n Running benchmarks...\n")
runner = BenchmarkRunner()
@runner.benchmark("file_scan", iterations=10)
async def bench_file_scan():
from src.collectors.file_crawler import FileCrawler
crawler = FileCrawler()
await crawler.collect_all(".")
@runner.benchmark("ast_parse", iterations=50)
def bench_ast_parse():
from src.analyzers.ast_analyzer import ASTAnalyzer
analyzer = ASTAnalyzer()
# Parse a sample file
import ast
code = "def test(): pass"
ast.parse(code)
results = await runner.run_all()
print(runner.format_results(results))
return 0
async def cmd_security(args):
"""Run security scan."""
from src.security.security_scanner import SecurityScanner, SecurityConfig
repo_path = Path(args.repo_path).resolve()
if not repo_path.exists():
logger.error(f"Repository not found: {repo_path}")
return 1
print(f"\n Running security scan on: {repo_path}\n")
config = SecurityConfig(
scan_code=True,
scan_secrets=True,
scan_dependencies=True,
)
scanner = SecurityScanner(config)
result = scanner.scan_directory(str(repo_path))
print("=" * 60)
print("SECURITY SCAN RESULTS")
print("=" * 60)
print(f"\nScore: {result.score:.1f}/100 {' PASSED' if result.passed else ' FAILED'}")
print(f"Total Findings: {result.total_findings}")
print(f"Files Scanned: {result.scanned_files}")
print(f"Scan Duration: {result.scan_duration_ms:.2f}ms")
print("\n By Severity:")
for sev, count in result.summary.items():
if count > 0:
icon = "" if sev == "critical" else "" if sev == "high" else "" if sev == "medium" else ""
print(f" {icon} {sev.upper()}: {count}")
if result.recommendations:
print("\n Recommendations:")
for rec in result.recommendations:
print(f" {rec}")
if args.output:
report = scanner.generate_report(result)
Path(args.output).write_text(report)
print(f"\n Full report saved to: {args.output}")
return 0 if result.passed else 1
async def cmd_knowledge_graph(args):
"""Build and query knowledge graph."""
from src.knowledge.knowledge_graph import KnowledgeGraph
from src.knowledge.graph_builder import GraphBuilder
from src.knowledge.query_interface import GraphQueryInterface
repo_path = Path(args.repo_path).resolve()
if not repo_path.exists():
logger.error(f"Repository not found: {repo_path}")
return 1
print(f"\n Building knowledge graph for: {repo_path}\n")
# Collect files and analyze
crawler = FileCrawler()
files = await crawler.collect_all(str(repo_path))
analyzer = ASTAnalyzer()
source_files = [f for f in files if f.extension in [".py", ".js", ".ts", ".tsx"]][:200]
ast_results = await analyzer.analyze_files([f.path for f in source_files])
# Build graph
builder = GraphBuilder()
graph = builder.build_from_analysis(
files=[f.to_dict() for f in files],
ast_results=ast_results,
)
stats = graph.get_statistics()
print("=" * 60)
print("KNOWLEDGE GRAPH")
print("=" * 60)
print(f"\nNodes: {stats['total_nodes']}")
print(f"Edges: {stats['total_edges']}")
print(f"Density: {stats['density']:.4f}")
print("\n Nodes by Type:")
for ntype, count in stats['nodes_by_type'].items():
if count > 0:
print(f" {ntype}: {count}")
# Query if requested
if args.query:
print(f"\n Query: {args.query}")
query_interface = GraphQueryInterface(graph)
result = query_interface.query(args.query)
print(f" Result: {result.message}")
for node in result.nodes[:10]:
print(f" * {node.name} ({node.node_type.value})")
# Export if requested
if args.export:
if args.export.endswith('.json'):
graph.export_json(args.export)
elif args.export.endswith('.dot'):
graph.export_dot(args.export)
else:
graph.export_json(args.export + '.json')
print(f"\n Graph exported to: {args.export}")
return 0
async def cmd_generate(args):
"""Generate code from specifications."""
from src.generation.code_generator import CodeGenerator, GenerationConfig
print(f"\n Generating {args.type}: {args.name}\n")
config = GenerationConfig(
language=args.language,
include_tests=True,
include_docs=True,
)
generator = CodeGenerator(config)
if args.type == "function":
result = generator.generate_function(
name=args.name,
description=args.description,
)
elif args.type == "class":
result = generator.generate_class(
name=args.name,
description=args.description,
)
elif args.type == "api":
result = generator.generate_api_endpoint(
name=args.name,
path=f"/{args.name.lower()}",
method="GET",
description=args.description,
)
elif args.type == "model":
result = generator.generate_data_model(
name=args.name,
description=args.description,
fields=[],
)
else:
print(f"Unknown type: {args.type}")
return 1
print("=" * 60)
print("GENERATED CODE")
print("=" * 60)
print(result.code)
if result.tests:
print("\n" + "-" * 60)
print("GENERATED TESTS")
print("-" * 60)
print(result.tests)
return 0
async def cmd_profile(args):
"""Profile code for performance issues."""
from src.profiler.profiler import CodeProfiler
repo_path = Path(args.repo_path).resolve()
if not repo_path.exists():
logger.error(f"Repository not found: {repo_path}")
return 1
print(f"\n Profiling code in: {repo_path}\n")
profiler = CodeProfiler()
# Collect files
files_data = []
for file_path in repo_path.rglob("*.py"):
try:
content = file_path.read_text(errors="ignore")
files_data.append({"path": str(file_path), "content": content})
except Exception:
continue
result = profiler.profile_codebase(files_data[:100])
print("=" * 60)
print("PERFORMANCE PROFILE")
print("=" * 60)
print(f"\nComplexity Score: {result.complexity_score:.1f}")
print(f"Total Findings: {result.total_findings}")
print("\n By Issue Type:")
for issue, count in result.summary.items():
if count > 0:
print(f" {issue}: {count}")
if result.recommendations:
print("\n Recommendations:")
for rec in result.recommendations:
print(f" {rec}")
if result.findings:
print("\n Top Issues:")
for finding in result.findings[:5]:
print(f"\n [{finding.severity.upper()}] {finding.description}")
print(f" File: {finding.file_path}:{finding.line_number}")
print(f" Suggestion: {finding.suggestion}")
return 0
async def cmd_docs(args):
"""Generate documentation."""
from src.docgen.doc_generator import DocumentationGenerator, DocConfig
repo_path = Path(args.repo_path).resolve()
if not repo_path.exists():
logger.error(f"Repository not found: {repo_path}")
return 1
print(f"\n Generating {args.type} documentation for: {repo_path}\n")
config = DocConfig(
output_format="markdown",
include_examples=True,
include_toc=True,
)
generator = DocumentationGenerator(config)
# Collect analysis data
crawler = FileCrawler()
files = await crawler.collect_all(str(repo_path))
file_stats = await crawler.get_stats(files)
analyzer = ASTAnalyzer()
source_files = [f for f in files if f.extension in [".py", ".js", ".ts", ".tsx"]][:100]
ast_results = await analyzer.analyze_files([f.path for f in source_files])
analysis_data = {
"files": {
"total": file_stats.get("total_files", 0),
"total_lines": file_stats.get("total_lines", 0),
"by_extension": file_stats.get("by_extension", {}),
},
"code_units": {
"functions": sum(1 for r in ast_results for u in r.get("code_units", []) if u.get("type") == "function"),
"classes": sum(1 for r in ast_results for u in r.get("code_units", []) if u.get("type") == "class"),
},
}
if args.type == "api":
result = generator.generate_api_docs(ast_results, repo_path.name)
elif args.type == "readme":
result = generator.generate_readme(
repo_path.name,
"Auto-generated README",
["Feature 1", "Feature 2"],
analysis_data=analysis_data,
)
elif args.type == "architecture":
result = generator.generate_architecture_doc(repo_path.name, analysis_data)
else:
result = generator.generate_api_docs(ast_results, repo_path.name)
print("=" * 60)
print("GENERATED DOCUMENTATION")
print("=" * 60)
print(f"\nSections: {', '.join(result.sections)}")
print(f"Word Count: {result.word_count}")
if args.output:
Path(args.output).write_text(result.content)
print(f"\n Documentation saved to: {args.output}")
else:
print("\n" + result.content[:2000])
if len(result.content) > 2000:
print(f"\n... ({len(result.content) - 2000} more characters)")
return 0
async def cmd_commit_history(args):
"""Analyze commit history to find when bugs were introduced."""
from src.git.commit_analyzer import CommitAnalyzer, CommitAnalysisConfig
repo_path = Path(args.repo_path).resolve()
if not repo_path.exists():
logger.error(f"Repository not found: {repo_path}")
return 1
print(f"\n Analyzing commit history: {repo_path}")
print(f" Branch: {args.branch}\n")
# Create config
config = CommitAnalysisConfig(
branch=args.branch,
max_commits=args.max_commits,
start_commit=args.start,
end_commit=args.end,
analyze_security=not args.no_security,
analyze_complexity=not args.no_complexity,
skip_merge_commits=True,
)
# Create analyzer
analyzer = CommitAnalyzer(str(repo_path), config)
# Analyze commits
print(" This may take a while for large repositories...\n")
results = await analyzer.analyze_all_commits()
if not results:
print(" No commits found to analyze")
return 1
# Generate report
report = analyzer.generate_report(results)
# Display summary
print("\n" + "="*60)
print("COMMIT HISTORY ANALYSIS")
print("="*60)
summary = report["summary"]
print(f"\n Total commits analyzed: {summary['total_commits']}")
print(f" Date range: {summary['date_range']['first'][:10]} - {summary['date_range']['last'][:10]}")
print(f" Total changes: +{summary['total_changes']['insertions']} / -{summary['total_changes']['deletions']}")
current = report["current_state"]
print(f"\n Current state:")
print(f" Lines of code: {current['total_lines']:,}")
print(f" Functions: {current['total_functions']}")
print(f" Classes: {current['total_classes']}")
print(f" Avg complexity: {current['avg_complexity']:.2f}")
print(f" Security issues: {current['security_issues']}")
# Show problematic commits
problematic = report["problematic_commits"]
if problematic["complexity_spikes"]:
print(f"\n Complexity Spikes (top 5):")
for commit in problematic["complexity_spikes"][:5]: