diff options
author | Kevin Van Brunt <kmvanbrunt@gmail.com> | 2020-09-09 01:03:21 -0400 |
---|---|---|
committer | Kevin Van Brunt <kmvanbrunt@gmail.com> | 2020-09-09 01:03:21 -0400 |
commit | d582466335d3182a15dc40bf2d8b6737fb158d46 (patch) | |
tree | 912c44bae977727cb0faa2d307fe87d1c48495b4 | |
parent | a95034f9537b498acb09943cde7c323001206937 (diff) | |
download | cmd2-git-d582466335d3182a15dc40bf2d8b6737fb158d46.tar.gz |
Moved two classes from cmd2.py to utils.py.
-rw-r--r-- | cmd2/__init__.py | 4 | ||||
-rw-r--r-- | cmd2/ansi.py | 4 | ||||
-rw-r--r-- | cmd2/cmd2.py | 54 | ||||
-rw-r--r-- | cmd2/rl_utils.py | 4 | ||||
-rw-r--r-- | cmd2/table_creator.py | 6 | ||||
-rw-r--r-- | cmd2/utils.py | 39 | ||||
-rw-r--r-- | docs/api/cmd.rst | 23 | ||||
-rw-r--r-- | docs/api/utils.rst | 27 | ||||
-rwxr-xr-x | tests/test_completion.py | 1 |
9 files changed, 83 insertions, 79 deletions
diff --git a/cmd2/__init__.py b/cmd2/__init__.py index 0ef038f5..f507dc28 100644 --- a/cmd2/__init__.py +++ b/cmd2/__init__.py @@ -27,7 +27,7 @@ if cmd2_parser_module is not None: # Get the current value for argparse_custom.DEFAULT_ARGUMENT_PARSER from .argparse_custom import DEFAULT_ARGUMENT_PARSER -from .cmd2 import Cmd, CompletionMode +from .cmd2 import Cmd from .command_definition import CommandSet, with_default_category from .constants import COMMAND_NAME, DEFAULT_SHORTCUTS from .decorators import with_argument_list, with_argparser, with_argparser_and_unknown_args, with_category, \ @@ -36,4 +36,4 @@ from .exceptions import Cmd2ArgparseError, CommandSetRegistrationError, Completi from . import plugin from .parsing import Statement from .py_bridge import CommandResult -from .utils import categorize, Settable +from .utils import categorize, CompletionMode, CustomCompletionSettings, Settable diff --git a/cmd2/ansi.py b/cmd2/ansi.py index f172b87f..afef06ce 100644 --- a/cmd2/ansi.py +++ b/cmd2/ansi.py @@ -3,9 +3,9 @@ Support for ANSI escape sequences which are used for things like applying style to text, setting the window title, and asynchronous alerts. """ +import enum import functools import re -from enum import Enum from typing import IO, Any, List, Union import colorama @@ -49,7 +49,7 @@ The default is ``STYLE_TERMINAL``. ANSI_STYLE_RE = re.compile(r'\x1b\[[^m]*m') -class ColorBase(Enum): +class ColorBase(enum.Enum): """ Base class used for defining color enums. See fg and bg classes for examples. diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 172d5264..8d9627aa 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -30,7 +30,6 @@ Git repository on GitHub at https://github.com/python-cmd2/cmd2 # setting is True import argparse import cmd -import enum import functools import glob import inspect @@ -97,40 +96,6 @@ except ImportError: # pragma: no cover ipython_available = False -class CompletionMode(enum.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 - - class _SavedReadlineSettings: """readline settings that are backed up when switching between readline environments""" @@ -1633,7 +1598,7 @@ class Cmd(cmd.Cmd): orig_pyreadline_display(matches_to_display) def _perform_completion(self, text: str, line: str, begidx: int, endidx: int, - custom_settings: Optional[CustomCompletionSettings] = None) -> None: + custom_settings: Optional[utils.CustomCompletionSettings] = None) -> None: """ Helper function for complete() that performs the actual completion @@ -1805,7 +1770,8 @@ class Cmd(cmd.Cmd): if len(self.completion_matches) == 1 and self.allow_closing_quote and unclosed_quote: self.completion_matches[0] += unclosed_quote - def complete(self, text: str, state: int, custom_settings: Optional[CustomCompletionSettings] = None) -> Optional[str]: + def complete(self, text: str, state: int, + custom_settings: Optional[utils.CustomCompletionSettings] = None) -> Optional[str]: """Override of cmd2's complete method which returns the next possible completion for 'text' This completer function is called by readline as complete(text, state), for state in 0, 1, 2, …, @@ -1863,7 +1829,7 @@ class Cmd(cmd.Cmd): parser = DEFAULT_ARGUMENT_PARSER(add_help=False) parser.add_argument('command', metavar="COMMAND", help="command, alias, or macro name", choices=self._get_commands_aliases_and_macros_for_completion()) - custom_settings = CustomCompletionSettings(parser) + custom_settings = utils.CustomCompletionSettings(parser) self._perform_completion(text, line, begidx, endidx, custom_settings) @@ -2557,7 +2523,7 @@ class Cmd(cmd.Cmd): def read_input(self, prompt: str, *, history: Optional[List[str]] = None, - completion_mode: CompletionMode = CompletionMode.NONE, + completion_mode: utils.CompletionMode = utils.CompletionMode.NONE, preserve_quotes: bool = False, choices: Iterable = None, choices_provider: Optional[Callable] = None, @@ -2613,14 +2579,14 @@ class Cmd(cmd.Cmd): saved_completer = readline.get_completer() # Disable completion - if completion_mode == CompletionMode.NONE: + if completion_mode == utils.CompletionMode.NONE: # noinspection PyUnusedLocal def complete_none(text: str, state: int): # pragma: no cover return None complete_func = complete_none # Complete commands - elif completion_mode == CompletionMode.COMMANDS: + elif completion_mode == utils.CompletionMode.COMMANDS: complete_func = self.complete # Set custom completion settings @@ -2630,13 +2596,13 @@ class Cmd(cmd.Cmd): parser.add_argument('arg', suppress_tab_hint=True, choices=choices, choices_provider=choices_provider, completer=completer) - custom_settings = CustomCompletionSettings(parser, preserve_quotes=preserve_quotes) + custom_settings = utils.CustomCompletionSettings(parser, preserve_quotes=preserve_quotes) complete_func = functools.partial(self.complete, custom_settings=custom_settings) readline.set_completer(complete_func) # Overwrite history if not completing commands or new history was provided - if completion_mode != CompletionMode.COMMANDS or history is not None: + if completion_mode != utils.CompletionMode.COMMANDS or history is not None: saved_history = [] for i in range(1, readline.get_current_history_length() + 1): # noinspection PyArgumentList @@ -2721,7 +2687,7 @@ class Cmd(cmd.Cmd): self.terminal_lock.release() except RuntimeError: pass - return self.read_input(prompt, completion_mode=CompletionMode.COMMANDS) + return self.read_input(prompt, completion_mode=utils.CompletionMode.COMMANDS) except EOFError: return 'eof' finally: diff --git a/cmd2/rl_utils.py b/cmd2/rl_utils.py index 099d76b7..9163efd8 100644 --- a/cmd2/rl_utils.py +++ b/cmd2/rl_utils.py @@ -2,8 +2,8 @@ """ Imports the proper readline for the platform and provides utility functions for it """ +import enum import sys -from enum import Enum # Prefer statically linked gnureadline if available (for macOS compatibility due to issues with libedit) try: @@ -19,7 +19,7 @@ except ImportError: pass -class RlType(Enum): +class RlType(enum.Enum): """Readline library types we recognize""" GNU = 1 PYREADLINE = 2 diff --git a/cmd2/table_creator.py b/cmd2/table_creator.py index 7a5c826c..fc2398f2 100644 --- a/cmd2/table_creator.py +++ b/cmd2/table_creator.py @@ -6,10 +6,10 @@ The general use case is to inherit from TableCreator to create a table class wit There are already implemented and ready-to-use examples of this below TableCreator's code. """ import copy +import enum import functools import io from collections import deque -from enum import Enum from typing import Any, Optional, Sequence, Tuple, Union from wcwidth import wcwidth @@ -39,14 +39,14 @@ EMPTY = '' SPACE = ' ' -class HorizontalAlignment(Enum): +class HorizontalAlignment(enum.Enum): """Horizontal alignment of text in a cell""" LEFT = 1 CENTER = 2 RIGHT = 3 -class VerticalAlignment(Enum): +class VerticalAlignment(enum.Enum): """Vertical alignment of text in a cell""" TOP = 1 MIDDLE = 2 diff --git a/cmd2/utils.py b/cmd2/utils.py index c5874d6e..b89d57bb 100644 --- a/cmd2/utils.py +++ b/cmd2/utils.py @@ -1,8 +1,10 @@ # coding=utf-8 """Shared utility functions""" +import argparse import collections import collections.abc as collections_abc +import enum import functools import glob import inspect @@ -12,7 +14,6 @@ import subprocess import sys import threading import unicodedata -from enum import Enum from typing import Any, Callable, Dict, Iterable, List, Optional, TextIO, Union from . import constants @@ -651,7 +652,7 @@ class RedirectionSavedState: self.saved_redirecting = saved_redirecting -class TextAlignment(Enum): +class TextAlignment(enum.Enum): """Horizontal text alignment""" LEFT = 1 CENTER = 2 @@ -1017,3 +1018,37 @@ def get_defining_class(meth): if isinstance(cls, type): return cls return getattr(meth, '__objclass__', None) # handle special descriptor objects + + +class CompletionMode(enum.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 diff --git a/docs/api/cmd.rst b/docs/api/cmd.rst index 3bcc302f..6fdfbf27 100644 --- a/docs/api/cmd.rst +++ b/docs/api/cmd.rst @@ -65,26 +65,3 @@ cmd2.Cmd The symbol name which :ref:`features/scripting:Python Scripts` run using the :ref:`features/builtin_commands:run_pyscript` command can use to reference the parent ``cmd2`` application. - -.. autoclass:: cmd2.CompletionMode - - .. attribute:: NONE - - Tab completion will be disabled during read_input() call. Use of custom - up-arrow history supported. - - .. attribute:: COMMANDS - - 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. - - .. attribute:: CUSTOM - - read_input() will tab complete based on one of its following parameters - (choices, choices_provider, completer, parser). Use of custom up-arrow - history supported - -.. autoclass:: cmd2.cmd2.CustomCompletionSettings - - .. automethod:: __init__
\ No newline at end of file diff --git a/docs/api/utils.rst b/docs/api/utils.rst index 188f5b16..9276587f 100644 --- a/docs/api/utils.rst +++ b/docs/api/utils.rst @@ -36,6 +36,33 @@ IO Handling :members: +Tab Completion +-------------- + +.. autoclass:: cmd2.utils.CompletionMode + + .. attribute:: NONE + + Tab completion will be disabled during read_input() call. Use of custom + up-arrow history supported. + + .. attribute:: COMMANDS + + 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. + + .. attribute:: CUSTOM + + read_input() will tab complete based on one of its following parameters + (choices, choices_provider, completer, parser). Use of custom up-arrow + history supported + +.. autoclass:: cmd2.utils.CustomCompletionSettings + + .. automethod:: __init__ + + Text Alignment -------------- diff --git a/tests/test_completion.py b/tests/test_completion.py index d0771795..48f93a5a 100755 --- a/tests/test_completion.py +++ b/tests/test_completion.py @@ -22,7 +22,6 @@ import pytest import cmd2 from cmd2 import utils from examples.subcommands import SubcommandsExample - from .conftest import complete_tester, normalize, run_cmd # List of strings used with completion functions |