#!/usr/bin/env python3
"""
Check code complexity and reject changes that are too complex.
Uses radon for Python, or custom heuristics for other languages.
"""
import json
import sys
import subprocess
import re
def check_python_complexity(file_path):
"""Check Python file complexity using radon."""
try:
result = subprocess.run(
['radon', 'cc', file_path, '-s', '-n', 'C'],
capture_output=True,
text=True,
timeout=10
)
if result.returncode == 0 and result.stdout:
print(f"❌ Code complexity too high in {file_path}", file=sys.stderr)
print(result.stdout, file=sys.stderr)
print("\nPlease simplify the code by:", file=sys.stderr)
print("- Breaking down large functions", file=sys.stderr)
print("- Reducing nesting levels", file=sys.stderr)
print("- Extracting helper functions", file=sys.stderr)
return False
except (subprocess.SubprocessError, FileNotFoundError):
pass
return True
def check_js_complexity(file_path):
"""Basic complexity check for JavaScript/TypeScript."""
with open(file_path, 'r') as f:
content = f.read()
# Count nesting level (very basic check)
max_nesting = 0
current_nesting = 0
for char in content:
if char == '{':
current_nesting += 1
max_nesting = max(max_nesting, current_nesting)
elif char == '}':
current_nesting -= 1
if max_nesting > 5:
print(f"⚠️ High nesting level ({max_nesting}) in {file_path}", file=sys.stderr)
print("Consider refactoring to reduce nesting.", file=sys.stderr)
# Warning only, don't block
return True
try:
input_data = json.load(sys.stdin)
file_path = input_data.get('tool_input', {}).get('file_path', '')
if not file_path:
sys.exit(0)
if file_path.endswith('.py'):
if not check_python_complexity(file_path):
sys.exit(2)
elif file_path.endswith(('.js', '.jsx', '.ts', '.tsx')):
if not check_js_complexity(file_path):
sys.exit(2)
except Exception as e:
print(f"Error checking complexity: {e}", file=sys.stderr)
sys.exit(0) # Don't block on errors