Skip to content

Commit

Permalink
update postparsing hooks
Browse files Browse the repository at this point in the history
Previously redirection information was lost by the postparsing hooks
add_whitespace_hook() and downcase_hook(). This was fine for this simple
shell, but sets a bad example for more complicated use cases.

To fix this, when parsing the new Statement object, include the
`post_command` attribute from the original Statement.
  • Loading branch information
Case Ploeg authored and kmvanbrunt committed Apr 13, 2022
1 parent 036f185 commit 830c7b4
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions examples/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,17 +62,19 @@ def add_whitespace_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.
command_pattern = re.compile(r'^([^\s\d]+)(\d+)')
match = command_pattern.search(command)
if match:
data.statement = self.statement_parser.parse(
"{} {} {}".format(match.group(1), match.group(2), '' if data.statement.args is None else data.statement.args)
)
command = match.group(1)
first_arg = match.group(2)
rest_args = data.statement.args
post_command = data.statement.post_command
data.statement = self.statement_parser.parse(f'{command} {first_arg} {rest_args} {post_command}')
return data

def downcase_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
"""A hook to make uppercase commands lowercase."""
command = data.statement.command.lower()
data.statement = self.statement_parser.parse(
"{} {}".format(command, '' if data.statement.args is None else data.statement.args)
)
args = data.statement.args
post_command = data.statement.post_command
data.statement = self.statement_parser.parse(f'{command} {args} {post_command}')
return data

def abbrev_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
Expand Down

0 comments on commit 830c7b4

Please sign in to comment.