Coverage for /Users/les/Projects/crackerjack/crackerjack/executors/individual_hook_executor.py: 0%
276 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 asyncio
2import re
3import subprocess
4import time
5import typing as t
6from dataclasses import dataclass
7from pathlib import Path
9from rich.console import Console
11from crackerjack.config.hooks import HookDefinition, HookStrategy
12from crackerjack.models.task import HookResult
15@dataclass
16class HookProgress:
17 hook_name: str
18 status: str
19 start_time: float
20 end_time: float | None = None
21 duration: float | None = None
22 errors_found: int = 0
23 warnings_found: int = 0
24 files_processed: int = 0
25 lines_processed: int = 0
26 output_lines: list[str] | None = None
27 error_details: list[dict[str, t.Any]] | None = None
29 def __post_init__(self) -> None:
30 if self.output_lines is None:
31 self.output_lines = []
32 if self.error_details is None:
33 self.error_details = []
34 if self.end_time and self.start_time:
35 self.duration = self.end_time - self.start_time
37 def to_dict(self) -> dict[str, t.Any]:
38 return {
39 "hook_name": self.hook_name,
40 "status": self.status,
41 "start_time": self.start_time,
42 "end_time": self.end_time,
43 "duration": self.duration,
44 "errors_found": self.errors_found,
45 "warnings_found": self.warnings_found,
46 "files_processed": self.files_processed,
47 "lines_processed": self.lines_processed,
48 "output_lines": self.output_lines[-10:] if self.output_lines else [],
49 "error_details": self.error_details,
50 }
53@dataclass
54class IndividualExecutionResult:
55 strategy_name: str
56 hook_results: list[HookResult]
57 hook_progress: list[HookProgress]
58 total_duration: float
59 success: bool
60 execution_order: list[str]
62 @property
63 def failed_hooks(self) -> list[str]:
64 return [p.hook_name for p in self.hook_progress if p.status == "failed"]
66 @property
67 def total_errors(self) -> int:
68 return sum(p.errors_found for p in self.hook_progress)
70 @property
71 def total_warnings(self) -> int:
72 return sum(p.warnings_found for p in self.hook_progress)
75class HookOutputParser:
76 HOOK_PATTERNS: dict[str, dict[str, re.Pattern[str]]] = {
77 "ruff-check": {
78 "error": re.compile(r"^(.+?): (\d +): (\d +): ([A-Z]\d +) (.+)$"),
79 "summary": re.compile(r"Found (\d +) error"),
80 },
81 "pyright": {
82 "error": re.compile(r"^(.+?): (\d +): (\d +)-error: (.+)$"),
83 "warning": re.compile(r"^(.+?): (\d +): (\d +)-warning: (.+)$"),
84 "summary": re.compile(r"(\d +) error[s]?, (\d +) warning[s]?"),
85 },
86 "bandit": {
87 "issue": re.compile(r" > > Issue: \[([A-Z]\d +): \w +\] (.+)"),
88 "location": re.compile(r" Location: (.+?): (\d +): (\d +)"),
89 "confidence": re.compile(r" Confidence: (\w +)"),
90 "severity": re.compile(r" Severity: (\w +)"),
91 },
92 "mypy": {
93 "error": re.compile(r"^(.+?): (\d +): error: (.+)$"),
94 "note": re.compile(r"^(.+?): (\d +): note: (.+)$"),
95 },
96 "vulture": {
97 "unused": re.compile(r"^(.+?): (\d +): unused (.+) '(.+)'"),
98 },
99 "complexipy": {
100 "complex": re.compile(
101 r"^(.+?): (\d +): (\d +)-(.+) is too complex \((\d +)\)",
102 ),
103 },
104 }
106 def parse_hook_output(
107 self,
108 hook_name: str,
109 output_lines: list[str],
110 ) -> dict[str, t.Any]:
111 if hook_name not in self.HOOK_PATTERNS:
112 return self._parse_generic_output(output_lines)
114 result: dict[str, t.Any] = {
115 "errors": [],
116 "warnings": [],
117 "files_processed": set(),
118 }
119 patterns = self.HOOK_PATTERNS[hook_name]
121 parser_map = {
122 "ruff-check": self._parse_ruff_check,
123 "pyright": self._parse_pyright,
124 "bandit": self._parse_bandit,
125 "vulture": self._parse_vulture,
126 "complexipy": self._parse_complexipy,
127 }
129 parser_map.get(hook_name, self._parse_default_hook)(
130 output_lines, patterns, result
131 )
133 result["files_processed"] = list(result["files_processed"])
134 return result
136 def _parse_ruff_check(
137 self,
138 output_lines: list[str],
139 patterns: dict[str, re.Pattern[str]],
140 result: dict[str, t.Any],
141 ) -> None:
142 for line in output_lines:
143 line = line.strip()
144 if not line:
145 continue
146 if match := patterns["error"].match(line):
147 file_path, line_num, col_num, code, message = match.groups()
148 result["files_processed"].add(file_path)
149 result["errors"].append(
150 {
151 "file": file_path,
152 "line": int(line_num),
153 "column": int(col_num),
154 "code": code,
155 "message": message,
156 "type": "error",
157 },
158 )
160 def _parse_pyright(
161 self,
162 output_lines: list[str],
163 patterns: dict[str, re.Pattern[str]],
164 result: dict[str, t.Any],
165 ) -> None:
166 for line in output_lines:
167 line = line.strip()
168 if not line:
169 continue
170 if match := patterns["error"].match(line):
171 file_path, line_num, col_num, message = match.groups()
172 result["files_processed"].add(file_path)
173 result["errors"].append(
174 {
175 "file": file_path,
176 "line": int(line_num),
177 "column": int(col_num),
178 "message": message,
179 "type": "error",
180 },
181 )
182 elif match := patterns["warning"].match(line):
183 file_path, line_num, col_num, message = match.groups()
184 result["files_processed"].add(file_path)
185 result["warnings"].append(
186 {
187 "file": file_path,
188 "line": int(line_num),
189 "column": int(col_num),
190 "message": message,
191 "type": "warning",
192 },
193 )
195 def _parse_bandit(
196 self,
197 output_lines: list[str],
198 patterns: dict[str, re.Pattern[str]],
199 result: dict[str, t.Any],
200 ) -> None:
201 for line in output_lines:
202 line = line.strip()
203 if not line:
204 continue
205 if match := patterns["issue"].match(line):
206 code, message = match.groups()
207 result["errors"].append(
208 {"code": code, "message": message, "type": "security"},
209 )
211 def _parse_vulture(
212 self,
213 output_lines: list[str],
214 patterns: dict[str, re.Pattern[str]],
215 result: dict[str, t.Any],
216 ) -> None:
217 for line in output_lines:
218 line = line.strip()
219 if not line:
220 continue
221 if match := patterns["unused"].match(line):
222 file_path, line_num, item_type, item_name = match.groups()
223 result["files_processed"].add(file_path)
224 result["warnings"].append(
225 {
226 "file": file_path,
227 "line": int(line_num),
228 "message": f"unused {item_type} '{item_name}'",
229 "type": "unused_code",
230 },
231 )
233 def _parse_complexipy(
234 self,
235 output_lines: list[str],
236 patterns: dict[str, re.Pattern[str]],
237 result: dict[str, t.Any],
238 ) -> None:
239 for line in output_lines:
240 line = line.strip()
241 if not line:
242 continue
243 if match := patterns["complex"].match(line):
244 file_path, line_num, col_num, function_name, complexity = match.groups()
245 result["files_processed"].add(file_path)
246 result["errors"].append(
247 {
248 "file": file_path,
249 "line": int(line_num),
250 "column": int(col_num),
251 "message": f"{function_name} is too complex ({complexity})",
252 "type": "complexity",
253 },
254 )
256 def _parse_default_hook(
257 self,
258 output_lines: list[str],
259 patterns: dict[str, re.Pattern[str]],
260 result: dict[str, t.Any],
261 ) -> None:
262 for line in output_lines:
263 line = line.strip()
264 if not line:
265 continue
267 if "error" in line.lower() or "fail" in line.lower():
268 result["errors"].append(
269 {
270 "message": line,
271 "type": "generic_error",
272 },
273 )
274 elif "warning" in line.lower():
275 result["warnings"].append(
276 {
277 "message": line,
278 "type": "generic_warning",
279 },
280 )
282 def _parse_generic_output(self, output_lines: list[str]) -> dict[str, t.Any]:
283 errors: list[dict[str, str]] = []
284 warnings: list[dict[str, str]] = []
286 error_keywords = ["error", "failed", "violation", "issue"]
287 warning_keywords = ["warning", "caution", "note"]
289 for line in output_lines:
290 line_lower = line.lower()
291 if any(keyword in line_lower for keyword in error_keywords):
292 errors.append({"message": line.strip(), "type": "generic_error"})
293 elif any(keyword in line_lower for keyword in warning_keywords):
294 warnings.append({"message": line.strip(), "type": "generic_warning"})
296 return {
297 "errors": errors,
298 "warnings": warnings,
299 "files_processed": 0,
300 "total_lines": len(output_lines),
301 }
304class IndividualHookExecutor:
305 def __init__(self, console: Console, pkg_path: Path) -> None:
306 self.console = console
307 self.pkg_path = pkg_path
308 self.parser = HookOutputParser()
309 self.progress_callback: t.Callable[[HookProgress], None] | None = None
310 self.suppress_realtime_output = False
311 self.progress_callback_interval = 1
313 def set_progress_callback(self, callback: t.Callable[[HookProgress], None]) -> None:
314 self.progress_callback = callback
316 def set_mcp_mode(self, enable: bool = True) -> None:
317 self.suppress_realtime_output = enable
318 if enable:
319 self.progress_callback_interval = 10
321 async def execute_strategy_individual(
322 self,
323 strategy: HookStrategy,
324 ) -> IndividualExecutionResult:
325 start_time = time.time()
326 self._print_strategy_header(strategy)
328 execution_state = self._initialize_execution_state()
330 for hook in strategy.hooks:
331 await self._execute_single_hook_in_strategy(hook, execution_state)
333 return self._finalize_execution_result(strategy, execution_state, start_time)
335 def _initialize_execution_state(self) -> dict[str, t.Any]:
336 return {"hook_results": [], "hook_progress": [], "execution_order": []}
338 async def _execute_single_hook_in_strategy(
339 self,
340 hook: HookDefinition,
341 execution_state: dict[str, t.Any],
342 ) -> None:
343 execution_state["execution_order"].append(hook.name)
345 progress = HookProgress(
346 hook_name=hook.name,
347 status="pending",
348 start_time=time.time(),
349 )
350 execution_state["hook_progress"].append(progress)
352 result = await self._execute_individual_hook(hook, progress)
353 execution_state["hook_results"].append(result)
355 self._update_hook_progress_status(progress, result)
357 def _update_hook_progress_status(
358 self,
359 progress: HookProgress,
360 result: HookResult,
361 ) -> None:
362 progress.status = "completed" if result.status == "passed" else "failed"
363 progress.end_time = time.time()
364 progress.duration = progress.end_time - progress.start_time
366 if self.progress_callback:
367 self.progress_callback(progress)
369 def _finalize_execution_result(
370 self,
371 strategy: HookStrategy,
372 execution_state: dict[str, t.Any],
373 start_time: float,
374 ) -> IndividualExecutionResult:
375 total_duration = time.time() - start_time
376 success = all(r.status == "passed" for r in execution_state["hook_results"])
378 self._print_individual_summary(
379 strategy,
380 execution_state["hook_results"],
381 execution_state["hook_progress"],
382 )
384 return IndividualExecutionResult(
385 strategy_name=f"{strategy.name}_individual",
386 hook_results=execution_state["hook_results"],
387 hook_progress=execution_state["hook_progress"],
388 total_duration=total_duration,
389 success=success,
390 execution_order=execution_state["execution_order"],
391 )
393 async def _execute_individual_hook(
394 self,
395 hook: HookDefinition,
396 progress: HookProgress,
397 ) -> HookResult:
398 progress.status = "running"
399 if self.progress_callback:
400 self.progress_callback(progress)
402 self.console.print(f"\n[bold cyan]🔍 Running {hook.name}[/ bold cyan]")
404 cmd = hook.get_command()
406 try:
407 result = await self._run_command_with_streaming(cmd, hook.timeout, progress)
409 parsed_output = self.parser.parse_hook_output(
410 hook.name,
411 progress.output_lines or [],
412 )
413 progress.errors_found = len(parsed_output["errors"])
414 progress.warnings_found = len(parsed_output["warnings"])
415 progress.files_processed = parsed_output["files_processed"]
416 progress.lines_processed = parsed_output["total_lines"]
417 progress.error_details = parsed_output["errors"] + parsed_output["warnings"]
419 hook_result = HookResult(
420 id=hook.name,
421 name=hook.name,
422 status="passed" if result.returncode == 0 else "failed",
423 duration=progress.duration or 0,
424 )
426 self._print_hook_summary(hook.name, hook_result, progress)
428 return hook_result
430 except TimeoutError:
431 progress.status = "failed"
432 error_msg = f"Hook {hook.name} timed out after {hook.timeout}s"
433 self.console.print(f"[red]⏰ {error_msg}[/ red]")
435 return HookResult(
436 id=hook.name,
437 name=hook.name,
438 status="failed",
439 duration=hook.timeout,
440 )
442 async def _run_command_with_streaming(
443 self,
444 cmd: list[str],
445 timeout: int,
446 progress: HookProgress,
447 ) -> subprocess.CompletedProcess[str]:
448 process = await self._create_subprocess(cmd)
450 stdout_lines: list[str] = []
451 stderr_lines: list[str] = []
453 tasks = self._create_stream_reader_tasks(
454 process,
455 stdout_lines,
456 stderr_lines,
457 progress,
458 )
460 try:
461 await self._wait_for_process_completion(process, tasks, timeout)
462 except TimeoutError:
463 self._handle_process_timeout(process, tasks)
464 raise
466 return self._create_completed_process(cmd, process, stdout_lines, stderr_lines)
468 async def _create_subprocess(self, cmd: list[str]) -> asyncio.subprocess.Process:
469 return await asyncio.create_subprocess_exec(
470 *cmd,
471 cwd=self.pkg_path,
472 stdout=asyncio.subprocess.PIPE,
473 stderr=asyncio.subprocess.PIPE,
474 )
476 def _create_stream_reader_tasks(
477 self,
478 process: asyncio.subprocess.Process,
479 stdout_lines: list[str],
480 stderr_lines: list[str],
481 progress: HookProgress,
482 ) -> list[asyncio.Task[None]]:
483 return [
484 asyncio.create_task(
485 self._read_stream(process.stdout, stdout_lines, progress),
486 ),
487 asyncio.create_task(
488 self._read_stream(process.stderr, stderr_lines, progress),
489 ),
490 ]
492 async def _read_stream(
493 self,
494 stream: asyncio.StreamReader | None,
495 output_list: list[str],
496 progress: HookProgress,
497 ) -> None:
498 if not stream:
499 return
501 line_count = 0
502 while True:
503 try:
504 line = await stream.readline()
505 if not line:
506 break
508 line_str = self._process_stream_line(line)
509 self._update_progress_with_line(
510 line_str,
511 output_list,
512 progress,
513 line_count,
514 )
515 line_count += 1
517 except Exception:
518 break
520 def _process_stream_line(self, line: bytes | str) -> str:
521 return (line.decode() if isinstance(line, bytes) else line).rstrip()
523 def _update_progress_with_line(
524 self,
525 line_str: str,
526 output_list: list[str],
527 progress: HookProgress,
528 line_count: int,
529 ) -> None:
530 output_list.append(line_str)
531 progress.output_lines = progress.output_lines or []
532 progress.output_lines.append(line_str)
534 self._maybe_print_line(line_str)
535 self._maybe_callback_progress(progress, line_count)
537 def _maybe_print_line(self, line_str: str) -> None:
538 if not self.suppress_realtime_output and line_str.strip():
539 self.console.print(f"[dim] {line_str}[/ dim]")
541 def _maybe_callback_progress(self, progress: HookProgress, line_count: int) -> None:
542 if self.progress_callback and (
543 line_count % self.progress_callback_interval == 0
544 ):
545 self.progress_callback(progress)
547 async def _wait_for_process_completion(
548 self,
549 process: asyncio.subprocess.Process,
550 tasks: list[asyncio.Task[None]],
551 timeout: int,
552 ) -> None:
553 await asyncio.wait_for(process.wait(), timeout=timeout)
554 await asyncio.gather(*tasks, return_exceptions=True)
556 def _handle_process_timeout(
557 self,
558 process: asyncio.subprocess.Process,
559 tasks: list[asyncio.Task[None]],
560 ) -> None:
561 process.kill()
562 for task in tasks:
563 task.cancel()
565 def _create_completed_process(
566 self,
567 cmd: list[str],
568 process: asyncio.subprocess.Process,
569 stdout_lines: list[str],
570 stderr_lines: list[str],
571 ) -> subprocess.CompletedProcess[str]:
572 return subprocess.CompletedProcess(
573 args=cmd,
574 returncode=process.returncode or 0,
575 stdout="\n".join(stdout_lines),
576 stderr="\n".join(stderr_lines),
577 )
579 def _print_strategy_header(self, strategy: HookStrategy) -> None:
580 self.console.print("\n" + "=" * 80)
581 self.console.print(
582 f"[bold bright_cyan]🔍 INDIVIDUAL HOOK EXECUTION[/ bold bright_cyan] "
583 f"[bold bright_white]{strategy.name.upper()} HOOKS[/ bold bright_white]",
584 )
585 self.console.print(
586 f"[dim]Running {len(strategy.hooks)} hooks individually with real-time streaming[/ dim]",
587 )
588 self.console.print("=" * 80)
590 def _print_hook_summary(
591 self,
592 hook_name: str,
593 result: HookResult,
594 progress: HookProgress,
595 ) -> None:
596 status_icon = "✅" if result.status == "passed" else "❌"
597 duration_str = f"{progress.duration: .1f}s" if progress.duration else "0.0s"
599 summary_parts: list[str] = []
600 if progress.errors_found > 0:
601 summary_parts.append(f"{progress.errors_found} errors")
602 if progress.warnings_found > 0:
603 summary_parts.append(f"{progress.warnings_found} warnings")
604 if progress.files_processed > 0:
605 summary_parts.append(f"{progress.files_processed} files")
607 summary = ", ".join(summary_parts) if summary_parts else "clean"
609 self.console.print(
610 f"[bold]{status_icon} {hook_name}[/ bold] - {duration_str}-{summary}",
611 )
613 def _print_individual_summary(
614 self,
615 strategy: HookStrategy,
616 results: list[HookResult],
617 progress_list: list[HookProgress],
618 ) -> None:
619 passed = sum(1 for r in results if r.status == "passed")
620 failed = sum(1 for r in results if r.status == "failed")
621 total_errors = sum(p.errors_found for p in progress_list)
622 total_warnings = sum(p.warnings_found for p in progress_list)
623 total_duration = sum(p.duration or 0 for p in progress_list)
625 self.console.print("\n" + "-" * 80)
626 self.console.print(
627 f"[bold]📊 INDIVIDUAL EXECUTION SUMMARY[/ bold]-{strategy.name.upper()}",
628 )
629 self.console.print(f"✅ Passed: {passed} | ❌ Failed: {failed}")
630 if total_errors > 0:
631 self.console.print(f"🚨 Total Errors: {total_errors}")
632 if total_warnings > 0:
633 self.console.print(f"⚠️ Total Warnings: {total_warnings}")
634 self.console.print(f"⏱️ Total Duration: {total_duration: .1f}s")
636 if failed > 0:
637 self.console.print("\n[bold red]Failed Hooks: [/ bold red]")
638 for progress in progress_list:
639 if progress.status == "failed":
640 error_summary = (
641 f"{progress.errors_found} errors"
642 if progress.errors_found > 0
643 else "failed"
644 )
645 self.console.print(f" ❌ {progress.hook_name}-{error_summary}")
647 self.console.print("-" * 80)