Overview
The code analysis tool performs static analysis on Python source files using the built-inast module. It computes cyclomatic complexity, categorizes imports into stdlib/third-party/local, and analyzes code structure metrics like nesting depth and function sizes.
Tool
code_analysis
Perform AST-based static analysis on Python files to compute complexity, dependencies, or structure metrics.File or directory path to analyze. Relative paths resolve from workspace.
Type of analysis to perform. Options:
complexity, dependencies, structure.Analysis Types
complexity
Computes cyclomatic complexity for every function and method in the file. Metrics computed:- Decision points per function (if/elif/for/while/except/and/or)
- Average complexity across all functions
- Total complexity score
- Lines of code per function
- 1-5: Simple, easy to test
- 6-10: Moderate complexity, acceptable
- 11-20: High complexity, consider refactoring
- 21+: Very high complexity, definitely refactor
dependencies
Analyzes import statements and categorizes them into stdlib, third-party, and local modules. Categories:- stdlib: Built-in Python standard library modules
- third_party: External packages from PyPI
- local: Relative imports from the same project
structure
Analyzes code organization with class/function counts, size distribution, and nesting depth. Metrics computed:- Total classes and functions
- Maximum nesting depth of control structures
- Average, largest, and smallest function sizes
Multi-File Analysis
When analyzing a directory, the tool processes up to 50 Python files and returns analysis for each. Example:Error Handling
Syntax errors are reported without crashing:Use Cases
- Code review: Identify overly complex functions before PR merge
- Refactoring: Find high-complexity hotspots that need simplification
- Dependency audit: Track third-party dependencies and import patterns
- Architecture analysis: Understand code structure and organization
- Onboarding: Generate quick overviews of unfamiliar codebases
Implementation
Defined ingrip/tools/code_analysis.py at code_analysis.py:213. Uses:
- Python’s built-in
astmodule (zero external dependencies) - Cyclomatic complexity calculation via AST traversal
- Stdlib detection using
sys.stdlib_module_names - Recursive nesting depth analysis
- Limited to 50 files per directory to prevent performance issues