-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathanalyze_code.py
More file actions
188 lines (153 loc) Β· 5.43 KB
/
analyze_code.py
File metadata and controls
188 lines (153 loc) Β· 5.43 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
#!/usr/bin/env python3
"""
Run static analysis on Python code.
Usage:
python analyze_code.py <path> [--type TYPE]
"""
import sys
from pathlib import Path
try:
import codomyrmex
except ImportError:
project_root = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(project_root / "src"))
import argparse
import ast
import subprocess
def analyze_python_file(file_path: Path) -> dict:
"""Analyze a Python file."""
with open(file_path) as f:
source = f.read()
stats = {
"lines": len(source.split("\n")),
"functions": 0,
"classes": 0,
"imports": 0,
"docstrings": 0,
"todos": source.lower().count("todo"),
"complexity_warning": False,
}
try:
tree = ast.parse(source)
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
stats["functions"] += 1
if ast.get_docstring(node):
stats["docstrings"] += 1
elif isinstance(node, ast.ClassDef):
stats["classes"] += 1
if ast.get_docstring(node):
stats["docstrings"] += 1
elif isinstance(node, (ast.Import, ast.ImportFrom)):
stats["imports"] += 1
# Simple complexity check
if stats["functions"] > 20 or stats["lines"] > 500:
stats["complexity_warning"] = True
except SyntaxError as e:
stats["syntax_error"] = str(e)
return stats
def run_external_linter(path: str, linter: str) -> list:
"""Run an external linter."""
cmd_map = {
"ruff": ["ruff", "check", path],
"flake8": ["flake8", path],
"pylint": ["pylint", "--output-format=text", path],
"mypy": ["mypy", path],
}
if linter not in cmd_map:
return [f"Unknown linter: {linter}"]
try:
result = subprocess.run(
cmd_map[linter], capture_output=True, text=True, timeout=60
)
output = result.stdout + result.stderr
return [l for l in output.split("\n") if l.strip()][:20]
except FileNotFoundError:
return [f"{linter} not installed"]
except Exception as e:
return [str(e)]
def main():
# Auto-injected: Load configuration
from pathlib import Path
import yaml
config_path = (
Path(__file__).resolve().parent.parent.parent
/ "config"
/ "static_analysis"
/ "config.yaml"
)
if config_path.exists():
with open(config_path) as f:
yaml.safe_load(f) or {}
print("Loaded config from config/static_analysis/config.yaml")
parser = argparse.ArgumentParser(description="Static code analysis")
parser.add_argument("path", nargs="?", help="File or directory to analyze")
parser.add_argument(
"--type",
"-t",
choices=["basic", "ruff", "flake8", "pylint", "mypy"],
default="basic",
)
parser.add_argument("--verbose", "-v", action="store_true")
args = parser.parse_args()
if not args.path:
print("π Code Analyzer\n")
print("Usage:")
print(" python analyze_code.py src/")
print(" python analyze_code.py script.py --type ruff")
print("\nAnalysis types:")
print(" basic - Built-in AST analysis")
print(" ruff - Fast Python linter")
print(" flake8 - Style guide enforcement")
print(" pylint - Comprehensive linting")
print(" mypy - Type checking")
return 0
target = Path(args.path)
if not target.exists():
print(f"β Path not found: {args.path}")
return 1
print(f"π Analyzing: {target}\n")
if args.type != "basic":
results = run_external_linter(str(target), args.type)
if results:
print(f"π {args.type.upper()} results:\n")
for r in results:
print(f" {r}")
return 1 if len(results) > 1 else 0
print(f"β
No issues found by {args.type}")
return 0
# Basic analysis
files = [target] if target.is_file() else list(target.rglob("*.py"))
files = [f for f in files if "__pycache__" not in str(f)]
total = {"files": 0, "lines": 0, "functions": 0, "classes": 0, "todos": 0}
issues = []
for f in files[:50]:
stats = analyze_python_file(f)
total["files"] += 1
total["lines"] += stats["lines"]
total["functions"] += stats["functions"]
total["classes"] += stats["classes"]
total["todos"] += stats["todos"]
if "syntax_error" in stats:
issues.append(f"{f.name}: Syntax error - {stats['syntax_error']}")
if stats["complexity_warning"]:
issues.append(f"{f.name}: Complexity warning (>20 functions or >500 lines)")
if args.verbose:
print(
f" π {f.name}: {stats['lines']} lines, {stats['functions']} funcs, {stats['classes']} classes"
)
print(f"π Summary ({total['files']} files):")
print(f" Lines: {total['lines']:,}")
print(f" Functions: {total['functions']}")
print(f" Classes: {total['classes']}")
if total["todos"]:
print(f" TODOs: {total['todos']}")
if issues:
print(f"\nβ οΈ Issues ({len(issues)}):")
for issue in issues[:10]:
print(f" β’ {issue}")
else:
print("\nβ
No issues detected")
return 0
if __name__ == "__main__":
sys.exit(main())