Skip to content

Commit

Permalink
Adds a base sigint_handler() method to the CommandSet.
Browse files Browse the repository at this point in the history
The sigint_handler() in Cmd will now delegate to the CommandSet.

Addresses #1197
  • Loading branch information
anselor committed Sep 25, 2023
1 parent 9886b82 commit 1e5ef48
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
17 changes: 15 additions & 2 deletions cmd2/cmd2.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,9 @@ def __init__(
self.suggest_similar_command = suggest_similar_command
self.default_suggestion_message = "Did you mean {}?"

# the current command being executed
self.current_command: Optional[Statement] = None

def find_commandsets(self, commandset_type: Type[CommandSet], *, subclass_match: bool = False) -> List[CommandSet]:
"""
Find all CommandSets that match the provided CommandSet type.
Expand Down Expand Up @@ -2363,7 +2366,13 @@ def sigint_handler(self, signum: int, _: FrameType) -> None:

# Check if we are allowed to re-raise the KeyboardInterrupt
if not self.sigint_protection:
self._raise_keyboard_interrupt()
raise_interrupt = True
if self.current_command is not None:
command_set = self.find_commandset_for_command(self.current_command.command)
if command_set is not None:
raise_interrupt = not command_set.sigint_handler()

Check warning on line 2373 in cmd2/cmd2.py

View check run for this annotation

Codecov / codecov/patch

cmd2/cmd2.py#L2371-L2373

Added lines #L2371 - L2373 were not covered by tests
if raise_interrupt:
self._raise_keyboard_interrupt()

def _raise_keyboard_interrupt(self) -> None:
"""Helper function to raise a KeyboardInterrupt"""
Expand Down Expand Up @@ -2953,7 +2962,11 @@ def onecmd(self, statement: Union[Statement, str], *, add_to_history: bool = Tru
):
self.history.append(statement)

stop = func(statement)
try:
self.current_command = statement
stop = func(statement)
finally:
self.current_command = None

else:
stop = self.default(statement)
Expand Down
9 changes: 9 additions & 0 deletions cmd2/command_definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,12 @@ def remove_settable(self, name: str) -> None:
del self._settables[name]
except KeyError:
raise KeyError(name + " is not a settable parameter")

def sigint_handler(self) -> bool:
"""
Handle a SIGINT that occurred for a command in this CommandSet.
:return: True if this completes the interrupt handling and no KeyboardInterrupt will be raised.
False to raise a KeyboardInterrupt.
"""
return False

Check warning on line 176 in cmd2/command_definition.py

View check run for this annotation

Codecov / codecov/patch

cmd2/command_definition.py#L176

Added line #L176 was not covered by tests

0 comments on commit 1e5ef48

Please sign in to comment.