Skip to content

Commit

Permalink
Add black for automatic code format
Browse files Browse the repository at this point in the history
  • Loading branch information
tleonhardt committed Feb 1, 2021
1 parent 918200c commit f456b80
Show file tree
Hide file tree
Showing 91 changed files with 3,001 additions and 2,122 deletions.
28 changes: 28 additions & 0 deletions .github/workflows/format.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# For documentation on GitHub Actions Workflows, see:
# https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions
name: Format

on: [push, pull_request]

jobs:
lint:
strategy:
matrix:
os: [ubuntu-latest]
python-version: [3.9]
fail-fast: false
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2 # https://github.com/actions/checkout
with:
# Only a single commit is fetched by default, for the ref/SHA that triggered the workflow.
# Set fetch-depth: 0 to fetch all history for all branches and tags.
fetch-depth: 0 # Needed for setuptools_scm to work correctly
- name: Set up Python
uses: actions/setup-python@v2 # https://github.com/actions/setup-python
with:
python-version: ${{ matrix.python-version }}
- name: Install python prerequisites
run: pip install -U --user pip setuptools setuptools-scm black
- name: Black
run: python -m black
5 changes: 3 additions & 2 deletions cmd2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,19 @@

# Check if user has defined a module that sets a custom value for argparse_custom.DEFAULT_ARGUMENT_PARSER
import argparse

cmd2_parser_module = getattr(argparse, 'cmd2_parser_module', None)
if cmd2_parser_module is not None:
import importlib

importlib.import_module(cmd2_parser_module)

# Get the current value for argparse_custom.DEFAULT_ARGUMENT_PARSER
from .argparse_custom import DEFAULT_ARGUMENT_PARSER
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, \
as_subcommand_to
from .decorators import with_argument_list, with_argparser, with_argparser_and_unknown_args, with_category, as_subcommand_to
from .exceptions import Cmd2ArgparseError, SkipPostcommandHooks, CommandSetRegistrationError
from . import plugin
from .parsing import Statement
Expand Down
26 changes: 16 additions & 10 deletions cmd2/ansi.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@
"""
import functools
import re
from enum import (
Enum,
)
from enum import Enum
from typing import (
IO,
Any,
Expand All @@ -21,9 +19,7 @@
Fore,
Style,
)
from wcwidth import (
wcswidth,
)
from wcwidth import wcswidth

# On Windows, filter ANSI escape codes out of text sent to stdout/stderr, and replace them with equivalent Win32 calls
colorama.init(strip=False)
Expand Down Expand Up @@ -72,6 +68,7 @@ class ColorBase(Enum):
value: anything that when cast to a string returns an ANSI sequence
"""

def __str__(self) -> str:
"""
Return ANSI color sequence instead of enum name
Expand Down Expand Up @@ -105,6 +102,7 @@ def colors(cls) -> List[str]:
# noinspection PyPep8Naming
class fg(ColorBase):
"""Enum class for foreground colors"""

black = Fore.BLACK
red = Fore.RED
green = Fore.GREEN
Expand All @@ -128,6 +126,7 @@ class fg(ColorBase):
# noinspection PyPep8Naming
class bg(ColorBase):
"""Enum class for background colors"""

black = Back.BLACK
red = Back.RED
green = Back.GREEN
Expand Down Expand Up @@ -197,8 +196,7 @@ def style_aware_write(fileobj: IO, msg: str) -> None:
:param fileobj: the file object being written to
:param msg: the string being written
"""
if allow_style.lower() == STYLE_NEVER.lower() or \
(allow_style.lower() == STYLE_TERMINAL.lower() and not fileobj.isatty()):
if allow_style.lower() == STYLE_NEVER.lower() or (allow_style.lower() == STYLE_TERMINAL.lower() and not fileobj.isatty()):
msg = strip_style(msg)
fileobj.write(msg)

Expand Down Expand Up @@ -240,8 +238,15 @@ def bg_lookup(bg_name: Union[str, bg]) -> str:


# noinspection PyShadowingNames
def style(text: Any, *, fg: Union[str, fg] = '', bg: Union[str, bg] = '', bold: bool = False,
dim: bool = False, underline: bool = False) -> str:
def style(
text: Any,
*,
fg: Union[str, fg] = '',
bg: Union[str, bg] = '',
bold: bool = False,
dim: bool = False,
underline: bool = False
) -> str:
"""
Apply ANSI colors and/or styles to a string and return it.
The styling is self contained which means that at the end of the string reset code(s) are issued
Expand Down Expand Up @@ -315,6 +320,7 @@ def async_alert_str(*, terminal_columns: int, prompt: str, line: str, cursor_off
:return: the correct string so that the alert message appears to the user to be printed above the current line.
"""
from colorama import Cursor

# Split the prompt lines since it can contain newline characters.
prompt_lines = prompt.splitlines()

Expand Down
98 changes: 54 additions & 44 deletions cmd2/argparse_completer.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@
import inspect
import numbers
import shutil
from collections import (
deque,
)
from collections import deque
from typing import (
Dict,
List,
Expand All @@ -34,9 +32,7 @@
CompletionItem,
generate_range_error,
)
from .command_definition import (
CommandSet,
)
from .command_definition import CommandSet
from .table_creator import (
Column,
SimpleTable,
Expand Down Expand Up @@ -105,12 +101,13 @@ def _looks_like_flag(token: str, parser: argparse.ArgumentParser) -> bool:

class _ArgumentState:
"""Keeps state of an argument being parsed"""

def __init__(self, arg_action: argparse.Action) -> None:
self.action = arg_action
self.min = None
self.max = None
self.count = 0
self.is_remainder = (self.action.nargs == argparse.REMAINDER)
self.is_remainder = self.action.nargs == argparse.REMAINDER

# Check if nargs is a range
nargs_range = getattr(self.action, ATTR_NARGS_RANGE, None)
Expand Down Expand Up @@ -143,10 +140,11 @@ def __init__(self, flag_arg_state: _ArgumentState) -> None:
CompletionError which occurs when the user has not finished the current flag
:param flag_arg_state: information about the unfinished flag action
"""
error = "Error: argument {}: {} ({} entered)".\
format(argparse._get_action_name(flag_arg_state.action),
generate_range_error(flag_arg_state.min, flag_arg_state.max),
flag_arg_state.count)
error = "Error: argument {}: {} ({} entered)".format(
argparse._get_action_name(flag_arg_state.action),
generate_range_error(flag_arg_state.min, flag_arg_state.max),
flag_arg_state.count,
)
super().__init__(error)


Expand All @@ -165,8 +163,10 @@ def __init__(self, parser: argparse.ArgumentParser, arg_action: argparse.Action)
# noinspection PyProtectedMember
class ArgparseCompleter:
"""Automatic command line tab completion based on argparse parameters"""
def __init__(self, parser: argparse.ArgumentParser, cmd2_app: cmd2.Cmd, *,
parent_tokens: Optional[Dict[str, List[str]]] = None) -> None:

def __init__(
self, parser: argparse.ArgumentParser, cmd2_app: cmd2.Cmd, *, parent_tokens: Optional[Dict[str, List[str]]] = None
) -> None:
"""
Create an ArgparseCompleter
Expand All @@ -183,10 +183,10 @@ def __init__(self, parser: argparse.ArgumentParser, cmd2_app: cmd2.Cmd, *,
parent_tokens = dict()
self._parent_tokens = parent_tokens

self._flags = [] # all flags in this command
self._flag_to_action = {} # maps flags to the argparse action object
self._positional_actions = [] # actions for positional arguments (by position index)
self._subcommand_action = None # this will be set if self._parser has subcommands
self._flags = [] # all flags in this command
self._flag_to_action = {} # maps flags to the argparse action object
self._positional_actions = [] # actions for positional arguments (by position index)
self._subcommand_action = None # this will be set if self._parser has subcommands

# Start digging through the argparse structures.
# _actions is the top level container of parameter definitions
Expand All @@ -205,8 +205,9 @@ def __init__(self, parser: argparse.ArgumentParser, cmd2_app: cmd2.Cmd, *,
if isinstance(action, argparse._SubParsersAction):
self._subcommand_action = action

def complete_command(self, tokens: List[str], text: str, line: str, begidx: int, endidx: int, *,
cmd_set: Optional[CommandSet] = None) -> List[str]:
def complete_command(
self, tokens: List[str], text: str, line: str, begidx: int, endidx: int, *, cmd_set: Optional[CommandSet] = None
) -> List[str]:
"""
Complete the command using the argparse metadata and provided argument dictionary
:raises: CompletionError for various types of tab completion errors
Expand Down Expand Up @@ -262,9 +263,9 @@ def update_mutex_groups(arg_action: argparse.Action) -> None:
if arg_action == completer_action:
return

error = ("Error: argument {}: not allowed with argument {}".
format(argparse._get_action_name(arg_action),
argparse._get_action_name(completer_action)))
error = "Error: argument {}: not allowed with argument {}".format(
argparse._get_action_name(arg_action), argparse._get_action_name(completer_action)
)
raise CompletionError(error)

# Mark that this action completed the group
Expand Down Expand Up @@ -334,9 +335,7 @@ def update_mutex_groups(arg_action: argparse.Action) -> None:

if action is not None:
update_mutex_groups(action)
if isinstance(action, (argparse._AppendAction,
argparse._AppendConstAction,
argparse._CountAction)):
if isinstance(action, (argparse._AppendAction, argparse._AppendConstAction, argparse._CountAction)):
# Flags with action set to append, append_const, and count can be reused
# Therefore don't erase any tokens already consumed for this flag
consumed_arg_values.setdefault(action.dest, [])
Expand Down Expand Up @@ -381,10 +380,12 @@ def update_mutex_groups(arg_action: argparse.Action) -> None:
if action.dest != argparse.SUPPRESS:
parent_tokens[action.dest] = [token]

completer = ArgparseCompleter(self._subcommand_action.choices[token], self._cmd2_app,
parent_tokens=parent_tokens)
return completer.complete_command(tokens[token_index:], text, line, begidx, endidx,
cmd_set=cmd_set)
completer = ArgparseCompleter(
self._subcommand_action.choices[token], self._cmd2_app, parent_tokens=parent_tokens
)
return completer.complete_command(
tokens[token_index:], text, line, begidx, endidx, cmd_set=cmd_set
)
else:
# Invalid subcommand entered, so no way to complete remaining tokens
return []
Expand Down Expand Up @@ -428,9 +429,9 @@ def update_mutex_groups(arg_action: argparse.Action) -> None:

# Check if we are completing a flag's argument
if flag_arg_state is not None:
completion_results = self._complete_for_arg(flag_arg_state, text, line,
begidx, endidx, consumed_arg_values,
cmd_set=cmd_set)
completion_results = self._complete_for_arg(
flag_arg_state, text, line, begidx, endidx, consumed_arg_values, cmd_set=cmd_set
)

# If we have results, then return them
if completion_results:
Expand All @@ -440,8 +441,11 @@ def update_mutex_groups(arg_action: argparse.Action) -> None:
return completion_results

# Otherwise, print a hint if the flag isn't finished or text isn't possibly the start of a flag
elif flag_arg_state.count < flag_arg_state.min or \
not _single_prefix_char(text, self._parser) or skip_remaining_flags:
elif (
flag_arg_state.count < flag_arg_state.min
or not _single_prefix_char(text, self._parser)
or skip_remaining_flags
):
raise _NoResultsError(self._parser, flag_arg_state.action)

# Otherwise check if we have a positional to complete
Expand All @@ -452,9 +456,9 @@ def update_mutex_groups(arg_action: argparse.Action) -> None:
action = remaining_positionals.popleft()
pos_arg_state = _ArgumentState(action)

completion_results = self._complete_for_arg(pos_arg_state, text, line,
begidx, endidx, consumed_arg_values,
cmd_set=cmd_set)
completion_results = self._complete_for_arg(
pos_arg_state, text, line, begidx, endidx, consumed_arg_values, cmd_set=cmd_set
)

# If we have results, then return them
if completion_results:
Expand Down Expand Up @@ -510,8 +514,7 @@ def _complete_flags(self, text: str, line: str, begidx: int, endidx: int, matche

def _format_completions(self, arg_state: _ArgumentState, completions: List[Union[str, CompletionItem]]) -> List[str]:
# Check if the results are CompletionItems and that there aren't too many to display
if 1 < len(completions) <= self._cmd2_app.max_completion_items and \
isinstance(completions[0], CompletionItem):
if 1 < len(completions) <= self._cmd2_app.max_completion_items and isinstance(completions[0], CompletionItem):

# If the user has not already sorted the CompletionItems, then sort them before appending the descriptions
if not self._cmd2_app.matches_sorted:
Expand Down Expand Up @@ -549,7 +552,7 @@ def _format_completions(self, arg_state: _ArgumentState, completions: List[Union
initial_width = base_width + token_width + desc_width

if initial_width < min_width:
desc_width += (min_width - initial_width)
desc_width += min_width - initial_width

cols = list()
cols.append(Column(destination.upper(), width=token_width))
Expand Down Expand Up @@ -602,10 +605,17 @@ def format_help(self, tokens: List[str]) -> str:
break
return self._parser.format_help()

def _complete_for_arg(self, arg_state: _ArgumentState,
text: str, line: str, begidx: int, endidx: int,
consumed_arg_values: Dict[str, List[str]], *,
cmd_set: Optional[CommandSet] = None) -> List[str]:
def _complete_for_arg(
self,
arg_state: _ArgumentState,
text: str,
line: str,
begidx: int,
endidx: int,
consumed_arg_values: Dict[str, List[str]],
*,
cmd_set: Optional[CommandSet] = None
) -> List[str]:
"""
Tab completion routine for an argparse argument
:return: list of completions
Expand Down
Loading

0 comments on commit f456b80

Please sign in to comment.