pivotalcli/util.py

77 lines
1.8 KiB
Python
Raw Normal View History

2018-04-03 10:56:07 +00:00
import commands.login
import shutil
import textwrap
from typing import Any, Callable, Optional
from config import Config
class Color:
2018-08-17 12:55:27 +00:00
BLACK = 0
RED = 1
GREEN = 2
YELLOW = 3
BLUE = 4
MAGENTA = 5
CYAN = 6
WHITE = 7
BRIGHT_BLACK = 8
BRIGHT_RED = 9
BRIGHT_GREEN = 10
BRIGHT_YELLOW = 11
BRIGHT_BLUE = 12
BRIGHT_MAGENTA = 13
BRIGHT_CYAN = 14
BRIGHT_WHITE = 15
2018-04-03 10:56:07 +00:00
def __init__(self, foreground: Optional[int],
background: Optional[int] = None) -> None:
self.foreground = foreground
self.background = background
def print(self, *args: Any, end: str = '\n') -> None:
print(self.format(*args), end=end)
def format(self, *args: Any) -> str:
colors = ['0']
if self.foreground is not None:
2018-08-17 12:55:27 +00:00
colors.append(f"38;5;{self.foreground}")
2018-04-03 10:56:07 +00:00
if self.background is not None:
2018-08-17 12:55:27 +00:00
colors.append(f"48;5;{self.background}")
2018-04-03 10:56:07 +00:00
color_str = ';'.join(colors)
text = ' '.join(str(a) for a in args)
return f'\033[{color_str}m{text}\033[0m'
def print_wrap(text: str, indent: str = '', end: str = '\n') -> None:
w, _ = shutil.get_terminal_size((80, 20))
if w > 72:
w = 72
lines = text.split('\n')
for i, line in enumerate(lines):
_end = '\n' if i < len(lines) - 1 else end
if not line:
print(indent, end=_end)
continue
wrapped = textwrap.fill(
line, w, initial_indent=indent, subsequent_indent=indent)
print(wrapped, end=_end)
def require_login(function: Callable) -> Callable:
def wrapper(*args: Any, **kwargs: Any) -> Any:
while 'api_token' not in Config['user']:
commands.login.login(None)
return function(*args, **kwargs)
return wrapper