summaryrefslogtreecommitdiff
path: root/cmd2/argparse_custom.py
diff options
context:
space:
mode:
authorEric Lin <anselor@gmail.com>2020-07-27 11:43:16 -0400
committeranselor <anselor@gmail.com>2020-08-04 13:38:08 -0400
commit3a6db395cb28b5b13dde38284dc22791583012fa (patch)
treea901fe8323d47cb061d9c2d4961565603f27b773 /cmd2/argparse_custom.py
parent06cee9126839c465a356f8b44a5f008853eb8cad (diff)
downloadcmd2-git-3a6db395cb28b5b13dde38284dc22791583012fa.tar.gz
Adds support for injectable subcommands as part of CommandSet
load/unload. Updated examples and documentation to include discussion of injectable sub-commands.
Diffstat (limited to 'cmd2/argparse_custom.py')
-rw-r--r--cmd2/argparse_custom.py32
1 files changed, 30 insertions, 2 deletions
diff --git a/cmd2/argparse_custom.py b/cmd2/argparse_custom.py
index 74bddfc7..689c1db7 100644
--- a/cmd2/argparse_custom.py
+++ b/cmd2/argparse_custom.py
@@ -724,6 +724,24 @@ class Cmd2HelpFormatter(argparse.RawTextHelpFormatter):
return result
+class _UnloadableSubParsersAction(argparse._SubParsersAction):
+ """Extends the argparse internal SubParsers action to allow sub-parsers to be removed dynamically"""
+ def remove_parser(self, name):
+ """Removes a sub-parser from the sub-parsers group"""
+ for choice_action in self._choices_actions:
+ if choice_action.dest == name:
+ self._choices_actions.remove(choice_action)
+ break
+
+ subparser = self._name_parser_map[name]
+ to_remove = []
+ for name, parser in self._name_parser_map.items():
+ if parser is subparser:
+ to_remove.append(name)
+ for name in to_remove:
+ del self._name_parser_map[name]
+
+
# noinspection PyCompatibility
class Cmd2ArgumentParser(argparse.ArgumentParser):
"""Custom ArgumentParser class that improves error and help output"""
@@ -754,12 +772,22 @@ class Cmd2ArgumentParser(argparse.ArgumentParser):
conflict_handler=conflict_handler,
add_help=add_help,
allow_abbrev=allow_abbrev)
+ self.register('action', 'unloadable_parsers', _UnloadableSubParsersAction)
+
+ def add_subparsers(self, unloadable=False, **kwargs):
+ """
+ Custom override. Sets a default title if one was not given.
- def add_subparsers(self, **kwargs):
- """Custom override. Sets a default title if one was not given."""
+ :param unloadable: Flag whether this sub-parsers group will support unloading parsers
+ :param kwargs: additional keyword arguments
+ :return: argparse Subparser Action
+ """
if 'title' not in kwargs:
kwargs['title'] = 'subcommands'
+ if unloadable:
+ kwargs['action'] = 'unloadable_parsers'
+
return super().add_subparsers(**kwargs)
def error(self, message: str) -> None: