|
| 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