Repository navigation
Expand file tree
/
Copy pathcode_evaluation_server.py
More file actions
5317 lines (4444 loc) · 203 KB
/
Copy pathcode_evaluation_server.py
File metadata and controls
5317 lines (4444 loc) · 203 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
"""
Code Evaluation MCP Server
This MCP server provides comprehensive code analysis and evaluation tools
for repository-level validation and assessment.
Core Features:
1. Repository structure analysis and mapping
2. Dependency detection and validation
3. Code quality assessment and metrics
4. Documentation completeness evaluation
5. Reproduction readiness assessment
6. Multi-language project support
Tools Provided:
- analyze_repo_structure: Deep repository structure analysis
- detect_dependencies: Intelligent dependency detection across languages
- assess_code_quality: Code quality metrics and issue identification
- evaluate_documentation: Documentation completeness and quality assessment
- check_reproduction_readiness: Assess readiness for reproduction
- generate_evaluation_summary: Comprehensive evaluation report generation
Usage:
python tools/code_evaluation_server.py
"""
import os
import json
import sys
import subprocess
import re
import ast
import time
import tempfile
import shutil
import traceback as tb
import networkx as nx
import asyncio
import threading
from pathlib import Path
from typing import Dict, Any, List, Optional, Tuple, Set, Union
import logging
from dataclasses import dataclass, asdict
from collections import defaultdict, Counter
# Import MCP modules
from mcp.server.fastmcp import FastMCP
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Create FastMCP server instance
mcp = FastMCP("code-evaluation")
@dataclass
class FileInfo:
"""Information about a single file"""
path: str
size: int
lines: int
language: str
complexity_score: float = 0.0
issues: List[str] = None
def __post_init__(self):
if self.issues is None:
self.issues = []
@dataclass
class DependencyInfo:
"""Dependency information structure"""
name: str
version: Optional[str]
source: str # requirements.txt, package.json, etc.
is_dev: bool = False
is_optional: bool = False
@dataclass
class RepoStructureInfo:
"""Repository structure analysis results"""
total_files: int
total_lines: int
languages: Dict[str, int] # language -> file count
directories: List[str]
file_details: List[FileInfo]
main_entry_points: List[str]
test_files: List[str]
config_files: List[str]
documentation_files: List[str]
@dataclass
class CodeQualityAssessment:
"""Code quality assessment results"""
overall_score: float # 0-100
complexity_issues: List[str]
style_issues: List[str]
potential_bugs: List[str]
security_issues: List[str]
maintainability_score: float
test_coverage_estimate: float
@dataclass
class DocumentationAssessment:
"""Documentation quality assessment"""
completeness_score: float # 0-100
has_readme: bool
has_api_docs: bool
has_examples: bool
has_installation_guide: bool
documentation_files_count: int
missing_documentation: List[str]
@dataclass
class StaticAnalysisIssue:
"""Individual static analysis issue"""
file_path: str
line: int
column: int
severity: str # error, warning, info
code: str
message: str
rule: str
fixable: bool = False
@dataclass
class StaticAnalysisResult:
"""Static analysis results for a file"""
file_path: str
language: str
issues: List[StaticAnalysisIssue]
formatted: bool = False
syntax_valid: bool = True
auto_fixes_applied: List[str] = None
def __post_init__(self):
if self.auto_fixes_applied is None:
self.auto_fixes_applied = []
@dataclass
class RepositoryStaticAnalysis:
"""Complete repository static analysis results"""
repo_path: str
analyzed_files: List[StaticAnalysisResult]
total_files: int
total_issues: int
error_count: int
warning_count: int
info_count: int
fixable_issues: int
auto_fixes_applied: int
languages_detected: List[str]
analysis_tools_used: List[str]
analysis_duration: float
# ===== PHASE 4: ADVANCED ERROR ANALYSIS DATACLASSES =====
@dataclass
class ErrorLocation:
"""Individual error location from traceback"""
file_path: str
function_name: str
line_number: int
code_line: str = ""
confidence: float = 1.0 # How confident we are this is relevant
@dataclass
class TracebackAnalysis:
"""Parsed traceback information"""
error_type: str
error_message: str
error_locations: List[ErrorLocation]
root_cause_file: Optional[str] = None
exception_chain: List[str] = None
def __post_init__(self):
if self.exception_chain is None:
self.exception_chain = []
@dataclass
class ImportRelationship:
"""Import relationship between files"""
importer: str
imported: str
import_type: str # "direct", "from", "as"
symbol: Optional[str] = None
line_number: Optional[int] = None
@dataclass
class LSPSymbolInfo:
"""LSP symbol information"""
name: str
kind: str # function, class, variable, module
file_path: str
line: int
column: int
references: List[Tuple[str, int, int]] = None # (file, line, col)
definitions: List[Tuple[str, int, int]] = None
def __post_init__(self):
if self.references is None:
self.references = []
if self.definitions is None:
self.definitions = []
@dataclass
class SuspectFile:
"""Suspect file for error remediation"""
file_path: str
confidence_score: float
reasons: List[str]
error_context: List[ErrorLocation]
suggested_focus_areas: List[str]
related_symbols: List[LSPSymbolInfo] = None
def __post_init__(self):
if self.related_symbols is None:
self.related_symbols = []
@dataclass
class ErrorAnalysisReport:
"""Comprehensive error analysis report"""
traceback_analysis: TracebackAnalysis
suspect_files: List[SuspectFile]
import_graph: Dict[str, List[str]]
call_chain_analysis: Dict[str, List[str]]
remediation_suggestions: List[str]
execution_context: Optional[Dict[str, Any]] = None
@dataclass
class SandboxResult:
"""Result from sandbox execution (Phase 4+)"""
success: bool
stdout: str
stderr: str
exit_code: int
execution_time: float
error_traceback: Optional[str] = None
resource_usage: Optional[Dict[str, Any]] = None
# ===== LSP CLIENT INFRASTRUCTURE (Phase 4+) =====
@dataclass
class LSPSymbol:
"""LSP symbol information"""
name: str
kind: int # SymbolKind from LSP
location: Dict[str, Any] # LSP Location
container_name: Optional[str] = None
detail: Optional[str] = None
@dataclass
class LSPDiagnostic:
"""LSP diagnostic information"""
range: Dict[str, Any] # LSP Range
severity: int # DiagnosticSeverity
code: Optional[str] = None
message: str = ""
source: Optional[str] = None
@dataclass
class LSPCodeAction:
"""LSP code action"""
title: str
kind: Optional[str] = None
diagnostics: Optional[List[LSPDiagnostic]] = None
edit: Optional[Dict[str, Any]] = None
command: Optional[Dict[str, Any]] = None
@dataclass
class LSPReference:
"""LSP reference location"""
uri: str
range: Dict[str, Any] # LSP Range
class LSPClient:
"""LSP client for communicating with language servers"""
def __init__(self, server_command: List[str], workspace_root: str):
self.server_command = server_command
self.workspace_root = os.path.abspath(workspace_root)
self.process = None
self.request_id = 0
self.response_futures = {}
self.initialized = False
self.logger = logging.getLogger(__name__ + ".LSPClient")
async def start(self):
"""Start the LSP server"""
try:
self.process = await asyncio.create_subprocess_exec(
*self.server_command,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
# Start reading responses
asyncio.create_task(self._read_responses())
# Initialize the server
await self._initialize()
self.logger.info(f"LSP server started: {' '.join(self.server_command)}")
except Exception as e:
self.logger.error(f"Failed to start LSP server: {e}")
raise
async def stop(self):
"""Stop the LSP server"""
if self.process:
try:
await self._send_notification("exit")
self.process.terminate()
await self.process.wait()
except Exception as e:
self.logger.error(f"Error stopping LSP server: {e}")
async def _initialize(self):
"""Initialize the LSP server"""
init_params = {
"processId": os.getpid(),
"rootUri": f"file://{self.workspace_root}",
"capabilities": {
"textDocument": {
"publishDiagnostics": {"relatedInformation": True},
"synchronization": {"didSave": True},
"completion": {"completionItem": {"snippetSupport": True}},
"definition": {"linkSupport": True},
"references": {"context": True},
"documentSymbol": {"hierarchicalDocumentSymbolSupport": True},
"codeAction": {"codeActionLiteralSupport": True},
"rename": {"prepareSupport": True}
},
"workspace": {
"workspaceFolders": True,
"symbol": {"symbolKind": {"valueSet": list(range(1, 27))}},
"executeCommand": {}
}
}
}
response = await self._send_request("initialize", init_params)
if response.get("error"):
raise Exception(f"LSP initialization failed: {response['error']}")
await self._send_notification("initialized", {})
self.initialized = True
async def _send_request(self, method: str, params: Dict[str, Any]) -> Dict[str, Any]:
"""Send an LSP request and wait for response"""
self.request_id += 1
request = {
"jsonrpc": "2.0",
"id": self.request_id,
"method": method,
"params": params
}
# Create future for response
future = asyncio.Future()
self.response_futures[self.request_id] = future
# Send request
message = json.dumps(request) + "\n"
content_length = len(message.encode())
full_message = f"Content-Length: {content_length}\r\n\r\n{message}"
self.process.stdin.write(full_message.encode())
await self.process.stdin.drain()
# Wait for response
try:
response = await asyncio.wait_for(future, timeout=30.0)
return response
except asyncio.TimeoutError:
self.logger.error(f"LSP request timeout: {method}")
return {"error": "Request timeout"}
async def _send_notification(self, method: str, params: Dict[str, Any] = None):
"""Send an LSP notification (no response expected)"""
notification = {
"jsonrpc": "2.0",
"method": method,
}
if params is not None:
notification["params"] = params
message = json.dumps(notification) + "\n"
content_length = len(message.encode())
full_message = f"Content-Length: {content_length}\r\n\r\n{message}"
self.process.stdin.write(full_message.encode())
await self.process.stdin.drain()
async def _read_responses(self):
"""Read responses from LSP server"""
buffer = b""
while self.process.returncode is None:
try:
data = await self.process.stdout.read(4096)
if not data:
break
buffer += data
while b"\r\n\r\n" in buffer:
header_end = buffer.find(b"\r\n\r\n")
header = buffer[:header_end].decode()
content_length = 0
for line in header.split("\r\n"):
if line.startswith("Content-Length:"):
content_length = int(line.split(":")[1].strip())
break
if len(buffer) >= header_end + 4 + content_length:
content = buffer[header_end + 4:header_end + 4 + content_length]
buffer = buffer[header_end + 4 + content_length:]
try:
message = json.loads(content.decode())
await self._handle_message(message)
except json.JSONDecodeError as e:
self.logger.error(f"Failed to parse LSP message: {e}")
else:
break
except Exception as e:
self.logger.error(f"Error reading LSP responses: {e}")
break
async def _handle_message(self, message: Dict[str, Any]):
"""Handle incoming LSP message"""
if "id" in message:
# Response to our request
request_id = message["id"]
if request_id in self.response_futures:
future = self.response_futures.pop(request_id)
if not future.done():
future.set_result(message)
else:
# Notification from server
method = message.get("method")
if method == "textDocument/publishDiagnostics":
# Handle diagnostics
pass
async def open_document(self, file_path: str) -> bool:
"""Open a document in the LSP server"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
params = {
"textDocument": {
"uri": f"file://{os.path.abspath(file_path)}",
"languageId": self._get_language_id(file_path),
"version": 1,
"text": content
}
}
await self._send_notification("textDocument/didOpen", params)
return True
except Exception as e:
self.logger.error(f"Failed to open document {file_path}: {e}")
return False
async def get_diagnostics(self, file_path: str) -> List[LSPDiagnostic]:
"""Get diagnostics for a file"""
# Diagnostics are sent via notifications, we'd need to store them
# For now, return empty list
return []
async def get_symbols(self, file_path: str) -> List[LSPSymbol]:
"""Get document symbols"""
try:
params = {
"textDocument": {
"uri": f"file://{os.path.abspath(file_path)}"
}
}
response = await self._send_request("textDocument/documentSymbol", params)
if response.get("error"):
self.logger.error(f"Get symbols failed: {response['error']}")
return []
symbols = []
for symbol_data in response.get("result", []):
symbol = LSPSymbol(
name=symbol_data.get("name", ""),
kind=symbol_data.get("kind", 0),
location=symbol_data.get("location", {}),
container_name=symbol_data.get("containerName"),
detail=symbol_data.get("detail")
)
symbols.append(symbol)
return symbols
except Exception as e:
self.logger.error(f"Failed to get symbols for {file_path}: {e}")
return []
async def find_references(self, file_path: str, line: int, character: int) -> List[LSPReference]:
"""Find references to symbol at position"""
try:
params = {
"textDocument": {
"uri": f"file://{os.path.abspath(file_path)}"
},
"position": {
"line": line,
"character": character
},
"context": {
"includeDeclaration": True
}
}
response = await self._send_request("textDocument/references", params)
if response.get("error"):
self.logger.error(f"Find references failed: {response['error']}")
return []
references = []
for ref_data in response.get("result", []):
reference = LSPReference(
uri=ref_data.get("uri", ""),
range=ref_data.get("range", {})
)
references.append(reference)
return references
except Exception as e:
self.logger.error(f"Failed to find references: {e}")
return []
async def get_code_actions(self, file_path: str, range_data: Dict[str, Any], diagnostics: List[LSPDiagnostic] = None) -> List[LSPCodeAction]:
"""Get code actions for a range"""
try:
params = {
"textDocument": {
"uri": f"file://{os.path.abspath(file_path)}"
},
"range": range_data,
"context": {
"diagnostics": [asdict(d) for d in (diagnostics or [])]
}
}
response = await self._send_request("textDocument/codeAction", params)
if response.get("error"):
self.logger.error(f"Get code actions failed: {response['error']}")
return []
actions = []
for action_data in response.get("result", []):
if isinstance(action_data, dict):
action = LSPCodeAction(
title=action_data.get("title", ""),
kind=action_data.get("kind"),
edit=action_data.get("edit"),
command=action_data.get("command")
)
actions.append(action)
return actions
except Exception as e:
self.logger.error(f"Failed to get code actions: {e}")
return []
def _get_language_id(self, file_path: str) -> str:
"""Get LSP language ID for file"""
ext = os.path.splitext(file_path)[1].lower()
language_map = {
'.py': 'python',
'.js': 'javascript',
'.ts': 'typescript',
'.jsx': 'javascriptreact',
'.tsx': 'typescriptreact',
'.java': 'java',
'.cpp': 'cpp',
'.c': 'c',
'.h': 'c',
'.hpp': 'cpp',
'.rs': 'rust',
'.go': 'go',
'.php': 'php',
'.rb': 'ruby',
'.cs': 'csharp',
'.vb': 'vb',
'.sql': 'sql',
'.json': 'json',
'.xml': 'xml',
'.html': 'html',
'.css': 'css',
'.scss': 'scss',
'.less': 'less',
'.md': 'markdown',
'.yml': 'yaml',
'.yaml': 'yaml'
}
return language_map.get(ext, 'plaintext')
class LSPManager:
"""Manager for multiple LSP servers"""
def __init__(self, workspace_root: str):
self.workspace_root = workspace_root
self.clients = {}
self.logger = logging.getLogger(__name__ + ".LSPManager")
async def start_server(self, language: str, command: List[str]) -> bool:
"""Start LSP server for a language"""
try:
if language in self.clients:
return True
client = LSPClient(command, self.workspace_root)
await client.start()
self.clients[language] = client
self.logger.info(f"Started LSP server for {language}")
return True
except Exception as e:
self.logger.error(f"Failed to start LSP server for {language}: {e}")
return False
async def stop_all(self):
"""Stop all LSP servers"""
for language, client in self.clients.items():
try:
await client.stop()
self.logger.info(f"Stopped LSP server for {language}")
except Exception as e:
self.logger.error(f"Error stopping LSP server for {language}: {e}")
self.clients.clear()
def get_client(self, language: str) -> Optional[LSPClient]:
"""Get LSP client for language"""
return self.clients.get(language)
async def setup_for_repository(self, repo_path: str) -> Dict[str, bool]:
"""Automatically set up LSP servers for detected languages in repository"""
languages_detected = detect_repository_languages(repo_path)
setup_results = {}
# Language server commands
server_commands = {
'python': ['python', '-m', 'pylsp'], # python-lsp-server
'javascript': ['typescript-language-server', '--stdio'],
'typescript': ['typescript-language-server', '--stdio'],
'java': ['jdtls'], # Eclipse JDT Language Server
'cpp': ['clangd'],
'c': ['clangd'],
'rust': ['rust-analyzer'],
'go': ['gopls'],
'php': ['intelephense', '--stdio'],
'ruby': ['solargraph', 'stdio'],
'csharp': ['omnisharp', '--lsp']
}
for language, files in languages_detected.items():
if language in server_commands:
success = await self.start_server(language, server_commands[language])
setup_results[language] = success
if success:
# Open some representative files
client = self.get_client(language)
for file_path in files[:5]: # Open first 5 files
await client.open_document(file_path)
else:
setup_results[language] = False
self.logger.warning(f"No LSP server configured for {language}")
return setup_results
# Language detection patterns
LANGUAGE_PATTERNS = {
'.py': 'python',
'.js': 'javascript',
'.ts': 'typescript',
'.java': 'java',
'.cpp': 'cpp',
'.c': 'c',
'.h': 'c',
'.hpp': 'cpp',
'.cs': 'csharp',
'.go': 'go',
'.rs': 'rust',
'.php': 'php',
'.rb': 'ruby',
'.swift': 'swift',
'.kt': 'kotlin',
'.scala': 'scala',
'.r': 'r',
'.m': 'matlab',
'.sh': 'shell',
'.sql': 'sql',
'.md': 'markdown',
'.yml': 'yaml',
'.yaml': 'yaml',
'.json': 'json',
'.xml': 'xml',
'.html': 'html',
'.css': 'css'
}
# Configuration and dependency files
CONFIG_FILES = [
'requirements.txt', 'setup.py', 'setup.cfg', 'pyproject.toml', 'Pipfile',
'package.json', 'package-lock.json', 'yarn.lock',
'pom.xml', 'build.gradle', 'Cargo.toml',
'Makefile', 'CMakeLists.txt', 'configure.ac',
'Dockerfile', 'docker-compose.yml',
'.gitignore', '.env', '.env.example'
]
# Documentation file patterns
DOC_PATTERNS = [
r'README.*',
r'INSTALL.*',
r'CHANGELOG.*',
r'CONTRIBUTING.*',
r'LICENSE.*',
r'docs?/.*',
r'documentation/.*',
r'.*\.md$',
r'.*\.rst$',
r'.*\.txt$'
]
# Static analysis tool configurations
STATIC_ANALYSIS_TOOLS = {
'python': {
'formatters': ['black', 'isort'],
'linters': ['flake8', 'pylint', 'mypy'],
'syntax_checker': 'python',
'extensions': ['.py']
},
'javascript': {
'formatters': ['prettier'],
'linters': ['eslint'],
'syntax_checker': 'node',
'extensions': ['.js', '.jsx']
},
'typescript': {
'formatters': ['prettier'],
'linters': ['eslint', 'tsc'],
'syntax_checker': 'tsc',
'extensions': ['.ts', '.tsx']
},
'java': {
'formatters': ['google-java-format'],
'linters': ['checkstyle', 'spotbugs'],
'syntax_checker': 'javac',
'extensions': ['.java']
},
'go': {
'formatters': ['gofmt', 'goimports'],
'linters': ['golint', 'go vet'],
'syntax_checker': 'go',
'extensions': ['.go']
},
'rust': {
'formatters': ['rustfmt'],
'linters': ['clippy'],
'syntax_checker': 'rustc',
'extensions': ['.rs']
},
'cpp': {
'formatters': ['clang-format'],
'linters': ['cppcheck', 'clang-tidy'],
'syntax_checker': 'clang++',
'extensions': ['.cpp', '.cxx', '.cc']
},
'c': {
'formatters': ['clang-format'],
'linters': ['cppcheck'],
'syntax_checker': 'clang',
'extensions': ['.c', '.h']
}
}
def get_file_language(file_path: str) -> str:
"""Determine programming language from file extension"""
ext = Path(file_path).suffix.lower()
return LANGUAGE_PATTERNS.get(ext, 'unknown')
def count_lines_in_file(file_path: str) -> int:
"""Count non-empty lines in a file"""
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
return len([line for line in f if line.strip()])
except Exception:
return 0
def calculate_complexity_score(file_path: str, language: str) -> float:
"""Calculate basic complexity score for a file"""
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
complexity = 0
if language == 'python':
# Count control structures, functions, classes
complexity += len(re.findall(r'\b(if|elif|while|for|try|except|with)\b', content))
complexity += len(re.findall(r'\bdef\s+\w+', content))
complexity += len(re.findall(r'\bclass\s+\w+', content))
elif language in ['javascript', 'typescript']:
complexity += len(re.findall(r'\b(if|else|while|for|switch|try|catch|function)\b', content))
complexity += len(re.findall(r'=>', content))
elif language == 'java':
complexity += len(re.findall(r'\b(if|else|while|for|switch|try|catch|public|private|protected)\b', content))
complexity += len(re.findall(r'\bclass\s+\w+', content))
# Normalize by file size
lines = len(content.split('\n'))
return min(complexity / max(lines, 1) * 100, 100)
except Exception:
return 0
def detect_issues_in_file(file_path: str, language: str) -> List[str]:
"""Detect potential issues in a file"""
issues = []
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
# Common issues across languages
if len(content.split('\n')) > 1000:
issues.append("File is very large (>1000 lines)")
if 'TODO' in content.upper() or 'FIXME' in content.upper():
issues.append("Contains TODO/FIXME comments")
if language == 'python':
# Python-specific checks
if 'import *' in content:
issues.append("Uses wildcard imports")
if re.search(r'except:', content):
issues.append("Uses bare except clauses")
if 'eval(' in content or 'exec(' in content:
issues.append("Uses potentially dangerous eval/exec")
elif language in ['javascript', 'typescript']:
# JavaScript/TypeScript-specific checks
if 'eval(' in content:
issues.append("Uses dangerous eval function")
if re.search(r'var\s+\w+', content):
issues.append("Uses var instead of let/const")
except Exception as e:
issues.append(f"Error analyzing file: {str(e)}")
return issues
def find_entry_points(repo_path: str) -> List[str]:
"""Find main entry points in the repository"""
entry_points = []
common_entry_files = [
'main.py', '__main__.py', 'app.py', 'run.py', 'start.py',
'index.js', 'main.js', 'app.js', 'server.js',
'Main.java', 'Application.java',
'main.cpp', 'main.c'
]
for root, dirs, files in os.walk(repo_path):
for file in files:
file_path = os.path.join(root, file)
rel_path = os.path.relpath(file_path, repo_path)
# Check for common entry point names
if file in common_entry_files:
entry_points.append(rel_path)
continue
# Check for executable scripts
if file.endswith('.py'):
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
first_line = f.readline()
if first_line.startswith('#!') or 'if __name__ == "__main__"' in f.read():
entry_points.append(rel_path)
except Exception:
pass
return entry_points
def find_test_files(repo_path: str) -> List[str]:
"""Find test files in the repository"""
test_files = []
test_patterns = [
r'test_.*\.py$',
r'.*_test\.py$',
r'tests?/.*\.py$',
r'.*\.test\.js$',
r'.*\.spec\.js$',
r'test/.*\.js$',
r'.*Test\.java$',
r'.*Tests\.java$'
]
for root, dirs, files in os.walk(repo_path):
for file in files:
file_path = os.path.join(root, file)
rel_path = os.path.relpath(file_path, repo_path)
for pattern in test_patterns:
if re.match(pattern, rel_path, re.IGNORECASE):
test_files.append(rel_path)
break
return test_files
def find_documentation_files(repo_path: str) -> List[str]:
"""Find documentation files in the repository"""
doc_files = []
for root, dirs, files in os.walk(repo_path):
for file in files:
file_path = os.path.join(root, file)
rel_path = os.path.relpath(file_path, repo_path)
for pattern in DOC_PATTERNS:
if re.match(pattern, rel_path, re.IGNORECASE):
doc_files.append(rel_path)
break
return doc_files
def parse_python_dependencies(repo_path: str) -> List[DependencyInfo]:
"""Parse Python dependencies from various files"""
deps = []
# requirements.txt
req_file = os.path.join(repo_path, 'requirements.txt')
if os.path.exists(req_file):
try:
with open(req_file, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#'):
# Parse package==version or package>=version
match = re.match(r'^([a-zA-Z0-9\-_]+)([><=!]+.*)?', line)
if match:
name = match.group(1)
version = match.group(2) if match.group(2) else None
deps.append(DependencyInfo(name, version, 'requirements.txt'))
except Exception as e:
logger.warning(f"Error parsing requirements.txt: {e}")
# setup.py
setup_file = os.path.join(repo_path, 'setup.py')
if os.path.exists(setup_file):
try:
with open(setup_file, 'r', encoding='utf-8') as f:
content = f.read()