Skip to content

Commit

Permalink
Added 'colored' to helper functions
Browse files Browse the repository at this point in the history
  • Loading branch information
dhondta committed Jul 31, 2020
1 parent 5b015da commit 8ca23ac
Show file tree
Hide file tree
Showing 5 changed files with 82 additions and 5 deletions.
1 change: 1 addition & 0 deletions docs/helpers.md
Expand Up @@ -26,6 +26,7 @@ It also defines a few compatibility/utility functions for working with the same
:---: | :---:
`b` | bytes conversion function, overloading `six.b` for a better compatibility
`byteindex` | selects the byte value from a string at the given index
`colored` | allows to color text in a similar way to [`termcolor.colored`](https://pypi.org/project/termcolor/) (which is NOT in Tinyscript's requirements) but relying on [`colorful`](https://pypi.org/project/colorful/) (which is in Tinyscript's requirements)
`ensure_binary` | identical to `six.ensure_binary`
`ensure_str` | similar to `six.ensure_str`
`ensure_unicode` | dummy alias for `six.text_type`, by analogy to `ensure_binary` and `ensure_unicode`
Expand Down
23 changes: 23 additions & 0 deletions tests/test_helpers_inputs.py
Expand Up @@ -4,6 +4,7 @@
"""
from tinyscript.helpers.compat import b
from tinyscript.helpers.constants import TTY
from tinyscript.helpers.inputs import *
from tinyscript.helpers.inputs import _keyboard, hotkeys_enabled
from tinyscript.loglib import logger as ts_logger
Expand Down Expand Up @@ -76,4 +77,26 @@ def test_keystrokes_function(self):
hotkeys({'ctrl': ("CTRL", ts_logger.info)})
from tinyscript.helpers.inputs import Key
_keyboard.press(Key.ctrl)

def test_styling_functions(self):
STR = "test string"
self.assertIsNotNone(colored(STR, "green"))
self.assertRaises(ValueError, colored, STR, "BAD_COLOR")
self.assertRaises(ValueError, colored, STR, "bold")
self.assertIsNotNone(colored(STR, "black", "green"))
self.assertRaises(ValueError, colored, STR, "black", "BAD_COLOR")
self.assertRaises(ValueError, colored, STR, "black", "bold")
self.assertIsNotNone(colored(STR, "black", "green", "bold"))
self.assertRaises(ValueError, colored, STR, "black", "green", "BAD_MODIFIER")
self.assertRaises(ValueError, colored, STR, "black", "green", "red")
self.assertRaises(ValueError, colored, STR, "black", "green", ["bold", "BAD_MODIFIER"])
self.assertIsNotNone(colored(STR, style="bold_on_green"))
self.assertIsNotNone(colored(STR, style=["bold", "underlined", "green"]))
self.assertIsNotNone(colored(STR, palette="solarized"))
# style argument has precedence on color, on_color and attrs
a = getattr(self, "assert%sEqual" % ["", "Not"][TTY])
a(colored(STR, "black", "green", "bold"), colored(STR, "black", "green", "bold", "bold_yellow_on_red"))
self.assertIsNotNone(colored(STR, "bold", style="bold_yellow_on_red"))
if TTY:
self.assertRaises(AttributeError, colored, STR, style="BAD_STYLE")

3 changes: 2 additions & 1 deletion tinyscript/helpers/__init__.py
Expand Up @@ -86,4 +86,5 @@
for h in __helpers__:
setattr(ts, h, globals()[h])

__all__ = __features__ = ["pprint", "ts"] + _clsprop + _compat + _csts
__all__ = __features__ = ["colored", "pprint", "ts"] + _clsprop + _compat + _csts

59 changes: 55 additions & 4 deletions tinyscript/helpers/inputs.py
Expand Up @@ -8,6 +8,7 @@
import signal
import sys
from ast import literal_eval
from colorful.core import COLOR_PALETTE
from six import StringIO

from .compat import ensure_str
Expand All @@ -29,8 +30,10 @@
hotkeys_enabled = False


__all__ = __features__ = ["capture", "clear", "confirm", "hotkeys", "pause", "silent", "std_input", "stdin_flush",
"stdin_pipe", "user_input", "Capture"]
__all__ = ["capture", "clear", "confirm", "hotkeys", "pause", "silent", "std_input", "stdin_flush", "stdin_pipe",
"user_input", "Capture"]
__features__ = [x for x in __all__]
__all__ += ["colored"]

pause = lambda *a, **kw: std_input("Press Enter to continue", *a, **kw) or None

Expand All @@ -57,6 +60,54 @@ def clear():
system("cls")


def colored(text, color=None, on_color=None, attrs=None, style=None, palette=None):
"""
Colorize text.
:param text: text to be colorized
:param color: text color
:param on_color: background color
:param attrs: single styling attribute or list of styling attributes
:param style: colorful styling function, e.g. red_on_green (for green foreground and red background colors)
:param palette: predefined palette's name (e.g. 'monokai')
:return: styled string
Available styling attributes:
blinkrapid, blinkslow, bold, concealed, dimmed, inversed, italic, reset, struckthrough, underlined
Available palettes:
monokai, solarized
"""
if isinstance(style, (list, tuple)):
style = "_".join(style)
s = style or ""
if palette:
colorful.use_style(palette)
if s == "":
if attrs:
if not isinstance(attrs, list):
attrs = [attrs]
for attr in attrs:
if attr not in colorful.ansi.MODIFIERS.keys():
raise ValueError("Bad ANSI modifier '%s'" % attr)
s += str(attr) + "_"
if color:
if color not in colorful.colorpalette.keys():
raise ValueError("Bad color '%s'" % color)
s += str(color) + "_"
if on_color:
if on_color not in colorful.colorpalette.keys():
raise ValueError("Bad color '%s'" % on_color)
s += "on_" + str(on_color)
if s != "":
c = getattr(colorful, s.rstrip("_"))
try:
return c(text).styled_string if s and TTY else text
finally:
# ensure that the palette is restored
colorful.use_palette(COLOR_PALETTE)


def confirm(prompt="Are you sure ?", style="bold"):
"""
Ask for confirmation.
Expand Down Expand Up @@ -156,11 +207,11 @@ def std_input(prompt="", style=None, palette=None):
:param style: colorful styling function, e.g. red_on_green (for green foreground and red background colors)
:param palette: dictionary for defining new styles
"""
colorful.update_palette(palette or {})
if style is not None:
colorful.update_palette(palette or {})
if isinstance(style, (list, tuple, set)):
style = "_".join(style)
prompt = getattr(colorful, style)(prompt)
prompt = colored(prompt, style=style)
return (input(prompt) if PYTHON3 else raw_input(prompt)).strip()


Expand Down
1 change: 1 addition & 0 deletions tinyscript/preimports/__init__.py
Expand Up @@ -47,6 +47,7 @@
"binascii",
"codecs",
"collections",
"colorful",
"configparser",
"ctypes",
"fileinput",
Expand Down

0 comments on commit 8ca23ac

Please sign in to comment.