Coverage for /Users/les/Projects/crackerjack/crackerjack/plugins/loader.py: 0%

178 statements  

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

1import importlib 

2import importlib.util 

3import json 

4import logging 

5import typing as t 

6from pathlib import Path 

7 

8from crackerjack.config.hooks import HookStage 

9 

10from .base import ( 

11 PluginBase, 

12 PluginMetadata, 

13 PluginRegistry, 

14 PluginType, 

15 get_plugin_registry, 

16) 

17from .hooks import CustomHookDefinition, CustomHookPlugin 

18 

19 

20class PluginLoadError(Exception): 

21 pass 

22 

23 

24class PluginLoader: 

25 def __init__(self, registry: PluginRegistry | None = None) -> None: 

26 self.registry = registry or get_plugin_registry() 

27 self.logger = logging.getLogger("crackerjack.plugin_loader") 

28 

29 def load_plugin_from_file(self, plugin_file: Path) -> PluginBase: 

30 if not plugin_file.exists(): 

31 msg = f"Plugin file not found: {plugin_file}" 

32 raise PluginLoadError(msg) 

33 

34 if plugin_file.suffix != ".py": 

35 msg = f"Plugin file must be .py: {plugin_file}" 

36 raise PluginLoadError(msg) 

37 

38 spec = importlib.util.spec_from_file_location(plugin_file.stem, plugin_file) 

39 if not spec or not spec.loader: 

40 msg = f"Could not create module spec for: {plugin_file}" 

41 raise PluginLoadError(msg) 

42 

43 module = importlib.util.module_from_spec(spec) 

44 

45 try: 

46 spec.loader.exec_module(module) 

47 except Exception as e: 

48 msg = f"Failed to execute plugin module {plugin_file}: {e}" 

49 raise PluginLoadError(msg) 

50 

51 plugin = self._extract_plugin_from_module(module, plugin_file) 

52 

53 if not isinstance(plugin, PluginBase): 

54 msg = f"Plugin {plugin_file} does not provide a PluginBase instance" 

55 raise PluginLoadError( 

56 msg, 

57 ) 

58 

59 return plugin 

60 

61 def load_plugin_from_config(self, config_file: Path) -> PluginBase: 

62 if not config_file.exists(): 

63 msg = f"Plugin config file not found: {config_file}" 

64 raise PluginLoadError(msg) 

65 

66 try: 

67 if config_file.suffix == ".json": 

68 with config_file.open() as f: 

69 config = json.load(f) 

70 elif config_file.suffix in (".yaml", ".yml"): 

71 import yaml 

72 

73 with config_file.open() as f: 

74 config = yaml.safe_load(f) 

75 else: 

76 msg = f"Unsupported config format: {config_file.suffix}" 

77 raise PluginLoadError( 

78 msg, 

79 ) 

80 except Exception as e: 

81 msg = f"Failed to parse config file {config_file}: {e}" 

82 raise PluginLoadError(msg) 

83 

84 return self._create_plugin_from_config(config, config_file) 

85 

86 def _extract_plugin_from_module( 

87 self, 

88 module: t.Any, 

89 plugin_file: Path, 

90 ) -> PluginBase: 

91 plugin = self._try_standard_entry_points(module) 

92 if plugin: 

93 return plugin 

94 

95 plugin = self._try_plugin_subclasses(module, plugin_file) 

96 if plugin: 

97 return plugin 

98 

99 msg = f"No valid plugin found in {plugin_file}" 

100 raise PluginLoadError(msg) 

101 

102 def _try_standard_entry_points(self, module: t.Any) -> PluginBase | None: 

103 entry_points = [ 

104 "plugin", 

105 "create_plugin", 

106 "PLUGIN", 

107 ] 

108 

109 for entry_point in entry_points: 

110 plugin = self._try_single_entry_point(module, entry_point) 

111 if plugin: 

112 return plugin 

113 

114 return None 

115 

116 def _try_single_entry_point( 

117 self, 

118 module: t.Any, 

119 entry_point: str, 

120 ) -> PluginBase | None: 

121 if not hasattr(module, entry_point): 

122 return None 

123 

124 obj = getattr(module, entry_point) 

125 

126 if isinstance(obj, PluginBase): 

127 return obj 

128 if callable(obj): 

129 return self._try_factory_function(obj, entry_point) 

130 

131 return None 

132 

133 def _try_factory_function( 

134 self, 

135 factory: t.Callable, 

136 name: str, 

137 ) -> PluginBase | None: 

138 try: 

139 result = factory() 

140 if isinstance(result, PluginBase): 

141 return result 

142 except Exception as e: 

143 self.logger.warning(f"Plugin factory {name} failed: {e}") 

144 return None 

145 

146 def _try_plugin_subclasses( 

147 self, 

148 module: t.Any, 

149 plugin_file: Path, 

150 ) -> PluginBase | None: 

151 for name, obj in vars(module).items(): 

152 if self._is_valid_plugin_class(obj): 

153 plugin = self._try_instantiate_plugin_class(obj, name, plugin_file) 

154 if plugin: 

155 return plugin 

156 return None 

157 

158 def _is_valid_plugin_class(self, obj: t.Any) -> bool: 

159 return ( 

160 isinstance(obj, type) 

161 and issubclass(obj, PluginBase) 

162 and obj is not PluginBase 

163 ) 

164 

165 def _try_instantiate_plugin_class( 

166 self, 

167 plugin_class: type[PluginBase], 

168 name: str, 

169 plugin_file: Path, 

170 ) -> PluginBase | None: 

171 try: 

172 metadata = PluginMetadata( 

173 name=plugin_file.stem, 

174 version="1.0.0", 

175 plugin_type=PluginType.HOOK, 

176 description="Custom plugin", 

177 ) 

178 return plugin_class(metadata) 

179 except Exception as e: 

180 self.logger.warning(f"Failed to instantiate plugin class {name}: {e}") 

181 return None 

182 

183 def _create_plugin_from_config( 

184 self, 

185 config: dict[str, t.Any], 

186 config_file: Path, 

187 ) -> PluginBase: 

188 metadata = PluginMetadata( 

189 name=config.get("name", config_file.stem), 

190 version=config.get("version", "1.0.0"), 

191 plugin_type=PluginType(config.get("type", "hook")), 

192 description=config.get("description", "Custom plugin"), 

193 author=config.get("author", ""), 

194 license=config.get("license", ""), 

195 dependencies=config.get("dependencies", []), 

196 ) 

197 

198 if metadata.plugin_type == PluginType.HOOK: 

199 return self._create_hook_plugin_from_config(metadata, config) 

200 msg = f"Unsupported plugin type: {metadata.plugin_type}" 

201 raise PluginLoadError(msg) 

202 

203 def _create_hook_plugin_from_config( 

204 self, 

205 metadata: PluginMetadata, 

206 config: dict[str, t.Any], 

207 ) -> CustomHookPlugin: 

208 hooks_config = config.get("hooks", []) 

209 hook_definitions = [] 

210 

211 for hook_config in hooks_config: 

212 hook_def = CustomHookDefinition( 

213 name=hook_config["name"], 

214 description=hook_config.get("description", ""), 

215 command=hook_config.get("command", []), 

216 file_patterns=hook_config.get("file_patterns", []), 

217 timeout=hook_config.get("timeout", 60), 

218 stage=HookStage(hook_config.get("stage", "comprehensive")), 

219 requires_files=hook_config.get("requires_files", True), 

220 parallel_safe=hook_config.get("parallel_safe", True), 

221 ) 

222 hook_definitions.append(hook_def) 

223 

224 return CustomHookPlugin(metadata, hook_definitions) 

225 

226 def load_and_register(self, plugin_source: Path) -> bool: 

227 try: 

228 if plugin_source.suffix == ".py": 

229 plugin = self.load_plugin_from_file(plugin_source) 

230 elif plugin_source.suffix in (".json", ".yaml", ".yml"): 

231 plugin = self.load_plugin_from_config(plugin_source) 

232 else: 

233 self.logger.error(f"Unsupported plugin file type: {plugin_source}") 

234 return False 

235 

236 success = self.registry.register(plugin) 

237 if success: 

238 self.logger.info(f"Successfully loaded plugin: {plugin.name}") 

239 else: 

240 self.logger.warning(f"Plugin already registered: {plugin.name}") 

241 

242 return success 

243 

244 except PluginLoadError as e: 

245 self.logger.exception(f"Failed to load plugin from {plugin_source}: {e}") 

246 return False 

247 except Exception as e: 

248 self.logger.exception( 

249 f"Unexpected error loading plugin {plugin_source}: {e}" 

250 ) 

251 return False 

252 

253 

254class PluginDiscovery: 

255 def __init__(self, loader: PluginLoader | None = None) -> None: 

256 self.loader = loader or PluginLoader() 

257 self.logger = logging.getLogger("crackerjack.plugin_discovery") 

258 

259 def discover_in_directory( 

260 self, 

261 directory: Path, 

262 recursive: bool = False, 

263 ) -> list[Path]: 

264 if not directory.exists() or not directory.is_dir(): 

265 return [] 

266 

267 plugin_files = [] 

268 

269 patterns = ["*.py", "*.json", "*.yaml", "*.yml"] 

270 

271 for pattern in patterns: 

272 if recursive: 

273 plugin_files.extend(directory.rglob(pattern)) 

274 else: 

275 plugin_files.extend(directory.glob(pattern)) 

276 

277 return [f for f in plugin_files if self._looks_like_plugin_file(f)] 

278 

279 def discover_in_project(self, project_path: Path) -> list[Path]: 

280 plugin_files = [] 

281 

282 plugin_dirs = [ 

283 project_path / "plugins", 

284 project_path / ".cache" / "crackerjack" / "plugins", 

285 project_path / "tools" / "crackerjack", 

286 ] 

287 

288 for plugin_dir in plugin_dirs: 

289 if plugin_dir.exists(): 

290 plugin_files.extend( 

291 self.discover_in_directory(plugin_dir, recursive=True), 

292 ) 

293 

294 return plugin_files 

295 

296 def load_discovered_plugins(self, plugin_files: list[Path]) -> dict[str, bool]: 

297 results = {} 

298 

299 for plugin_file in plugin_files: 

300 self.logger.info(f"Loading plugin: {plugin_file}") 

301 success = self.loader.load_and_register(plugin_file) 

302 results[str(plugin_file)] = success 

303 

304 return results 

305 

306 def auto_discover_and_load(self, project_path: Path) -> dict[str, bool]: 

307 plugin_files = self.discover_in_project(project_path) 

308 

309 if plugin_files: 

310 self.logger.info(f"Found {len(plugin_files)} potential plugin files") 

311 return self.load_discovered_plugins(plugin_files) 

312 self.logger.info("No plugin files found") 

313 return {} 

314 

315 def _looks_like_plugin_file(self, file_path: Path) -> bool: 

316 name_lower = file_path.name.lower() 

317 

318 if name_lower.startswith(("test_", "__", ".")): 

319 return False 

320 

321 if name_lower in ("__init__.py", "setup.py", "conftest.py"): 

322 return False 

323 

324 plugin_indicators = [ 

325 "plugin", 

326 "hook", 

327 "extension", 

328 "addon", 

329 "crackerjack", 

330 "check", 

331 "lint", 

332 "format", 

333 ] 

334 

335 return any(indicator in name_lower for indicator in plugin_indicators)