Coverage for /Users/les/Projects/crackerjack/crackerjack/core/phase_coordinator.py: 0%
325 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 logging
2import time
3import typing as t
4from pathlib import Path
6from rich.console import Console
8from crackerjack.code_cleaner import CodeCleaner, PackageCleaningResult
9from crackerjack.models.protocols import (
10 FileSystemInterface,
11 GitInterface,
12 HookManager,
13 OptionsProtocol,
14 PublishManager,
15 TestManagerProtocol,
16)
17from crackerjack.services.config import ConfigurationService
19from .session_coordinator import SessionCoordinator
22class PhaseCoordinator:
23 def __init__(
24 self,
25 console: Console,
26 pkg_path: Path,
27 session: SessionCoordinator,
28 filesystem: FileSystemInterface,
29 git_service: GitInterface,
30 hook_manager: HookManager,
31 test_manager: TestManagerProtocol,
32 publish_manager: PublishManager,
33 ) -> None:
34 self.console = console
35 self.pkg_path = pkg_path
36 self.session = session
38 self.filesystem = filesystem
39 self.git_service = git_service
40 self.hook_manager = hook_manager
41 self.test_manager = test_manager
42 self.publish_manager = publish_manager
44 self.code_cleaner = CodeCleaner(console=console, base_directory=pkg_path)
45 self.config_service = ConfigurationService(console=console, pkg_path=pkg_path)
47 self.logger = logging.getLogger("crackerjack.phases")
49 def run_cleaning_phase(self, options: OptionsProtocol) -> bool:
50 if not options.clean:
51 return True
53 self.session.track_task("cleaning", "Code cleaning")
54 try:
55 self._display_cleaning_header()
56 return self._execute_cleaning_process()
57 except Exception as e:
58 self.console.print(f"[red]❌[/ red] Cleaning failed: {e}")
59 self.session.fail_task("cleaning", str(e))
60 return False
62 def _display_cleaning_header(self) -> None:
63 self.console.print("\n" + "-" * 80)
64 self.console.print(
65 "[bold bright_magenta]🛠️ SETUP[/ bold bright_magenta] [bold bright_white]Initializing project structure[/ bold bright_white]",
66 )
67 self.console.print("-" * 80 + "\n")
68 self.console.print("[yellow]🧹[/ yellow] Starting code cleaning...")
70 def _execute_cleaning_process(self) -> bool:
71 # Use the comprehensive backup cleaning system for safety
72 cleaning_result = self.code_cleaner.clean_files(self.pkg_path, use_backup=True)
74 if isinstance(cleaning_result, list):
75 # Legacy mode (should not happen with use_backup=True, but handle gracefully)
76 cleaned_files = [str(r.file_path) for r in cleaning_result if r.success]
77 self._report_cleaning_results(cleaned_files)
78 return all(r.success for r in cleaning_result) if cleaning_result else True
79 else:
80 # PackageCleaningResult from backup mode
81 self._report_package_cleaning_results(cleaning_result)
82 return cleaning_result.overall_success
84 def _handle_no_files_to_clean(self) -> bool:
85 self.console.print("[yellow]⚠️[/ yellow] No Python files found to clean")
86 self.session.complete_task("cleaning", "No files to clean")
87 return True
89 def _report_cleaning_results(self, cleaned_files: list[str]) -> None:
90 if cleaned_files:
91 self.console.print(f"[green]✅[/ green] Cleaned {len(cleaned_files)} files")
92 self.session.complete_task(
93 "cleaning",
94 f"Cleaned {len(cleaned_files)} files",
95 )
96 else:
97 self.console.print("[green]✅[/ green] No cleaning needed")
98 self.session.complete_task("cleaning", "No cleaning needed")
100 def _report_package_cleaning_results(self, result: PackageCleaningResult) -> None:
101 """Report package cleaning results with backup information."""
102 if result.overall_success:
103 self.console.print(
104 f"[green]✅[/ green] Package cleaning completed successfully! "
105 f"({result.successful_files}/{result.total_files} files cleaned)"
106 )
107 self.session.complete_task(
108 "cleaning",
109 f"Cleaned {result.successful_files}/{result.total_files} files with backup protection",
110 )
111 else:
112 self.console.print(
113 f"[red]❌[/ red] Package cleaning failed! "
114 f"({result.failed_files}/{result.total_files} files failed)"
115 )
117 if result.backup_restored:
118 self.console.print(
119 "[yellow]⚠️[/ yellow] Files were automatically restored from backup"
120 )
121 self.session.complete_task(
122 "cleaning", "Failed with automatic backup restoration"
123 )
124 else:
125 self.session.fail_task(
126 "cleaning", f"Failed to clean {result.failed_files} files"
127 )
129 if result.backup_metadata:
130 self.console.print(
131 f"[blue]📦[/ blue] Backup available at: {result.backup_metadata.backup_directory}"
132 )
134 def run_configuration_phase(self, options: OptionsProtocol) -> bool:
135 if options.no_config_updates:
136 return True
137 self.session.track_task("configuration", "Configuration updates")
138 try:
139 success = True
141 if self._is_crackerjack_project():
142 if not self._copy_config_files_to_package():
143 success = False
145 if not self.config_service.update_precommit_config(options):
146 success = False
147 if not self.config_service.update_pyproject_config(options):
148 success = False
149 self.session.complete_task(
150 "configuration",
151 "Configuration updated successfully"
152 if success
153 else "Some configuration updates failed",
154 )
155 return success
156 except Exception as e:
157 self.session.fail_task("configuration", str(e))
158 return False
160 def _is_crackerjack_project(self) -> bool:
161 pyproject_path = self.pkg_path / "pyproject.toml"
162 if not pyproject_path.exists():
163 return False
165 try:
166 import tomllib
168 with pyproject_path.open("rb") as f:
169 data = tomllib.load(f)
171 project_name = data.get("project", {}).get("name", "")
172 return project_name == "crackerjack"
173 except Exception:
174 return False
176 def _copy_config_files_to_package(self) -> bool:
177 try:
178 files_to_copy = [
179 "pyproject.toml",
180 ".pre-commit-config.yaml",
181 "CLAUDE.md",
182 "RULES.md",
183 ".gitignore",
184 "example.mcp.json",
185 "uv.lock",
186 ]
188 package_dir = self.pkg_path / "crackerjack"
189 if not package_dir.exists():
190 self.console.print(
191 "[yellow]⚠️[/ yellow] Package directory not found: crackerjack /",
192 )
193 return False
195 copied_count = 0
196 for filename in files_to_copy:
197 src_path = self.pkg_path / filename
198 if src_path.exists():
199 dst_path = package_dir / filename
200 try:
201 import shutil
203 shutil.copy2(src_path, dst_path)
204 copied_count += 1
205 self.logger.debug(f"Copied {filename} to package directory")
206 except Exception as e:
207 self.console.print(
208 f"[yellow]⚠️[/ yellow] Failed to copy {filename}: {e}",
209 )
211 if copied_count > 0:
212 self.console.print(
213 f"[green]✅[/ green] Copied {copied_count} config files to package directory",
214 )
216 return True
217 except Exception as e:
218 self.console.print(
219 f"[red]❌[/ red] Failed to copy config files to package: {e}",
220 )
221 return False
223 def run_hooks_phase(self, options: OptionsProtocol) -> bool:
224 if options.skip_hooks:
225 return True
227 temp_config = self.config_service.get_temp_config_path()
228 if temp_config:
229 self.hook_manager.set_config_path(temp_config)
231 if not self.run_fast_hooks_only(options):
232 return False
234 return self.run_comprehensive_hooks_only(options)
236 def run_fast_hooks_only(self, options: OptionsProtocol) -> bool:
237 if options.skip_hooks:
238 return True
240 return self._execute_hooks_with_retry(
241 "fast",
242 self.hook_manager.run_fast_hooks,
243 options,
244 )
246 def run_comprehensive_hooks_only(self, options: OptionsProtocol) -> bool:
247 if options.skip_hooks:
248 return True
250 return self._execute_hooks_with_retry(
251 "comprehensive",
252 self.hook_manager.run_comprehensive_hooks,
253 options,
254 )
256 def run_testing_phase(self, options: OptionsProtocol) -> bool:
257 if not options.test:
258 return True
259 self.session.track_task("testing", "Test execution")
260 try:
261 self.console.print("\n" + "-" * 80)
262 self.console.print(
263 "[bold bright_blue]🧪 TESTS[/ bold bright_blue] [bold bright_white]Running test suite[/ bold bright_white]",
264 )
265 self.console.print("-" * 80 + "\n")
266 if not self.test_manager.validate_test_environment():
267 self.session.fail_task("testing", "Test environment validation failed")
268 return False
269 test_success = self.test_manager.run_tests(options)
270 if test_success:
271 coverage_info = self.test_manager.get_coverage()
272 self.session.complete_task(
273 "testing",
274 f"Tests passed, coverage: {coverage_info.get('total_coverage', 0): .1f}%",
275 )
276 else:
277 self.session.fail_task("testing", "Tests failed")
279 return test_success
280 except Exception as e:
281 self.console.print(f"Testing error: {e}")
282 self.session.fail_task("testing", str(e))
283 return False
285 def run_publishing_phase(self, options: OptionsProtocol) -> bool:
286 version_type = self._determine_version_type(options)
287 if not version_type:
288 return True
290 self.session.track_task("publishing", f"Publishing ({version_type})")
291 try:
292 return self._execute_publishing_workflow(options, version_type)
293 except Exception as e:
294 self.console.print(f"[red]❌[/ red] Publishing failed: {e}")
295 self.session.fail_task("publishing", str(e))
296 return False
298 def _determine_version_type(self, options: OptionsProtocol) -> str | None:
299 if options.publish:
300 return options.publish
301 if options.all:
302 return options.all
303 if options.bump:
304 self._handle_version_bump_only(options.bump)
305 return None
306 return None
308 def _execute_publishing_workflow(
309 self,
310 options: OptionsProtocol,
311 version_type: str,
312 ) -> bool:
313 new_version = self.publish_manager.bump_version(version_type)
315 if not options.no_git_tags:
316 self.publish_manager.create_git_tag(new_version)
318 if self.publish_manager.publish_package():
319 self._handle_successful_publish(options, new_version)
320 return True
321 self.session.fail_task("publishing", "Package publishing failed")
322 return False
324 def _handle_successful_publish(
325 self,
326 options: OptionsProtocol,
327 new_version: str,
328 ) -> None:
329 self.console.print(f"[green]🚀[/ green] Successfully published {new_version}!")
331 if options.cleanup_pypi:
332 self.publish_manager.cleanup_old_releases(options.keep_releases)
334 self.session.complete_task("publishing", f"Published {new_version}")
336 def run_commit_phase(self, options: OptionsProtocol) -> bool:
337 if not options.commit:
338 return True
339 self.session.track_task("commit", "Git commit and push")
340 try:
341 changed_files = self.git_service.get_changed_files()
342 if not changed_files:
343 return self._handle_no_changes_to_commit()
344 commit_message = self._get_commit_message(changed_files, options)
345 return self._execute_commit_and_push(changed_files, commit_message)
346 except Exception as e:
347 self.console.print(f"[red]❌[/ red] Commit failed: {e}")
348 self.session.fail_task("commit", str(e))
349 return False
351 def _handle_no_changes_to_commit(self) -> bool:
352 self.console.print("[yellow]ℹ️[/ yellow] No changes to commit")
353 self.session.complete_task("commit", "No changes to commit")
354 return True
356 def _execute_commit_and_push(
357 self,
358 changed_files: list[str],
359 commit_message: str,
360 ) -> bool:
361 if not self.git_service.add_files(changed_files):
362 self.session.fail_task("commit", "Failed to stage files")
363 return False
365 if not self.git_service.commit(commit_message):
366 self.session.fail_task("commit", "Commit failed")
367 return False
369 return self._handle_push_result(commit_message)
371 def _handle_push_result(self, commit_message: str) -> bool:
372 if self.git_service.push():
373 self.console.print(
374 f"[green]🎉[/ green] Committed and pushed: {commit_message}",
375 )
376 self.session.complete_task(
377 "commit",
378 f"Committed and pushed: {commit_message}",
379 )
380 else:
381 self.console.print(
382 f"[yellow]⚠️[/ yellow] Committed but push failed: {commit_message}",
383 )
384 self.session.complete_task(
385 "commit",
386 f"Committed (push failed): {commit_message}",
387 )
388 return True
390 def execute_hooks_with_retry(
391 self,
392 hook_type: str,
393 hook_runner: t.Callable[[], list[t.Any]],
394 options: OptionsProtocol,
395 ) -> bool:
396 return self._execute_hooks_with_retry(hook_type, hook_runner, options)
398 def _handle_version_bump_only(self, bump_type: str) -> bool:
399 self.session.track_task("version_bump", f"Version bump ({bump_type})")
400 try:
401 new_version = self.publish_manager.bump_version(bump_type)
402 self.console.print(f"[green]🎯[/ green] Version bumped to {new_version}")
403 self.session.complete_task("version_bump", f"Bumped to {new_version}")
404 return True
405 except Exception as e:
406 self.console.print(f"[red]❌[/ red] Version bump failed: {e}")
407 self.session.fail_task("version_bump", str(e))
408 return False
410 def _get_commit_message(
411 self,
412 changed_files: list[str],
413 options: OptionsProtocol,
414 ) -> str:
415 suggestions = self.git_service.get_commit_message_suggestions(changed_files)
417 if not suggestions:
418 return "Update project files"
420 if not options.interactive:
421 return suggestions[0]
423 return self._interactive_commit_message_selection(suggestions)
425 def _interactive_commit_message_selection(self, suggestions: list[str]) -> str:
426 self._display_commit_suggestions(suggestions)
428 try:
429 choice = self.console.input(
430 f"\nSelect message (1-{len(suggestions)}) or enter custom: ",
431 )
432 return self._process_commit_choice(choice, suggestions)
433 except (KeyboardInterrupt, EOFError):
434 return suggestions[0]
436 def _display_commit_suggestions(self, suggestions: list[str]) -> None:
437 self.console.print("[cyan]📝[/ cyan] Commit message suggestions: ")
438 for i, suggestion in enumerate(suggestions, 1):
439 self.console.print(f" {i}. {suggestion}")
441 def _process_commit_choice(self, choice: str, suggestions: list[str]) -> str:
442 if choice.isdigit() and 1 <= int(choice) <= len(suggestions):
443 return suggestions[int(choice) - 1]
444 return choice or suggestions[0]
446 def _execute_hooks_with_retry(
447 self,
448 hook_type: str,
449 hook_runner: t.Callable[[], list[t.Any]],
450 options: OptionsProtocol,
451 ) -> bool:
452 self._initialize_hook_execution(hook_type)
453 max_retries = self._get_max_retries(hook_type)
455 for attempt in range(max_retries):
456 try:
457 results = hook_runner()
458 summary = self.hook_manager.get_hook_summary(results)
460 if self._has_hook_failures(summary):
461 if self._should_retry_hooks(
462 hook_type,
463 attempt,
464 max_retries,
465 results,
466 ):
467 continue
469 return self._handle_hook_failures(
470 hook_type,
471 options,
472 summary,
473 results,
474 attempt,
475 max_retries,
476 )
477 return self._handle_hook_success(hook_type, summary)
479 except Exception as e:
480 return self._handle_hook_exception(hook_type, e)
482 return False
484 def _initialize_hook_execution(self, hook_type: str) -> None:
485 self.logger.info(f"Starting {hook_type} hooks execution")
486 self.session.track_task(
487 f"{hook_type}_hooks",
488 f"{hook_type.title()} hooks execution",
489 )
491 def _get_max_retries(self, hook_type: str) -> int:
492 return 2 if hook_type == "fast" else 1
494 def _has_hook_failures(self, summary: dict[str, t.Any]) -> bool:
495 return summary["failed"] > 0 or summary["errors"] > 0
497 def _should_retry_hooks(
498 self,
499 hook_type: str,
500 attempt: int,
501 max_retries: int,
502 results: list[t.Any],
503 ) -> bool:
504 if hook_type == "fast" and attempt < max_retries - 1:
505 if self._should_retry_fast_hooks(results):
506 self.console.print(
507 "[yellow]🔄[/ yellow] Fast hooks modified files, retrying all fast hooks...",
508 )
509 return True
510 return False
512 def _handle_hook_failures(
513 self,
514 hook_type: str,
515 options: OptionsProtocol,
516 summary: dict[str, t.Any],
517 results: list[t.Any],
518 attempt: int,
519 max_retries: int,
520 ) -> bool:
521 self.logger.warning(
522 f"{hook_type} hooks failed: {summary['failed']} failed, {summary['errors']} errors",
523 )
525 self.console.print(
526 f"[red]❌[/ red] {hook_type.title()} hooks failed: {summary['failed']} failed, {summary['errors']} errors",
527 )
529 detailed_error_msg = self._build_detailed_hook_error_message(results, summary)
531 self.session.fail_task(
532 f"{hook_type}_hooks",
533 detailed_error_msg,
534 )
535 return False
537 def _build_detailed_hook_error_message(
538 self, results: list[t.Any], summary: dict[str, t.Any]
539 ) -> str:
540 error_parts = [f"{summary['failed']} failed, {summary['errors']} errors"]
542 failed_hooks = []
543 for result in results:
544 if hasattr(result, "failed") and result.failed:
545 hook_name = getattr(result, "hook_id", "") or getattr(
546 result, "name", "unknown"
547 )
548 failed_hooks.append(hook_name.lower())
550 if failed_hooks:
551 error_parts.append(f"Failed hooks: {', '.join(failed_hooks)}")
553 return " | ".join(error_parts)
555 def _should_retry_fast_hooks(self, results: list[t.Any]) -> bool:
556 for result in results:
557 if hasattr(result, "failed") and result.failed:
558 return True
560 status = getattr(result, "status", "")
561 if status in ("failed", "error", "timeout"):
562 return True
563 return False
565 def _apply_retry_backoff(self, attempt: int) -> None:
566 if attempt > 0:
567 backoff_delay = 2 ** (attempt - 1)
568 self.logger.debug(f"Applying exponential backoff: {backoff_delay}s")
569 self.console.print(f"[dim]Waiting {backoff_delay}s before retry...[/ dim]")
570 time.sleep(backoff_delay)
572 def _handle_hook_success(self, hook_type: str, summary: dict[str, t.Any]) -> bool:
573 self.logger.info(
574 f"{hook_type} hooks passed: {summary['passed']} / {summary['total']}",
575 )
576 self.console.print(
577 f"[green]✅[/ green] {hook_type.title()} hooks passed: {summary['passed']} / {summary['total']}",
578 )
579 self.session.complete_task(
580 f"{hook_type}_hooks",
581 f"{summary['passed']} / {summary['total']} passed",
582 )
583 return True
585 def _handle_hook_exception(self, hook_type: str, e: Exception) -> bool:
586 self.console.print(f"[red]❌[/ red] {hook_type.title()} hooks error: {e}")
587 self.session.fail_task(f"{hook_type}_hooks", str(e))
588 return False