-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.py
More file actions
1410 lines (1149 loc) · 62.9 KB
/
context.py
File metadata and controls
1410 lines (1149 loc) · 62.9 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
"""
Context Extractor for AI Knowledge Base Codebase
This script extracts structured context from a Python/Flask codebase, focusing on:
- Function signatures and docstrings
- Class definitions and methods
- Flask routes and blueprints
- HTML template structure
- Command-line arguments
Usage:
python context_extractor.py [output_file]
"""
import os
import re
import sys
import ast
import json
import inspect
from typing import List, Dict, Tuple, Any, Optional, Set
from collections import defaultdict
import argparse
# Configuration
DEFAULT_CONFIG = {
"extensions": [".py", ".html", ".js", ".sql"],
"exclude_dirs": [
"venv", "__pycache__", "node_modules",
"Instagram-Scraper/logs", "Instagram-Scraper/responses", "Instagram-Scraper/visualisations",
"Instagram-Scraper/data", "Instagram-Scraper/static", "Instagram-Scraper/venv",
"Instagram-Scraper/templates", "site-packages"
],
"exclude_files": [
".test.", ".spec.", ".min.js", ".map", "setup.py",
".gitignore", "package-lock.json", ".env"
],
"include_dirs": [
"Instagram-Scraper", "evaluation", "api"
],
"max_file_size": 1024 * 1024, # 1MB
"max_lines": 15000, # Target maximum lines for output
}
class CodeContextExtractor:
"""Extracts structured context from a Python/Flask codebase"""
def __init__(self, config: Dict[str, Any]):
self.config = config
self.blueprint_routes = defaultdict(list)
self.flask_routes = []
self.command_line_args = []
self.template_hierarchy = {}
self.file_summaries = []
self.total_lines = 0
# Add new tracking structures
self.import_graph = defaultdict(set) # Map of module -> imported modules
self.function_calls = defaultdict(set) # Map of function -> called functions
self.module_functions = defaultdict(set) # Map of module -> defined functions
self.api_endpoints = [] # List of API endpoints with metadata
self.db_tables = {} # Database table schema
self.db_relationships = [] # Database relationships
self.complex_functions = [] # Track functions with high complexity
def should_exclude_file(self, file_path: str) -> bool:
"""Check if a file should be excluded based on config"""
normalized_path = os.path.normpath(file_path)
# Check excluded patterns
for pattern in self.config["exclude_files"]:
if pattern in normalized_path:
return True
# Check file extension
ext = os.path.splitext(file_path)[1].lower()
if ext not in self.config["extensions"]:
return True
return False
def should_exclude_dir(self, dir_path: str) -> bool:
"""Check if a directory should be excluded based on config"""
normalized_path = os.path.normpath(dir_path)
dir_name = os.path.basename(normalized_path)
# Check if the directory name itself is in the exclude list
if dir_name in self.config["exclude_dirs"]:
print(f"Excluding directory (name match): {normalized_path}")
return True
# Check if the path contains any of the excluded directory patterns
for exclude_dir in self.config["exclude_dirs"]:
if exclude_dir in normalized_path:
print(f"Excluding directory (path match): {normalized_path} - matched: {exclude_dir}")
return True
# If we have include_dirs, check if this is in it
if self.config["include_dirs"]:
for include_dir in self.config["include_dirs"]:
if include_dir in normalized_path:
return False
# If not in any include_dirs, exclude it
return True
return False
def collect_files(self, root_dir: str) -> List[Tuple[str, str]]:
"""Collect all eligible files in the directory"""
results = []
print(f"Collecting files from: {root_dir}")
print(f"Exclusion patterns: {self.config['exclude_dirs']}")
for root, dirs, files in os.walk(root_dir):
# Process directories
dirs_before = len(dirs)
dirs[:] = [d for d in dirs if not self.should_exclude_dir(os.path.join(root, d))]
if dirs_before > len(dirs):
print(f" In {root}: Filtered out {dirs_before - len(dirs)} directories")
for file in files:
file_path = os.path.join(root, file)
rel_path = os.path.relpath(file_path, root_dir)
# Check exclusion patterns
if self.should_exclude_file(rel_path):
continue
# Check file size
if os.path.getsize(file_path) > self.config["max_file_size"]:
continue
# Check if the file is in an excluded directory
file_dir = os.path.dirname(file_path)
if self.should_exclude_dir(file_dir):
print(f" Skipping file in excluded directory: {rel_path}")
continue
results.append((file_path, rel_path))
print(f"Collected {len(results)} files for processing")
return results
def calculate_cyclomatic_complexity(self, node: ast.FunctionDef) -> int:
"""Calculate the cyclomatic complexity of a function"""
# Start with complexity of 1 (one path through the function)
complexity = 1
# Increment for each statement that branches the control flow
for subnode in ast.walk(node):
# If statements
if isinstance(subnode, ast.If):
complexity += 1
# Handle complex boolean expressions with 'and'/'or'
if isinstance(subnode.test, ast.BoolOp):
complexity += len(subnode.test.values) - 1
# For loops
elif isinstance(subnode, ast.For) or isinstance(subnode, ast.AsyncFor):
complexity += 1
# While loops
elif isinstance(subnode, ast.While):
complexity += 1
# Handle complex boolean expressions with 'and'/'or'
if isinstance(subnode.test, ast.BoolOp):
complexity += len(subnode.test.values) - 1
# Try/except blocks (each except handler adds a branch)
elif isinstance(subnode, ast.Try):
complexity += len(subnode.handlers)
# List/dict/set comprehensions and generator expressions
elif isinstance(subnode, (ast.ListComp, ast.DictComp, ast.SetComp, ast.GeneratorExp)):
complexity += 1
# Match/case statements (Python 3.10+)
elif hasattr(ast, 'Match') and isinstance(subnode, ast.Match):
complexity += len(subnode.cases)
# Boolean operations with 'or' (short-circuiting can create branches)
elif isinstance(subnode, ast.BoolOp) and isinstance(subnode.op, ast.Or):
complexity += len(subnode.values) - 1
return complexity
def extract_python_function_info(self, node: ast.FunctionDef) -> Dict[str, Any]:
"""Extract information from a function definition"""
function_info = {
"name": node.name,
"docstring": ast.get_docstring(node) or "",
"params": []
}
# Calculate complexity
complexity = self.calculate_cyclomatic_complexity(node)
function_info["complexity"] = complexity
# Track complex functions (complexity > 10)
if complexity > 10:
self.complex_functions.append({
"name": node.name,
"complexity": complexity,
"line_number": node.lineno,
"source_file": inspect.getfile(node) if hasattr(node, "_filename") else None
})
# Extract parameters
for arg in node.args.args:
param = {"name": arg.arg}
if arg.annotation and isinstance(arg.annotation, ast.Name):
param["type"] = arg.annotation.id
function_info["params"].append(param)
# Extract default values safely
try:
if node.args.defaults:
default_offset = len(node.args.args) - len(node.args.defaults)
for i, default in enumerate(node.args.defaults):
param_index = default_offset + i
if 0 <= param_index < len(function_info["params"]):
if isinstance(default, ast.Constant):
function_info["params"][param_index]["default"] = default.value
else:
# Handle non-constant default values
function_info["params"][param_index]["default"] = "..."
except Exception as e:
# Skip setting defaults if any error occurs
pass
return function_info
def extract_class_info(self, node: ast.ClassDef) -> Dict[str, Any]:
"""Extract information from a class definition"""
class_info = {
"name": node.name,
"docstring": ast.get_docstring(node) or "",
"methods": [],
"bases": []
}
# Extract base classes
for base in node.bases:
if isinstance(base, ast.Name):
class_info["bases"].append(base.id)
# Extract methods
for body_item in node.body:
if isinstance(body_item, ast.FunctionDef):
method_info = self.extract_python_function_info(body_item)
class_info["methods"].append(method_info)
return class_info
def extract_flask_routes(self, node: ast.FunctionDef, decorator_prefix: str = "") -> List[Dict[str, Any]]:
"""Extract Flask route information from a function with route decorators"""
routes = []
for decorator in node.decorator_list:
route_info = {}
# Extract @app.route or @blueprint.route decorators
if isinstance(decorator, ast.Call) and hasattr(decorator.func, 'attr') and decorator.func.attr == 'route':
if isinstance(decorator.func.value, ast.Name):
blueprint_name = decorator.func.value.id
route_info["blueprint"] = blueprint_name
# Extract route path
if decorator.args:
route_info["path"] = decorator.prefix + decorator.args[0].value if decorator_prefix else decorator.args[0].value
# Extract HTTP methods
for keyword in decorator.keywords:
if keyword.arg == 'methods' and isinstance(keyword.value, ast.List):
methods = []
for elt in keyword.value.elts:
if isinstance(elt, ast.Constant):
methods.append(elt.value)
route_info["methods"] = methods
if route_info:
route_info["function"] = node.name
route_info["docstring"] = ast.get_docstring(node) or ""
routes.append(route_info)
return routes
def extract_blueprint_registration(self, content: str) -> List[Dict[str, Any]]:
"""Extract Blueprint registration from content using regex"""
registrations = []
# Pattern for app.register_blueprint(blueprint_name, url_prefix='/path')
pattern = r'app\.register_blueprint\(([^,)]+)(?:,\s*(?:url_prefix=[\'"](.*?)[\'"]))?'
matches = re.findall(pattern, content)
for blueprint_name, url_prefix in matches:
registrations.append({
"blueprint": blueprint_name.strip(),
"url_prefix": url_prefix if url_prefix else "/"
})
return registrations
def extract_argparse_arguments(self, content: str) -> List[Dict[str, Any]]:
"""Extract command line arguments defined with argparse"""
arguments = []
# Pattern for parser.add_argument('--name', ...)
pattern = r'parser\.add_argument\([\'"](-{1,2}[^\'"]+)[\'"](?:,\s*(?:action=[\'"]([^\'"]+)[\'"]|help=[\'"]([^\'"]+)[\'"]|type=([^,)]+)|default=([^,)]+)))*\)'
matches = re.findall(pattern, content)
for match in matches:
arg_name, action, help_text, arg_type, default = match
arguments.append({
"name": arg_name,
"action": action,
"help": help_text,
"type": arg_type,
"default": default
})
return arguments
def extract_jinja_template_structure(self, file_path: str) -> Dict[str, Any]:
"""Extract structure from a Jinja template"""
with open(file_path, 'r', encoding='utf-8', errors='replace') as f:
content = f.read()
template_info = {
"extends": None,
"blocks": [],
"includes": []
}
# Extract template inheritance
extends_match = re.search(r'{%\s*extends\s+[\'"]([^\'"]+)[\'"]', content)
if extends_match:
template_info["extends"] = extends_match.group(1)
# Extract blocks
block_matches = re.findall(r'{%\s*block\s+([^\s%]+)[^%]*%}', content)
template_info["blocks"] = list(set(block_matches))
# Extract includes
include_matches = re.findall(r'{%\s*include\s+[\'"]([^\'"]+)[\'"]', content)
template_info["includes"] = list(set(include_matches))
return template_info
def process_python_file(self, file_path: str) -> Dict[str, Any]:
"""Process a Python file to extract its structure"""
with open(file_path, 'r', encoding='utf-8', errors='replace') as f:
content = f.read()
# Get module name from file path
rel_path = os.path.relpath(file_path)
module_name = os.path.splitext(rel_path)[0].replace('/', '.')
file_info = {
"functions": [],
"classes": [],
"flask_routes": [],
"imports": [],
"blueprint_registrations": [],
"function_calls": [],
"api_endpoints": [],
"orm_models": []
}
# Extract imports and build import graph
import_lines = re.findall(r'^(?:from [^.]+(?:\.[^.]+)* )?import .+', content, re.MULTILINE)
file_info["imports"] = import_lines
self.extract_import_graph(content, module_name)
# Extract command line arguments if found
if "argparse" in content and "add_argument" in content:
self.command_line_args.extend(self.extract_argparse_arguments(content))
# Extract Blueprint registrations
if "app.register_blueprint" in content:
file_info["blueprint_registrations"] = self.extract_blueprint_registration(content)
try:
tree = ast.parse(content)
for node in ast.walk(tree):
# Extract functions
if isinstance(node, ast.FunctionDef):
# Register function in module
self.module_functions[module_name].add(node.name)
# Extract function calls
calls = self.extract_function_calls(node, module_name)
if calls:
file_info["function_calls"].append({
"function": node.name,
"calls": calls
})
# Check if it's a route handler
routes = self.extract_flask_routes(node)
if routes:
file_info["flask_routes"].extend(routes)
self.flask_routes.extend(routes)
# Extract API endpoint details for each route
for route in routes:
endpoint_info = self.extract_api_endpoint_details(route, rel_path)
file_info["api_endpoints"].append(endpoint_info)
else:
# Regular function
function_info = self.extract_python_function_info(node)
file_info["functions"].append(function_info)
# Extract classes
elif isinstance(node, ast.ClassDef):
class_info = self.extract_class_info(node)
file_info["classes"].append(class_info)
# Check if this class might be an ORM model
base_classes = [base for base in node.bases if isinstance(base, ast.Name)]
orm_base_names = ['Model', 'Base', 'DeclarativeBase']
is_orm_model = False
for base in base_classes:
if base.id in orm_base_names:
is_orm_model = True
break
# Check for SQLAlchemy columns in the class body
if not is_orm_model:
for item in node.body:
if isinstance(item, ast.Assign) and isinstance(item.value, ast.Call):
if hasattr(item.value.func, 'id') and item.value.func.id == 'Column':
is_orm_model = True
break
if is_orm_model:
orm_model = self.extract_orm_model(node)
if "orm_models" not in file_info:
file_info["orm_models"] = []
file_info["orm_models"].append(orm_model)
# Extract variable assignments that might be blueprints
elif isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name) and isinstance(node.value, ast.Call):
if (hasattr(node.value.func, 'id') and node.value.func.id == 'Blueprint'):
# Found a Blueprint definition
if len(node.value.args) >= 2:
blueprint_name = target.id
for route in self.flask_routes:
if route.get('blueprint') == blueprint_name:
self.blueprint_routes[blueprint_name].append(route)
except SyntaxError:
# Fallback for files with syntax errors
print(f"Syntax error in {file_path}, using regex fallback")
# Find functions with regex
functions = re.findall(r'def\s+([^\(]+)\(([^\)]*)\)(?:\s*[-=]>\s*[^\:]+)?:', content)
for func_name, params in functions:
file_info["functions"].append({
"name": func_name.strip(),
"params": [{"name": p.strip()} for p in params.split(',') if p.strip()],
"docstring": "Extracted via regex. Docstring unavailable."
})
# Find classes with regex
classes = re.findall(r'class\s+([^\(:]+)(?:\(([^\)]+)\))?:', content)
for class_name, bases in classes:
class_info = {
"name": class_name.strip(),
"bases": [b.strip() for b in bases.split(',') if b.strip()],
"methods": [],
"docstring": "Extracted via regex. Docstring unavailable."
}
file_info["classes"].append(class_info)
return file_info
def process_html_template(self, file_path: str) -> Dict[str, Any]:
"""Process an HTML template file"""
template_info = self.extract_jinja_template_structure(file_path)
# Store in template hierarchy
template_name = os.path.basename(file_path)
self.template_hierarchy[template_name] = template_info
return template_info
def format_function_signature(self, func_info: Dict[str, Any]) -> str:
"""Format a function signature with docstring"""
params = []
for param in func_info["params"]:
param_str = param["name"]
if "type" in param:
param_str += f": {param['type']}"
if "default" in param:
param_str += f" = {param['default']}"
params.append(param_str)
signature = f"def {func_info['name']}({', '.join(params)})"
# Add complexity if available
if "complexity" in func_info:
complexity = func_info["complexity"]
complexity_label = ""
if complexity <= 5:
complexity_label = "low"
elif complexity <= 10:
complexity_label = "medium"
else:
complexity_label = "high"
signature += f" [complexity: {complexity} - {complexity_label}]"
# Format docstring - just first line for brevity
docstring = func_info.get("docstring", "").split('\n')[0].strip()
if docstring:
signature += f": \"{docstring}\""
return signature
def format_class_info(self, class_info: Dict[str, Any]) -> List[str]:
"""Format a class definition with methods"""
lines = []
# Class definition with bases
bases = ""
if class_info["bases"]:
bases = f"({', '.join(class_info['bases'])})"
class_def = f"class {class_info['name']}{bases}"
# First line of docstring
docstring = class_info.get("docstring", "").split('\n')[0].strip()
if docstring:
class_def += f": \"{docstring}\""
lines.append(class_def)
# Add methods with indentation
for method in class_info["methods"]:
method_signature = self.format_function_signature(method)
lines.append(f" {method_signature}")
return lines
def format_flask_routes(self, routes: List[Dict[str, Any]]) -> List[str]:
"""Format Flask routes for output"""
lines = []
for route in routes:
methods = route.get("methods", ["GET"])
methods_str = ", ".join(methods)
docstring = route.get("docstring", "").split('\n')[0].strip()
if "blueprint" in route:
route_str = f"@{route['blueprint']}.route('{route.get('path', '/')}', methods=[{methods_str}])"
else:
route_str = f"@app.route('{route.get('path', '/')}', methods=[{methods_str}])"
lines.append(route_str)
lines.append(f"def {route['function']}(): \"{docstring}\"")
return lines
def format_blueprint_registrations(self, registrations: List[Dict[str, Any]]) -> List[str]:
"""Format Blueprint registrations for output"""
lines = []
for reg in registrations:
if reg["url_prefix"] and reg["url_prefix"] != "/":
lines.append(f"app.register_blueprint({reg['blueprint']}, url_prefix='{reg['url_prefix']}')")
else:
lines.append(f"app.register_blueprint({reg['blueprint']})")
return lines
def format_template_structure(self, template_name: str, template_info: Dict[str, Any]) -> List[str]:
"""Format template structure for output"""
lines = []
if template_info["extends"]:
lines.append(f"{{% extends '{template_info['extends']}' %}}")
if template_info["blocks"]:
for block in template_info["blocks"]:
lines.append(f"{{% block {block} %}}...{{% endblock %}}")
if template_info["includes"]:
for include in template_info["includes"]:
lines.append(f"{{% include '{include}' %}}")
return lines
def format_command_line_args(self) -> List[str]:
"""Format command line arguments for output"""
lines = []
for arg in self.command_line_args:
arg_str = f"parser.add_argument('{arg['name']}'"
if arg["action"]:
arg_str += f", action='{arg['action']}'"
if arg["help"]:
arg_str += f", help='{arg['help']}'"
if arg["type"]:
arg_str += f", type={arg['type']}"
if arg["default"]:
arg_str += f", default={arg['default']}"
arg_str += ")"
lines.append(arg_str)
return lines
def process_file(self, file_path: str) -> Dict[str, Any]:
"""Process a file based on its type"""
ext = os.path.splitext(file_path)[1].lower()
if ext == '.py':
return self.process_python_file(file_path)
elif ext == '.html':
return self.process_html_template(file_path)
elif ext == '.sql':
return {
"type": "sql",
"schema": self.extract_sql_schema(file_path)
}
else:
# Just return basic info for other file types
return {"type": ext[1:], "info": f"File summary not available for {ext} files"}
def format_file_summary(self, file_path: str, rel_path: str, file_info: Dict[str, Any]) -> List[str]:
"""Format the summary of a file for the output"""
ext = os.path.splitext(file_path)[1].lower()
lines = []
if ext == '.py':
# Add imports summary
if file_info["imports"]:
lines.append("# Key imports:")
lines.extend(["# " + imp for imp in file_info["imports"][:5]])
if len(file_info["imports"]) > 5:
lines.append(f"# ... and {len(file_info['imports']) - 5} more imports")
lines.append("")
# Add blueprint registrations
if file_info["blueprint_registrations"]:
lines.append("# Blueprint registrations:")
lines.extend(self.format_blueprint_registrations(file_info["blueprint_registrations"]))
lines.append("")
# Add Flask routes
if file_info["flask_routes"]:
lines.append("# Flask routes:")
lines.extend(self.format_flask_routes(file_info["flask_routes"]))
lines.append("")
# Add functions
if file_info["functions"]:
lines.append("# Functions:")
for func in file_info["functions"]:
lines.append(self.format_function_signature(func))
lines.append("")
# Add classes
if file_info["classes"]:
lines.append("# Classes:")
for cls in file_info["classes"]:
lines.extend(self.format_class_info(cls))
lines.append("")
# Add ORM models if found
if "orm_models" in file_info and file_info["orm_models"]:
lines.append("# ORM Models:")
for model in file_info["orm_models"]:
lines.append(f"class {model['name']} (table: {model['table_name']}):")
if model["columns"]:
for column in model["columns"]:
col_attrs = []
if column.get("primary_key"):
col_attrs.append("primary_key")
if not column.get("nullable", True):
col_attrs.append("not null")
if column.get("unique"):
col_attrs.append("unique")
if column.get("foreign_key"):
fk = column["foreign_key"]
col_attrs.append(f"-> {fk['table']}.{fk['column']}")
attrs_str = ", ".join(col_attrs)
if attrs_str:
attrs_str = f" ({attrs_str})"
lines.append(f" {column['name']}: {column.get('type', 'Unknown')}{attrs_str}")
if model["relationships"]:
lines.append(" # Relationships:")
for rel in model["relationships"]:
rel_desc = f"{rel['name']} -> {rel['target']}"
if rel["back_populates"]:
rel_desc += f" (back_populates: {rel['back_populates']})"
lines.append(f" {rel_desc}")
lines.append("")
elif ext == '.html':
# Template structure
template_name = os.path.basename(file_path)
lines.append("# Template structure:")
lines.extend(self.format_template_structure(template_name, file_info))
lines.append("")
elif ext == '.sql':
# Format SQL schema information
schema = file_info.get("schema", {})
if "tables" in schema and schema["tables"]:
lines.append("# Database Tables:")
for table in schema["tables"]:
lines.append(f"CREATE TABLE {table['name']} (")
for column in table["columns"]:
col_line = f" {column['name']} {column['type']}"
if column.get("constraints"):
col_line += f" {column['constraints']}"
lines.append(col_line)
lines.append(");")
lines.append("")
if "indexes" in schema and schema["indexes"]:
lines.append("# Indexes:")
for index in schema["indexes"]:
lines.append(f"CREATE INDEX {index['name']} ON {index['table']} ({', '.join(index['columns'])});")
lines.append("")
else:
# Basic info for other file types
lines.append(f"# {file_info['type']} file - detailed extraction not supported")
return lines
def extract_function_calls(self, node: ast.FunctionDef, module_name: str) -> List[str]:
"""Extract function calls made within a function"""
calls = []
for subnode in ast.walk(node):
if isinstance(subnode, ast.Call) and isinstance(subnode.func, ast.Name):
calls.append(subnode.func.id)
elif isinstance(subnode, ast.Call) and isinstance(subnode.func, ast.Attribute):
if isinstance(subnode.func.value, ast.Name):
calls.append(f"{subnode.func.value.id}.{subnode.func.attr}")
# Register these calls in our tracking structure
func_id = f"{module_name}.{node.name}"
self.function_calls[func_id].update(calls)
return calls
def extract_import_graph(self, content: str, module_name: str) -> List[str]:
"""Build a graph of import relationships"""
imports = []
# Extract regular imports
import_matches = re.findall(r'^import\s+([^#\n]+)', content, re.MULTILINE)
for match in import_matches:
for module in match.split(','):
module = module.strip()
if ' as ' in module:
module = module.split(' as ')[0].strip()
imports.append(module)
self.import_graph[module_name].add(module)
# Extract from imports
from_matches = re.findall(r'^from\s+([^\s]+)\s+import\s+([^#\n]+)', content, re.MULTILINE)
for base_module, submodules in from_matches:
base_module = base_module.strip()
for submodule in submodules.split(','):
submodule = submodule.strip()
if ' as ' in submodule:
submodule = submodule.split(' as ')[0].strip()
full_module = f"{base_module}.{submodule}"
imports.append(full_module)
self.import_graph[module_name].add(full_module)
return imports
def extract_api_endpoint_details(self, route_info: Dict[str, Any], file_path: str) -> Dict[str, Any]:
"""Extract detailed API endpoint information including parameters and return types"""
endpoint_info = {
"path": route_info.get("path", "/"),
"methods": route_info.get("methods", ["GET"]),
"function": route_info.get("function", ""),
"file_path": file_path,
"docstring": route_info.get("docstring", ""),
"parameters": [],
"return_type": None
}
# Parse docstring for more information if available
docstring = route_info.get("docstring", "")
if docstring:
# Extract parameters from docstring
param_matches = re.findall(r'@param\s+(\w+)\s*:?\s*([^\n]*)', docstring)
for param_name, param_desc in param_matches:
endpoint_info["parameters"].append({
"name": param_name,
"description": param_desc.strip()
})
# Extract return type from docstring
return_match = re.search(r'@return\s*:?\s*([^\n]*)', docstring)
if return_match:
endpoint_info["return_type"] = return_match.group(1).strip()
self.api_endpoints.append(endpoint_info)
return endpoint_info
def extract_sql_schema(self, file_path: str) -> Dict[str, Any]:
"""Extract database schema from SQL files"""
with open(file_path, 'r', encoding='utf-8', errors='replace') as f:
content = f.read()
schema_info = {
"tables": [],
"indexes": [],
"constraints": []
}
# Extract CREATE TABLE statements
create_table_pattern = r'CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"]?(\w+)[`"]?\s*\((.*?)\);'
table_matches = re.findall(create_table_pattern, content, re.DOTALL | re.IGNORECASE)
for table_name, columns_text in table_matches:
table_info = {
"name": table_name,
"columns": []
}
# Extract column definitions
column_pattern = r'[`"]?(\w+)[`"]?\s+([^\s,]+)(?:\s+([^,]+))?'
column_matches = re.findall(column_pattern, columns_text)
for col_name, col_type, constraints in column_matches:
column_info = {
"name": col_name,
"type": col_type,
"constraints": constraints.strip() if constraints else ""
}
# Extract primary key
if "PRIMARY KEY" in constraints.upper():
column_info["primary_key"] = True
# Extract foreign key
fk_match = re.search(r'REFERENCES\s+[`"]?(\w+)[`"]?\s*\(\s*[`"]?(\w+)[`"]?\s*\)', constraints, re.IGNORECASE)
if fk_match:
column_info["foreign_key"] = {
"table": fk_match.group(1),
"column": fk_match.group(2)
}
# Add to relationships
self.db_relationships.append({
"from_table": table_name,
"from_column": col_name,
"to_table": fk_match.group(1),
"to_column": fk_match.group(2)
})
table_info["columns"].append(column_info)
# Add table to schema
schema_info["tables"].append(table_info)
self.db_tables[table_name] = table_info
# Extract CREATE INDEX statements
index_pattern = r'CREATE\s+(?:UNIQUE\s+)?INDEX\s+[`"]?(\w+)[`"]?\s+ON\s+[`"]?(\w+)[`"]?\s*\(([^)]+)\)'
index_matches = re.findall(index_pattern, content, re.IGNORECASE)
for index_name, table_name, columns in index_matches:
index_info = {
"name": index_name,
"table": table_name,
"columns": [col.strip('"` ') for col in columns.split(',')]
}
schema_info["indexes"].append(index_info)
return schema_info
def extract_orm_model(self, node: ast.ClassDef) -> Dict[str, Any]:
"""Extract ORM model definition from a class"""
model_info = {
"name": node.name,
"table_name": None,
"columns": [],
"relationships": []
}
# Extract table name from __tablename__ attribute
for item in node.body:
if isinstance(item, ast.Assign) and len(item.targets) == 1:
if isinstance(item.targets[0], ast.Name) and item.targets[0].id == "__tablename__":
if isinstance(item.value, ast.Constant):
model_info["table_name"] = item.value.value
# If no explicit table name, use class name
if not model_info["table_name"]:
model_info["table_name"] = self.convert_camel_to_snake(node.name)
# Extract columns and relationships
for item in node.body:
if isinstance(item, ast.Assign) and len(item.targets) == 1:
if isinstance(item.targets[0], ast.Name):
column_name = item.targets[0].id
# Skip special attributes
if column_name.startswith("__") and column_name.endswith("__"):
continue
# Check if it's a Column definition
if isinstance(item.value, ast.Call):
if hasattr(item.value.func, 'id') and item.value.func.id == 'Column':
column_info = self.extract_column_definition(column_name, item.value)
model_info["columns"].append(column_info)
# Update global schema
if model_info["table_name"] not in self.db_tables:
self.db_tables[model_info["table_name"]] = {
"name": model_info["table_name"],
"columns": []
}
self.db_tables[model_info["table_name"]]["columns"].append(column_info)
# Check if it's a relationship
elif hasattr(item.value.func, 'id') and item.value.func.id == 'relationship':
rel_info = {
"name": column_name,
"target": None,
"back_populates": None,
"foreign_keys": None
}
# Extract target model
if item.value.args:
if isinstance(item.value.args[0], ast.Constant):
rel_info["target"] = item.value.args[0].value
# Extract relationship options
for keyword in item.value.keywords:
if keyword.arg == 'back_populates' and isinstance(keyword.value, ast.Constant):
rel_info["back_populates"] = keyword.value.value
elif keyword.arg == 'foreign_keys' and isinstance(keyword.value, ast.List):
rel_info["foreign_keys"] = []
for elt in keyword.value.elts:
if isinstance(elt, ast.Attribute):
if isinstance(elt.value, ast.Name):
rel_info["foreign_keys"].append(f"{elt.value.id}.{elt.attr}")
model_info["relationships"].append(rel_info)
# Add to global relationships if we have enough info
if rel_info["target"] and model_info["table_name"]:
self.db_relationships.append({
"from_table": model_info["table_name"],
"relationship_name": column_name,
"to_table": self.convert_camel_to_snake(rel_info["target"]),
"back_populates": rel_info["back_populates"]
})
return model_info
def extract_column_definition(self, column_name: str, node: ast.Call) -> Dict[str, Any]:
"""Extract column definition from a SQLAlchemy Column call"""
column_info = {
"name": column_name,
"type": None,
"primary_key": False,
"nullable": True,
"unique": False,
"foreign_key": None
}
# Extract column type
if node.args:
arg0 = node.args[0]
if isinstance(arg0, ast.Call):
if hasattr(arg0.func, 'id'):
column_info["type"] = arg0.func.id
elif hasattr(arg0.func, 'attr'):
column_info["type"] = arg0.func.attr