forked from danilofalcao/jarvis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_analyzer.py
More file actions
280 lines (244 loc) · 10.3 KB
/
Copy pathcode_analyzer.py
File metadata and controls
280 lines (244 loc) · 10.3 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
"""Code analyzer module for analyzing and processing code files."""
# pylama:ignore=E501,E251
import os
import re
from dataclasses import dataclass
from typing import List
@dataclass
class CodeIssue:
"""Class to represent a code issue found during analysis."""
file: str
line: int
issue_type: str
message: str
suggestion: str = None
class CodeAnalyzer:
"""Analyzes code files for potential improvements."""
def __init__(self):
self.max_line_length = 100
self.max_function_length = 50
self.max_params = 5
def analyze_directory(self,
directory: str,
file_pattern: str = None) -> List[CodeIssue]:
"""Analyze all code files in a directory."""
issues = []
for root, _, files in os.walk(directory):
for file in files:
if file_pattern and not re.match(file_pattern, file):
continue
file_path = os.path.join(root, file)
relative_path = os.path.relpath(file_path, directory)
# Skip non-code files
if not self._is_code_file(file):
continue
try:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
# Analyze based on file type
if file.endswith(".py"):
issues.extend(
self._analyze_python_file(relative_path, content))
elif file.endswith(".js"):
issues.extend(
self._analyze_javascript_file(
relative_path, content))
else:
issues.extend(
self._analyze_generic_file(relative_path, content))
except Exception as e:
print(f"Error analyzing {file_path}: {str(e)}")
return issues
def _is_code_file(self, filename: str) -> bool:
"""Check if a file is a code file based on extension."""
code_extensions = {
".py",
".js",
".jsx",
".ts",
".tsx",
".java",
".cpp",
".c",
".h",
".cs",
".php",
".rb",
".go",
}
return any(filename.endswith(ext) for ext in code_extensions)
def _analyze_python_file(self, file_path: str,
content: str) -> List[CodeIssue]:
"""Analyze a Python file for potential issues."""
issues = []
lines = content.splitlines()
in_function = False
function_lines = 0
for i, line in enumerate(lines, 1):
# Check line length
if len(line.strip()) > self.max_line_length:
issues.append(
CodeIssue(
file=file_path,
line=i,
issue_type="style",
message=
f"Line exceeds {self.max_line_length} characters",
suggestion=
"Consider breaking this line into multiple lines",
))
# Check for function definitions
if re.match(r"^\s*def\s+\w+\s*\(", line):
in_function = True
function_lines = 0
# Check number of parameters
params = re.search(r"\((.*?)\)", line)
if params:
param_count = len(
[p for p in params.group(1).split(",") if p.strip()])
if param_count > self.max_params:
issues.append(
CodeIssue(
file=file_path,
line=i,
issue_type="complexity",
message=
f"Function has {param_count} parameters (max {self.max_params})",
suggestion=
"Consider grouping parameters into a class or using keyword arguments",
))
# Count function lines
if in_function:
function_lines += 1
if function_lines > self.max_function_length:
issues.append(
CodeIssue(
file=file_path,
line=i,
issue_type="complexity",
message=
f"Function is {function_lines} lines long (max {self.max_function_length})",
suggestion=
"Consider breaking this function into smaller functions",
))
in_function = False # Only report once per function
# Check for debugging statements
if re.search(r"print\s*\(|pdb\.set_trace\(\)", line):
issues.append(
CodeIssue(
file=file_path,
line=i,
issue_type="debugging",
message="Found debugging statement",
suggestion=
"Remove debugging statements before committing",
))
return issues
def _analyze_javascript_file(self, file_path: str,
content: str) -> List[CodeIssue]:
"""Analyze a JavaScript file for potential issues."""
issues = []
lines = content.splitlines()
in_function = False
function_lines = 0
for i, line in enumerate(lines, 1):
# Check line length
if len(line.strip()) > self.max_line_length:
issues.append(
CodeIssue(
file=file_path,
line=i,
issue_type="style",
message=
f"Line exceeds {self.max_line_length} characters",
suggestion=
"Consider breaking this line into multiple lines",
))
# Check for function definitions
if re.search(r"(function\s+\w+\s*\(|=>|\w+\s*=\s*function\s*\()",
line):
in_function = True
function_lines = 0
# Check number of parameters
params = re.search(r"\((.*?)\)", line)
if params:
param_count = len(
[p for p in params.group(1).split(",") if p.strip()])
if param_count > self.max_params:
issues.append(
CodeIssue(
file=file_path,
line=i,
issue_type="complexity",
message=
f"Function has {param_count} parameters (max {self.max_params})",
suggestion=
"Consider grouping parameters into an object or using destructuring",
))
# Count function lines
if in_function:
function_lines += 1
if function_lines > self.max_function_length:
issues.append(
CodeIssue(
file=file_path,
line=i,
issue_type="complexity",
message=
f"Function is {function_lines} lines long (max {self.max_function_length})",
suggestion=
"Consider breaking this function into smaller functions",
))
in_function = False # Only report once per function
# Check for debugging statements
if re.search(r"console\.(log|debug|info|warn|error)\s*\(", line):
issues.append(
CodeIssue(
file=file_path,
line=i,
issue_type="debugging",
message="Found console statement",
suggestion=
"Remove console statements before committing",
))
return issues
def _analyze_generic_file(self, file_path: str,
content: str) -> List[CodeIssue]:
"""Analyze any code file for generic issues."""
issues = []
lines = content.splitlines()
for i, line in enumerate(lines, 1):
# Check line length
if len(line.strip()) > self.max_line_length:
issues.append(
CodeIssue(
file=file_path,
line=i,
issue_type="style",
message=
f"Line exceeds {self.max_line_length} characters",
suggestion=
"Consider breaking this line into multiple lines",
))
# Check for TODO comments
if re.search(r"TODO|FIXME|XXX", line, re.IGNORECASE):
issues.append(
CodeIssue(
file=file_path,
line=i,
issue_type="documentation",
message="Found TODO comment",
suggestion="Consider addressing this TODO item",
))
# Check for hardcoded values
if re.search(r'[\'"]\d+[\'"]|\b\d{4,}\b', line):
issues.append(
CodeIssue(
file=file_path,
line=i,
issue_type="maintainability",
message="Found hardcoded value",
suggestion=
"Consider using a named constant or configuration value",
))
return issues