diff options
-rwxr-xr-x | cmd2/cmd2.py | 31 | ||||
-rw-r--r-- | docs/hooks.rst | 19 |
2 files changed, 49 insertions, 1 deletions
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index f480b3ae..6f111c7a 100755 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -402,6 +402,10 @@ class Cmd(cmd.Cmd): import atexit atexit.register(readline.write_history_file, persistent_history_file) + # initialize plugin system + # needs to be done before we call __init__(0) + self._initialize_plugin_system() + # Call super class constructor super().__init__(completekey=completekey, stdin=stdin, stdout=stdout) @@ -1621,6 +1625,11 @@ class Cmd(cmd.Cmd): """ return statement + # + def hook_postparsing(self, statement: Statement) -> Tuple[bool, Statement]: + stop = False + return stop, statement + # noinspection PyMethodMayBeStatic def postparsing_precmd(self, statement: Statement) -> Tuple[bool, Statement]: """This runs after parsing the command-line, but before anything else; even before adding cmd to history. @@ -1682,8 +1691,15 @@ class Cmd(cmd.Cmd): stop = False try: statement = self._complete_statement(line) - (stop, statement) = self.postparsing_precmd(statement) + # call the postparsing hooks + for func in self._postparsing_hooks: + (stop, statement) = func(statement) + if stop: + break + if not stop: + (stop, statement) = self.postparsing_precmd(statement) if stop: + #stop = self.hook_cmdcompleted(stop) return self.postparsing_postcmd(stop) try: @@ -2974,6 +2990,19 @@ Script should contain one command per line, just like command would be typed in # Run the postloop() no matter what self.postloop() + ### + # + # plugin related functions + # + ### + def _initialize_plugin_system(self): + """Initialize the plugin system""" + self._postparsing_hooks = [] + + def register_postparsing_hook(self, func): + """Register a function to be called after parsing user input but before running the command""" + self._postparsing_hooks.append(func) + class HistoryItem(str): """Class used to represent an item in the History list. diff --git a/docs/hooks.rst b/docs/hooks.rst index c28f9b8f..1402fee5 100644 --- a/docs/hooks.rst +++ b/docs/hooks.rst @@ -59,3 +59,22 @@ the various hook methods, presented in chronological order starting with the one .. automethod:: cmd2.cmd2.Cmd.postcmd .. automethod:: cmd2.cmd2.Cmd.postparsing_postcmd + +Registering hooks +----------------- + +As an alternative to overriding one of the hook methods, you can register any number of functions +to be called when the hook is processed. These registered functions are called before any overridden +method. + +This method of registering and calling multiple hooks allows plugins to tap into the hook mechanism +without interfering with each other or with your code. + +register_preloop_hook +register_postloop_hook + +register_preparsing_hook +register_postparsing_hook +register_precmd_hook +register_postcmd_hook +register_cmdcompleted_hook |