Coverage for /Users/les/Projects/crackerjack/crackerjack/agents/formatting_agent.py: 0%
105 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
2from pathlib import Path
4from .base import (
5 AgentContext,
6 FixResult,
7 Issue,
8 IssueType,
9 SubAgent,
10 agent_registry,
11)
14class FormattingAgent(SubAgent):
15 def __init__(self, context: AgentContext) -> None:
16 super().__init__(context)
17 self.supported_tools = [
18 "ruff",
19 "trailing-whitespace",
20 "end-of-file-fixer",
21 ]
23 def get_supported_types(self) -> set[IssueType]:
24 return {IssueType.FORMATTING, IssueType.IMPORT_ERROR}
26 async def can_handle(self, issue: Issue) -> float:
27 if issue.type not in self.get_supported_types():
28 return 0.0
30 message_lower = issue.message.lower()
32 if any(
33 keyword in message_lower
34 for keyword in (
35 "would reformat",
36 "trailing whitespace",
37 "missing newline",
38 "import sorting",
39 "unused import",
40 "ruff",
41 "format",
42 )
43 ):
44 return 1.0
46 if any(
47 keyword in message_lower
48 for keyword in (
49 "whitespace",
50 "indent",
51 "spacing",
52 "line length",
53 "import",
54 "style",
55 "format",
56 )
57 ):
58 return 0.8
60 if issue.type == IssueType.FORMATTING:
61 return 0.6
63 return 0.0
65 async def analyze_and_fix(self, issue: Issue) -> FixResult:
66 self.log(f"Analyzing formatting issue: {issue.message}")
68 fixes_applied: list[str] = []
69 files_modified: list[str] = []
71 try:
72 ruff_fixes = await self._apply_ruff_fixes()
73 fixes_applied.extend(ruff_fixes)
75 whitespace_fixes = await self._apply_whitespace_fixes()
76 fixes_applied.extend(whitespace_fixes)
78 import_fixes = await self._apply_import_fixes()
79 fixes_applied.extend(import_fixes)
81 if issue.file_path:
82 file_fixes = await self._fix_specific_file(issue.file_path, issue)
83 fixes_applied.extend(file_fixes)
84 if file_fixes:
85 files_modified.append(issue.file_path)
87 success = len(fixes_applied) > 0
88 confidence = 0.9 if success else 0.3
90 return FixResult(
91 success=success,
92 confidence=confidence,
93 fixes_applied=fixes_applied,
94 files_modified=files_modified,
95 recommendations=[
96 "Run ruff format regularly for consistent styling",
97 "Configure pre-commit hooks for automatic formatting",
98 ]
99 if not success
100 else [],
101 )
103 except Exception as e:
104 self.log(f"Error fixing formatting issue: {e}", "ERROR")
105 return FixResult(
106 success=False,
107 confidence=0.0,
108 remaining_issues=[f"Failed to apply formatting fixes: {e}"],
109 )
111 async def _apply_ruff_fixes(self) -> list[str]:
112 fixes: list[str] = []
114 returncode, _, stderr = await self.run_command(
115 ["uv", "run", "ruff", "format", "."],
116 )
118 if returncode == 0:
119 fixes.append("Applied ruff code formatting")
120 self.log("Successfully applied ruff formatting")
121 else:
122 self.log(f"Ruff format failed: {stderr}", "WARN")
124 returncode, _, stderr = await self.run_command(
125 ["uv", "run", "ruff", "check", ".", "--fix"],
126 )
128 if returncode == 0:
129 fixes.append("Applied ruff linting fixes")
130 self.log("Successfully applied ruff linting fixes")
131 else:
132 self.log(f"Ruff check --fix had issues: {stderr}", "WARN")
134 return fixes
136 async def _apply_whitespace_fixes(self) -> list[str]:
137 fixes: list[str] = []
139 returncode, _, _ = await self.run_command(
140 [
141 "uv",
142 "run",
143 "pre-commit",
144 "run",
145 "trailing-whitespace",
146 "--all-files",
147 ],
148 )
150 if returncode == 0:
151 fixes.append("Fixed trailing whitespace")
152 self.log("Fixed trailing whitespace")
154 returncode, _, _ = await self.run_command(
155 [
156 "uv",
157 "run",
158 "pre-commit",
159 "run",
160 "end-of-file-fixer",
161 "--all-files",
162 ],
163 )
165 if returncode == 0:
166 fixes.append("Fixed end-of-file formatting")
167 self.log("Fixed end-of-file formatting")
169 return fixes
171 async def _apply_import_fixes(self) -> list[str]:
172 fixes: list[str] = []
174 returncode, _, _ = await self.run_command(
175 [
176 "uv",
177 "run",
178 "ruff",
179 "check",
180 ".",
181 "--select",
182 "I,F401",
183 "--fix",
184 ],
185 )
187 if returncode == 0:
188 fixes.append("Organized imports and removed unused imports")
189 self.log("Fixed import organization")
191 return fixes
193 async def _fix_specific_file(self, file_path: str, issue: Issue) -> list[str]:
194 fixes: list[str] = []
196 try:
197 path = Path(file_path)
198 content = self._validate_and_get_file_content(path)
199 if not content:
200 return fixes
202 original_content = content
203 cleaned_content = self._apply_content_formatting(content)
205 if cleaned_content != original_content:
206 if self.context.write_file_content(path, cleaned_content):
207 fixes.append(f"Fixed formatting in {file_path}")
208 self.log(f"Applied file-specific fixes to {file_path}")
210 except Exception as e:
211 self.log(f"Error fixing file {file_path}: {e}", "ERROR")
213 return fixes
215 def _validate_and_get_file_content(self, path: Path) -> str | None:
216 if not path.exists() or not path.is_file():
217 return None
219 content = self.context.get_file_content(path)
220 return content or None
222 def _apply_content_formatting(self, content: str) -> str:
223 content = re.sub(r"[ \t]+$", "", content, flags=re.MULTILINE)
225 if content and not content.endswith("\n"):
226 content += "\n"
228 content = re.sub(r"\n{3,}", "\n\n", content)
230 return self._convert_tabs_to_spaces(content)
232 def _convert_tabs_to_spaces(self, content: str) -> str:
233 lines = content.split("\n")
234 fixed_lines = [line.expandtabs(4) for line in lines]
235 return "\n".join(fixed_lines)
238agent_registry.register(FormattingAgent)