Skip to content

Commit eeb4588

Browse files
committed
.
1 parent 1747db6 commit eeb4588

File tree

1 file changed

+137
-0
lines changed

1 file changed

+137
-0
lines changed
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
# Cyclomatic Complexity Analyzer
2+
3+
This example demonstrates how to analyze the cyclomatic complexity of Python codebases using Codegen. The script provides detailed insights into code complexity by analyzing control flow structures and providing a comprehensive report.
4+
5+
> [!NOTE]
6+
> The cyclomatic complexity metric helps identify complex code that might need refactoring. A higher score indicates more complex code with multiple decision points.
7+
8+
## How the Analysis Script Works
9+
10+
The script (`run.py`) performs the complexity analysis in several key steps:
11+
12+
1. **Codebase Loading**
13+
```python
14+
codebase = Codebase.from_repo("fastapi/fastapi")
15+
```
16+
- Loads any Python codebase into Codegen's analysis engine
17+
- Works with local or remote Git repositories
18+
- Supports analyzing specific commits
19+
20+
2. **Complexity Calculation**
21+
```python
22+
def calculate_cyclomatic_complexity(code_block):
23+
complexity = 1 # Base complexity
24+
for statement in code_block.statements:
25+
if isinstance(statement, IfBlockStatement):
26+
complexity += 1 + len(statement.elif_statements)
27+
```
28+
- Analyzes control flow structures (if/elif/else, loops, try/except)
29+
- Calculates complexity based on decision points
30+
- Handles nested structures appropriately
31+
32+
3. **Function Analysis**
33+
```python
34+
callables = codebase.functions + [m for c in codebase.classes for m in c.methods]
35+
for function in callables:
36+
complexity = calculate_cyclomatic_complexity(function.code_block)
37+
```
38+
- Processes both standalone functions and class methods
39+
- Calculates complexity for each callable
40+
- Tracks file locations and function names
41+
42+
4. **Report Generation**
43+
```python
44+
print("\n📊 Cyclomatic Complexity Analysis")
45+
print(f" • Total Functions: {total_functions}")
46+
print(f" • Average Complexity: {average:.2f}")
47+
```
48+
- Provides comprehensive complexity statistics
49+
- Shows distribution of complexity across functions
50+
- Identifies the most complex functions
51+
52+
## Output
53+
```
54+
📊 Cyclomatic Complexity Analysis
55+
============================================================
56+
57+
📈 Overall Stats:
58+
• Total Functions: 3538
59+
• Average Complexity: 1.27
60+
• Total Complexity: 4478
61+
62+
🔍 Top 10 Most Complex Functions:
63+
------------------------------------------------------------
64+
• jsonable_encoder 16 | fastapi/encoders.py
65+
• get_openapi 13 | fastapi/openapi/utils.py
66+
• __init__ 12 | fastapi/routing.py
67+
• solve_dependencies 10 | fastapi/dependencies/utils.py
68+
• main 9 | scripts/notify_translations.py
69+
• analyze_param 9 | fastapi/dependencies/utils.py
70+
• __init__ 8 | fastapi/params.py
71+
• __init__ 8 | fastapi/params.py
72+
• main 7 | scripts/deploy_docs_status.py
73+
• create_model_field 7 | fastapi/utils.py
74+
75+
📉 Complexity Distribution:
76+
• Low (1-5): 3514 functions (99.3%)
77+
• Medium (6-10): 21 functions (0.6%)
78+
• High (>10): 3 functions (0.1%)
79+
```
80+
81+
## Complexity Metrics
82+
83+
The analyzer tracks several key metrics:
84+
85+
### Complexity Sources
86+
- If statements (+1)
87+
- Elif statements (+1 each)
88+
- Else statements (+1)
89+
- Loops (while/for) (+1)
90+
- Try-except blocks (+1 per except)
91+
92+
### Complexity Categories
93+
- Low (1-5): Generally clean and maintainable code
94+
- Medium (6-10): Moderate complexity, may need attention
95+
- High (>10): Complex code that should be reviewed
96+
97+
## Running the Analysis
98+
99+
```bash
100+
# Install Codegen
101+
pip install codegen
102+
103+
# Run the analysis
104+
python run.py
105+
```
106+
107+
## Example Output
108+
109+
```
110+
📊 Cyclomatic Complexity Analysis
111+
============================================================
112+
113+
📈 Overall Stats:
114+
• Total Functions: 150
115+
• Average Complexity: 3.45
116+
• Total Complexity: 518
117+
118+
🔍 Top 10 Most Complex Functions:
119+
------------------------------------------------------------
120+
• validate_response 12 | ...api/endpoints/auth.py
121+
• process_request 10 | ...core/middleware.py
122+
• handle_exception 9 | ...utils/error_handlers.py
123+
124+
📉 Complexity Distribution:
125+
• Low (1-5): 105 functions (70.0%)
126+
• Medium (6-10): 35 functions (23.3%)
127+
• High (>10): 10 functions (6.7%)
128+
```
129+
130+
## Learn More
131+
132+
- [About Cyclomatic Complexity](https://en.wikipedia.org/wiki/Cyclomatic_complexity)
133+
- [Codegen Documentation](https://docs.codegen.com)
134+
135+
## Contributing
136+
137+
Feel free to submit issues and enhancement requests!

0 commit comments

Comments
 (0)