Coverage for /Users/les/Projects/crackerjack/crackerjack/plugins/hooks.py: 0%
125 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 abc
2import subprocess
3from dataclasses import dataclass, field
4from pathlib import Path
6from rich.console import Console
8from crackerjack.config.hooks import HookDefinition, HookStage
9from crackerjack.models.protocols import OptionsProtocol
10from crackerjack.models.task import HookResult
12from .base import PluginBase, PluginMetadata, PluginType
15@dataclass
16class CustomHookDefinition:
17 name: str
18 description: str
19 command: list[str] | None = None
20 file_patterns: list[str] = field(default_factory=list)
21 timeout: int = 60
22 stage: HookStage = HookStage.COMPREHENSIVE
23 requires_files: bool = True
24 parallel_safe: bool = True
26 def to_hook_definition(self) -> HookDefinition:
27 cmd = self.command or []
28 return HookDefinition(
29 name=self.name,
30 command=cmd,
31 timeout=self.timeout,
32 stage=self.stage,
33 manual_stage=self.stage == HookStage.COMPREHENSIVE,
34 )
37class HookPluginBase(PluginBase, abc.ABC):
38 def __init__(self, metadata: PluginMetadata) -> None:
39 super().__init__(metadata)
40 assert metadata.plugin_type == PluginType.HOOK
41 self.console: Console | None = None
42 self.pkg_path: Path | None = None
44 def initialize(self, console: Console, pkg_path: Path) -> None:
45 self.console = console
46 self.pkg_path = pkg_path
48 @abc.abstractmethod
49 def get_hook_definitions(self) -> list[CustomHookDefinition]:
50 pass
52 @abc.abstractmethod
53 def execute_hook(
54 self,
55 hook_name: str,
56 files: list[Path],
57 options: OptionsProtocol,
58 ) -> HookResult:
59 pass
61 def should_run_hook(self, hook_name: str, files: list[Path]) -> bool:
62 hook_def = self._get_hook_definition(hook_name)
63 if not hook_def or not hook_def.requires_files:
64 return True
66 if not hook_def.file_patterns:
67 return bool(files)
69 for file_path in files:
70 for pattern in hook_def.file_patterns:
71 if file_path.match(pattern):
72 return True
74 return False
76 def _get_hook_definition(self, hook_name: str) -> CustomHookDefinition | None:
77 for hook_def in self.get_hook_definitions():
78 if hook_def.name == hook_name:
79 return hook_def
80 return None
83class CustomHookPlugin(HookPluginBase):
84 def __init__(
85 self,
86 metadata: PluginMetadata,
87 hook_definitions: list[CustomHookDefinition],
88 ) -> None:
89 super().__init__(metadata)
90 self._hook_definitions = hook_definitions
92 def get_hook_definitions(self) -> list[CustomHookDefinition]:
93 return self._hook_definitions.copy()
95 def execute_hook(
96 self,
97 hook_name: str,
98 files: list[Path],
99 options: OptionsProtocol,
100 ) -> HookResult:
101 hook_def = self._get_hook_definition(hook_name)
102 if not hook_def:
103 return HookResult(
104 id=hook_name,
105 name=hook_name,
106 status="error",
107 duration=0.0,
108 issues_found=[f"Hook definition not found: {hook_name}"],
109 )
111 if not hook_def.command:
112 return HookResult(
113 id=hook_name,
114 name=hook_name,
115 status="error",
116 duration=0.0,
117 issues_found=[f"No command defined for hook: {hook_name}"],
118 )
120 return self._execute_command_hook(hook_def, files)
122 def _execute_command_hook(
123 self,
124 hook_def: CustomHookDefinition,
125 files: list[Path],
126 ) -> HookResult:
127 import time
129 start_time = time.time()
131 try:
132 cmd = hook_def.command.copy()
133 if hook_def.requires_files and files:
134 cmd.extend(str(f) for f in files)
136 result = subprocess.run(
137 cmd,
138 check=False,
139 cwd=self.pkg_path,
140 capture_output=True,
141 text=True,
142 timeout=hook_def.timeout,
143 )
145 duration = time.time() - start_time
146 status = "passed" if result.returncode == 0 else "failed"
148 issues = [result.stderr] if result.returncode != 0 and result.stderr else []
149 return HookResult(
150 id=hook_def.name,
151 name=hook_def.name,
152 status=status,
153 duration=duration,
154 issues_found=issues,
155 )
157 except subprocess.TimeoutExpired:
158 return HookResult(
159 id=hook_def.name,
160 name=hook_def.name,
161 status="timeout",
162 duration=time.time() - start_time,
163 issues_found=[f"Hook timed out after {hook_def.timeout}s"],
164 )
165 except Exception as e:
166 return HookResult(
167 id=hook_def.name,
168 name=hook_def.name,
169 status="error",
170 duration=time.time() - start_time,
171 issues_found=[f"Execution error: {e}"],
172 )
174 def activate(self) -> bool:
175 return True
177 def deactivate(self) -> bool:
178 return True
181class HookPluginRegistry:
182 def __init__(self) -> None:
183 self._hook_plugins: dict[str, HookPluginBase] = {}
185 def register_hook_plugin(self, plugin: HookPluginBase) -> bool:
186 if plugin.name in self._hook_plugins:
187 return False
189 self._hook_plugins[plugin.name] = plugin
190 return True
192 def unregister_hook_plugin(self, plugin_name: str) -> bool:
193 return self._hook_plugins.pop(plugin_name, None) is not None
195 def get_all_custom_hooks(self) -> dict[str, CustomHookDefinition]:
196 hooks = {}
198 for plugin in self._hook_plugins.values():
199 if not plugin.enabled:
200 continue
202 for hook_def in plugin.get_hook_definitions():
203 if hook_def.name not in hooks:
204 hooks[hook_def.name] = hook_def
206 return hooks
208 def execute_custom_hook(
209 self,
210 hook_name: str,
211 files: list[Path],
212 options: OptionsProtocol,
213 ) -> HookResult | None:
214 for plugin in self._hook_plugins.values():
215 if not plugin.enabled:
216 continue
218 hook_defs = plugin.get_hook_definitions()
219 if any(h.name == hook_name for h in hook_defs):
220 return plugin.execute_hook(hook_name, files, options)
222 return None
224 def get_hooks_for_files(self, files: list[Path]) -> list[str]:
225 applicable_hooks = []
227 for plugin in self._hook_plugins.values():
228 if not plugin.enabled:
229 continue
231 for hook_def in plugin.get_hook_definitions():
232 if plugin.should_run_hook(hook_def.name, files):
233 applicable_hooks.append(hook_def.name)
235 return applicable_hooks
237 def initialize_all_plugins(self, console: Console, pkg_path: Path) -> None:
238 for plugin in self._hook_plugins.values():
239 plugin.initialize(console, pkg_path)
242_hook_registry = HookPluginRegistry()
245def get_hook_plugin_registry() -> HookPluginRegistry:
246 return _hook_registry