Skip to content

Commit

Permalink
fix: Version 2.6.1
Browse files Browse the repository at this point in the history
  • Loading branch information
MPCodeWriter21 committed Aug 5, 2023
1 parent 158bd25 commit 69a06f3
Show file tree
Hide file tree
Showing 20 changed files with 1,341 additions and 607 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ Help this project by [Donation](DONATE.md)
Changes
-----------

### 2.6.1

Added `encoding` to `log21.CrashReporter.FileReporter`.
Added configs for `pylint`, `yapf` and `isort` to `pyproject.toml`.
Added optional `dev` dependencies to `pyproject.toml`.
Improved overall code quality.

### 2.6.0

Added the `Argumentify` module. Check the examples.
Expand Down
11 changes: 7 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,12 @@ pip install git+https://github.com/MPCodeWriter21/log21
Changes
-------

### 2.6.0
### 2.6.1

Added the `Argumentify` module. Check the examples.
Added `encoding` to `log21.CrashReporter.FileReporter`.
Added configs for `pylint`, `yapf` and `isort` to `pyproject.toml`.
Added optional `dev` dependencies to `pyproject.toml`.
Improved overall code quality.

[Full CHANGELOG](https://github.com/MPCodeWriter21/log21/blob/master/CHANGELOG.md)

Expand Down Expand Up @@ -97,7 +100,7 @@ logger.error(log21.get_colors('LightRed') + "I'm still here ;1")

----------------

### Argument Parsing (See Also: [Argumentify](https://github.com/MPCodeWriter21/log21#argumentify))
### Argument Parsing (See Also: [Argumentify](https://github.com/MPCodeWriter21/log21#argumentify-check-out-the-manual-way))

```python
import log21
Expand Down Expand Up @@ -255,7 +258,7 @@ for i in range(84):

------------------

### Argumentify (Check out [the manual way](https://github.com/MPCodeWriter21/log21#argument-parsing))
### Argumentify (Check out [the manual way](https://github.com/MPCodeWriter21/log21#argumentify-check-out-the-manual-way))

```python
# Common Section
Expand Down
30 changes: 29 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ dependencies = [
"webcolors",
"docstring-parser"
]
version = "2.6.0"
version = "2.6.1"

[tool.setuptools.packages.find]
where = ["src"]
Expand All @@ -35,3 +35,31 @@ where = ["src"]
Homepage = "https://github.com/MPCodeWriter21/log21"
Donations = "https://github.com/MPCodeWriter21/log21/blob/master/DONATE.md"
Source = "https://github.com/MPCodeWriter21/log21"

[project.optional-dependencies]
dev = ["yapf", "isort", "docformatter", "pylint"]

[tool.pylint.messages_control]
max-line-length = 88

disable = [
"protected-access",
"too-few-public-methods",
"too-many-arguments",
"too-many-locals",
"fixme",
]

[tool.pylint.design]
max-returns = 8

[tool.yapf]
column_limit = 88
split_before_dot = true
split_before_first_argument = true
dedent_closing_brackets = true

[tool.isort]
line_length = 88
combine_as_imports = true
order_by_type = true
99 changes: 66 additions & 33 deletions src/log21/Argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,32 @@

import re as _re
import sys as _sys
import log21 as _log21
import argparse as _argparse

from typing import Mapping as _Mapping, Optional as _Optional
from gettext import gettext as _gettext
from textwrap import TextWrapper as _TextWrapper
from typing import Mapping as _Mapping, Optional as _Optional

import log21 as _log21
from log21.Colors import get_colors as _gc
from log21.Formatters import DecolorizingFormatter as _Formatter

__all__ = ['ColorizingArgumentParser', 'ColorizingHelpFormatter', 'ColorizingTextWrapper']
__all__ = [
'ColorizingArgumentParser', 'ColorizingHelpFormatter', 'ColorizingTextWrapper'
]


class ColorizingHelpFormatter(_argparse.HelpFormatter):
def __init__(self, prog, indent_increment=2, max_help_position=24, width=None,
colors: _Optional[_Mapping[str, str]] = None):

def __init__(
self,
prog,
indent_increment=2,
max_help_position=24,
width=None,
colors: _Optional[_Mapping[str, str]] = None
):
super().__init__(prog, indent_increment, max_help_position, width)

self.colors = {
'usage': 'Cyan',
'brackets': 'LightRed',
Expand All @@ -39,6 +47,7 @@ def __init__(self, prog, indent_increment=2, max_help_position=24, width=None,
self.colors[key] = value

class _Section(object):

def __init__(self, formatter, parent, heading=None):
self.formatter = formatter
self.parent = parent
Expand Down Expand Up @@ -67,30 +76,36 @@ def format_help(self):
heading = ''

# join the section-initial newline, the heading and the help
return join(['\n', heading, _gc(self.formatter.colors['help']), item_help, '\n'])
return join(
['\n', heading,
_gc(self.formatter.colors['help']), item_help, '\n']
)

def _add_item(self, func, args):
self._current_section.items.append((func, args))

def _fill_text(self, text, width, indent):
text = self._whitespace_matcher.sub(' ', text).strip()
return ColorizingTextWrapper(width=width, initial_indent=indent, subsequent_indent=indent).fill(text)
return ColorizingTextWrapper(
width=width, initial_indent=indent, subsequent_indent=indent
).fill(text)

def _split_lines(self, text, width):
text = self._whitespace_matcher.sub(' ', text).strip()
return ColorizingTextWrapper(width=width).wrap(text)

def start_section(self, heading):
self._indent()
section = self._Section(self, self._current_section,
_gc(self.colors['section headers']) + str(heading) + '\033[0m')
section = self._Section(
self, self._current_section,
_gc(self.colors['section headers']) + str(heading) + '\033[0m'
)
self._add_item(section.format_help, [])
self._current_section = section

def _format_action(self, action):
# determine the required width and the entry label
help_position = min(self._action_max_length + 2,
self._max_help_position)
help_position = min(self._action_max_length + 2, self._max_help_position)
help_width = max(self._width - help_position, 11)
action_width = help_position - self._current_indent - 2
action_header = _gc('rst') + self._format_action_invocation(action)
Expand All @@ -101,7 +116,9 @@ def _format_action(self, action):
action_header = self._current_indent * ' ' + action_header + '\n'
# short action name; start on the same line and pad two spaces
elif len(action_header) <= action_width:
action_header = '%*s%-*s ' % (self._current_indent, '', action_width, action_header)
action_header = '%*s%-*s ' % (
self._current_indent, '', action_width, action_header
)
# long action name; start on the next line
else:
action_header = self._current_indent * ' ' + action_header + '\n'
Expand Down Expand Up @@ -181,7 +198,8 @@ def get_lines(parts, indent, prefix=None):
else:
line_len = len(indent) - 1
for part in parts:
if line_len + 1 + len(_Formatter.decolorize(part)) > text_width and line:
if line_len + 1 + len(_Formatter.decolorize(part)
) > text_width and line:
lines.append(indent + ' '.join(line))
line = []
line_len = len(indent) - 1
Expand Down Expand Up @@ -297,13 +315,15 @@ def _format_actions_usage(self, actions: list, groups):
else:
default = self._get_default_metavar_for_optional(action)
args_string = self._format_args(action, default)
part = _gc(self.colors['switches']) + '%s %s%s' % (option_string, _gc(self.colors['values']),
args_string)
part = _gc(self.colors['switches']) + '%s %s%s' % (
option_string, _gc(self.colors['values']), args_string
)

# make it look optional if it's not required or in a group
if not action.required and action not in group_actions:
part = _gc(self.colors['brackets']) + '[' + part + _gc(
self.colors['brackets']) + ']\033[0m'
self.colors['brackets']
) + ']\033[0m'

# add the action string to the list
parts.append(part)
Expand Down Expand Up @@ -348,8 +368,10 @@ def _format_action_invocation(self, action):
default = self._get_default_metavar_for_optional(action)
args_string = self._format_args(action, default)
for option_string in action.option_strings:
parts.append(_gc(self.colors['switches']) + '%s %s%s' % (option_string, _gc(self.colors['values']),
args_string))
parts.append(
_gc(self.colors['switches']) + '%s %s%s' %
(option_string, _gc(self.colors['values']), args_string)
)

return _gc(self.colors['commas']) + ', '.join(parts)

Expand All @@ -368,7 +390,7 @@ def format(tuple_size):
if isinstance(result, tuple):
return result
else:
return (result,) * tuple_size
return (result, ) * tuple_size

return format

Expand Down Expand Up @@ -421,7 +443,8 @@ def _wrap_chunks(self, chunks): # noqa: C901

# First chunk on the line is whitespace -- drop it, unless this
# is the very beginning of the text (i.e. no lines started yet).
if self.drop_whitespace and _Formatter.decolorize(chunks[-1]).strip() == '' and lines:
if self.drop_whitespace and _Formatter.decolorize(chunks[-1]
).strip() == '' and lines:
del chunks[-1]

while chunks:
Expand All @@ -444,24 +467,23 @@ def _wrap_chunks(self, chunks): # noqa: C901
current_len = sum(map(len, current_line))

# If the last chunk on this line is all whitespace, drop it.
if self.drop_whitespace and current_line and _Formatter.decolorize(current_line[-1]).strip() == '':
if self.drop_whitespace and current_line and _Formatter.decolorize(
current_line[-1]).strip() == '':
current_len -= len(_Formatter.decolorize(current_line[-1]))
del current_line[-1]

if current_line:
if (self.max_lines is None or
len(lines) + 1 < self.max_lines or
(not chunks or
self.drop_whitespace and
len(chunks) == 1 and
not chunks[0].strip()) and current_len <= width):
if (self.max_lines is None or len(lines) + 1 < self.max_lines
or (not chunks or self.drop_whitespace and len(chunks) == 1
and not chunks[0].strip()) and current_len <= width):
# Convert current line back to a string and store it in
# list of all lines (return value).
lines.append(indent + ''.join(current_line))
else:
while current_line:
if _Formatter.decolorize(current_line[-1]).strip() and current_len + len(
self.placeholder) <= width:
if _Formatter.decolorize(
current_line[-1]
).strip() and current_len + len(self.placeholder) <= width:
current_line.append(self.placeholder)
lines.append(indent + ''.join(current_line))
break
Expand All @@ -481,7 +503,13 @@ def _wrap_chunks(self, chunks): # noqa: C901


class ColorizingArgumentParser(_argparse.ArgumentParser):
def __init__(self, formatter_class=ColorizingHelpFormatter, colors: _Optional[_Mapping[str, str]] = None, **kwargs):

def __init__(
self,
formatter_class=ColorizingHelpFormatter,
colors: _Optional[_Mapping[str, str]] = None,
**kwargs
):
self.logger = _log21.Logger('ArgumentParser')
self.colors = colors
super().__init__(formatter_class=formatter_class, **kwargs)
Expand All @@ -501,7 +529,12 @@ def exit(self, status=0, message=None):
def error(self, message):
self.print_usage(_sys.stderr)
args = {'prog': self.prog, 'message': message}
self.exit(2, _gettext(f'%(prog)s: {_gc("r")}error{_gc("lr")}:{_gc("rst")} %(message)s\n') % args)
self.exit(
2,
_gettext(
f'%(prog)s: {_gc("r")}error{_gc("lr")}:{_gc("rst")} %(message)s\n'
) % args
)

def _get_formatter(self):
if hasattr(self.formatter_class, 'colors'):
Expand Down
11 changes: 7 additions & 4 deletions src/log21/Argumentify.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ def __post_init__(self):
self.arguments[parameter.arg_name].help = parameter.description


def generate_flag(
def generate_flag( # pylint: disable=too-many-branches
argument: Argument,
no_dash: bool = False,
reserved_flags: _Optional[_Set[str]] = None
Expand Down Expand Up @@ -210,9 +210,12 @@ def generate_flag(
)
if flag1 in reserved_flags:
flag1 = flag1_base + normalize_name(argument.name, sep_char='-').upper()
if flag1 in reserved_flags and no_dash:
raise FlagGenerationError(f"Failed to generate a flag for argument: {argument}")
if flag1 not in reserved_flags:
if flag1 in reserved_flags:
if no_dash:
raise FlagGenerationError(
f"Failed to generate a flag for argument: {argument}"
)
else:
flags.append(flag1)

if not no_dash:
Expand Down
4 changes: 2 additions & 2 deletions src/log21/Colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ def get_color_name(

def get_color(color: _Union[str, _Sequence], raise_exceptions: bool = False) -> str:
"""Gets a color name and returns it in ansi format
>>>
>>> get_color('LightRed')
'\x1b[91m'
Expand All @@ -288,7 +288,7 @@ def get_color(color: _Union[str, _Sequence], raise_exceptions: bool = False) ->
[21:21:21] [INFO] Hello World!
>>> # Note that you must run it yourself to see the colorful result ;D
>>>
:param color: color name(Example: Blue)
:param raise_exceptions: bool = False:
False: It will return '' instead of raising exceptions when an error occurs.
Expand Down
Loading

0 comments on commit 69a06f3

Please sign in to comment.