Skip to content

Commit

Permalink
Tidy up and auto-format
Browse files Browse the repository at this point in the history
  • Loading branch information
ines committed Nov 17, 2018
1 parent 0a6cd11 commit 30ce299
Show file tree
Hide file tree
Showing 7 changed files with 119 additions and 92 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ lightweight, has zero dependencies and works across Python 2 and 3.
[![Travis](https://img.shields.io/travis/ines/wasabi/master.svg?style=flat-square&logo=travis)](https://travis-ci.org/ines/wasabi)
[![PyPi](https://img.shields.io/pypi/v/wasabi.svg?style=flat-square)](https://pypi.python.org/pypi/wasabi)
[![GitHub](https://img.shields.io/github/release/ines/wasabi/all.svg?style=flat-square)](https://github.com/ines/wasabi)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg?style=flat-square)](https://github.com/ambv/black)

<img width="609" src="https://user-images.githubusercontent.com/13643239/48663861-8c9ea000-ea96-11e8-8b04-d120c52276a8.png">

Expand Down
26 changes: 13 additions & 13 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,35 +7,35 @@


def setup_package():
package_name = 'wasabi'
package_name = "wasabi"
root = Path(__file__).parent.resolve()

# Read in package meta from about.py
about_path = root / package_name / 'about.py'
with about_path.open('r', encoding='utf8') as f:
about_path = root / package_name / "about.py"
with about_path.open("r", encoding="utf8") as f:
about = {}
exec(f.read(), about)

# Get readme
readme_path = root / 'README.md'
with readme_path.open('r', encoding='utf8') as f:
readme_path = root / "README.md"
with readme_path.open("r", encoding="utf8") as f:
readme = f.read()

setup(
name=package_name,
description=about['__summary__'],
description=about["__summary__"],
long_description=readme,
long_description_content_type='text/markdown',
author=about['__author__'],
author_email=about['__email__'],
url=about['__uri__'],
version=about['__version__'],
license=about['__license__'],
long_description_content_type="text/markdown",
author=about["__author__"],
author_email=about["__email__"],
url=about["__uri__"],
version=about["__version__"],
license=about["__license__"],
packages=find_packages(),
install_requires=[],
zip_safe=False,
)


if __name__ == '__main__':
if __name__ == "__main__":
setup_package()
20 changes: 12 additions & 8 deletions tests/test_printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,12 @@ def test_printer_no_pretty():


def test_printer_custom():
colors = {'yellow': 220, 'purple': 99}
icons = {'warn': '\u26a0\ufe0f', 'question': "?"}
colors = {"yellow": 220, "purple": 99}
icons = {"warn": "\u26a0\ufe0f", "question": "?"}
p = Printer(no_print=True, colors=colors, icons=icons)
text = "This is a test."
assert p.text(text, color='purple', icon='question') == "\x1b[38;5;99m? This is a test.\x1b[0m"
purple_questipn = p.text(text, color="purple", icon="question")
assert purple_question == "\x1b[38;5;99m? This is a test.\x1b[0m"
assert p.warn(text) == "\x1b[38;5;3m\u26a0\ufe0f This is a test.\x1b[0m"


Expand All @@ -53,16 +54,19 @@ def test_printer_counts():
def test_printer_divider():
p = Printer(line_max=20, no_print=True)
p.divider() == "\x1b[1m\n================\x1b[0m"
p.divider('test') == "\x1b[1m\n====== test ======\x1b[0m"
p.divider('test', char='*') == "\x1b[1m\n****** test ******\x1b[0m"
p.divider('This is a very long text, it is very long') == "\x1b[1m\n This is a very long text, it is very long \x1b[0m"
p.divider("test") == "\x1b[1m\n====== test ======\x1b[0m"
p.divider("test", char="*") == "\x1b[1m\n****** test ******\x1b[0m"
assert (
p.divider("This is a very long text, it is very long")
== "\x1b[1m\n This is a very long text, it is very long \x1b[0m"
)
with pytest.raises(ValueError):
p.divider('test', char='~.')
p.divider("test", char="~.")


def test_printer_loading():
p = Printer()
print('\n')
print("\n")
with p.loading("Loading..."):
time.sleep(1)
p.good("Success!")
Expand Down
17 changes: 11 additions & 6 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,25 @@


def test_color():
assert color('test', fg='green') == '\x1b[38;5;2mtest\x1b[0m'
assert color('test', fg=4) == '\x1b[38;5;4mtest\x1b[0m'
assert color('test', bold=True) == '\x1b[1mtest\x1b[0m'
assert color('test', fg=7, bg='red', bold=True) == '\x1b[1;38;5;7;48;5;1mtest\x1b[0m'
assert color("test", fg="green") == "\x1b[38;5;2mtest\x1b[0m"
assert color("test", fg=4) == "\x1b[38;5;4mtest\x1b[0m"
assert color("test", bold=True) == "\x1b[1mtest\x1b[0m"
assert (
color("test", fg=7, bg="red", bold=True) == "\x1b[1;38;5;7;48;5;1mtest\x1b[0m"
)


def test_wrap():
text = "Hello world, this is a test."
assert wrap(text, indent=0) == text
assert wrap(text, indent=4) == " Hello world, this is a test."
assert wrap(text, wrap_max=10, indent=0) == "Hello\nworld,\nthis is a\ntest."
assert wrap(text, wrap_max=5, indent=2) == " Hello\n world,\n this\n is\n a\n test."
assert (
wrap(text, wrap_max=5, indent=2)
== " Hello\n world,\n this\n is\n a\n test."
)


@pytest.mark.parametrize('text', ['abc', '\u2714 abc', '👻'])
@pytest.mark.parametrize("text", ["abc", "\u2714 abc", "👻"])
def test_locale_escape(text):
assert locale_escape(text)
14 changes: 7 additions & 7 deletions wasabi/about.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
__title__ = 'wasabi'
__version__ = '0.0.3'
__summary__ = 'A lightweight console printing and formatting toolkit'
__uri__ = 'https://ines.io'
__author__ = 'Ines Montani'
__email__ = '[email protected]'
__license__ = 'MIT'
__title__ = "wasabi"
__version__ = "0.0.3"
__summary__ = "A lightweight console printing and formatting toolkit"
__uri__ = "https://ines.io"
__author__ = "Ines Montani"
__email__ = "[email protected]"
__license__ = "MIT"
69 changes: 40 additions & 29 deletions wasabi/printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,17 @@


class Printer(object):
def __init__(self, pretty=True, no_print=False, colors=None, icons=None,
line_max=80, animation='⠙⠹⠸⠼⠴⠦⠧⠇⠏', animation_ascii='|/-\\',
ignore_warnings=False):
def __init__(
self,
pretty=True,
no_print=False,
colors=None,
icons=None,
line_max=80,
animation="⠙⠹⠸⠼⠴⠦⠧⠇⠏",
animation_ascii="|/-\\",
ignore_warnings=False,
):
"""Initialize the command-line printer.
pretty (bool): Pretty-print output (colors, icons).
Expand Down Expand Up @@ -50,23 +58,23 @@ def counts(self):
"""
return self._counts

def good(self, text='', show=True):
def good(self, text="", show=True):
"""Print a success message."""
return self._get_msg(text, style=MESSAGES.GOOD, show=show)

def fail(self, text='', show=True):
def fail(self, text="", show=True):
"""Print an error message."""
return self._get_msg(text, style=MESSAGES.FAIL, show=show)

def warn(self, text='', show=True):
def warn(self, text="", show=True):
"""Print a warning message."""
return self._get_msg(text, style=MESSAGES.WARN, show=show)

def info(self, text='', show=True):
def info(self, text="", show=True):
"""Print an error message."""
return self._get_msg(text, style=MESSAGES.INFO, show=show)

def text(self, text='', color=None, icon=None, show=True):
def text(self, text="", color=None, icon=None, show=True):
"""Print a message.
text (unicode): The text to print.
Expand All @@ -80,13 +88,13 @@ def text(self, text='', color=None, icon=None, show=True):
if self.pretty and self.supports_ansi:
color = self.colors.get(color)
icon = self.icons.get(icon)
text = locale_escape('{} {}'.format(icon, text) if icon else text)
text = locale_escape("{} {}".format(icon, text) if icon else text)
text = _color(text, fg=color)
if self.no_print:
return text
print(text)

def divider(self, text='', char='=', show=True):
def divider(self, text="", char="=", show=True):
"""Print a divider with a headline:
============================ Headline here ===========================
Expand All @@ -95,32 +103,35 @@ def divider(self, text='', char='=', show=True):
show (bool): Whether to print or not.
"""
if len(char) != 1:
raise ValueError("Divider chars need to be one character long. "
"Received: {}".format(char))
raise ValueError(
"Divider chars need to be one character long. "
"Received: {}".format(char)
)
if self.pretty:
deco = char * (int(round((self.line_max - len(text))) / 2) - 2)
text = ' {} '.format(text) if text else ''
text = _color('\n{deco}{text}{deco}'.format(deco=deco, text=text),
bold=True)
text = " {} ".format(text) if text else ""
text = _color(
"\n{deco}{text}{deco}".format(deco=deco, text=text), bold=True
)
if len(text) < self.line_max:
text = text + char * (self.line_max - len(text))
if self.no_print:
return text
print(text)

@contextmanager
def loading(self, text=''):
def loading(self, text=""):
sys.stdout.flush()
t = Process(target=self._spinner, args=(text,))
t.start()
yield
t.terminate()
sys.stdout.write('\r\x1b[2K') # erase line
sys.stdout.write("\r\x1b[2K") # erase line
sys.stdout.flush()

def _spinner(self, text='Loading...'):
def _spinner(self, text="Loading..."):
for char in itertools.cycle(self.anim):
sys.stdout.write('\r{} {}'.format(char, text))
sys.stdout.write("\r{} {}".format(char, text))
sys.stdout.flush()
time.sleep(0.1)

Expand All @@ -137,18 +148,18 @@ def print_message(*texts, **kwargs):
*texts (unicode): Texts to print. Each argument is rendered as paragraph.
**kwargs: 'title' becomes headline. exits=1 performs sys exit.
"""
exits = kwargs.get('exits')
indent = kwargs.get('indent', 4)
nowrap = kwargs.get('nowrap', False)
title = kwargs.get('title', None)
title_tpl = '{}\n'
exits = kwargs.get("exits")
indent = kwargs.get("indent", 4)
nowrap = kwargs.get("nowrap", False)
title = kwargs.get("title", None)
title_tpl = "{}\n"
if nowrap:
title = title_tpl.format(title) if title else ''
message = '\n\n'.join(texts)
title = title_tpl.format(title) if title else ""
message = "\n\n".join(texts)
else:
title = title_tpl.format(wrap(title, indent=indent)) if title else ''
message = '\n\n'.join([wrap(text, indent=indent) for text in texts])
print('\n{}{}\n'.format(title, message))
title = title_tpl.format(wrap(title, indent=indent)) if title else ""
message = "\n\n".join([wrap(text, indent=indent) for text in texts])
print("\n{}{}\n".format(title, message))
if exits is not None:
sys.stdout.flush()
sys.stderr.flush()
Expand Down
Loading

0 comments on commit 30ce299

Please sign in to comment.