-
Notifications
You must be signed in to change notification settings - Fork 127
Load/Unload commands at runtime - Implements #943 #945
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
Closed
Closed
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
f22013e
Initial implementation of modular command loading
anselor 744cfbf
Some minor cleanup of how imports work. Fixed issue with help documen…
anselor 8300fa1
Added new constructor parameter to flag whether commands should autol…
anselor a92e261
add ability to remove commands and commandsets
anselor 8a55193
Fixes issue with locating help_ annd complete_ functions when autoloa…
anselor 1490e9d
Fixes to sphinx generation
anselor 564ffdf
Added explicit tests for dir and setattr. Minor type hinting changes
anselor 35c37b8
Added more command validation. Moved some common behavior into privat…
anselor 07b2ec1
Appears to be a type hinting olution that works for flake, sphinx, an…
anselor be70feb
Sort imports using isort
tleonhardt ba7f85d
cleanup
anselor 1cd01c2
Adjusted decorators to accept variable positional parameters
anselor 91a9ed5
Added an additional check for isinstance(method, Callable) since ther…
anselor c794059
added additional documentation for new decorator behavior
anselor 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
Large diffs are not rendered by default.
Oops, something went wrong.
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,129 @@ | ||
| # coding=utf-8 | ||
| """ | ||
| Supports the definition of commands in separate classes to be composed into cmd2.Cmd | ||
| """ | ||
| import functools | ||
| from typing import Callable, Dict, Iterable, Optional, Type | ||
|
|
||
| from .constants import COMMAND_FUNC_PREFIX | ||
|
|
||
| # Allows IDEs to resolve types without impacting imports at runtime, breaking circular dependency issues | ||
| try: # pragma: no cover | ||
| from typing import TYPE_CHECKING | ||
| if TYPE_CHECKING: | ||
| import cmd2 | ||
|
|
||
| except ImportError: # pragma: no cover | ||
| pass | ||
|
|
||
| _REGISTERED_COMMANDS = {} # type: Dict[str, Callable] | ||
| """ | ||
| Registered command tuples. (command, ``do_`` function) | ||
| """ | ||
|
|
||
|
|
||
| def _partial_passthru(func: Callable, *args, **kwargs) -> functools.partial: | ||
| """ | ||
| Constructs a partial function that passes arguments through to the wrapped function. | ||
| Must construct a new type every time so that each wrapped function's __doc__ can be copied correctly. | ||
|
|
||
| :param func: wrapped function | ||
| :param args: positional arguments | ||
| :param kwargs: keyword arguments | ||
| :return: partial function that exposes attributes of wrapped function | ||
| """ | ||
| def __getattr__(self, item): | ||
| return getattr(self.func, item) | ||
|
|
||
| def __setattr__(self, key, value): | ||
| return setattr(self.func, key, value) | ||
tleonhardt marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| def __dir__(self) -> Iterable[str]: | ||
| return dir(self.func) | ||
tleonhardt marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| passthru_type = type('PassthruPartial' + func.__name__, | ||
| (functools.partial,), | ||
| { | ||
| '__getattr__': __getattr__, | ||
| '__setattr__': __setattr__, | ||
| '__dir__': __dir__, | ||
| }) | ||
| passthru_type.__doc__ = func.__doc__ | ||
| return passthru_type(func, *args, **kwargs) | ||
|
|
||
|
|
||
| def register_command(cmd_func: Callable): | ||
| """ | ||
| Decorator that allows an arbitrary function to be automatically registered as a command. | ||
| If there is a ``help_`` or ``complete_`` function that matches this command, that will also be registered. | ||
|
|
||
| :param cmd_func: Function to register as a cmd2 command | ||
| :type cmd_func: Callable[[cmd2.Cmd, Union[Statement, argparse.Namespace]], None] | ||
| :return: | ||
| """ | ||
| assert cmd_func.__name__.startswith(COMMAND_FUNC_PREFIX), 'Command functions must start with `do_`' | ||
|
|
||
| cmd_name = cmd_func.__name__[len(COMMAND_FUNC_PREFIX):] | ||
|
|
||
| if cmd_name not in _REGISTERED_COMMANDS: | ||
| _REGISTERED_COMMANDS[cmd_name] = cmd_func | ||
| else: | ||
| raise KeyError('Command ' + cmd_name + ' is already registered') | ||
| return cmd_func | ||
|
|
||
|
|
||
| def with_default_category(category: str): | ||
| """ | ||
| Decorator that applies a category to all ``do_*`` command methods in a class that do not already | ||
| have a category specified. | ||
|
|
||
| :param category: category to put all uncategorized commands in | ||
| :return: decorator function | ||
| """ | ||
|
|
||
| def decorate_class(cls: Type[CommandSet]): | ||
| from .constants import CMD_ATTR_HELP_CATEGORY | ||
| import inspect | ||
| from .decorators import with_category | ||
| methods = inspect.getmembers( | ||
| cls, | ||
| predicate=lambda meth: inspect.isfunction(meth) and meth.__name__.startswith(COMMAND_FUNC_PREFIX)) | ||
| category_decorator = with_category(category) | ||
| for method in methods: | ||
| if not hasattr(method[1], CMD_ATTR_HELP_CATEGORY): | ||
| setattr(cls, method[0], category_decorator(method[1])) | ||
| return cls | ||
| return decorate_class | ||
|
|
||
|
|
||
| class CommandSet(object): | ||
| """ | ||
| Base class for defining sets of commands to load in cmd2. | ||
|
|
||
| ``with_default_category`` can be used to apply a default category to all commands in the CommandSet. | ||
|
|
||
| ``do_``, ``help_``, and ``complete_`` functions differ only in that they're now required to accept | ||
| a reference to ``cmd2.Cmd`` as the first argument after self. | ||
| """ | ||
|
|
||
| def __init__(self): | ||
| self._cmd = None # type: Optional[cmd2.Cmd] | ||
|
|
||
| def on_register(self, cmd): | ||
| """ | ||
| Called by cmd2.Cmd when a CommandSet is registered. Subclasses can override this | ||
| to perform an initialization requiring access to the Cmd object. | ||
|
|
||
| :param cmd: The cmd2 main application | ||
| :type cmd: cmd2.Cmd | ||
| """ | ||
| self._cmd = cmd | ||
|
|
||
| def on_unregister(self, cmd): | ||
| """ | ||
| Called by ``cmd2.Cmd`` when a CommandSet is unregistered and removed. | ||
|
|
||
| :param cmd: | ||
| :type cmd: cmd2.Cmd | ||
| """ | ||
| self._cmd = None | ||
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
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,5 @@ | ||
| cmd2.command_definition | ||
| ======================= | ||
|
|
||
| .. automodule:: cmd2.command_definition | ||
| :members: |
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
Empty file.
Oops, something went wrong.
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.
Before merging in this would need a CHANGELOG entry for version 1.2.0 or whatever.