Coverage for /Users/les/Projects/crackerjack/crackerjack/executors/cached_hook_executor.py: 0%

109 statements  

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

1import logging 

2import time 

3import typing as t 

4from pathlib import Path 

5 

6from rich.console import Console 

7 

8from crackerjack.config.hooks import HookDefinition, HookStrategy 

9from crackerjack.models.task import HookResult 

10from crackerjack.services.cache import CrackerjackCache 

11from crackerjack.services.file_hasher import FileHasher 

12 

13from .hook_executor import HookExecutionResult, HookExecutor 

14 

15 

16class CachedHookExecutor: 

17 def __init__( 

18 self, 

19 console: Console, 

20 pkg_path: Path, 

21 cache: CrackerjackCache | None = None, 

22 cache_ttl_seconds: int = 1800, 

23 ) -> None: 

24 self.console = console 

25 self.pkg_path = pkg_path 

26 self.cache = cache or CrackerjackCache() 

27 self.cache_ttl_seconds = cache_ttl_seconds 

28 self.file_hasher = FileHasher(self.cache) 

29 self.base_executor = HookExecutor(console, pkg_path, quiet=True) 

30 self.logger = logging.getLogger("crackerjack.cached_executor") 

31 

32 self.file_patterns = { 

33 "python": [" * .py"], 

34 "config": [" * .toml", " * .cfg", " * .ini", " * .yaml", " * .yml"], 

35 "all": [ 

36 " * .py", 

37 " * .toml", 

38 " * .cfg", 

39 " * .ini", 

40 " * .yaml", 

41 " * .yml", 

42 " * .md", 

43 " * .txt", 

44 ], 

45 } 

46 

47 def execute_strategy(self, strategy: HookStrategy) -> HookExecutionResult: 

48 self.logger.info( 

49 f"Executing cached strategy '{strategy.name}' with {len(strategy.hooks)} hooks", 

50 ) 

51 

52 start_time = time.time() 

53 results: list[HookResult] = [] 

54 cache_hits = 0 

55 cache_misses = 0 

56 

57 relevant_files = self._get_relevant_files_for_strategy(strategy) 

58 current_file_hashes = self.file_hasher.get_files_hash_list(relevant_files) 

59 

60 for hook_def in strategy.hooks: 

61 cached_result = None 

62 try: 

63 cached_result = self.cache.get_hook_result( 

64 hook_def.name, 

65 current_file_hashes, 

66 ) 

67 except Exception as e: 

68 self.logger.warning(f"Cache error for hook {hook_def.name}: {e}") 

69 cached_result = None 

70 

71 if cached_result and self._is_cache_valid(cached_result, hook_def): 

72 self.logger.debug(f"Using cached result for hook: {hook_def.name}") 

73 results.append(cached_result) 

74 cache_hits += 1 

75 else: 

76 self.logger.debug(f"Executing hook (cache miss): {hook_def.name}") 

77 

78 hook_result = self.base_executor.execute_single_hook(hook_def) 

79 results.append(hook_result) 

80 cache_misses += 1 

81 

82 if hook_result.status == "passed": 

83 try: 

84 self.cache.set_hook_result( 

85 hook_def.name, 

86 current_file_hashes, 

87 hook_result, 

88 ) 

89 except Exception as e: 

90 self.logger.warning( 

91 f"Failed to cache result for {hook_def.name}: {e}", 

92 ) 

93 

94 total_time = time.time() - start_time 

95 success = all(result.status == "passed" for result in results) 

96 

97 self.logger.info( 

98 f"Cached strategy '{strategy.name}' completed in {total_time: .2f}s-" 

99 f"Success: {success}, Cache hits: {cache_hits}, Cache misses: {cache_misses}", 

100 ) 

101 

102 return HookExecutionResult( 

103 strategy_name=strategy.name, 

104 results=results, 

105 success=success, 

106 total_duration=total_time, 

107 cache_hits=cache_hits, 

108 cache_misses=cache_misses, 

109 ) 

110 

111 def _get_relevant_files_for_strategy(self, strategy: HookStrategy) -> list[Path]: 

112 if self._strategy_affects_python_only(strategy): 

113 patterns = self.file_patterns["python"] 

114 elif self._strategy_affects_config_only(strategy): 

115 patterns = self.file_patterns["config"] 

116 else: 

117 patterns = self.file_patterns["all"] 

118 

119 files: list[Path] = [] 

120 for pattern in patterns: 

121 files.extend(list(self.pkg_path.rglob(pattern))) 

122 

123 return [f for f in files if f.is_file() and not self._should_ignore_file(f)] 

124 

125 def _strategy_affects_python_only(self, strategy: HookStrategy) -> bool: 

126 python_only_hooks = { 

127 "ruff-format", 

128 "ruff-check", 

129 "pyright", 

130 "bandit", 

131 "vulture", 

132 "refurb", 

133 "complexipy", 

134 } 

135 return all(hook.name in python_only_hooks for hook in strategy.hooks) 

136 

137 def _strategy_affects_config_only(self, strategy: HookStrategy) -> bool: 

138 config_only_hooks = {"creosote"} 

139 return all(hook.name in config_only_hooks for hook in strategy.hooks) 

140 

141 def _should_ignore_file(self, file_path: Path) -> bool: 

142 ignore_patterns = [ 

143 ".git /", 

144 ".venv /", 

145 "__pycache__ /", 

146 ".pytest_cache /", 

147 ".coverage", 

148 ".crackerjack_cache /", 

149 "node_modules /", 

150 ".tox /", 

151 "dist /", 

152 "build /", 

153 ".egg-info /", 

154 ] 

155 

156 path_str = str(file_path) 

157 return any(pattern in path_str for pattern in ignore_patterns) 

158 

159 def _is_cache_valid( 

160 self, 

161 cached_result: HookResult, 

162 hook_def: HookDefinition, 

163 ) -> bool: 

164 if cached_result.status != "passed": 

165 return False 

166 

167 cache_age = time.time() - getattr(cached_result, "timestamp", time.time()) 

168 return not cache_age > self.cache_ttl_seconds 

169 

170 def invalidate_hook_cache(self, hook_name: str | None = None) -> None: 

171 self.cache.invalidate_hook_cache(hook_name) 

172 self.logger.info(f"Invalidated cache for hook: {hook_name or 'all hooks'}") 

173 

174 def get_cache_stats(self) -> dict[str, t.Any]: 

175 return self.cache.get_cache_stats() 

176 

177 def cleanup_cache(self) -> dict[str, int]: 

178 return self.cache.cleanup_all() 

179 

180 

181class SmartCacheManager: 

182 def __init__(self, cached_executor: CachedHookExecutor) -> None: 

183 self.cached_executor = cached_executor 

184 self.logger = logging.getLogger("crackerjack.cache_manager") 

185 

186 def should_use_cache_for_hook( 

187 self, 

188 hook_name: str, 

189 project_state: dict[str, t.Any], 

190 ) -> bool: 

191 external_hooks = {"detect-secrets"} 

192 if hook_name in external_hooks: 

193 return False 

194 

195 expensive_hooks = {"pyright", "bandit", "vulture", "complexipy"} 

196 if hook_name in expensive_hooks: 

197 return True 

198 

199 formatting_hooks = { 

200 "ruff-format", 

201 "trailing-whitespace", 

202 "end-of-file-fixer", 

203 } 

204 if hook_name in formatting_hooks: 

205 recent_changes = project_state.get("recent_changes", 0) 

206 return recent_changes < 5 

207 

208 return True 

209 

210 def get_optimal_cache_strategy( 

211 self, 

212 hook_strategy: HookStrategy, 

213 ) -> dict[str, bool]: 

214 project_state = self._analyze_project_state() 

215 

216 cache_decisions = {} 

217 for hook_def in hook_strategy.hooks: 

218 cache_decisions[hook_def.name] = self.should_use_cache_for_hook( 

219 hook_def.name, 

220 project_state, 

221 ) 

222 

223 return cache_decisions 

224 

225 def _analyze_project_state(self) -> dict[str, t.Any]: 

226 pkg_path = self.cached_executor.pkg_path 

227 

228 recent_changes = 0 

229 for py_file in pkg_path.rglob("*.py"): 

230 if py_file.is_file(): 

231 from contextlib import suppress 

232 

233 with suppress(OSError): 

234 mtime = py_file.stat().st_mtime 

235 if time.time() - mtime < 3600: 

236 recent_changes += 1 

237 

238 return { 

239 "recent_changes": recent_changes, 

240 "total_python_files": len(list(pkg_path.rglob("*.py"))), 

241 "project_size": "large" if recent_changes > 50 else "small", 

242 }