-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodesplain.py
More file actions
1605 lines (1314 loc) · 62.5 KB
/
codesplain.py
File metadata and controls
1605 lines (1314 loc) · 62.5 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
"""
CodeSplain - Local Codebase Analyzer & Summarizer
Analyze Python, JavaScript, TypeScript, and React projects.
Generate comprehensive summaries, relationships, and call graphs.
"""
import os
import ast
import sys
import argparse
import json
from pathlib import Path
from datetime import datetime
from collections import defaultdict, Counter
from typing import Dict, List, Set, Tuple, Optional, Any
import re
try:
import esprima
HAS_ESPRIMA = True
except ImportError:
HAS_ESPRIMA = False
class CodeSplainAnalyzer:
def __init__(self, project_path: str):
self.project_path = Path(project_path).resolve()
self.project_name = self.project_path.name
self.timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M")
self.output_dir = Path("codesplain_results") / f"{self.project_name}_{self.timestamp}"
# Analysis storage
self.files_data = {} # file_path -> analysis data
self.imports = defaultdict(set) # file -> set of imports
self.reverse_imports = defaultdict(set) # imported_module -> set of files that import it
self.function_calls = defaultdict(set) # function -> set of callers
self.classes = {} # file -> list of classes
self.functions = {} # file -> list of functions
self.api_endpoints = [] # detected API endpoints
self.entry_points = [] # main files
# Project metadata
self.language_stats = defaultdict(int)
self.primary_language = None
self.project_type = None
self.frameworks = set()
self.package_manager = None
def analyze_project(self):
"""Main analysis pipeline"""
print(f"🔍 Analyzing {self.project_name}...")
# Detect project type first
self._detect_project_structure()
# Find all relevant files based on detected languages
all_files = self._collect_source_files()
if not all_files:
print("❌ No source files found!")
return
print(f"\n📊 Project Analysis:")
print(f" Primary Language: {self.primary_language}")
print(f" Project Type: {self.project_type}")
if self.frameworks:
print(f" Frameworks: {', '.join(self.frameworks)}")
if self.package_manager:
print(f" Package Manager: {self.package_manager}")
print(f"\n📁 Files by Language:")
for lang, count in sorted(self.language_stats.items(), key=lambda x: x[1], reverse=True):
print(f" {lang}: {count} files")
# Analyze each file
for file_path in all_files:
try:
self._analyze_file(file_path)
except Exception as e:
print(f"Warning: Could not analyze {file_path}: {e}")
# Create output directory
self.output_dir.mkdir(parents=True, exist_ok=True)
# Generate all analysis files
self._generate_overview()
self._generate_structure()
self._generate_dependencies()
self._generate_call_graph()
self._generate_api_surface()
self._generate_module_summaries()
self._generate_prompts()
print(f"✅ Analysis complete! Results saved to: {self.output_dir}")
def _detect_project_structure(self):
"""Detect project type, languages, and frameworks"""
# Check for package managers and config files
if (self.project_path / "package.json").exists():
self.package_manager = "npm/yarn"
self._analyze_package_json()
elif (self.project_path / "package-lock.json").exists():
self.package_manager = "npm"
elif (self.project_path / "yarn.lock").exists():
self.package_manager = "yarn"
elif (self.project_path / "pnpm-lock.yaml").exists():
self.package_manager = "pnpm"
if (self.project_path / "requirements.txt").exists() or (self.project_path / "setup.py").exists() or (self.project_path / "pyproject.toml").exists():
self.package_manager = self.package_manager or "pip/poetry"
# Detect TypeScript
if (self.project_path / "tsconfig.json").exists():
self.frameworks.add("TypeScript")
# Count files by language
for ext, lang in [
("*.py", "Python"),
("*.js", "JavaScript"),
("*.jsx", "JavaScript/React"),
("*.ts", "TypeScript"),
("*.tsx", "TypeScript/React"),
("*.vue", "Vue"),
("*.svelte", "Svelte")
]:
files = list(self.project_path.rglob(ext))
files = [f for f in files if not self._should_skip_file(f)]
if files:
self.language_stats[lang] = len(files)
# Determine primary language
if self.language_stats:
self.primary_language = max(self.language_stats.items(), key=lambda x: x[1])[0]
else:
self.primary_language = "Unknown"
# Detect frameworks from file structure
if (self.project_path / "src" / "App.jsx").exists() or (self.project_path / "src" / "App.tsx").exists():
self.frameworks.add("React")
if (self.project_path / "angular.json").exists():
self.frameworks.add("Angular")
if (self.project_path / "nuxt.config.js").exists() or (self.project_path / "nuxt.config.ts").exists():
self.frameworks.add("Nuxt")
if (self.project_path / "next.config.js").exists() or (self.project_path / "next.config.ts").exists():
self.frameworks.add("Next.js")
if (self.project_path / "vite.config.js").exists() or (self.project_path / "vite.config.ts").exists():
self.frameworks.add("Vite")
if (self.project_path / "webpack.config.js").exists():
self.frameworks.add("Webpack")
if (self.project_path / "manage.py").exists():
self.frameworks.add("Django")
if any((self.project_path / f).exists() for f in ["app.py", "wsgi.py", "application.py"]):
self.frameworks.add("Flask/FastAPI")
def _analyze_package_json(self):
"""Extract framework info from package.json"""
try:
package_json = self.project_path / "package.json"
with open(package_json, 'r', encoding='utf-8') as f:
data = json.load(f)
deps = {**data.get('dependencies', {}), **data.get('devDependencies', {})}
# Detect frameworks
if 'react' in deps:
self.frameworks.add("React")
if 'vue' in deps:
self.frameworks.add("Vue")
if 'angular' in deps or '@angular/core' in deps:
self.frameworks.add("Angular")
if 'next' in deps:
self.frameworks.add("Next.js")
if 'nuxt' in deps:
self.frameworks.add("Nuxt")
if 'svelte' in deps:
self.frameworks.add("Svelte")
if 'express' in deps:
self.frameworks.add("Express")
if 'fastify' in deps:
self.frameworks.add("Fastify")
if 'nestjs' in deps or '@nestjs/core' in deps:
self.frameworks.add("NestJS")
if 'vite' in deps:
self.frameworks.add("Vite")
if 'webpack' in deps:
self.frameworks.add("Webpack")
if 'gatsby' in deps:
self.frameworks.add("Gatsby")
# Determine project type
if any(fw in self.frameworks for fw in ['React', 'Vue', 'Angular', 'Svelte']):
self.project_type = "Frontend Web Application"
elif any(fw in self.frameworks for fw in ['Express', 'Fastify', 'NestJS']):
self.project_type = "Backend/API Server"
elif 'Next.js' in self.frameworks or 'Nuxt' in self.frameworks:
self.project_type = "Full-Stack Web Application"
elif 'electron' in deps:
self.project_type = "Desktop Application (Electron)"
elif 'react-native' in deps:
self.project_type = "Mobile Application (React Native)"
except Exception as e:
print(f"Warning: Could not parse package.json: {e}")
def _collect_source_files(self):
"""Collect all relevant source files based on detected languages"""
extensions = []
# Add extensions based on detected languages
if "Python" in self.language_stats:
extensions.append("*.py")
if any(lang in self.language_stats for lang in ["JavaScript", "JavaScript/React"]):
extensions.extend(["*.js", "*.jsx", "*.mjs", "*.cjs"])
if any(lang in self.language_stats for lang in ["TypeScript", "TypeScript/React"]):
extensions.extend(["*.ts", "*.tsx"])
if "Vue" in self.language_stats:
extensions.append("*.vue")
if "Svelte" in self.language_stats:
extensions.append("*.svelte")
# If no languages detected, scan for common extensions
if not extensions:
extensions = ["*.py", "*.js", "*.jsx", "*.ts", "*.tsx"]
all_files = []
for ext in extensions:
files = list(self.project_path.rglob(ext))
files = [f for f in files if not self._should_skip_file(f)]
all_files.extend(files)
return all_files
def _should_skip_file(self, file_path: Path) -> bool:
"""Skip test files, migrations, cache, build artifacts, etc."""
skip_patterns = [
"__pycache__", ".pytest_cache", ".git", "node_modules",
"venv", "env", ".env", "migrations", "test_", "_test",
"tests.py", "conftest.py", ".spec.", ".test.",
"dist", "build", "coverage", ".next", ".nuxt",
"out", "bundle", ".cache", "vendor", "target"
]
path_str = str(file_path).lower()
return any(pattern in path_str for pattern in skip_patterns)
def _analyze_file(self, file_path: Path):
"""Analyze a single source file based on its language"""
relative_path = file_path.relative_to(self.project_path)
file_ext = file_path.suffix.lower()
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# Initialize file data
self.files_data[str(relative_path)] = {
'path': relative_path,
'lines': len(content.splitlines()),
'classes': [],
'functions': [],
'imports': [],
'components': [], # React/Vue components
'exports': [], # JavaScript exports
'docstring': '',
'complexity': 0,
'is_entry_point': False,
'language': self._detect_file_language(file_ext)
}
# Route to appropriate analyzer based on file type
if file_ext == '.py':
self._analyze_python_file(file_path, content, str(relative_path))
elif file_ext in ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs']:
self._analyze_javascript_file(file_path, content, str(relative_path))
elif file_ext == '.vue':
self._analyze_vue_file(file_path, content, str(relative_path))
else:
# Basic analysis for unknown types
self.files_data[str(relative_path)]['docstring'] = "Unknown file type"
if self.files_data[str(relative_path)]['is_entry_point']:
self.entry_points.append(str(relative_path))
except Exception as e:
print(f"Error analyzing {file_path}: {e}")
def _detect_file_language(self, ext: str) -> str:
"""Detect language from file extension"""
lang_map = {
'.py': 'Python',
'.js': 'JavaScript',
'.jsx': 'JavaScript/React',
'.ts': 'TypeScript',
'.tsx': 'TypeScript/React',
'.mjs': 'JavaScript (ESM)',
'.cjs': 'JavaScript (CommonJS)',
'.vue': 'Vue',
'.svelte': 'Svelte'
}
return lang_map.get(ext, 'Unknown')
def _analyze_python_file(self, file_path: Path, content: str, relative_path: str):
"""Analyze Python file using AST"""
try:
tree = ast.parse(content)
self.files_data[relative_path]['docstring'] = self._extract_module_docstring(tree)
self.files_data[relative_path]['is_entry_point'] = self._is_python_entry_point(content)
# Analyze AST
visitor = PythonFileAnalyzer(self, relative_path)
visitor.visit(tree)
except Exception as e:
print(f"Error parsing Python file {file_path}: {e}")
def _analyze_javascript_file(self, file_path: Path, content: str, relative_path: str):
"""Analyze JavaScript/TypeScript file"""
if not HAS_ESPRIMA and file_path.suffix in ['.js', '.jsx', '.mjs', '.cjs']:
# Fallback to regex-based analysis
self._analyze_js_with_regex(content, relative_path)
return
try:
# Try to parse with esprima for JS files
if HAS_ESPRIMA and file_path.suffix in ['.js', '.jsx', '.mjs', '.cjs']:
tree = esprima.parseModule(content, {'jsx': True, 'tolerant': True})
visitor = JavaScriptAnalyzer(self, relative_path, content)
visitor.analyze(tree)
# Also run regex extraction for components (esprima doesn't detect them well)
self._extract_react_components(content, relative_path)
else:
# Use regex-based analysis for TypeScript
self._analyze_js_with_regex(content, relative_path)
# Detect entry points
self.files_data[relative_path]['is_entry_point'] = self._is_js_entry_point(content, file_path)
except Exception as e:
# Fallback to regex-based analysis
self._analyze_js_with_regex(content, relative_path)
def _extract_react_components(self, content: str, relative_path: str):
"""Extract React/Vue components using regex"""
component_patterns = [
r"(?:export\s+(?:default\s+)?)?(?:function|const)\s+([A-Z]\w+)",
r"class\s+([A-Z]\w+)\s+extends\s+(?:React\.)?Component"
]
for pattern in component_patterns:
for match in re.finditer(pattern, content):
comp_name = match.group(1)
if comp_name not in [c['name'] for c in self.files_data[relative_path]['components']]:
self.files_data[relative_path]['components'].append({
'name': comp_name,
'type': 'React Component'
})
def _analyze_js_with_regex(self, content: str, relative_path: str):
"""Regex-based JavaScript/TypeScript analysis"""
# Extract imports
import_patterns = [
r"import\s+.*?\s+from\s+['\"](.+?)['\"]",
r"require\(['\"](.+?)['\"]\)",
r"import\(['\"](.+?)['\"]\)"
]
for pattern in import_patterns:
for match in re.finditer(pattern, content):
module = match.group(1)
self.files_data[relative_path]['imports'].append({
'module': module,
'type': 'import'
})
self.imports[relative_path].add(module)
# Extract functions
func_patterns = [
r"(?:export\s+)?(?:async\s+)?function\s+(\w+)",
r"(?:export\s+)?const\s+(\w+)\s*=\s*(?:async\s*)?\([^)]*\)\s*=>",
r"(\w+)\s*:\s*(?:async\s*)?function",
]
for pattern in func_patterns:
for match in re.finditer(pattern, content):
func_name = match.group(1)
if not func_name.startswith('_'):
self.files_data[relative_path]['functions'].append({
'name': func_name,
'args': [],
'line_number': content[:match.start()].count('\n') + 1
})
# Extract classes
class_pattern = r"class\s+(\w+)"
for match in re.finditer(class_pattern, content):
self.files_data[relative_path]['classes'].append({
'name': match.group(1),
'methods': [],
'line_number': content[:match.start()].count('\n') + 1
})
# Extract React components
component_patterns = [
r"(?:export\s+(?:default\s+)?)?(?:function|const)\s+([A-Z]\w+)",
r"class\s+([A-Z]\w+)\s+extends\s+(?:React\.)?Component"
]
for pattern in component_patterns:
for match in re.finditer(pattern, content):
comp_name = match.group(1)
if comp_name not in [c['name'] for c in self.files_data[relative_path]['components']]:
self.files_data[relative_path]['components'].append({
'name': comp_name,
'type': 'React Component'
})
# Extract API routes/endpoints
route_patterns = [
r"(?:app|router)\.(get|post|put|delete|patch)\(['\"](.+?)['\"]",
r"@(Get|Post|Put|Delete|Patch)\(['\"](.+?)['\"]\)" # NestJS decorators
]
for pattern in route_patterns:
for match in re.finditer(pattern, content, re.IGNORECASE):
method = match.group(1).upper()
path = match.group(2) if len(match.groups()) > 1 else 'unknown'
self.api_endpoints.append({
'method': method,
'path': path,
'file': relative_path
})
def _analyze_vue_file(self, file_path: Path, content: str, relative_path: str):
"""Analyze Vue single-file component"""
# Extract component name from file name
comp_name = file_path.stem
self.files_data[relative_path]['components'].append({
'name': comp_name,
'type': 'Vue Component'
})
# Extract script section and analyze
script_match = re.search(r'<script[^>]*>(.*?)</script>', content, re.DOTALL)
if script_match:
script_content = script_match.group(1)
self._analyze_js_with_regex(script_content, relative_path)
self.files_data[relative_path]['is_entry_point'] = 'App.vue' in str(file_path)
def _is_js_entry_point(self, content: str, file_path: Path) -> bool:
"""Check if JS/TS file is an entry point"""
file_name = file_path.name.lower()
# Check filename
entry_files = ['index.js', 'index.ts', 'main.js', 'main.ts', 'app.js', 'app.ts',
'server.js', 'server.ts', 'index.jsx', 'index.tsx', 'app.jsx', 'app.tsx']
if file_name in entry_files:
return True
# Check for common entry point patterns
entry_indicators = [
'ReactDOM.render',
'ReactDOM.createRoot',
'createApp(',
'app.listen(',
'server.listen(',
'express()',
'fastify()',
'new Vue(',
]
return any(indicator in content for indicator in entry_indicators)
def _extract_module_docstring(self, tree: ast.Module) -> str:
"""Extract module-level docstring"""
if (tree.body and isinstance(tree.body[0], ast.Expr) and
isinstance(tree.body[0].value, ast.Constant) and
isinstance(tree.body[0].value.value, str)):
return tree.body[0].value.value.strip()
return ""
def _is_python_entry_point(self, content: str) -> bool:
"""Check if Python file is likely an entry point"""
entry_indicators = [
"if __name__ == '__main__':",
"app = FastAPI(",
"app = Flask(",
"def main(",
"uvicorn.run(",
"app.run("
]
return any(indicator in content for indicator in entry_indicators)
def _generate_overview(self):
"""Generate OVERVIEW.md"""
total_files = len(self.files_data)
total_lines = sum(data['lines'] for data in self.files_data.values())
# Detect project type
project_type = self._detect_project_type()
overview = f"""# {self.project_name} - Project Overview
**ANALYZED:** {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
**FILES:** {total_files} Python files ({total_lines:,} total lines)
**TYPE:** {project_type}
**ENTRY POINTS:** {len(self.entry_points)} detected
## Quick Summary
{self._generate_quick_summary()}
## Key Entry Points
{self._format_entry_points()}
## Project Structure Highlights
- **Main directories:** {len(set(str(Path(f).parent) for f in self.files_data.keys() if '/' in f))}
- **Classes defined:** {sum(len(data['classes']) for data in self.files_data.values())}
- **Functions defined:** {sum(len(data['functions']) for data in self.files_data.values())}
- **Import relationships:** {len(self.imports)} files import from others
## Complexity Overview
{self._generate_complexity_overview()}
"""
with open(self.output_dir / "OVERVIEW.md", 'w', encoding='utf-8') as f:
f.write(overview)
def _detect_project_type(self) -> str:
"""Detect what type of project this is"""
# Return already detected type if available
if self.project_type:
return self.project_type
# Detect based on imports and structure
all_imports = set()
for file_data in self.files_data.values():
all_imports.update(imp['module'] for imp in file_data['imports'])
all_imports_str = ' '.join(all_imports).lower()
files_str = ' '.join(self.files_data.keys()).lower()
# Web frameworks
if any(fw in self.frameworks for fw in ['React', 'Vue', 'Angular']):
return "Frontend Web Application"
elif any(fw in self.frameworks for fw in ['Next.js', 'Nuxt', 'Gatsby']):
return "Full-Stack Web Application"
elif any(fw in self.frameworks for fw in ['Express', 'Fastify', 'NestJS']):
return "Backend/API Server"
elif 'Django' in self.frameworks or 'django' in all_imports_str:
return "Django Web Application"
elif 'fastapi' in all_imports_str or 'uvicorn' in all_imports_str:
return "FastAPI Application"
elif 'flask' in all_imports_str:
return "Flask Application"
# Other types
if any(keyword in all_imports_str for keyword in ['pandas', 'numpy', 'matplotlib', 'jupyter']):
return "Data Science/Analytics"
elif any(keyword in all_imports_str for keyword in ['argparse', 'click', 'typer']):
return "CLI Tool"
# Default based on primary language
if self.primary_language and 'JavaScript' in self.primary_language:
return "JavaScript Application"
elif self.primary_language and 'TypeScript' in self.primary_language:
return "TypeScript Application"
elif self.primary_language == 'Python':
return "Python Application"
return "Mixed/Unknown"
def _generate_quick_summary(self) -> str:
"""Generate a quick project summary"""
summaries = []
# Framework summary
if self.frameworks:
summaries.append(f"- Uses {', '.join(list(self.frameworks)[:3])}")
# Language summary
if len(self.language_stats) > 1:
langs = [f"{lang} ({count})" for lang, count in sorted(self.language_stats.items(), key=lambda x: x[1], reverse=True)[:3]]
summaries.append(f"- Multi-language project: {', '.join(langs)}")
# Component summary
total_components = sum(len(data.get('components', [])) for data in self.files_data.values())
if total_components > 0:
summaries.append(f"- {total_components} UI components detected")
# API endpoints
if self.api_endpoints:
summaries.append(f"- {len(self.api_endpoints)} API endpoints")
# Database
all_imports_str = ' '.join(str(data['imports']) for data in self.files_data.values()).lower()
if 'sqlalchemy' in all_imports_str or 'mongoose' in all_imports_str or 'sequelize' in all_imports_str:
summaries.append("- Database integration detected")
# Auth
if any('auth' in f.lower() or 'jwt' in all_imports_str for f in self.files_data.keys()):
summaries.append("- Authentication system")
return '\n'.join(summaries) if summaries else f"- {self.primary_language} application"
def _format_entry_points(self) -> str:
"""Format entry points list"""
if not self.entry_points:
return "None detected"
result = []
for ep in self.entry_points:
data = self.files_data[ep]
result.append(f"- **{ep}** ({data['lines']} lines)")
return '\n'.join(result)
def _generate_complexity_overview(self) -> str:
"""Generate complexity metrics"""
lines_by_file = [(f, data['lines']) for f, data in self.files_data.items()]
lines_by_file.sort(key=lambda x: x[1], reverse=True)
result = "**Largest files:**\n"
for file_path, lines in lines_by_file[:5]:
result += f"- {file_path}: {lines} lines\n"
return result
def _generate_structure(self):
"""Generate STRUCTURE.md"""
structure = f"""# {self.project_name} - Directory Structure & File Purposes
## Directory Tree
```
{self._generate_tree_view()}
```
## File Purposes
{self._generate_file_purposes()}
"""
with open(self.output_dir / "STRUCTURE.md", 'w', encoding='utf-8') as f:
f.write(structure)
def _generate_tree_view(self) -> str:
"""Generate directory tree view"""
# Build tree structure
tree = {}
for file_path in self.files_data.keys():
parts = Path(file_path).parts
current = tree
for part in parts[:-1]: # directories
if part not in current:
current[part] = {}
current = current[part]
# Add file
current[parts[-1]] = None
def build_tree_string(node, prefix="", is_last=True):
if node is None:
return ""
result = ""
items = list(node.items())
for i, (name, subtree) in enumerate(items):
is_last_item = i == len(items) - 1
current_prefix = "└── " if is_last_item else "├── "
result += prefix + current_prefix + name + "\n"
if subtree is not None: # directory
extension = " " if is_last_item else "│ "
result += build_tree_string(subtree, prefix + extension, is_last_item)
return result
return build_tree_string(tree)
def _generate_file_purposes(self) -> str:
"""Generate file purpose descriptions"""
result = []
for file_path, data in sorted(self.files_data.items()):
purpose = self._infer_file_purpose(file_path, data)
result.append(f"**{file_path}** - {purpose}")
return '\n\n'.join(result)
def _infer_file_purpose(self, file_path: str, data: Dict) -> str:
"""Infer what a file is for based on name and contents"""
file_name = Path(file_path).name.lower()
language = data.get('language', 'Unknown')
# Use docstring if available
if data.get('docstring'):
return data['docstring'].split('\n')[0]
# JavaScript/TypeScript specific patterns
if 'JavaScript' in language or 'TypeScript' in language:
if file_name in ['index.js', 'index.ts', 'index.jsx', 'index.tsx']:
return "Module entry point / barrel export"
elif file_name in ['app.js', 'app.ts', 'app.jsx', 'app.tsx']:
return "Main application component"
elif file_name in ['server.js', 'server.ts']:
return "Server entry point"
elif file_name.endswith('.config.js') or file_name.endswith('.config.ts'):
return "Configuration file"
elif file_name.endswith('.test.js') or file_name.endswith('.spec.ts'):
return "Test file"
elif 'route' in file_name or 'router' in file_name:
return "API routes and routing"
elif 'controller' in file_name:
return "Request controller"
elif 'service' in file_name:
return "Business logic service"
elif 'hook' in file_name and 'React' in str(data.get('imports', [])):
return "React custom hooks"
elif 'context' in file_name and 'React' in str(data.get('imports', [])):
return "React context provider"
elif data.get('components'):
comp_names = [c['name'] for c in data['components'][:3]]
return f"UI Components: {', '.join(comp_names)}"
# Vue specific
if language == 'Vue':
return f"Vue component: {Path(file_path).stem}"
# Python specific patterns
if language == 'Python':
if file_name == '__init__.py':
return "Package initialization"
elif file_name in ['main.py', 'app.py']:
return "Main application entry point"
elif file_name == 'config.py' or file_name == 'settings.py':
return "Configuration and settings"
elif file_name.startswith('test_') or file_name.endswith('_test.py'):
return "Test module"
elif 'model' in file_name:
return "Data models and database schemas"
# Common patterns across languages
if 'api' in file_name:
return "API endpoints and routing"
elif 'auth' in file_name:
return "Authentication and authorization"
elif 'util' in file_name or 'helper' in file_name:
return "Utility functions and helpers"
elif 'middleware' in file_name:
return "Middleware components"
elif 'handler' in file_name:
return "Request/event handlers"
elif 'service' in file_name:
return "Business logic services"
elif 'database' in file_name or 'db' in file_name:
return "Database connection and operations"
elif 'type' in file_name and 'TypeScript' in language:
return "TypeScript type definitions"
elif 'interface' in file_name:
return "Interface definitions"
elif 'constant' in file_name or file_name == 'constants.js' or file_name == 'constants.ts':
return "Application constants"
# Infer from content
if data.get('components'):
comp_names = [c['name'] for c in data['components'][:3]]
return f"Components: {', '.join(comp_names)}"
elif data.get('classes'):
class_names = [cls['name'] for cls in data['classes'][:3]]
return f"Defines classes: {', '.join(class_names)}"
elif data.get('functions'):
func_names = [func['name'] for func in data['functions'][:3]]
return f"Functions: {', '.join(func_names)}"
return f"{language} module ({data['lines']} lines)"
def _generate_dependencies(self):
"""Generate DEPENDENCIES.md"""
deps = f"""# {self.project_name} - Dependencies & Import Relationships
## Import Graph
{self._generate_import_graph()}
## External Dependencies
{self._generate_external_deps()}
## Internal Dependencies
{self._generate_internal_deps()}
"""
with open(self.output_dir / "DEPENDENCIES.md", 'w', encoding='utf-8') as f:
f.write(deps)
def _generate_import_graph(self) -> str:
"""Generate visual import relationships"""
result = []
for file_path, imports in self.imports.items():
if imports:
result.append(f"**{file_path}**")
for imp in imports:
result.append(f" └── {imp}")
result.append("")
return '\n'.join(result)
def _generate_external_deps(self) -> str:
"""List external package dependencies"""
external_deps = set()
# Python standard library modules to exclude
py_stdlib = {'os', 'sys', 'json', 're', 'datetime', 'pathlib', 'typing', 'collections',
'argparse', 'logging', 'unittest', 'time', 'math', 'random', 'itertools',
'functools', 'copy', 'io', 'tempfile', 'shutil', 'subprocess', 'threading'}
# JavaScript/Node.js built-in modules to exclude
js_builtins = {'fs', 'path', 'http', 'https', 'url', 'util', 'events', 'stream',
'crypto', 'os', 'process', 'buffer', 'querystring', 'child_process',
'cluster', 'dns', 'net', 'tls', 'zlib', 'assert', 'console'}
for file_data in self.files_data.values():
for imp in file_data['imports']:
module = imp['module'].split('/')[0].split('.')[0]
# Skip relative imports
if module.startswith('.'):
continue
# Skip standard library
if module in py_stdlib or module in js_builtins:
continue
# Skip scoped packages prefix for counting
if module.startswith('@'):
# Include the full scope name like @angular/core
parts = imp['module'].split('/')
if len(parts) >= 2:
module = f"{parts[0]}/{parts[1]}"
else:
module = parts[0]
external_deps.add(module)
if not external_deps:
return "None detected"
return '\n'.join(f"- {dep}" for dep in sorted(external_deps))
def _generate_internal_deps(self) -> str:
"""Show internal module dependencies"""
internal_deps = defaultdict(set)
for file_path, file_data in self.files_data.items():
for imp in file_data['imports']:
if imp['module'].startswith('.') or imp['module'] in [f.replace('/', '.').replace('.py', '') for f in self.files_data.keys()]:
internal_deps[file_path].add(imp['module'])
if not internal_deps:
return "No internal dependencies detected"
result = []
for file_path, deps in internal_deps.items():
result.append(f"**{file_path}**")
for dep in sorted(deps):
result.append(f" → {dep}")
result.append("")
return '\n'.join(result)
def _generate_call_graph(self):
"""Generate CALL_GRAPH.md"""
call_graph = f"""# {self.project_name} - Function Call Graph
## High-Traffic Functions
{self._generate_high_traffic_functions()}
## Call Relationships
{self._generate_call_relationships()}
"""
with open(self.output_dir / "CALL_GRAPH.md", 'w', encoding='utf-8') as f:
f.write(call_graph)
def _generate_high_traffic_functions(self) -> str:
"""Find most-called functions"""
call_counts = Counter()
for file_data in self.files_data.values():
for func in file_data['functions']:
if 'calls' in func:
for call in func['calls']:
call_counts[call] += 1
if not call_counts:
return "No function calls detected"
result = []
for func, count in call_counts.most_common(10):
result.append(f"{count}. **{func}** - Called {count} times")
return '\n'.join(result)
def _generate_call_relationships(self) -> str:
"""Generate function call hierarchy"""
result = []
for file_path, file_data in self.files_data.items():
if file_data['functions']:
result.append(f"## {file_path}")
result.append("")
for func in file_data['functions']:
result.append(f"**{func['name']}()**")
if 'calls' in func and func['calls']:
for call in func['calls'][:5]: # Limit to first 5 calls
result.append(f" └── {call}")
result.append("")
return '\n'.join(result)
def _generate_api_surface(self):
"""Generate API_SURFACE.md"""
components_section = ""
if any(data.get('components') for data in self.files_data.values()):
components_section = f"""
## UI Components
{self._generate_components_list()}
"""
api_surface = f"""# {self.project_name} - API Surface
## Public API Endpoints
{self._generate_api_endpoints()}
{components_section}
## Public Classes & Methods
{self._generate_public_classes()}
## Utility Functions
{self._generate_utility_functions()}
"""
with open(self.output_dir / "API_SURFACE.md", 'w', encoding='utf-8') as f:
f.write(api_surface)
def _generate_components_list(self) -> str:
"""List all UI components (React, Vue, etc.)"""
components = []
for file_path, file_data in self.files_data.items():
if file_data.get('components'):
for comp in file_data['components']:
components.append(f"**{comp['name']}** ({comp['type']}) - {file_path}")
return '\n'.join(components) if components else "No components detected"
def _generate_api_endpoints(self) -> str:
"""Extract API endpoints from code"""
if not self.api_endpoints:
# Fallback to decorator-based detection
endpoints = []
for file_path, file_data in self.files_data.items():
for func in file_data.get('functions', []):
if 'decorators' in func:
for decorator in func['decorators']:
if any(keyword in decorator.lower() for keyword in ['route', 'get', 'post', 'put', 'delete']):
endpoints.append(f"{decorator} → {file_path}:{func['name']}")
return '\n'.join(endpoints) if endpoints else "No API endpoints detected"
# Group endpoints by file
endpoints_by_file = defaultdict(list)
for endpoint in self.api_endpoints:
endpoints_by_file[endpoint['file']].append(endpoint)
result = []
for file_path, endpoints in sorted(endpoints_by_file.items()):
result.append(f"**{file_path}**")
for ep in endpoints:
result.append(f" {ep['method']:6} {ep['path']}")
result.append("")
return '\n'.join(result)
def _generate_public_classes(self) -> str:
"""List public classes and their methods"""
result = []
for file_path, file_data in self.files_data.items():
if file_data['classes']:
for cls in file_data['classes']:
if not cls['name'].startswith('_'): # Public class
result.append(f"**{cls['name']}** ({file_path})")
if 'methods' in cls:
for method in cls['methods'][:5]: # Limit methods shown
result.append(f" └── {method}")
result.append("")
return '\n'.join(result) if result else "No public classes detected"
def _generate_utility_functions(self) -> str: