repl-toolkit 2.1.0__tar.gz → 2.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. {repl_toolkit-2.1.0/repl_toolkit.egg-info → repl_toolkit-2.3.0}/PKG-INFO +55 -4
  2. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/README.md +54 -3
  3. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/pyproject.toml +1 -1
  4. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/__init__.py +15 -11
  5. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/actions/registry.py +14 -30
  6. repl_toolkit-2.3.0/repl_toolkit/async_repl.py +450 -0
  7. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/headless_repl.py +2 -2
  8. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/images.py +47 -1
  9. repl_toolkit-2.3.0/repl_toolkit/ptypes.py +178 -0
  10. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_async_repl.py +6 -6
  11. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_cancellation.py +2 -2
  12. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0/repl_toolkit.egg-info}/PKG-INFO +55 -4
  13. repl_toolkit-2.1.0/repl_toolkit/async_repl.py +0 -536
  14. repl_toolkit-2.1.0/repl_toolkit/ptypes.py +0 -193
  15. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/LICENSE +0 -0
  16. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/actions/__init__.py +0 -0
  17. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/actions/action.py +0 -0
  18. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/completion/__init__.py +0 -0
  19. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/completion/prefix.py +0 -0
  20. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/completion/shell_expansion.py +0 -0
  21. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/formatting.py +0 -0
  22. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/__init__.py +0 -0
  23. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/conftest.py +0 -0
  24. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_actions.py +0 -0
  25. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_completion.py +0 -0
  26. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_ctrl_c_cancel.py +0 -0
  27. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_formatting.py +0 -0
  28. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_headless.py +0 -0
  29. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_image_utils.py +0 -0
  30. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_images.py +0 -0
  31. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_output_handling.py +0 -0
  32. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_types.py +0 -0
  33. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit.egg-info/SOURCES.txt +0 -0
  34. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit.egg-info/dependency_links.txt +0 -0
  35. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit.egg-info/requires.txt +0 -0
  36. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/repl_toolkit.egg-info/top_level.txt +0 -0
  37. {repl_toolkit-2.1.0 → repl_toolkit-2.3.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: repl-toolkit
3
- Version: 2.1.0
3
+ Version: 2.3.0
4
4
  Summary: A Python toolkit for building interactive REPL and headless interfaces with action support
5
5
  Author-email: REPL Toolkit Contributors <martin.j.bartlett@gmail.com>
6
6
  License: MIT
@@ -637,8 +637,15 @@ class CancellableBackend:
637
637
  def __init__(self):
638
638
  self._cancel_requested = False
639
639
 
640
- def cancel(self, message: Optional[str] = None) -> None:
641
- """Optional method to support cooperative cancellation."""
640
+ def cancel(self, message: Optional[str] = None) -> Optional[bool]:
641
+ """
642
+ Optional method to support cooperative cancellation.
643
+
644
+ Returns:
645
+ Optional[bool]:
646
+ - True or None (default): REPL force-cancels the asyncio task
647
+ - False: REPL lets handle_input() complete gracefully
648
+ """
642
649
  self._cancel_requested = True
643
650
  if message:
644
651
  print(f"Cancellation: {message}")
@@ -661,6 +668,49 @@ class CancellableBackend:
661
668
  return True
662
669
  ```
663
670
 
671
+ ### Cancellation Behavior Control (v2.3.0)
672
+
673
+ The `cancel()` method can return a boolean to control how the REPL handles cancellation:
674
+
675
+ ```python
676
+ class ForceCancel Backend:
677
+ """Traditional behavior - REPL cancels the asyncio task."""
678
+
679
+ def cancel(self, message: Optional[str] = None) -> bool:
680
+ self._cancelled = True
681
+ return True # or None - REPL force-cancels task
682
+ ```
683
+
684
+ ```python
685
+ class GracefulBackend:
686
+ """New behavior - let handle_input() complete gracefully."""
687
+
688
+ def cancel(self, message: Optional[str] = None) -> bool:
689
+ self._cancelled = True
690
+ return False # REPL waits for handle_input() to finish
691
+
692
+ async def handle_input(self, user_input: str, **kwargs) -> bool:
693
+ self._cancelled = False
694
+
695
+ # Your processing with checkpoints
696
+ for step in steps:
697
+ if self._cancelled:
698
+ await self.cleanup() # Cleanup hooks fire!
699
+ return False
700
+ await process(step)
701
+ return True
702
+ ```
703
+
704
+ **When to return False:**
705
+ - Backend uses cleanup hooks that need to fire
706
+ - Using agent frameworks with cleanup/finalization logic
707
+ - Need to save state or close connections gracefully
708
+
709
+ **When to return True/None:**
710
+ - Quick cancellation is preferred
711
+ - No cleanup needed
712
+ - Traditional async task cancellation is sufficient
713
+
664
714
  ### When cancel() is Called
665
715
 
666
716
  The REPL automatically calls `backend.cancel()` (if implemented) when:
@@ -682,11 +732,12 @@ class SubprocessBackend:
682
732
  self._cancel_requested = False
683
733
  self._current_process = None
684
734
 
685
- def cancel(self, message: Optional[str] = None) -> None:
735
+ def cancel(self, message: Optional[str] = None) -> bool:
686
736
  """Cancel current subprocess."""
687
737
  self._cancel_requested = True
688
738
  if self._current_process:
689
739
  self._current_process.terminate() # Stop the subprocess
740
+ return True # Force cancel the asyncio task
690
741
 
691
742
  async def handle_input(self, user_input: str, **kwargs) -> bool:
692
743
  """Run command with cancellation support."""
@@ -592,8 +592,15 @@ class CancellableBackend:
592
592
  def __init__(self):
593
593
  self._cancel_requested = False
594
594
 
595
- def cancel(self, message: Optional[str] = None) -> None:
596
- """Optional method to support cooperative cancellation."""
595
+ def cancel(self, message: Optional[str] = None) -> Optional[bool]:
596
+ """
597
+ Optional method to support cooperative cancellation.
598
+
599
+ Returns:
600
+ Optional[bool]:
601
+ - True or None (default): REPL force-cancels the asyncio task
602
+ - False: REPL lets handle_input() complete gracefully
603
+ """
597
604
  self._cancel_requested = True
598
605
  if message:
599
606
  print(f"Cancellation: {message}")
@@ -616,6 +623,49 @@ class CancellableBackend:
616
623
  return True
617
624
  ```
618
625
 
626
+ ### Cancellation Behavior Control (v2.3.0)
627
+
628
+ The `cancel()` method can return a boolean to control how the REPL handles cancellation:
629
+
630
+ ```python
631
+ class ForceCancel Backend:
632
+ """Traditional behavior - REPL cancels the asyncio task."""
633
+
634
+ def cancel(self, message: Optional[str] = None) -> bool:
635
+ self._cancelled = True
636
+ return True # or None - REPL force-cancels task
637
+ ```
638
+
639
+ ```python
640
+ class GracefulBackend:
641
+ """New behavior - let handle_input() complete gracefully."""
642
+
643
+ def cancel(self, message: Optional[str] = None) -> bool:
644
+ self._cancelled = True
645
+ return False # REPL waits for handle_input() to finish
646
+
647
+ async def handle_input(self, user_input: str, **kwargs) -> bool:
648
+ self._cancelled = False
649
+
650
+ # Your processing with checkpoints
651
+ for step in steps:
652
+ if self._cancelled:
653
+ await self.cleanup() # Cleanup hooks fire!
654
+ return False
655
+ await process(step)
656
+ return True
657
+ ```
658
+
659
+ **When to return False:**
660
+ - Backend uses cleanup hooks that need to fire
661
+ - Using agent frameworks with cleanup/finalization logic
662
+ - Need to save state or close connections gracefully
663
+
664
+ **When to return True/None:**
665
+ - Quick cancellation is preferred
666
+ - No cleanup needed
667
+ - Traditional async task cancellation is sufficient
668
+
619
669
  ### When cancel() is Called
620
670
 
621
671
  The REPL automatically calls `backend.cancel()` (if implemented) when:
@@ -637,11 +687,12 @@ class SubprocessBackend:
637
687
  self._cancel_requested = False
638
688
  self._current_process = None
639
689
 
640
- def cancel(self, message: Optional[str] = None) -> None:
690
+ def cancel(self, message: Optional[str] = None) -> bool:
641
691
  """Cancel current subprocess."""
642
692
  self._cancel_requested = True
643
693
  if self._current_process:
644
694
  self._current_process.terminate() # Stop the subprocess
695
+ return True # Force cancel the asyncio task
645
696
 
646
697
  async def handle_input(self, user_input: str, **kwargs) -> bool:
647
698
  """Run command with cancellation support."""
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "repl-toolkit"
7
- version = "2.1.0"
7
+ version = "2.3.0"
8
8
  description = "A Python toolkit for building interactive REPL and headless interfaces with action support"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.8"
@@ -16,25 +16,28 @@ Basic usage:
16
16
  >>> repl = AsyncREPL()
17
17
  >>> await repl.run(MyBackend())
18
18
 
19
- With image support:
20
- >>> class ImageBackend:
21
- ... async def handle_input(self, user_input: str, images=None) -> bool:
22
- ... from repl_toolkit import parse_image_references
19
+ With cancellation support:
20
+ >>> from repl_toolkit import CancellableBackend
21
+ >>>
22
+ >>> class MyCancellableBackend:
23
+ ... def __init__(self):
24
+ ... self._cancelled = False
23
25
  ...
24
- ... parsed = parse_image_references(user_input)
25
- ... for img_id in parsed.image_ids:
26
- ... img_data = images[img_id]
27
- ... # Process image: img_data.data, img_data.media_type
26
+ ... async def handle_input(self, user_input: str, **kwargs) -> bool:
27
+ ... self._cancelled = False
28
+ ... # ... processing with cancellation checkpoints ...
28
29
  ... return True
30
+ ...
31
+ ... def cancel(self, message: str = None) -> None:
32
+ ... self._cancelled = True
29
33
  """
30
34
 
31
35
  import logging
32
36
 
33
37
  # Add NullHandler to prevent "No handler found" warnings
34
- # Applications using this library should configure their own handlers
35
38
  logging.getLogger(__name__).addHandler(logging.NullHandler())
36
39
 
37
- __version__ = "2.1.0"
40
+ __version__ = "2.3.0"
38
41
 
39
42
  from .actions import Action, ActionContext, ActionRegistry
40
43
  from .async_repl import AsyncREPL, run_async_repl
@@ -55,7 +58,7 @@ from .images import (
55
58
  parse_image_references,
56
59
  reconstruct_message,
57
60
  )
58
- from .ptypes import ActionHandler, AsyncBackend, Completer
61
+ from .ptypes import ActionHandler, AsyncBackend, CancellableBackend, Completer
59
62
 
60
63
  __all__ = [
61
64
  # Core REPL
@@ -86,5 +89,6 @@ __all__ = [
86
89
  # Protocols
87
90
  "ActionHandler",
88
91
  "AsyncBackend",
92
+ "CancellableBackend",
89
93
  "Completer",
90
94
  ]
@@ -79,7 +79,6 @@ class ActionRegistry(ActionHandler):
79
79
  @property
80
80
  def backend(self):
81
81
  """The backend property getter."""
82
- logger.debug("ActionRegistry.backend getter")
83
82
  return self._backend
84
83
 
85
84
  @backend.setter
@@ -320,7 +319,7 @@ class ActionRegistry(ActionHandler):
320
319
  f"Failed to execute action '{action_name}': {e}", action_name
321
320
  ) # pragma: no cover
322
321
 
323
- def handle_command(self, command_string: str, **kwargs) -> None:
322
+ def handle_command(self, command_string: str, **kwargs: Any) -> None:
324
323
  """
325
324
  Handle a command string by mapping to appropriate action.
326
325
 
@@ -373,7 +372,7 @@ class ActionRegistry(ActionHandler):
373
372
  logger.exception(f"Unexpected error handling command '{command_string}'")
374
373
  logger.debug("ActionRegistry.handle_command() exit - unexpected error")
375
374
 
376
- def handle_shortcut(self, key_combo: str, event: Any, **kwargs) -> None:
375
+ def handle_shortcut(self, key_combo: str, event: Any, **kwargs: Any) -> None:
377
376
  """
378
377
  Handle a keyboard shortcut by mapping to appropriate action.
379
378
 
@@ -415,22 +414,18 @@ class ActionRegistry(ActionHandler):
415
414
  # ActionHandler protocol implementation
416
415
  def validate_action(self, action_name: str) -> bool:
417
416
  """Validate if an action is supported."""
418
- logger.debug("ActionRegistry.validate_action() entry/exit")
419
417
  return action_name in self.actions
420
418
 
421
419
  def list_actions(self) -> List[str]:
422
420
  """Return a list of all available action names."""
423
- logger.debug("ActionRegistry.list_actions() entry/exit")
424
421
  return list(self.actions.keys())
425
422
 
426
423
  def list_commands(self) -> List[str]:
427
424
  """Return a list of all available commands."""
428
- logger.debug("ActionRegistry.list_commands() entry/exit")
429
425
  return list(self.command_map.keys())
430
426
 
431
427
  def list_shortcuts(self) -> List[str]:
432
428
  """Return a list of all available keyboard shortcuts."""
433
- logger.debug("ActionRegistry.list_shortcuts() entry/exit")
434
429
  return list(self.key_map.keys())
435
430
 
436
431
  def is_registered_command(self, text: str) -> bool:
@@ -509,7 +504,7 @@ class ActionRegistry(ActionHandler):
509
504
 
510
505
  if action:
511
506
  self._show_action_help(action, context)
512
- else: # pragma: no cover
507
+ else:
513
508
  context.printer(f"No help available for: {context.args[0]}")
514
509
  else:
515
510
  # Show general help
@@ -520,22 +515,19 @@ class ActionRegistry(ActionHandler):
520
515
  def _show_action_help(self, action: Action, context: ActionContext) -> None:
521
516
  """Show detailed help for a specific action."""
522
517
  logger.debug("ActionRegistry._show_action_help() entry")
523
- # pragma: no cover
524
- context.printer(f"\n{action.description}") # pragma: no cover
518
+ context.printer(f"\n{action.description}")
525
519
  context.printer(f"Category: {action.category}")
526
520
 
527
- if action.command: # pragma: no cover
521
+ if action.command:
528
522
  context.printer(f"Command: {action.command_usage or action.command}")
529
523
 
530
524
  if action.keys:
531
525
  keys_str = ", ".join(action.get_keys_list())
532
- desc = (
533
- f" - {action.keys_description}" if action.keys_description else ""
534
- ) # pragma: no cover
526
+ desc = f" - {action.keys_description}" if action.keys_description else ""
535
527
  context.printer(f"Shortcut: {keys_str}{desc}")
536
528
 
537
- if not action.enabled: # pragma: no cover
538
- context.printer("Status: Disabled") # pragma: no cover
529
+ if not action.enabled:
530
+ context.printer("Status: Disabled")
539
531
  context.printer("")
540
532
 
541
533
  logger.debug("ActionRegistry._show_action_help() exit")
@@ -543,13 +535,12 @@ class ActionRegistry(ActionHandler):
543
535
  def _show_general_help(self, context: ActionContext) -> None:
544
536
  """Show general help with all actions organized by category."""
545
537
  logger.debug("ActionRegistry._show_general_help() entry")
546
- # pragma: no cover
547
- context.printer("\nAvailable Actions:") # pragma: no cover
538
+ context.printer("\nAvailable Actions:")
548
539
  context.printer("=" * 50)
549
540
 
550
541
  categories = self.get_actions_by_category()
551
542
 
552
- for category, actions in sorted(categories.items()): # pragma: no cover
543
+ for category, actions in sorted(categories.items()):
553
544
  context.printer(f"\n{category}:")
554
545
  for action in sorted(actions, key=lambda a: a.name):
555
546
  # Format display line
@@ -567,13 +558,9 @@ class ActionRegistry(ActionHandler):
567
558
  parts.append(" " * 15)
568
559
 
569
560
  parts.append(action.description)
570
- # pragma: no cover
571
561
  context.printer(" " + "".join(parts))
572
- # pragma: no cover
573
- context.printer(
574
- "\nUse '/help <command>' for detailed information about a specific action."
575
- ) # pragma: no cover
576
- context.printer("Use '/shortcuts' to see only keyboard shortcuts.") # pragma: no cover
562
+ context.printer("\nUse '/help <command>' for detailed information about a specific action.")
563
+ context.printer("Use '/shortcuts' to see only keyboard shortcuts.")
577
564
  context.printer("")
578
565
 
579
566
  logger.debug("ActionRegistry._show_general_help() exit")
@@ -581,8 +568,7 @@ class ActionRegistry(ActionHandler):
581
568
  def _list_shortcuts(self, context: ActionContext) -> None:
582
569
  """List all keyboard shortcuts."""
583
570
  logger.debug("ActionRegistry._list_shortcuts() entry")
584
- # pragma: no cover
585
- context.printer("\nKeyboard Shortcuts:") # pragma: no cover
571
+ context.printer("\nKeyboard Shortcuts:")
586
572
  context.printer("=" * 50)
587
573
 
588
574
  categories = self.get_actions_by_category()
@@ -591,13 +577,11 @@ class ActionRegistry(ActionHandler):
591
577
  shortcuts_in_category = [a for a in actions if a.keys]
592
578
  if not shortcuts_in_category:
593
579
  continue
594
- # pragma: no cover
595
580
  context.printer(f"\n{category}:")
596
581
  for action in sorted(shortcuts_in_category, key=lambda a: a.name):
597
582
  keys_str = ", ".join(action.get_keys_list())
598
- desc = action.keys_description or action.description # pragma: no cover
583
+ desc = action.keys_description or action.description
599
584
  context.printer(f" {keys_str:<15} {desc}")
600
- # pragma: no cover
601
585
  context.printer("")
602
586
 
603
587
  logger.debug("ActionRegistry._list_shortcuts() exit")