Coverage for /Users/les/Projects/crackerjack/crackerjack/agents/dry_agent.py: 0%
129 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
1import re
2import typing as t
3from pathlib import Path
5from .base import (
6 FixResult,
7 Issue,
8 IssueType,
9 SubAgent,
10 agent_registry,
11)
14class DRYAgent(SubAgent):
15 def get_supported_types(self) -> set[IssueType]:
16 return {IssueType.DRY_VIOLATION}
18 async def can_handle(self, issue: Issue) -> float:
19 if issue.type == IssueType.DRY_VIOLATION:
20 return 0.9
21 return 0.0
23 async def analyze_and_fix(self, issue: Issue) -> FixResult:
24 self.log(f"Analyzing DRY violation: {issue.message}")
26 validation_result = self._validate_dry_issue(issue)
27 if validation_result:
28 return validation_result
30 if issue.file_path is None:
31 return self._create_dry_error_result(
32 ValueError("File path is required for DRY violation"),
33 )
35 file_path = Path(issue.file_path)
37 try:
38 return await self._process_dry_violation(file_path)
39 except Exception as e:
40 return self._create_dry_error_result(e)
42 def _validate_dry_issue(self, issue: Issue) -> FixResult | None:
43 if not issue.file_path:
44 return FixResult(
45 success=False,
46 confidence=0.0,
47 remaining_issues=["No file path specified for DRY violation"],
48 )
50 file_path = Path(issue.file_path)
51 if not file_path.exists():
52 return FixResult(
53 success=False,
54 confidence=0.0,
55 remaining_issues=[f"File not found: {file_path}"],
56 )
58 return None
60 async def _process_dry_violation(self, file_path: Path) -> FixResult:
61 content = self.context.get_file_content(file_path)
62 if not content:
63 return FixResult(
64 success=False,
65 confidence=0.0,
66 remaining_issues=[f"Could not read file: {file_path}"],
67 )
69 violations = self._detect_dry_violations(content, file_path)
71 if not violations:
72 return FixResult(
73 success=True,
74 confidence=0.7,
75 recommendations=["No DRY violations detected"],
76 )
78 return self._apply_and_save_dry_fixes(file_path, content, violations)
80 def _apply_and_save_dry_fixes(
81 self,
82 file_path: Path,
83 content: str,
84 violations: list[dict[str, t.Any]],
85 ) -> FixResult:
86 fixed_content = self._apply_dry_fixes(content, violations)
88 if fixed_content == content:
89 return self._create_no_fixes_result()
91 success = self.context.write_file_content(file_path, fixed_content)
92 if not success:
93 return FixResult(
94 success=False,
95 confidence=0.0,
96 remaining_issues=[f"Failed to write fixed file: {file_path}"],
97 )
99 return FixResult(
100 success=True,
101 confidence=0.8,
102 fixes_applied=[
103 f"Fixed {len(violations)} DRY violations",
104 "Consolidated repetitive patterns",
105 ],
106 files_modified=[str(file_path)],
107 recommendations=["Verify functionality after DRY fixes"],
108 )
110 def _create_no_fixes_result(self) -> FixResult:
111 return FixResult(
112 success=False,
113 confidence=0.5,
114 remaining_issues=["Could not automatically fix DRY violations"],
115 recommendations=[
116 "Manual refactoring required",
117 "Consider extracting common patterns to utility functions",
118 "Create base classes or mixins for repeated functionality",
119 ],
120 )
122 def _create_dry_error_result(self, error: Exception) -> FixResult:
123 return FixResult(
124 success=False,
125 confidence=0.0,
126 remaining_issues=[f"Error processing file: {error}"],
127 )
129 def _detect_dry_violations(
130 self,
131 content: str,
132 file_path: Path,
133 ) -> list[dict[str, t.Any]]:
134 violations: list[dict[str, t.Any]] = []
136 violations.extend(self._detect_error_response_patterns(content))
138 violations.extend(self._detect_path_conversion_patterns(content))
140 violations.extend(self._detect_file_existence_patterns(content))
142 violations.extend(self._detect_exception_patterns(content))
144 return violations
146 def _detect_error_response_patterns(self, content: str) -> list[dict[str, t.Any]]:
147 violations: list[dict[str, t.Any]] = []
148 lines = content.split("\n")
150 error_pattern = re.compile(
151 r'return\s+f?[\'\"]\{[\'\""]error[\'\""]:\s*[\'\""]([^\'\"]*)[\'\""].*\}[\'\""]',
152 )
154 error_responses: list[dict[str, t.Any]] = []
155 for i, line in enumerate(lines):
156 match = error_pattern.search(line.strip())
157 if match:
158 error_responses.append(
159 {
160 "line_number": i + 1,
161 "content": line.strip(),
162 "error_message": match.group(1),
163 },
164 )
166 if len(error_responses) >= 3:
167 violations.append(
168 {
169 "type": "error_response_pattern",
170 "instances": error_responses,
171 "suggestion": "Extract to error utility function",
172 },
173 )
175 return violations
177 def _detect_path_conversion_patterns(self, content: str) -> list[dict[str, t.Any]]:
178 violations: list[dict[str, t.Any]] = []
179 lines = content.split("\n")
181 path_pattern = re.compile(
182 r"Path\([^)]+\)\s+if\s+isinstance\([^)]+,\s*str\)\s+else\s+[^)]+",
183 )
185 path_conversions: list[dict[str, t.Any]] = [
186 {
187 "line_number": i + 1,
188 "content": line.strip(),
189 }
190 for i, line in enumerate(lines)
191 if path_pattern.search(line)
192 ]
194 if len(path_conversions) >= 2:
195 violations.append(
196 {
197 "type": "path_conversion_pattern",
198 "instances": path_conversions,
199 "suggestion": "Extract to path utility function",
200 },
201 )
203 return violations
205 def _detect_file_existence_patterns(self, content: str) -> list[dict[str, t.Any]]:
206 violations: list[dict[str, t.Any]] = []
207 lines = content.split("\n")
209 existence_pattern = re.compile(r"if\s+not\s+\w+\.exists\(\):")
211 existence_checks: list[dict[str, t.Any]] = [
212 {
213 "line_number": i + 1,
214 "content": line.strip(),
215 }
216 for i, line in enumerate(lines)
217 if existence_pattern.search(line.strip())
218 ]
220 if len(existence_checks) >= 3:
221 violations.append(
222 {
223 "type": "file_existence_pattern",
224 "instances": existence_checks,
225 "suggestion": "Extract to file validation utility",
226 },
227 )
229 return violations
231 def _detect_exception_patterns(self, content: str) -> list[dict[str, t.Any]]:
232 violations: list[dict[str, t.Any]] = []
233 lines = content.split("\n")
235 exception_pattern = re.compile(r"except\s+\w*Exception\s+as\s+\w+:")
237 exception_handlers: list[dict[str, t.Any]] = []
238 for i, line in enumerate(lines):
239 if exception_pattern.search(line.strip()):
240 if (
241 i + 1 < len(lines)
242 and "error" in lines[i + 1]
243 and "str(" in lines[i + 1]
244 ):
245 exception_handlers.append(
246 {
247 "line_number": i + 1,
248 "content": line.strip(),
249 "next_line": lines[i + 1].strip(),
250 },
251 )
253 if len(exception_handlers) >= 3:
254 violations.append(
255 {
256 "type": "exception_handling_pattern",
257 "instances": exception_handlers,
258 "suggestion": "Extract to error handling utility or decorator",
259 },
260 )
262 return violations
264 def _apply_dry_fixes(self, content: str, violations: list[dict[str, t.Any]]) -> str:
265 lines = content.split("\n")
266 modified = False
268 for violation in violations:
269 if violation["type"] == "error_response_pattern":
270 lines, changed = self._fix_error_response_pattern(lines, violation)
271 modified = modified or changed
272 elif violation["type"] == "path_conversion_pattern":
273 lines, changed = self._fix_path_conversion_pattern(lines, violation)
274 modified = modified or changed
276 return "\n".join(lines) if modified else content
278 def _fix_error_response_pattern(
279 self,
280 lines: list[str],
281 violation: dict[str, t.Any],
282 ) -> tuple[list[str], bool]:
283 utility_function = """
284def _create_error_response(message: str, success: bool = False) -> str:
286 import json
287 return json.dumps({"error": message, "success": success})
289def _ensure_path(path: str | Path) -> Path:
291 return Path(path) if isinstance(path, str) else path
292"""
294 insert_pos = 0
295 for i, line in enumerate(lines):
296 if line.strip().startswith(("import ", "from ")):
297 insert_pos = i + 1
298 elif line.strip() and not line.strip().startswith("#"):
299 break
301 utility_lines = utility_function.strip().split("\n")
302 for i, util_line in enumerate(utility_lines):
303 lines.insert(insert_pos + i, util_line)
305 path_pattern = re.compile(
306 r"Path\([^)]+\)\s+if\s+isinstance\([^)]+,\s*str\)\s+else\s+([^)]+)",
307 )
309 for instance in violation["instances"]:
310 line_number: int = int(instance["line_number"])
311 line_idx = line_number - 1 + len(utility_lines)
312 if line_idx < len(lines):
313 original_line: str = lines[line_idx]
315 new_line: str = path_pattern.sub(r"_ensure_path(\1)", original_line)
316 lines[line_idx] = new_line
318 return lines, True
321agent_registry.register(DRYAgent)