-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathtree_code.py
More file actions
1679 lines (1395 loc) · 76.1 KB
/
tree_code.py
File metadata and controls
1679 lines (1395 loc) · 76.1 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 python
"""
Global code tree builder - Used to parse Python code repositories and create a structured code tree
Can save code tree locally and generate context content suitable for LLM browsing and analysis
"""
import os
import ast
import re
import json
import networkx as nx
from typing import Dict, List, Set, Tuple, Optional, Union, Any
import argparse
import logging
from collections import defaultdict
import time
import pickle
from tqdm import tqdm
import tiktoken
from src.core.code_utils import _get_code_abs, get_code_abs_token, should_ignore_path, ignored_dirs, ignored_file_patterns
from src.core.repo_summary import generate_repository_summary
import glob
from src.utils.data_preview import _parse_ipynb_file
# Import importance analyzer
try:
from src.core.importance_analyzer import ImportanceAnalyzer
except ImportError:
# Try relative import
try:
from src.core.importance_analyzer import ImportanceAnalyzer
except ImportError:
ImportanceAnalyzer = None
logging.warning("Cannot import ImportanceAnalyzer, code importance analysis will not be available.")
# Modify tree-sitter import
import tree_sitter
from tree_sitter_language_pack import get_language, get_parser
# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class GlobalCodeTreeBuilder:
"""Global code tree builder, used to parse code repositories and build LLM-friendly structured representations"""
def __init__(self, repo_path: str):
"""
Initialize code tree builder
Args:
repo_path: Path to the code repository
ignored_dirs: List of directories to ignore
ignored_file_patterns: List of file patterns to ignore
"""
self.repo_path = repo_path
self.call_graph = nx.DiGraph() # Function call graph
self.modules = {} # Module information
self.functions = {} # Function information
self.classes = {} # Class information
self.other_files = {} # Other file information
self.imports = defaultdict(list) # Import information
self.code_tree = { # Hierarchical code tree
'modules': {},
'stats': {
'total_modules': 0,
'total_classes': 0,
'total_functions': 0,
'total_lines': 0
},
'key_components': [] # Key components
}
# Uniformly define directories and file patterns to ignore, use defaults if not provided in parameters
self.ignored_dirs = ignored_dirs
self.ignored_file_patterns = ignored_file_patterns
# Check if Jupyter Notebook parsing is supported
self.jupyter_support = False
try:
import nbformat
self.jupyter_support = True
logger.info("Successfully loaded nbformat library, will support Jupyter Notebook parsing")
except ImportError:
logger.warning("Unable to import nbformat library, will skip Jupyter Notebook parsing")
# Initialize tree-sitter
self.parser = None
self.python_language = None
if tree_sitter is not None:
try:
# Use tree_sitter_languages to simplify language loading
self.parser = get_parser('python')
self.python_language = get_language('python')
if self.parser and self.python_language:
logger.info("Successfully loaded tree-sitter Python language")
else:
logger.warning("Unable to load tree-sitter Python language")
except Exception as e:
logger.warning(f"Unable to initialize tree-sitter: {e}, will use simple code display")
else:
logger.warning("tree-sitter library not available, will use simple code display")
def parse_repository(self) -> None:
"""Parse the entire code repository"""
logger.info(f"Starting to parse code repository: {self.repo_path}")
# Find and parse all Python files and Jupyter Notebook files
for root, dirs, files in os.walk(self.repo_path):
# Calculate current directory depth (relative to repository root)
rel_path = os.path.relpath(root, self.repo_path)
current_depth = 0 if rel_path == '.' else len(rel_path.split(os.sep))
# If directory depth exceeds 5, skip this directory and its subdirectories
if current_depth > 3:
dirs[:] = [] # Clear dirs list so os.walk won't enter subdirectories
# logger.info(f"Directory {rel_path} depth exceeds 4, skipping this directory and its subdirectories")
continue
# Modify dirs list in place, skip ignored directories
dirs[:] = [d for d in dirs if d not in self.ignored_dirs]
# Limit processing to maximum 40 files per directory
file_count = 0
max_files_per_dir = 40
if len(files) > 100:
continue
elif len(files) > 50:
files = files[:5]
for file in files:
# If already processed 40 files, ignore remaining files in this directory
if file_count >= max_files_per_dir:
# logger.info(f"Directory {rel_path} contains more than {max_files_per_dir} files, ignoring remaining files")
break
file_path = os.path.join(root, file)
rel_path = os.path.relpath(file_path, self.repo_path)
# Use unified function to check if should be ignored
if should_ignore_path(rel_path):
continue
# Add before processing files
file_size = os.path.getsize(file_path)
if file_size > 10 * 1024 * 1024: # Skip files larger than 10MB
# logger.info(f"File {rel_path} is too large ({file_size/1024/1024:.2f}MB), skipping")
continue
try:
if file.endswith('.py'):
self._parse_python_file(file_path, rel_path)
else:
self._parse_other_file(file_path, rel_path)
# Increment count after successfully processing file
file_count += 1
except Exception as e:
logger.error(f"Error parsing file {rel_path}: {e}", exc_info=True)
# Build various relationships
self._build_call_relationships()
self._resolve_base_classes()
self._build_hierarchical_code_tree()
# Identify key components
self._identify_key_class()
# Identify key modules
key_modules = self._identify_key_modules()
if key_modules:
self.code_tree['key_modules'] = key_modules
logger.info(f"Identified {len(key_modules)} key modules")
logger.info(f"Code repository parsing completed, found {len(self.modules)} modules, {len(self.classes)} classes, {len(self.functions)} functions")
def _parse_python_file(self, file_path: str, rel_path: str) -> None:
"""
Parse single Python file
Args:
file_path: Absolute path of the file
rel_path: Path relative to repository root
"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
module_node = ast.parse(content, filename=rel_path)
module_docstring = ast.get_docstring(module_node) or ""
# Create module ID with dot-separated path
module_id = rel_path.replace('/', '.').replace('\\', '.').replace('.py', '')
self.modules[module_id] = {
'path': rel_path,
'docstring': module_docstring,
'content': content,
'functions': [],
'classes': []
}
# Process import statements
self._process_imports(module_node, module_id)
# Parse functions and classes
for node in ast.walk(module_node):
# Process function definitions
if isinstance(node, ast.FunctionDef):
if not hasattr(node, 'parent_class'):
self._process_function(node, module_id, None)
# Process class definitions
elif isinstance(node, ast.ClassDef):
class_id = f"{module_id}.{node.name}"
class_docstring = ast.get_docstring(node) or ""
# Analyze class inheritance relationships
base_classes = []
for base in node.bases:
if isinstance(base, ast.Name):
base_classes.append(base.id)
elif isinstance(base, ast.Attribute):
base_classes.append(self._get_attribute_path(base))
self.classes[class_id] = {
'name': node.name,
'module': module_id,
'docstring': class_docstring,
'methods': [],
'base_classes': base_classes,
'source': self._get_source(content, node)
}
self.modules[module_id]['classes'].append(class_id)
# Process methods in the class
for class_node in node.body:
if isinstance(class_node, ast.FunctionDef):
# Add parent class attribute for method
class_node.parent_class = class_id
self._process_function(class_node, module_id, class_id)
except SyntaxError as e:
logger.warning(f"File {rel_path} has syntax errors: {e}")
except Exception as e:
logger.error(f"Error processing file {rel_path}: {e}")
def _parse_other_file(self, file_path: str, rel_path: str) -> None:
"""
Parse non-Python files, including Jupyter Notebooks etc
Args:
file_path: Absolute path of the file
rel_path: Path relative to repository root
"""
try:
if file_path.endswith('.ipynb'):
content = _parse_ipynb_file(file_path)
else:
content = open(file_path, 'r', encoding='utf-8').read()
# Create a simple module record for non-Python files
# Use file extension as "language" identifier
file_ext = os.path.splitext(file_path)[1][1:] # Remove the dot
module_id = rel_path.replace('/', '.').replace('\\', '.').replace(f'.{file_ext}', '')
self.other_files[module_id] = {
'path': rel_path,
'docstring': f"Non-Python file: {file_ext.upper()} code",
'content': content,
'functions': [],
'classes': [],
'language': file_ext
}
logger.debug(f"Recorded non-Python file: {rel_path}")
except Exception as e:
logger.error(f"Error processing non-Python file {rel_path}: {e}")
def _process_imports(self, module_node: ast.Module, module_id: str) -> None:
"""Process import statements in the module"""
for node in module_node.body:
if isinstance(node, ast.Import):
for name in node.names:
self.imports[module_id].append({
'type': 'import',
'name': name.name,
'alias': name.asname
})
elif isinstance(node, ast.ImportFrom):
module = node.module or ''
for name in node.names:
self.imports[module_id].append({
'type': 'importfrom',
'module': module,
'name': name.name,
'alias': name.asname
})
def _resolve_base_class(self, base_name: str, module_id: str) -> str:
"""
Resolve base class name to full path
Args:
base_name: Simple base class name (e.g., 'LLM')
module_id: Current module ID
Returns:
Full path of the base class if found, otherwise the original name
"""
# 1. Check if base class is defined in the same module
same_module_class_id = f"{module_id}.{base_name}"
if same_module_class_id in self.classes:
return same_module_class_id
# 2. Check imports for the base class
for imp in self.imports.get(module_id, []):
if imp['type'] == 'importfrom':
# from module import ClassName
if imp['name'] == base_name or imp.get('alias') == base_name:
return f"{imp['module']}.{imp['name']}"
elif imp['type'] == 'import':
# import module (base_name might be module.ClassName)
if base_name.startswith(imp['name'] + '.') or (imp.get('alias') and base_name.startswith(imp['alias'] + '.')):
return base_name
# 3. Check if any existing class matches this name
for class_id in self.classes:
if class_id.endswith('.' + base_name):
return class_id
# Return original name if not resolved
return base_name
def _resolve_base_classes(self) -> None:
"""Resolve all base class names to full paths after all classes are parsed"""
logger.info("Resolving base class names to full paths...")
for class_id, class_info in self.classes.items():
module_id = class_info['module']
resolved_bases = []
for base_name in class_info.get('base_classes', []):
# If already a full path (contains '.'), keep it
if '.' in base_name:
resolved_bases.append(base_name)
else:
resolved_bases.append(self._resolve_base_class(base_name, module_id))
class_info['base_classes'] = resolved_bases
def _process_function(self, node: ast.FunctionDef, module_id: str, class_id: Optional[str]) -> None:
"""Process function or method definition"""
function_name = node.name
if class_id:
function_id = f"{class_id}.{function_name}"
self.classes[class_id]['methods'].append(function_id)
else:
function_id = f"{module_id}.{function_name}"
self.modules[module_id]['functions'].append(function_id)
docstring = ast.get_docstring(node) or ""
# Get source code
source = self._get_source(self.modules[module_id]['content'], node)
# Analyze function parameters
parameters = []
for arg in node.args.args:
param_name = arg.arg
param_type = None
if hasattr(arg, 'annotation') and arg.annotation:
if isinstance(arg.annotation, ast.Name):
param_type = arg.annotation.id
elif isinstance(arg.annotation, ast.Attribute):
param_type = self._get_attribute_path(arg.annotation)
elif isinstance(arg.annotation, ast.Subscript):
param_type = self._get_subscript_annotation(arg.annotation)
parameters.append({
'name': param_name,
'type': param_type
})
# Analyze function return type
return_type = None
if hasattr(node, 'returns') and node.returns:
if isinstance(node.returns, ast.Name):
return_type = node.returns.id
elif isinstance(node.returns, ast.Attribute):
return_type = self._get_attribute_path(node.returns)
elif isinstance(node.returns, ast.Subscript):
return_type = self._get_subscript_annotation(node.returns)
# Analyze function calls in the function body
calls = self._extract_function_calls(node)
self.functions[function_id] = {
'name': function_name,
'module': module_id,
'class': class_id,
'docstring': docstring,
'parameters': parameters,
'return_type': return_type,
'calls': calls,
'called_by': [], # Will be populated when building call relationships
'source': source
}
# Add node to call graph
self.call_graph.add_node(function_id)
def _extract_function_calls(self, node: ast.FunctionDef) -> List[Dict]:
"""Extract function calls from function body"""
calls = []
for subnode in ast.walk(node):
if isinstance(subnode, ast.Call):
call_info = self._analyze_call(subnode)
if call_info:
calls.append(call_info)
return calls
def _analyze_call(self, node: ast.Call) -> Optional[Dict]:
"""Analyze function call expression"""
if isinstance(node.func, ast.Name):
# Simple function call func()
return {'type': 'simple', 'name': node.func.id}
elif isinstance(node.func, ast.Attribute):
# Attribute call obj.method()
if isinstance(node.func.value, ast.Name):
return {
'type': 'attribute',
'object': node.func.value.id,
'attribute': node.func.attr
}
# Nested attribute call module.sub.func()
return {
'type': 'nested_attribute',
'full_path': self._get_attribute_path(node.func)
}
return None
def _get_attribute_path(self, node: ast.Attribute) -> str:
"""Get complete attribute path (e.g. module.submodule.function)"""
parts = []
current = node
while isinstance(current, ast.Attribute):
parts.append(current.attr)
current = current.value
if isinstance(current, ast.Name):
parts.append(current.id)
return '.'.join(reversed(parts))
def _get_subscript_annotation(self, node: ast.Subscript) -> str:
"""Get subscript expression in type annotation (e.g. List[str])"""
# Handle Python 3.8+
try:
if isinstance(node.value, ast.Name):
container = node.value.id
elif isinstance(node.value, ast.Attribute):
container = self._get_attribute_path(node.value)
else:
return "unknown"
# Compatible with Python 3.8 and earlier
if hasattr(node, 'slice') and isinstance(node.slice, ast.Index):
slice_value = node.slice.value
if isinstance(slice_value, ast.Name):
param = slice_value.id
elif isinstance(slice_value, ast.Attribute):
param = self._get_attribute_path(slice_value)
else:
param = "unknown"
# Compatible with Python 3.9+
elif hasattr(node, 'slice'):
if isinstance(node.slice, ast.Name):
param = node.slice.id
elif isinstance(node.slice, ast.Attribute):
param = self._get_attribute_path(node.slice)
else:
param = "unknown"
else:
param = "unknown"
return f"{container}[{param}]"
except Exception:
return "unknown"
def _build_call_relationships(self) -> None:
"""Build call relationships between functions"""
logger.info("Building function call relationships...")
for func_id, func_info in self.functions.items():
calls = func_info['calls']
module_id = func_info['module']
for call in calls:
called_func_id = self._resolve_call(call, module_id, func_info['class'])
if called_func_id and called_func_id in self.functions:
# Add to call graph
self.call_graph.add_edge(func_id, called_func_id)
# Update called function information
if func_id not in self.functions[called_func_id]['called_by']:
self.functions[called_func_id]['called_by'].append(func_id)
def _resolve_call(self, call: Dict, module_id: str, class_id: Optional[str]) -> Optional[str]:
"""Resolve function call and return the ID of the called function"""
if call['type'] == 'simple':
# Check functions in the same module
direct_func_id = f"{module_id}.{call['name']}"
if direct_func_id in self.functions:
return direct_func_id
# Check methods in the same class
if class_id:
method_id = f"{class_id}.{call['name']}"
if method_id in self.functions:
return method_id
# Check methods in parent classes
if class_id in self.classes:
for base_class in self.classes[class_id]['base_classes']:
# Try to construct complete base class path
# If it's a simple name, try to find it in the same module
if '.' not in base_class:
potential_base = f"{module_id}.{base_class}"
if potential_base in self.classes:
base_method_id = f"{potential_base}.{call['name']}"
if base_method_id in self.functions:
return base_method_id
else:
# Already a complete path
base_method_id = f"{base_class}.{call['name']}"
if base_method_id in self.functions:
return base_method_id
# Check imported functions
for imp in self.imports[module_id]:
if imp['type'] == 'importfrom' and imp['name'] == call['name']:
imported_module = imp['module']
imported_func_id = f"{imported_module}.{call['name']}"
if imported_func_id in self.functions:
return imported_func_id
elif call['type'] == 'attribute':
obj_name = call['object']
attr_name = call['attribute']
# Check if it's a class instance method call
for cls_id in self.classes:
if cls_id.endswith(f".{obj_name}"):
method_id = f"{cls_id}.{attr_name}"
if method_id in self.functions:
return method_id
# Check imported modules
for imp in self.imports[module_id]:
if ((imp['type'] == 'import' and imp['name'] == obj_name) or
(imp['type'] == 'import' and imp['alias'] == obj_name)):
imported_func_id = f"{imp['name']}.{attr_name}"
if imported_func_id in self.functions:
return imported_func_id
elif call['type'] == 'nested_attribute':
# Handle nested attribute calls
full_path = call['full_path']
# Check exact match
if full_path in self.functions:
return full_path
# Check partial match
for func_id in self.functions:
if func_id.endswith(f".{full_path}"):
return func_id
return None
def _get_source(self, content: str, node: ast.AST) -> str:
"""Extract source code corresponding to AST node"""
source_lines = content.splitlines()
if hasattr(node, 'lineno') and hasattr(node, 'end_lineno'):
start_line = node.lineno - 1 # AST line numbers start from 1, list indices start from 0
end_line = node.end_lineno
return "\n".join(source_lines[start_line:end_line])
return ""
def _build_hierarchical_code_tree(self) -> None:
"""Build hierarchical code tree structure for easy browsing and analysis"""
logger.info("Building hierarchical code tree...")
# Calculate statistics
self.code_tree['stats']['total_modules'] = len(self.modules)
self.code_tree['stats']['total_classes'] = len(self.classes)
self.code_tree['stats']['total_functions'] = len(self.functions)
total_lines = 0
for module_id, module_info in self.modules.items():
module_lines = len(module_info['content'].splitlines())
total_lines += module_lines
# Create module node
path_parts = module_id.split('.')
self._add_to_tree(self.code_tree['modules'], path_parts, {
'type': 'module',
'id': module_id,
'name': path_parts[-1],
'docstring': module_info['docstring'][:100] + ('...' if len(module_info['docstring']) > 100 else ''),
'classes': [],
'functions': [],
'lines': module_lines,
'is_notebook': module_info.get('is_notebook', False) # Pass notebook flag
})
# Add classes
for class_id in module_info['classes']:
class_info = self.classes[class_id]
class_lines = len(class_info['source'].splitlines())
class_node = {
'type': 'class',
'id': class_id,
'name': class_info['name'],
'docstring': class_info['docstring'][:100] + ('...' if len(class_info['docstring']) > 100 else ''),
'methods': [],
'base_classes': class_info['base_classes'],
'lines': class_lines,
'from_notebook': class_info.get('from_notebook', False) # Pass from_notebook flag
}
# Ensure module node has classes key
if 'classes' not in self.code_tree['modules'][path_parts[0]]:
self.code_tree['modules'][path_parts[0]]['classes'] = []
self.code_tree['modules'][path_parts[0]]['classes'].append(class_node)
# Add methods
for method_id in class_info['methods']:
method_info = self.functions[method_id]
method_lines = len(method_info['source'].splitlines())
method_node = {
'type': 'method',
'id': method_id,
'name': method_info['name'],
'docstring': method_info['docstring'][:100] + ('...' if len(method_info['docstring']) > 100 else ''),
'parameters': method_info['parameters'],
'return_type': method_info['return_type'],
'calls': [c for c in method_info['calls'] if self._resolve_call(c, method_info['module'], method_info['class'])],
'called_by': method_info['called_by'],
'lines': method_lines
}
class_node['methods'].append(method_node)
# Add module-level functions
for func_id in module_info['functions']:
func_info = self.functions[func_id]
func_lines = len(func_info['source'].splitlines())
func_node = {
'type': 'function',
'id': func_id,
'name': func_info['name'],
'docstring': func_info['docstring'][:100] + ('...' if len(func_info['docstring']) > 100 else ''),
'parameters': func_info['parameters'],
'return_type': func_info['return_type'],
'calls': [c for c in func_info['calls'] if self._resolve_call(c, func_info['module'], None)],
'called_by': func_info['called_by'],
'lines': func_lines
}
# Get reference to module node
module_node = self._get_tree_node(self.code_tree['modules'], path_parts)
if module_node:
# Ensure module node has functions key
if 'functions' not in module_node:
module_node['functions'] = []
module_node['functions'].append(func_node)
self.code_tree['stats']['total_lines'] = total_lines
# Initialize importance analyzer
self.importance_analyzer = None
if ImportanceAnalyzer is not None:
try:
self.importance_analyzer = ImportanceAnalyzer(
repo_path=self.repo_path,
modules=self.modules,
classes=self.classes,
functions=self.functions,
imports=self.imports,
code_tree=self.code_tree,
call_graph=self.call_graph
)
logger.info("Initialized code importance analyzer")
except Exception as e:
logger.error(f"Error initializing code importance analyzer: {e}")
def _add_to_tree(self, tree: Dict, path: List[str], node_data: Dict) -> None:
"""
Add node to tree structure
Args:
tree: Tree structure
path: Path
node_data: Node data
"""
if len(path) == 1:
if path[0] not in tree:
tree[path[0]] = node_data
return
if path[0] not in tree:
tree[path[0]] = {
'type': 'package',
'name': path[0],
'children': {}
}
if 'children' not in tree[path[0]]:
tree[path[0]]['children'] = {}
self._add_to_tree(tree[path[0]]['children'], path[1:], node_data)
def _get_tree_node(self, tree: Dict, path: List[str]) -> Optional[Dict]:
"""
Get node from tree
Args:
tree: Tree structure
path: Path
Returns:
Found node or None
"""
if len(path) == 1:
return tree.get(path[0])
if path[0] not in tree:
return None
if 'children' not in tree[path[0]]:
return None
return self._get_tree_node(tree[path[0]]['children'], path[1:])
def _identify_key_components(self) -> None:
"""Identify key components in the codebase"""
logger.info("Identifying key components...")
# Only identify class-level key components
try:
# 1. Calculate class importance
class_importance = {}
# Create a virtual node for each class
class_graph = nx.DiGraph()
# Add all classes as nodes
for class_id in self.classes:
class_graph.add_node(class_id)
# Add call relationship edges between classes
for class_id, class_info in self.classes.items():
# Get all methods of this class
methods = class_info['methods']
# Record other classes called by this class
called_classes = set()
# Iterate through all methods of this class
for method_id in methods:
if method_id in self.functions:
method_info = self.functions[method_id]
# Iterate through all functions called by this method
for call in method_info['calls']:
called_func_id = self._resolve_call(call, method_info['module'], method_info['class'])
if called_func_id and called_func_id in self.functions:
called_func = self.functions[called_func_id]
# If calling a method of another class
if called_func['class'] and called_func['class'] != class_id:
called_classes.add(called_func['class'])
# Add edges for each call relationship
for called_class in called_classes:
class_graph.add_edge(class_id, called_class)
# If class graph is not empty, calculate PageRank
if len(class_graph.nodes()) > 0:
class_pagerank = nx.pagerank(class_graph, alpha=0.85, max_iter=100)
class_importance = class_pagerank
# Add important classes
key_components = []
for class_id, score in sorted(class_importance.items(), key=lambda x: x[1], reverse=True):
class_info = self.classes[class_id]
# Calculate total lines of the class
class_lines = len(class_info['source'].splitlines())
# Calculate number of methods in the class
methods_count = len(class_info['methods'])
# Calculate number of times the class is called (through its methods)
called_by_count = 0
for method_id in class_info['methods']:
if method_id in self.functions:
called_by_count += len(self.functions[method_id]['called_by'])
key_components.append({
'id': class_id,
'name': class_info['name'],
'type': 'class',
'module': class_info['module'],
'importance_score': score,
'methods_count': methods_count,
'called_by_count': called_by_count,
'lines': class_lines,
'path': self.modules[class_info['module']]['path'],
'docstring': class_info['docstring'][:200] if class_info['docstring'] else ""
})
# Sort by importance score
self.code_tree['key_components'] = sorted(key_components, key=lambda x: x['importance_score'], reverse=True)
except Exception as e:
logger.error(f"Error calculating component importance: {e}", exc_info=True)
# Fallback: use simple heuristic method
try:
key_components = []
# Process classes
class_stats = []
for class_id, class_info in self.classes.items():
# Calculate number of methods in the class
methods_count = len(class_info['methods'])
# Calculate number of times the class is called (through its methods)
called_by_count = 0
calls_count = 0
for method_id in class_info['methods']:
if method_id in self.functions:
method_info = self.functions[method_id]
called_by_count += len(method_info['called_by'])
calls_count += len([c for c in method_info['calls']
if self._resolve_call(c, method_info['module'], method_info['class'])])
# Simple weighted calculation of importance score
importance = (0.4 * called_by_count) + (0.3 * calls_count) + (0.3 * methods_count)
class_stats.append((class_id, importance))
# Get top 10 classes by importance ranking
for class_id, score in sorted(class_stats, key=lambda x: x[1], reverse=True)[:10]:
class_info = self.classes[class_id]
key_components.append({
'id': class_id,
'name': class_info['name'],
'type': 'class',
'module': class_info['module'],
'importance_score': score,
'methods_count': len(class_info['methods']),
'called_by_count': sum(len(self.functions[m]['called_by']) for m in class_info['methods'] if m in self.functions),
'lines': len(class_info['source'].splitlines()),
'docstring': class_info['docstring'][:200] if class_info['docstring'] else ""
})
# Sort by importance score
self.code_tree['key_components'] = sorted(key_components, key=lambda x: x['importance_score'], reverse=True)
except Exception as e:
logger.error(f"Error calculating component importance using fallback method: {e}", exc_info=True)
def _identify_key_modules(self) -> List[Dict]:
"""Identify key modules in the codebase"""
logger.info("Identifying key modules...")
# Only identify module-level key components
if not self.modules:
logger.warning("No module information available, unable to identify key modules")
return []
# Check if there are too many modules
if len(self.modules) > 300:
logger.warning(f"Too many modules ({len(self.modules)}), skipping key module importance calculation")
return []
key_modules = []
try:
# Collect all modules and calculate their importance
module_importance = {}
# Check if importance analyzer is available
if hasattr(self, 'importance_analyzer') and self.importance_analyzer is not None:
# Use ImportanceAnalyzer to calculate importance scores
for module_id, module_info in self.modules.items():
# Create node dictionary, ensure it has 'type' field
node_info = {'id': module_id, 'type': 'module'}
if 'docstring' in module_info:
node_info['docstring'] = module_info['docstring']
if 'path' in module_info:
node_info['path'] = module_info['path']
# Calculate importance score
try:
importance_score = self.importance_analyzer.calculate_node_importance(node_info)
module_importance[module_id] = importance_score
except Exception as e:
logger.warning(f"Error calculating importance for module {module_id}: {e}")
# Use backup calculation method
module_importance[module_id] = self._calculate_node_importance(node_info)
else:
# Use internal method to calculate importance
logger.info("Using internal method to calculate module importance")
for module_id, module_info in self.modules.items():
node_info = {
'id': module_id,
'type': 'module',
'docstring': module_info.get('docstring', ''),
'classes': module_info.get('classes', []),
'functions': module_info.get('functions', [])
}
if 'content' in module_info:
node_info['lines'] = len(module_info['content'].splitlines())
module_importance[module_id] = self._calculate_node_importance(node_info)
# Sort by importance and generate key modules list
for module_id, score in sorted(module_importance.items(), key=lambda x: x[1], reverse=True): # Get top 15 most important modules
module_info = self.modules[module_id]
# Calculate number of classes and functions in the module
classes_count = len(module_info.get('classes', []))
functions_count = len(module_info.get('functions', []))
lines_count = len(module_info.get('content', '').splitlines())
# Add to key modules list
key_modules.append({
'id': module_id,
'name': module_id.split('.')[-1],
'type': 'module',
'importance_score': score,
'classes_count': classes_count,
'functions_count': functions_count,
'lines': lines_count,
'path': module_info.get('path', ''),
'docstring': module_info.get('docstring', '')[:200] if module_info.get('docstring') else ""
})
logger.info(f"Identified {len(key_modules)} key modules")
# Add key modules to code tree
if 'key_modules' not in self.code_tree:
self.code_tree['key_modules'] = []
self.code_tree['key_modules'] = sorted(key_modules, key=lambda x: x['importance_score'], reverse=True)
except Exception as e:
logger.error(f"Error identifying key modules: {e}", exc_info=True)
# Error handling, ensure returning a valid list
if not key_modules:
# Use simple heuristic method as fallback
for module_id, module_info in list(self.modules.items())[:10]: # Only process first 10 modules
key_modules.append({
'id': module_id,
'name': module_id.split('.')[-1],
'type': 'module',
'importance_score': 0.5, # Default medium importance
'path': module_info.get('path', ''),
'docstring': module_info.get('docstring', '')[:200] if module_info.get('docstring') else ""
})
return key_modules
def _identify_key_class(self) -> None:
"""Use ImportanceAnalyzer to identify key components in the codebase"""
logger.info("Using ImportanceAnalyzer to identify key components...")
if not hasattr(self, 'importance_analyzer') or self.importance_analyzer is None: