-
Notifications
You must be signed in to change notification settings - Fork 124
Add hook example #478
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Add hook example #478
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| #!/usr/bin/env python | ||
| # coding=utf-8 | ||
| """ | ||
| A sample application for cmd2 demonstrating how to use hooks. | ||
|
|
||
| This application shows how to use postparsing hooks to allow case insensitive | ||
| command names, abbreviated commands, as well as allowing numeric arguments to | ||
| follow a command without any intervening whitespace. | ||
|
|
||
| """ | ||
|
|
||
| import re | ||
|
|
||
| from typing import List | ||
|
|
||
| import cmd2 | ||
|
|
||
|
|
||
| class CmdLineApp(cmd2.Cmd): | ||
| """Example cmd2 application demonstrating the use of hooks. | ||
|
|
||
| This simple application has one command, `list` which generates a list | ||
| of 10 numbers. This command takes one optional argument, which is the | ||
| number to start on. | ||
|
|
||
| We have three postparsing hooks, which allow the user to enter: | ||
|
|
||
| (Cmd) list 5 | ||
| (Cmd) L 5 | ||
| (Cmd) l 5 | ||
| (Cmd) L5 | ||
| (Cmd) LI5 | ||
|
|
||
| and have them all treated as valid input which prints a list of 10 numbers | ||
| starting with the number 5. | ||
| """ | ||
|
|
||
| # 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): | ||
| # sneakily remove the cmd2.Cmd command called load | ||
| # this lets a user enter a command like "l5" and allows it to | ||
| # be unambiguous | ||
| delattr(cmd2.Cmd, "do_load") | ||
|
|
||
| super().__init__(*args, **kwargs) | ||
|
|
||
| # register three hooks | ||
| self.register_postparsing_hook(self.add_whitespace_hook) | ||
| self.register_postparsing_hook(self.downcase_hook) | ||
| self.register_postparsing_hook(self.abbrev_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. | ||
|
|
||
| l24 -> l 24 | ||
| list24 -> list 24 | ||
| list 24 -> list 24 | ||
|
|
||
| """ | ||
| command = data.statement.command | ||
| # regular expression with looks for: | ||
| # ^ - the beginning of the string | ||
| # ([^\s\d]+) - one or more non-whitespace non-digit characters, set as capture group 1 | ||
| # (\d+) - one or more digit characters, set as capture group 2 | ||
| 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 | ||
| )) | ||
| 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 | ||
| )) | ||
| return data | ||
|
|
||
| def abbrev_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData: | ||
| """Accept unique abbreviated commands""" | ||
| target = 'do_' + data.statement.command | ||
| if target not in dir(self): | ||
| # check if the entered command might be an abbreviation | ||
| funcs = [func for func in self.keywords if func.startswith(data.statement.command)] | ||
| if len(funcs) == 1: | ||
| raw = data.statement.raw.replace(data.statement.command, funcs[0], 1) | ||
| data.statement = self.statement_parser.parse(raw) | ||
| return data | ||
|
|
||
| @cmd2.with_argument_list | ||
| def do_list(self, arglist: List[str]) -> None: | ||
| """Generate a list of 10 numbers.""" | ||
| if arglist: | ||
| first = arglist[0] | ||
| try: | ||
| first = int(first) | ||
| except ValueError: | ||
| first = 1 | ||
| else: | ||
| first = 1 | ||
| last = first + 10 | ||
|
|
||
| for x in range(first, last): | ||
| self.poutput(str(x)) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Everything looks good. TravisCI seems to be having some issues today. I restored one of the jobs since it failed for no good reason. This should be ready to merge once CI completes. |
||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| c = CmdLineApp() | ||
| c.cmdloop() | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Interesting use case for multiple postparsing hooks. I like the example, thanks for creating it.