Coverage for /Users/les/Projects/crackerjack/crackerjack/core/autofix_coordinator.py: 0%

131 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-03 15:39 -0700

1import logging 

2import subprocess 

3import typing as t 

4from pathlib import Path 

5 

6from rich.console import Console 

7 

8 

9class AutofixCoordinator: 

10 def __init__(self, console: Console, pkg_path: Path) -> None: 

11 self.console = console 

12 self.pkg_path = pkg_path 

13 self.logger = logging.getLogger("crackerjack.autofix") 

14 

15 def apply_autofix_for_hooks(self, mode: str, hook_results: list[t.Any]) -> bool: 

16 self.logger.debug( 

17 f"Applying autofix for {mode} mode with {len(hook_results)} hook results", 

18 ) 

19 try: 

20 if self._should_skip_autofix(hook_results): 

21 self.logger.info( 

22 f"Skipping autofix for {mode}-unfixable error patterns detected", 

23 ) 

24 return False 

25 if mode == "fast": 

26 result = self._apply_fast_stage_fixes() 

27 self.logger.debug(f"Fast stage fixes result: {result}") 

28 return result 

29 if mode == "comprehensive": 

30 result = self._apply_comprehensive_stage_fixes(hook_results) 

31 self.logger.debug(f"Comprehensive stage fixes result: {result}") 

32 return result 

33 self.logger.warning(f"Unknown autofix mode: {mode}") 

34 return False 

35 except Exception as e: 

36 self.logger.error(f"Auto-fix error in {mode} mode: {e}", exc_info=True) 

37 self.console.print(f"[dim red]Auto-fix error: {e}[/ dim red]") 

38 return False 

39 

40 def apply_fast_stage_fixes(self) -> bool: 

41 return self._apply_fast_stage_fixes() 

42 

43 def apply_comprehensive_stage_fixes(self, hook_results: list[t.Any]) -> bool: 

44 return self._apply_comprehensive_stage_fixes(hook_results) 

45 

46 def run_fix_command(self, cmd: list[str], description: str) -> bool: 

47 return self._run_fix_command(cmd, description) 

48 

49 def check_tool_success_patterns(self, cmd: list[str], result: t.Any) -> bool: 

50 return self._check_tool_success_patterns(cmd, result) 

51 

52 def validate_fix_command(self, cmd: list[str]) -> bool: 

53 return self._validate_fix_command(cmd) 

54 

55 def validate_hook_result(self, result: t.Any) -> bool: 

56 return self._validate_hook_result(result) 

57 

58 def should_skip_autofix(self, hook_results: list[t.Any]) -> bool: 

59 return self._should_skip_autofix(hook_results) 

60 

61 def _apply_fast_stage_fixes(self) -> bool: 

62 return self._execute_fast_fixes() 

63 

64 def _execute_fast_fixes(self) -> bool: 

65 fixes_applied = False 

66 fix_commands = [ 

67 (["uv", "run", "ruff", "format", "."], "ruff formatting"), 

68 (["uv", "run", "ruff", "check", ".", "--fix"], "ruff auto-fixes"), 

69 ] 

70 for cmd, description in fix_commands: 

71 if self._run_fix_command(cmd, description): 

72 fixes_applied = True 

73 

74 return fixes_applied 

75 

76 def _apply_comprehensive_stage_fixes(self, hook_results: list[t.Any]) -> bool: 

77 fixes_applied = False 

78 if self._apply_fast_stage_fixes(): 

79 fixes_applied = True 

80 failed_hooks = self._extract_failed_hooks(hook_results) 

81 hook_specific_fixes = self._get_hook_specific_fixes(failed_hooks) 

82 for cmd, description in hook_specific_fixes: 

83 if self._run_fix_command(cmd, description): 

84 fixes_applied = True 

85 

86 return fixes_applied 

87 

88 def _extract_failed_hooks(self, hook_results: list[t.Any]) -> set[str]: 

89 failed_hooks: set[str] = set() 

90 for result in hook_results: 

91 if self._validate_hook_result(result): 

92 hook_name: str = getattr(result, "name", "").lower() 

93 hook_status: str = getattr(result, "status", "") 

94 if hook_status == "Failed" and hook_name: 

95 failed_hooks.add(hook_name) 

96 

97 return failed_hooks 

98 

99 def _get_hook_specific_fixes( 

100 self, 

101 failed_hooks: set[str], 

102 ) -> list[tuple[list[str], str]]: 

103 hook_specific_fixes: list[tuple[list[str], str]] = [] 

104 if "bandit" in failed_hooks: 

105 hook_specific_fixes.append( 

106 ( 

107 ["uv", "run", "bandit", "- f", "json", ".", "- ll"], 

108 "bandit analysis", 

109 ), 

110 ) 

111 

112 return hook_specific_fixes 

113 

114 def _run_fix_command(self, cmd: list[str], description: str) -> bool: 

115 if not self._validate_fix_command(cmd): 

116 return False 

117 try: 

118 result = subprocess.run( 

119 cmd, 

120 check=False, 

121 capture_output=True, 

122 text=True, 

123 timeout=30, 

124 cwd=self.pkg_path, 

125 ) 

126 return self._handle_command_result(result, description) 

127 except Exception: 

128 return False 

129 

130 def _handle_command_result( 

131 self, 

132 result: subprocess.CompletedProcess[str], 

133 description: str, 

134 ) -> bool: 

135 return bool(result.returncode == 0 or self._is_successful_fix(result)) 

136 

137 def _is_successful_fix(self, result: subprocess.CompletedProcess[str]) -> bool: 

138 output = result.stdout.lower() 

139 return "fixed" in output or "reformatted" in output 

140 

141 def _check_tool_success_patterns(self, cmd: list[str], result: t.Any) -> bool: 

142 if not cmd or len(cmd) < 3: 

143 return False 

144 

145 tool_name = cmd[2] if len(cmd) > 2 else "" 

146 

147 if hasattr(result, "returncode"): 

148 return result.returncode == 0 

149 

150 if isinstance(result, str): 

151 output_lower = result.lower() 

152 if "ruff" in tool_name: 

153 return "fixed" in output_lower or "would reformat" in output_lower 

154 if "trailing-whitespace" in tool_name: 

155 return "fixing" in output_lower or "fixed" in output_lower 

156 

157 return False 

158 

159 def _validate_fix_command(self, cmd: list[str]) -> bool: 

160 if len(cmd) < 3: 

161 return False 

162 if cmd[0] != "uv" or cmd[1] != "run": 

163 return False 

164 tool_name = cmd[2] 

165 return tool_name in ("ruff", "bandit") 

166 

167 def _validate_hook_result(self, result: t.Any) -> bool: 

168 if not hasattr(result, "name") or not hasattr(result, "status"): 

169 self.logger.warning(f"Invalid hook result structure: {type(result)}") 

170 return False 

171 name = getattr(result, "name", None) 

172 status = getattr(result, "status", None) 

173 if not isinstance(name, str) or not name.strip(): 

174 self.logger.warning(f"Hook result has invalid name: {name}") 

175 return False 

176 if status not in ("Passed", "Failed", "Skipped", "Error"): 

177 self.logger.warning(f"Hook result has invalid status: {status}") 

178 return False 

179 

180 return True 

181 

182 def _should_skip_autofix(self, hook_results: list[t.Any]) -> bool: 

183 for result in hook_results: 

184 if hasattr(result, "raw_output"): 

185 output = getattr(result, "raw_output", "") 

186 if "ModuleNotFoundError" in output or "ImportError" in output: 

187 self.console.print( 

188 "[dim yellow] → Skipping autofix (import errors)[/ dim yellow]", 

189 ) 

190 return True 

191 return False