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

205 statements  

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

1import os 

2import subprocess 

3import time 

4import typing as t 

5from concurrent.futures import ThreadPoolExecutor, as_completed 

6from dataclasses import dataclass 

7from pathlib import Path 

8 

9from rich.console import Console 

10 

11from crackerjack.config.hooks import HookDefinition, HookStrategy, RetryPolicy 

12from crackerjack.models.task import HookResult 

13from crackerjack.services.secure_subprocess import execute_secure_subprocess 

14from crackerjack.services.security_logger import get_security_logger 

15 

16 

17@dataclass 

18class HookExecutionResult: 

19 strategy_name: str 

20 results: list[HookResult] 

21 total_duration: float 

22 success: bool 

23 concurrent_execution: bool = False 

24 cache_hits: int = 0 

25 cache_misses: int = 0 

26 

27 @property 

28 def failed_count(self) -> int: 

29 return sum(1 for r in self.results if r.status == "failed") 

30 

31 @property 

32 def passed_count(self) -> int: 

33 return sum(1 for r in self.results if r.status == "passed") 

34 

35 @property 

36 def cache_hit_rate(self) -> float: 

37 total_requests = self.cache_hits + self.cache_misses 

38 return (self.cache_hits / total_requests * 100) if total_requests > 0 else 0.0 

39 

40 @property 

41 def performance_summary(self) -> dict[str, t.Any]: 

42 return { 

43 "total_hooks": len(self.results), 

44 "passed": self.passed_count, 

45 "failed": self.failed_count, 

46 "duration_seconds": round(self.total_duration, 2), 

47 "concurrent": self.concurrent_execution, 

48 "cache_hits": self.cache_hits, 

49 "cache_misses": self.cache_misses, 

50 "cache_hit_rate_percent": round(self.cache_hit_rate, 1), 

51 } 

52 

53 

54class HookExecutor: 

55 def __init__( 

56 self, 

57 console: Console, 

58 pkg_path: Path, 

59 verbose: bool = False, 

60 quiet: bool = False, 

61 ) -> None: 

62 self.console = console 

63 self.pkg_path = pkg_path 

64 self.verbose = verbose 

65 self.quiet = quiet 

66 

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

68 start_time = time.time() 

69 

70 self._print_strategy_header(strategy) 

71 

72 if strategy.parallel and len(strategy.hooks) > 1: 

73 results = self._execute_parallel(strategy) 

74 else: 

75 results = self._execute_sequential(strategy) 

76 

77 if strategy.retry_policy != RetryPolicy.NONE: 

78 results = self._handle_retries(strategy, results) 

79 

80 total_duration = time.time() - start_time 

81 success = all(r.status == "passed" for r in results) 

82 

83 if not self.quiet: 

84 self._print_summary(strategy, results, success) 

85 

86 return HookExecutionResult( 

87 strategy_name=strategy.name, 

88 results=results, 

89 total_duration=total_duration, 

90 success=success, 

91 ) 

92 

93 def _print_strategy_header(self, strategy: HookStrategy) -> None: 

94 self.console.print("\n" + "-" * 80) 

95 if strategy.name == "fast": 

96 self.console.print( 

97 "[bold bright_cyan]🔍 HOOKS[/ bold bright_cyan] [bold bright_white]Running code quality checks[/ bold bright_white]", 

98 ) 

99 elif strategy.name == "comprehensive": 

100 self.console.print( 

101 "[bold bright_cyan]🔍 HOOKS[/ bold bright_cyan] [bold bright_white]Running comprehensive quality checks[/ bold bright_white]", 

102 ) 

103 else: 

104 self.console.print( 

105 f"[bold bright_cyan]🔍 HOOKS[/ bold bright_cyan] [bold bright_white]Running {strategy.name} hooks[/ bold bright_white]", 

106 ) 

107 self.console.print("-" * 80 + "\n") 

108 

109 def _execute_sequential(self, strategy: HookStrategy) -> list[HookResult]: 

110 results: list[HookResult] = [] 

111 for hook in strategy.hooks: 

112 result = self.execute_single_hook(hook) 

113 results.append(result) 

114 self._display_hook_result(result) 

115 return results 

116 

117 def _execute_parallel(self, strategy: HookStrategy) -> list[HookResult]: 

118 results: list[HookResult] = [] 

119 

120 formatting_hooks = [h for h in strategy.hooks if h.is_formatting] 

121 other_hooks = [h for h in strategy.hooks if not h.is_formatting] 

122 

123 for hook in formatting_hooks: 

124 result = self.execute_single_hook(hook) 

125 results.append(result) 

126 self._display_hook_result(result) 

127 

128 if other_hooks: 

129 with ThreadPoolExecutor(max_workers=strategy.max_workers) as executor: 

130 future_to_hook = { 

131 executor.submit(self.execute_single_hook, hook): hook 

132 for hook in other_hooks 

133 } 

134 

135 for future in as_completed(future_to_hook): 

136 try: 

137 result = future.result() 

138 results.append(result) 

139 self._display_hook_result(result) 

140 except Exception as e: 

141 hook = future_to_hook[future] 

142 error_result = HookResult( 

143 id=hook.name, 

144 name=hook.name, 

145 status="error", 

146 duration=0.0, 

147 issues_found=[str(e)], 

148 stage=hook.stage.value, 

149 ) 

150 results.append(error_result) 

151 self._display_hook_result(error_result) 

152 

153 return results 

154 

155 def execute_single_hook(self, hook: HookDefinition) -> HookResult: 

156 start_time = time.time() 

157 

158 try: 

159 result = self._run_hook_subprocess(hook) 

160 duration = time.time() - start_time 

161 

162 self._display_hook_output_if_needed(result) 

163 return self._create_hook_result_from_process(hook, result, duration) 

164 

165 except subprocess.TimeoutExpired: 

166 return self._create_timeout_result(hook, start_time) 

167 

168 except Exception as e: 

169 return self._create_error_result(hook, start_time, e) 

170 

171 def _run_hook_subprocess( 

172 self, hook: HookDefinition 

173 ) -> subprocess.CompletedProcess[str]: 

174 """Run hook subprocess with comprehensive security validation.""" 

175 # Get sanitized environment 

176 clean_env = self._get_clean_environment() 

177 

178 # Use secure subprocess execution 

179 try: 

180 return execute_secure_subprocess( 

181 command=hook.get_command(), 

182 cwd=self.pkg_path, 

183 env=clean_env, 

184 timeout=hook.timeout, 

185 capture_output=True, 

186 text=True, 

187 check=False, # Don't raise on non-zero exit codes 

188 ) 

189 except Exception as e: 

190 # Log security issues but convert to subprocess-compatible result 

191 security_logger = get_security_logger() 

192 security_logger.log_subprocess_failure( 

193 command=hook.get_command(), 

194 exit_code=-1, 

195 error_output=str(e), 

196 ) 

197 

198 # Create a compatible result object for hook processing 

199 class FailedProcessResult: 

200 def __init__(self, command: list[str], error: str): 

201 self.args = command 

202 self.returncode = -1 

203 self.stdout = "" 

204 self.stderr = f"Security validation failed: {error}" 

205 

206 return FailedProcessResult(hook.get_command(), str(e)) 

207 

208 def _display_hook_output_if_needed( 

209 self, result: subprocess.CompletedProcess[str] 

210 ) -> None: 

211 if result.returncode == 0 or not self.verbose: 

212 return 

213 

214 if result.stdout: 

215 self.console.print(result.stdout) 

216 if result.stderr: 

217 self.console.print(result.stderr) 

218 

219 def _create_hook_result_from_process( 

220 self, 

221 hook: HookDefinition, 

222 result: subprocess.CompletedProcess[str], 

223 duration: float, 

224 ) -> HookResult: 

225 status = "passed" if result.returncode == 0 else "failed" 

226 issues_found = self._extract_issues_from_process_output(result) 

227 

228 return HookResult( 

229 id=hook.name, 

230 name=hook.name, 

231 status=status, 

232 duration=duration, 

233 files_processed=0, 

234 issues_found=issues_found, 

235 stage=hook.stage.value, 

236 ) 

237 

238 def _extract_issues_from_process_output( 

239 self, result: subprocess.CompletedProcess[str] 

240 ) -> list[str]: 

241 if result.returncode == 0: 

242 return [] 

243 

244 error_output = (result.stdout + result.stderr).strip() 

245 if error_output: 

246 return [line.strip() for line in error_output.split("\n") if line.strip()] 

247 

248 return [f"Hook failed with code {result.returncode}"] 

249 

250 def _create_timeout_result( 

251 self, hook: HookDefinition, start_time: float 

252 ) -> HookResult: 

253 duration = time.time() - start_time 

254 return HookResult( 

255 id=hook.name, 

256 name=hook.name, 

257 status="timeout", 

258 duration=duration, 

259 issues_found=[f"Hook timed out after {duration: .1f}s"], 

260 stage=hook.stage.value, 

261 ) 

262 

263 def _create_error_result( 

264 self, hook: HookDefinition, start_time: float, error: Exception 

265 ) -> HookResult: 

266 duration = time.time() - start_time 

267 return HookResult( 

268 id=hook.name, 

269 name=hook.name, 

270 status="error", 

271 duration=duration, 

272 issues_found=[str(error)], 

273 stage=hook.stage.value, 

274 ) 

275 

276 def _parse_hook_output( 

277 self, 

278 result: subprocess.CompletedProcess[str], 

279 ) -> dict[str, t.Any]: 

280 output = result.stdout + result.stderr 

281 return { 

282 "hook_id": None, 

283 "exit_code": result.returncode, 

284 "files_processed": 0, 

285 "issues": [], 

286 "raw_output": output, 

287 } 

288 

289 def _display_hook_result(self, result: HookResult) -> None: 

290 status_icon = "✅" if result.status == "passed" else "❌" 

291 

292 max_width = 70 

293 

294 if len(result.name) > max_width: 

295 line = result.name[: max_width - 3] + "..." 

296 else: 

297 dots_needed = max_width - len(result.name) 

298 line = result.name + ("." * dots_needed) 

299 

300 self.console.print(f"{line} {status_icon}") 

301 

302 def _handle_retries( 

303 self, 

304 strategy: HookStrategy, 

305 results: list[HookResult], 

306 ) -> list[HookResult]: 

307 if strategy.retry_policy == RetryPolicy.FORMATTING_ONLY: 

308 return self._retry_formatting_hooks(strategy, results) 

309 if strategy.retry_policy == RetryPolicy.ALL_HOOKS: 

310 return self._retry_all_hooks(strategy, results) 

311 return results 

312 

313 def _retry_formatting_hooks( 

314 self, 

315 strategy: HookStrategy, 

316 results: list[HookResult], 

317 ) -> list[HookResult]: 

318 formatting_hooks_failed: set[str] = set() 

319 

320 for i, result in enumerate(results): 

321 hook = strategy.hooks[i] 

322 if hook.is_formatting and result.status == "failed": 

323 formatting_hooks_failed.add(hook.name) 

324 

325 if not formatting_hooks_failed: 

326 return results 

327 

328 updated_results: list[HookResult] = [] 

329 for i, hook in enumerate(strategy.hooks): 

330 prev_result = results[i] 

331 new_result = self.execute_single_hook(hook) 

332 

333 new_result.duration += prev_result.duration 

334 updated_results.append(new_result) 

335 self._display_hook_result(new_result) 

336 

337 return updated_results 

338 

339 def _retry_all_hooks( 

340 self, 

341 strategy: HookStrategy, 

342 results: list[HookResult], 

343 ) -> list[HookResult]: 

344 failed_hooks = [i for i, r in enumerate(results) if r.status == "failed"] 

345 

346 if not failed_hooks: 

347 return results 

348 

349 updated_results: list[HookResult] = results.copy() 

350 for i in failed_hooks: 

351 hook = strategy.hooks[i] 

352 prev_result = results[i] 

353 new_result = self.execute_single_hook(hook) 

354 

355 new_result.duration += prev_result.duration 

356 updated_results[i] = new_result 

357 self._display_hook_result(new_result) 

358 

359 return updated_results 

360 

361 def _get_clean_environment(self) -> dict[str, str]: 

362 """ 

363 Get a sanitized environment for hook execution. 

364 

365 This method now delegates to the secure subprocess utilities 

366 for comprehensive environment sanitization with security logging. 

367 """ 

368 # Create base environment with essential variables 

369 clean_env = { 

370 "HOME": os.environ.get("HOME", ""), 

371 "USER": os.environ.get("USER", ""), 

372 "SHELL": os.environ.get("SHELL", "/bin/bash"), 

373 "LANG": os.environ.get("LANG", "en_US.UTF-8"), 

374 "LC_ALL": os.environ.get("LC_ALL", ""), 

375 "TERM": os.environ.get("TERM", "xterm-256color"), 

376 } 

377 

378 # Handle PATH sanitization with venv filtering 

379 system_path = os.environ.get("PATH", "") 

380 if system_path: 

381 venv_bin = str(Path(self.pkg_path) / ".venv" / "bin") 

382 path_parts = [p for p in system_path.split(":") if p != venv_bin] 

383 clean_env["PATH"] = ":".join(path_parts) 

384 

385 # Define Python-specific variables to exclude 

386 python_vars_to_exclude = { 

387 "VIRTUAL_ENV", 

388 "PYTHONPATH", 

389 "PYTHON_PATH", 

390 "PIP_CONFIG_FILE", 

391 "PYTHONHOME", 

392 "CONDA_DEFAULT_ENV", 

393 "PIPENV_ACTIVE", 

394 "POETRY_ACTIVE", 

395 } 

396 

397 # Add other safe environment variables 

398 security_logger = get_security_logger() 

399 original_count = len(os.environ) 

400 filtered_count = 0 

401 

402 for key, value in os.environ.items(): 

403 if key not in python_vars_to_exclude and key not in clean_env: 

404 # Additional security filtering 

405 if not key.startswith( 

406 ("PYTHON", "PIP_", "CONDA_", "VIRTUAL_", "__PYVENV") 

407 ): 

408 # Check for dangerous environment variables 

409 if key not in {"LD_PRELOAD", "DYLD_INSERT_LIBRARIES", "IFS", "PS4"}: 

410 clean_env[key] = value 

411 else: 

412 filtered_count += 1 

413 security_logger.log_environment_variable_filtered( 

414 variable_name=key, 

415 reason="dangerous environment variable", 

416 value_preview=str(value)[:50] if value else None, 

417 ) 

418 else: 

419 filtered_count += 1 

420 

421 # Log environment sanitization if significant filtering occurred 

422 if filtered_count > 5: # Only log if substantial filtering 

423 security_logger.log_subprocess_environment_sanitized( 

424 original_count=original_count, 

425 sanitized_count=len(clean_env), 

426 filtered_vars=[], # Don't expose all filtered vars for performance 

427 ) 

428 

429 return clean_env 

430 

431 def _print_summary( 

432 self, 

433 strategy: HookStrategy, 

434 results: list[HookResult], 

435 success: bool, 

436 ) -> None: 

437 if success: 

438 self.console.print( 

439 f"[green]✅[/ green] {strategy.name.title()} hooks passed: {len(results)} / {len(results)}", 

440 ) 

441 else: 

442 failed_count = sum(1 for r in results if r.status == "failed") 

443 error_count = sum(1 for r in results if r.status in ("timeout", "error")) 

444 self.console.print( 

445 f"[red]❌[/ red] {strategy.name.title()} hooks failed: {failed_count} failed, {error_count} errors", 

446 )