Coverage for /Users/les/Projects/crackerjack/crackerjack/interactive.py: 0%
321 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 time
2import typing as t
3from dataclasses import dataclass
4from enum import Enum, auto
5from functools import partial
6from typing import Protocol
8from rich.console import Console
9from rich.panel import Panel
10from rich.prompt import Confirm
11from rich.table import Table
12from rich.text import Text
13from rich.tree import Tree
15from .errors import CrackerjackError, ErrorCode
18class TaskStatus(Enum):
19 PENDING = auto()
20 RUNNING = auto()
21 SUCCESS = auto()
22 FAILED = auto()
23 SKIPPED = auto()
26@dataclass
27class WorkflowOptions:
28 clean: bool = False
29 test: bool = False
30 publish: str | None = None
31 bump: str | None = None
32 commit: bool = False
33 create_pr: bool = False
34 interactive: bool = True
35 dry_run: bool = False
37 @classmethod
38 def from_args(cls, args: t.Any) -> "WorkflowOptions":
39 return cls(
40 clean=getattr(args, "clean", False),
41 test=getattr(args, "test", False),
42 publish=getattr(args, "publish", None),
43 bump=getattr(args, "bump", None),
44 commit=getattr(args, "commit", False),
45 create_pr=getattr(args, "create_pr", False),
46 interactive=getattr(args, "interactive", True),
47 dry_run=getattr(args, "dry_run", False),
48 )
51class TaskExecutor(Protocol):
52 def __call__(self) -> bool: ...
55@dataclass
56class TaskDefinition:
57 id: str
58 name: str
59 description: str
60 dependencies: list[str]
61 optional: bool = False
62 estimated_duration: float = 0.0
64 def __post_init__(self) -> None:
65 if not self.dependencies:
66 self.dependencies = []
69class Task:
70 def __init__(
71 self,
72 definition: TaskDefinition,
73 executor: TaskExecutor | None = None,
74 workflow_tasks: dict[str, "Task"] | None = None,
75 ) -> None:
76 self.definition = definition
77 self.executor = executor
78 self.status = TaskStatus.PENDING
79 self.start_time: float | None = None
80 self.end_time: float | None = None
81 self.error: CrackerjackError | None = None
82 self._workflow_tasks = workflow_tasks
83 import logging
85 self.logger = logging.getLogger(f"crackerjack.task.{definition.id}")
87 @property
88 def name(self) -> str:
89 return self.definition.name
91 @property
92 def description(self) -> str:
93 return self.definition.description
95 @property
96 def dependencies(self) -> list["Task"] | list[str]:
97 if self._workflow_tasks:
98 return [
99 self._workflow_tasks[dep_name]
100 for dep_name in self.definition.dependencies
101 if dep_name in self._workflow_tasks
102 ]
103 return self.definition.dependencies
105 def get_resolved_dependencies(
106 self,
107 workflow_tasks: dict[str, "Task"],
108 ) -> list["Task"]:
109 return [
110 workflow_tasks[dep_name]
111 for dep_name in self.definition.dependencies
112 if dep_name in workflow_tasks
113 ]
115 @property
116 def duration(self) -> float | None:
117 if self.start_time is None:
118 return None
119 end = self.end_time or time.time()
120 return end - self.start_time
122 def start(self) -> None:
123 self.status = TaskStatus.RUNNING
124 self.start_time = time.time()
125 self.logger.info("Task started", extra={"task_id": self.definition.id})
127 def complete(self, success: bool = True) -> None:
128 self.end_time = time.time()
129 self.status = TaskStatus.SUCCESS if success else TaskStatus.FAILED
131 self.logger.info(
132 "Task completed",
133 extra={
134 "task_id": self.definition.id,
135 "success": success,
136 "duration": self.duration,
137 },
138 )
140 def skip(self) -> None:
141 self.status = TaskStatus.SKIPPED
142 self.end_time = time.time()
143 self.logger.info("Task skipped", extra={"task_id": self.definition.id})
145 def fail(self, error: CrackerjackError) -> None:
146 self.status = TaskStatus.FAILED
147 self.end_time = time.time()
148 self.error = error
150 self.logger.error(
151 "Task failed",
152 extra={
153 "task_id": self.definition.id,
154 "error": str(error),
155 "duration": self.duration,
156 },
157 )
159 def can_run(self, completed_tasks: set[str]) -> bool:
160 if self._workflow_tasks:
161 resolved_deps = self.get_resolved_dependencies(self._workflow_tasks)
162 return all(
163 dep.status in (TaskStatus.SUCCESS, TaskStatus.SKIPPED)
164 for dep in resolved_deps
165 )
167 return all(dep in completed_tasks for dep in self.definition.dependencies)
170class WorkflowBuilder:
171 def __init__(self, console: Console) -> None:
172 self.console = console
173 self.tasks: dict[str, TaskDefinition] = {}
174 import logging
176 self.logger = logging.getLogger("crackerjack.workflow.builder")
178 def add_task(
179 self,
180 task_id: str,
181 name: str,
182 description: str,
183 dependencies: list[str] | None = None,
184 optional: bool = False,
185 estimated_duration: float = 0.0,
186 ) -> "WorkflowBuilder":
187 task_def = TaskDefinition(
188 id=task_id,
189 name=name,
190 description=description,
191 dependencies=dependencies or [],
192 optional=optional,
193 estimated_duration=estimated_duration,
194 )
196 self.tasks[task_id] = task_def
197 self.logger.debug("Task added to workflow", extra={"task_id": task_id})
198 return self
200 def add_conditional_task(
201 self,
202 condition: bool,
203 task_id: str,
204 name: str,
205 description: str,
206 dependencies: list[str] | None = None,
207 estimated_duration: float = 0.0,
208 ) -> str:
209 if condition:
210 self.add_task(
211 task_id=task_id,
212 name=name,
213 description=description,
214 dependencies=dependencies,
215 estimated_duration=estimated_duration,
216 )
217 return task_id
219 return dependencies[-1] if dependencies else ""
221 def build(self) -> dict[str, TaskDefinition]:
222 self._validate_workflow()
223 return self.tasks.copy()
225 def _validate_workflow(self) -> None:
226 self._validate_dependencies()
227 self._check_circular_dependencies()
229 def _validate_dependencies(self) -> None:
230 for task_id, task_def in self.tasks.items():
231 for dep in task_def.dependencies:
232 if dep not in self.tasks:
233 msg = f"Task {task_id} depends on unknown task {dep}"
234 raise ValueError(msg)
236 def _check_circular_dependencies(self) -> None:
237 visited: set[str] = set()
238 rec_stack: set[str] = set()
240 def has_cycle(task_id: str) -> bool:
241 visited.add(task_id)
242 rec_stack.add(task_id)
244 for dep in self.tasks[task_id].dependencies:
245 if dep not in visited:
246 if has_cycle(dep):
247 return True
248 elif dep in rec_stack:
249 return True
251 rec_stack.remove(task_id)
252 return False
254 for task_id in self.tasks:
255 if task_id not in visited and has_cycle(task_id):
256 msg = f"Circular dependency detected involving task {task_id}"
257 raise ValueError(
258 msg,
259 )
262class WorkflowManager:
263 def __init__(self, console: Console) -> None:
264 self.console = console
265 self.tasks: dict[str, Task] = {}
266 self.task_definitions: dict[str, TaskDefinition] = {}
267 import logging
269 self.logger = logging.getLogger("crackerjack.workflow.manager")
271 def load_workflow(self, task_definitions: dict[str, TaskDefinition]) -> None:
272 self.task_definitions = task_definitions
273 self.tasks = {
274 task_id: Task(definition)
275 for task_id, definition in task_definitions.items()
276 }
278 for task in self.tasks.values():
279 task._workflow_tasks = self.tasks
281 self.logger.info("Workflow loaded", extra={"task_count": len(self.tasks)})
283 def set_task_executor(self, task_id: str, executor: TaskExecutor) -> None:
284 if task_id in self.tasks:
285 self.tasks[task_id].executor = executor
287 def get_next_task(self) -> Task | None:
288 completed_tasks = {
289 task_id
290 for task_id, task in self.tasks.items()
291 if task.status == TaskStatus.SUCCESS
292 }
294 for task in self.tasks.values():
295 if task.status == TaskStatus.PENDING and task.can_run(completed_tasks):
296 return task
298 return None
300 def all_tasks_completed(self) -> bool:
301 return all(
302 task.status in (TaskStatus.SUCCESS, TaskStatus.FAILED, TaskStatus.SKIPPED)
303 for task in self.tasks.values()
304 )
306 def run_task(self, task: Task) -> bool:
307 if not task.executor:
308 return self._handle_task_without_executor(task)
310 return self._execute_task_with_executor(task)
312 def _handle_task_without_executor(self, task: Task) -> bool:
313 task.skip()
314 self.console.print(f"[yellow]⏭️ Skipped {task.name} (no executor)[/ yellow]")
315 return True
317 def _execute_task_with_executor(self, task: Task) -> bool:
318 task.start()
319 self.console.print(f"[blue]🔄 Running {task.name}...[/ blue]")
321 try:
322 return self._try_execute_task(task)
323 except Exception as e:
324 return self._handle_task_exception(task, e)
326 def _try_execute_task(self, task: Task) -> bool:
327 self.logger.info(f"Executing task: {task.definition.id}")
328 success = task.executor() if task.executor else False
329 task.complete(success)
331 self._display_task_result(task, success)
332 return success
334 def _display_task_result(self, task: Task, success: bool) -> None:
335 if success:
336 duration_str = f" ({task.duration: .1f}s)" if task.duration else ""
337 self.console.print(f"[green]✅ {task.name}{duration_str}[/ green]")
338 else:
339 self.console.print(f"[red]❌ {task.name} failed[/ red]")
341 def _handle_task_exception(self, task: Task, e: Exception) -> bool:
342 error = CrackerjackError(
343 message=f"Task {task.name} failed: {e}",
344 error_code=ErrorCode.COMMAND_EXECUTION_ERROR,
345 )
346 task.fail(error)
347 self.console.print(f"[red]💥 {task.name} crashed: {e}[/ red]")
348 return False
350 def display_task_tree(self) -> None:
351 tree = Tree("🚀 Workflow Tasks")
352 status_groups = self._get_status_groups()
354 for status, (label, color) in status_groups.items():
355 self._add_status_branch(tree, status, label, color)
357 self.console.print(tree)
359 def _get_status_groups(self) -> dict[TaskStatus, tuple[str, str]]:
360 return {
361 TaskStatus.SUCCESS: ("✅ Completed", "green"),
362 TaskStatus.RUNNING: ("🔄 Running", "blue"),
363 TaskStatus.FAILED: ("❌ Failed", "red"),
364 TaskStatus.SKIPPED: ("⏭️ Skipped", "yellow"),
365 TaskStatus.PENDING: ("⏳ Pending", "white"),
366 }
368 def _add_status_branch(
369 self,
370 tree: Tree,
371 status: TaskStatus,
372 label: str,
373 color: str,
374 ) -> None:
375 status_tasks = [task for task in self.tasks.values() if task.status == status]
377 if not status_tasks:
378 return
380 status_branch = tree.add(f"[{color}]{label}[/{color}]")
381 for task in status_tasks:
382 duration_str = f" ({task.duration: .1f}s)" if task.duration else ""
383 status_branch.add(f"{task.name}{duration_str}")
385 def get_workflow_summary(self) -> dict[str, int]:
386 summary = {status.name.lower(): 0 for status in TaskStatus}
388 for task in self.tasks.values():
389 summary[task.status.name.lower()] += 1
391 return summary
394class InteractiveCLI:
395 def __init__(self, console: Console | None = None) -> None:
396 self.console = console or Console()
397 self.workflow = WorkflowManager(self.console)
398 import logging
400 self.logger = logging.getLogger("crackerjack.interactive.cli")
402 def create_dynamic_workflow(self, options: WorkflowOptions) -> None:
403 builder = WorkflowBuilder(self.console)
405 workflow_steps = [
406 self._add_setup_phase,
407 self._add_config_phase,
408 partial(self._add_cleaning_phase, enabled=options.clean),
409 self._add_fast_hooks_phase,
410 partial(self._add_testing_phase, enabled=options.test),
411 self._add_comprehensive_hooks_phase,
412 partial(
413 self._add_version_phase,
414 enabled=bool(options.publish or options.bump),
415 ),
416 partial(self._add_publish_phase, enabled=bool(options.publish)),
417 partial(self._add_commit_phase, enabled=options.commit),
418 partial(self._add_pr_phase, enabled=options.create_pr),
419 ]
421 last_task = ""
422 for step in workflow_steps:
423 last_task = step(builder, last_task)
425 workflow_def = builder.build()
426 self.workflow.load_workflow(workflow_def)
428 self.logger.info(
429 "Dynamic workflow created",
430 extra={"task_count": len(workflow_def)},
431 )
433 def _add_setup_phase(self, builder: WorkflowBuilder, last_task: str) -> str:
434 builder.add_task(
435 "setup",
436 "Initialize",
437 "Initialize project structure",
438 estimated_duration=2.0,
439 )
440 return "setup"
442 def _add_config_phase(self, builder: WorkflowBuilder, last_task: str) -> str:
443 builder.add_task(
444 "config",
445 "Configure",
446 "Update configuration files",
447 dependencies=[last_task],
448 estimated_duration=3.0,
449 )
450 return "config"
452 def _add_cleaning_phase(
453 self,
454 builder: WorkflowBuilder,
455 last_task: str,
456 enabled: bool,
457 ) -> str:
458 return (
459 builder.add_conditional_task(
460 condition=enabled,
461 task_id="clean",
462 name="Clean Code",
463 description="Clean code (remove docstrings, comments)",
464 dependencies=[last_task],
465 estimated_duration=10.0,
466 )
467 or last_task
468 )
470 def _add_fast_hooks_phase(self, builder: WorkflowBuilder, last_task: str) -> str:
471 builder.add_task(
472 "fast_hooks",
473 "Format",
474 "Run formatting hooks",
475 dependencies=[last_task],
476 estimated_duration=15.0,
477 )
478 return "fast_hooks"
480 def _add_testing_phase(
481 self,
482 builder: WorkflowBuilder,
483 last_task: str,
484 enabled: bool,
485 ) -> str:
486 return (
487 builder.add_conditional_task(
488 condition=enabled,
489 task_id="test",
490 name="Test",
491 description="Run tests with coverage",
492 dependencies=[last_task],
493 estimated_duration=30.0,
494 )
495 or last_task
496 )
498 def _add_comprehensive_hooks_phase(
499 self,
500 builder: WorkflowBuilder,
501 last_task: str,
502 ) -> str:
503 builder.add_task(
504 "comprehensive_hooks",
505 "Quality Check",
506 "Run comprehensive hooks",
507 dependencies=[last_task],
508 estimated_duration=45.0,
509 )
510 return "comprehensive_hooks"
512 def _add_version_phase(
513 self,
514 builder: WorkflowBuilder,
515 last_task: str,
516 enabled: bool,
517 ) -> str:
518 return (
519 builder.add_conditional_task(
520 condition=enabled,
521 task_id="version",
522 name="Version",
523 description="Bump version",
524 dependencies=[last_task],
525 estimated_duration=5.0,
526 )
527 or last_task
528 )
530 def _add_publish_phase(
531 self,
532 builder: WorkflowBuilder,
533 last_task: str,
534 enabled: bool,
535 ) -> str:
536 return (
537 builder.add_conditional_task(
538 condition=enabled,
539 task_id="publish",
540 name="Publish",
541 description="Publish package",
542 dependencies=[last_task],
543 estimated_duration=20.0,
544 )
545 or last_task
546 )
548 def _add_commit_phase(
549 self,
550 builder: WorkflowBuilder,
551 last_task: str,
552 enabled: bool,
553 ) -> str:
554 return (
555 builder.add_conditional_task(
556 condition=enabled,
557 task_id="commit",
558 name="Commit",
559 description="Commit changes",
560 dependencies=[last_task],
561 estimated_duration=3.0,
562 )
563 or last_task
564 )
566 def _add_pr_phase(
567 self,
568 builder: WorkflowBuilder,
569 last_task: str,
570 enabled: bool,
571 ) -> str:
572 return (
573 builder.add_conditional_task(
574 condition=enabled,
575 task_id="pr",
576 name="Pull Request",
577 description="Create pull request",
578 dependencies=[last_task],
579 estimated_duration=5.0,
580 )
581 or last_task
582 )
584 def run_interactive_workflow(self, options: WorkflowOptions) -> bool:
585 self.logger.info(
586 f"Starting interactive workflow with options: {options.__dict__}",
587 )
588 self.create_dynamic_workflow(options)
590 self.console.print("[bold blue]🚀 Starting Interactive Workflow[/ bold blue]")
591 self.workflow.display_task_tree()
593 if not Confirm.ask("Continue with workflow?"):
594 self.console.print("[yellow]Workflow cancelled by user[/ yellow]")
595 return False
597 return self._execute_workflow_loop()
599 def _execute_workflow_loop(self) -> bool:
600 overall_success = True
602 while not self.workflow.all_tasks_completed():
603 next_task = self.workflow.get_next_task()
605 if next_task is None:
606 overall_success = self._handle_stuck_workflow()
607 break
609 if not self._should_run_task(next_task):
610 continue
612 success = self._execute_single_task(next_task)
613 if not success:
614 overall_success = False
615 if not self._should_continue_after_failure():
616 break
618 self._display_workflow_summary()
619 return overall_success
621 def _handle_stuck_workflow(self) -> bool:
622 pending_tasks = [
623 task
624 for task in self.workflow.tasks.values()
625 if task.status == TaskStatus.PENDING
626 ]
628 if pending_tasks:
629 self.console.print("[red]❌ Workflow stuck-unresolved dependencies[/ red]")
630 return False
631 return True
633 def _should_run_task(self, task: Task) -> bool:
634 if not Confirm.ask(f"Run {task.name}?", default=True):
635 task.skip()
636 return False
637 return True
639 def _execute_single_task(self, task: Task) -> bool:
640 return self.workflow.run_task(task)
642 def _should_continue_after_failure(self) -> bool:
643 return Confirm.ask("Continue despite failure?", default=True)
645 def _display_workflow_summary(self) -> None:
646 summary = self.workflow.get_workflow_summary()
648 self.console.print("\n[bold]📊 Workflow Summary[/ bold]")
650 table = Table(show_header=True, header_style="bold magenta")
651 table.add_column("Status", style="cyan")
652 table.add_column("Count", justify="right")
654 status_styles = {
655 "success": "green",
656 "failed": "red",
657 "skipped": "yellow",
658 "pending": "white",
659 }
661 for status, count in summary.items():
662 if count > 0:
663 style = status_styles.get(status, "white")
664 table.add_row(f"[{style}]{status.title()}[/{style}]", str(count))
666 self.console.print(table)
669def launch_interactive_cli(version: str, options: t.Any = None) -> None:
670 console = Console()
671 cli = InteractiveCLI(console)
673 title = Text("Crackerjack", style="bold cyan")
674 version_text = Text(f"v{version}", style="dim cyan")
675 subtitle = Text("Your Python project management toolkit", style="italic")
676 panel = Panel(
677 f"{title} {version_text}\n{subtitle}",
678 border_style="cyan",
679 expand=False,
680 )
681 console.print(panel)
682 console.print()
684 workflow_options = (
685 WorkflowOptions.from_args(options) if options else WorkflowOptions()
686 )
687 cli.create_dynamic_workflow(workflow_options)
688 cli.run_interactive_workflow(workflow_options)
691if __name__ == "__main__":
692 launch_interactive_cli("0.19.8")