summaryrefslogtreecommitdiff
path: root/cmd2/utils.py
diff options
context:
space:
mode:
authorTodd Leonhardt <todd.leonhardt@gmail.com>2021-02-19 21:35:13 -0500
committerTodd Leonhardt <todd.leonhardt@gmail.com>2021-02-19 21:35:13 -0500
commit3e180a810e9c4b9d251c135667d1d150b0bbd0dd (patch)
tree03e49d5da86d40efa9118eccfd8bd4bbf3dcf86b /cmd2/utils.py
parent4c70bdb03d34c43f833bf77c441452cd402d0715 (diff)
parent06aaf962689840631325c70ea7e9056d176c7f67 (diff)
downloadcmd2-git-3e180a810e9c4b9d251c135667d1d150b0bbd0dd.tar.gz
Merge branch 'master' into black
# Conflicts: # cmd2/__init__.py # cmd2/argparse_completer.py # cmd2/argparse_custom.py # cmd2/cmd2.py # cmd2/decorators.py # cmd2/exceptions.py # cmd2/utils.py # examples/arg_decorators.py # examples/argparse_completion.py # examples/modular_commands_main.py # tests/test_argparse_completer.py # tests/test_argparse_custom.py # tests/test_cmd2.py # tests/test_completion.py # tests/test_history.py
Diffstat (limited to 'cmd2/utils.py')
-rw-r--r--cmd2/utils.py115
1 files changed, 44 insertions, 71 deletions
diff --git a/cmd2/utils.py b/cmd2/utils.py
index 7e5f5af5..8dad5f4c 100644
--- a/cmd2/utils.py
+++ b/cmd2/utils.py
@@ -1,6 +1,7 @@
# coding=utf-8
"""Shared utility functions"""
+import argparse
import collections
import collections.abc as collections_abc
import functools
@@ -90,48 +91,13 @@ def str_to_bool(val: str) -> bool:
raise ValueError("must be True or False (case-insensitive)")
-class CompletionError(Exception):
- """
- Raised during tab completion operations to report any sort of error you want printed. This can also be used
- just to display a message, even if it's not an error. For instance, ArgparseCompleter raises CompletionErrors
- to display tab completion hints and sets apply_style to False so hints aren't colored like error text.
-
- Example use cases
-
- - Reading a database to retrieve a tab completion data set failed
- - A previous command line argument that determines the data set being completed is invalid
- - Tab completion hints
- """
-
- def __init__(self, *args, apply_style: bool = True, **kwargs):
- """
- Initializer for CompletionError
- :param apply_style: If True, then ansi.style_error will be applied to the message text when printed.
- Set to False in cases where the message text already has the desired style.
- Defaults to True.
- """
- self.apply_style = apply_style
-
- # noinspection PyArgumentList
- super().__init__(*args, **kwargs)
-
-
class Settable:
"""Used to configure a cmd2 instance member to be settable via the set command in the CLI"""
-
- def __init__(
- self,
- name: str,
- val_type: Callable,
- description: str,
- *,
- onchange_cb: Callable[[str, Any, Any], Any] = None,
- choices: Iterable = None,
- choices_function: Optional[Callable] = None,
- choices_method: Optional[Callable] = None,
- completer_function: Optional[Callable] = None,
- completer_method: Optional[Callable] = None
- ):
+ def __init__(self, name: str, val_type: Callable, description: str, *,
+ onchange_cb: Callable[[str, Any, Any], Any] = None,
+ choices: Iterable = None,
+ choices_provider: Optional[Callable] = None,
+ completer: Optional[Callable] = None):
"""
Settable Initializer
@@ -153,17 +119,8 @@ class Settable:
same settings in argparse-based tab completion. A maximum of one of these should be provided.
:param choices: iterable of accepted values
- :param choices_function: function that provides choices for this argument
- :param choices_method: cmd2-app method that provides choices for this argument (See note below)
- :param completer_function: tab completion function that provides choices for this argument
- :param completer_method: cmd2-app tab completion method that provides choices
- for this argument (See note below)
-
- Note:
- For choices_method and completer_method, do not set them to a bound method. This is because
- ArgparseCompleter passes the self argument explicitly to these functions.
-
- Therefore instead of passing something like self.path_complete, pass cmd2.Cmd.path_complete.
+ :param choices_provider: function that provides choices for this argument
+ :param completer: tab completion function that provides choices for this argument
"""
if val_type == bool:
val_type = str_to_bool
@@ -174,10 +131,8 @@ class Settable:
self.description = description
self.onchange_cb = onchange_cb
self.choices = choices
- self.choices_function = choices_function
- self.choices_method = choices_method
- self.completer_function = completer_function
- self.completer_method = completer_method
+ self.choices_provider = choices_provider
+ self.completer = completer
def namedtuple_with_defaults(typename: str, field_names: Union[str, List[str]], default_values: collections_abc.Iterable = ()):
@@ -732,22 +687,6 @@ class RedirectionSavedState:
self.saved_redirecting = saved_redirecting
-# noinspection PyUnusedLocal
-def basic_complete(text: str, line: str, begidx: int, endidx: int, match_against: Iterable) -> List[str]:
- """
- Basic tab completion function that matches against a list of strings without considering line contents
- or cursor position. The args required by this function are defined in the header of Python's cmd.py.
-
- :param text: the string prefix we are attempting to match (all matches must begin with it)
- :param line: the current input line with leading whitespace removed
- :param begidx: the beginning index of the prefix text
- :param endidx: the ending index of the prefix text
- :param match_against: the strings being matched against
- :return: a list of possible tab completions
- """
- return [cur_match for cur_match in match_against if cur_match.startswith(text)]
-
-
class TextAlignment(Enum):
"""Horizontal text alignment"""
@@ -1132,3 +1071,37 @@ def get_defining_class(meth) -> Type:
if isinstance(cls, type):
return cls
return getattr(meth, '__objclass__', None) # handle special descriptor objects
+
+
+class CompletionMode(Enum):
+ """Enum for what type of tab completion to perform in cmd2.Cmd.read_input()"""
+ # Tab completion will be disabled during read_input() call
+ # Use of custom up-arrow history supported
+ NONE = 1
+
+ # read_input() will tab complete cmd2 commands and their arguments
+ # cmd2's command line history will be used for up arrow if history is not provided.
+ # Otherwise use of custom up-arrow history supported.
+ COMMANDS = 2
+
+ # read_input() will tab complete based on one of its following parameters:
+ # choices, choices_provider, completer, parser
+ # Use of custom up-arrow history supported
+ CUSTOM = 3
+
+
+class CustomCompletionSettings:
+ """Used by cmd2.Cmd.complete() to tab complete strings other than command arguments"""
+ def __init__(self, parser: argparse.ArgumentParser, *, preserve_quotes: bool = False):
+ """
+ Initializer
+
+ :param parser: arg parser defining format of string being tab completed
+ :param preserve_quotes: if True, then quoted tokens will keep their quotes when processed by
+ ArgparseCompleter. This is helpful in cases when you're tab completing
+ flag-like tokens (e.g. -o, --option) and you don't want them to be
+ treated as argparse flags when quoted. Set this to True if you plan
+ on passing the string to argparse with the tokens still quoted.
+ """
+ self.parser = parser
+ self.preserve_quotes = preserve_quotes