Skip to content

Commit

Permalink
Add an educational postcommand hook
Browse files Browse the repository at this point in the history
Not necessary for the sake of the example, but might help some curious
individuals get a better feel for how the system works.
  • Loading branch information
Case Ploeg authored and kmvanbrunt committed Apr 13, 2022
1 parent 830c7b4 commit 49a6b26
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion examples/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,24 @@ class CmdLineApp(cmd2.Cmd):
and have them all treated as valid input which prints a list of 10 numbers
starting with the number 5.
We also add a postcommand hook, which updates the shell prompt to show the
raw contents of the Statement after the postparsing hooks are finished. To
use this hook, run `(Cmd) set debug True`. All of the above variations of
the list command should produce the same raw content.
"""

# Setting this true makes it run a shell command if a cmd2/cmd command doesn't exist
# default_to_shell = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

# register three hooks
# register four hooks
self.register_postparsing_hook(self.add_whitespace_hook)
self.register_postparsing_hook(self.downcase_hook)
self.register_postparsing_hook(self.abbrev_hook)
self.register_postcmd_hook(self.proof_hook)

def add_whitespace_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
"""A hook to split alphabetic command names immediately followed by a number.
Expand Down Expand Up @@ -88,6 +95,12 @@ def abbrev_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.Postpars
data.statement = self.statement_parser.parse(raw)
return data

def proof_hook(self, data: cmd2.plugin.PostcommandData) -> cmd2.plugin.PostcommandData:
"""Update the shell prompt with the new raw statement after postparsing hooks are finished"""
if self.debug:
self.prompt = f'({data.statement.raw})'
return data

@cmd2.with_argument_list
def do_list(self, arglist: List[str]) -> None:
"""Generate a list of 10 numbers."""
Expand Down

0 comments on commit 49a6b26

Please sign in to comment.