You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

237 lines
8.3 KiB

4 years ago
  1. # coding: utf8
  2. from __future__ import unicode_literals, print_function
  3. import datetime
  4. from collections import Counter
  5. from contextlib import contextmanager
  6. from multiprocessing import Process
  7. import itertools
  8. import sys
  9. import time
  10. import os
  11. from .tables import table, row
  12. from .util import wrap, supports_ansi, can_render, locale_escape
  13. from .util import MESSAGES, COLORS, ICONS
  14. from .util import color as _color
  15. class Printer(object):
  16. def __init__(
  17. self,
  18. pretty=True,
  19. no_print=False,
  20. colors=None,
  21. icons=None,
  22. line_max=80,
  23. animation="⠙⠹⠸⠼⠴⠦⠧⠇⠏",
  24. animation_ascii="|/-\\",
  25. hide_animation=False,
  26. ignore_warnings=False,
  27. env_prefix="WASABI",
  28. timestamp=False,
  29. ):
  30. """Initialize the command-line printer.
  31. pretty (bool): Pretty-print output (colors, icons).
  32. no_print (bool): Don't actually print, just return.
  33. colors (dict): Add or overwrite color values, name mapped to value.
  34. icons (dict): Add or overwrite icons. Name mapped to unicode icon.
  35. line_max (int): Maximum line length (for divider).
  36. animation (unicode): Steps of loading animation for loading() method.
  37. animation_ascii (unicode): Alternative animation for ASCII terminals.
  38. hide_animation (bool): Don't display animation, e.g. for logs.
  39. ignore_warnings (bool): Do not output messages of type MESSAGE.WARN.
  40. env_prefix (unicode): Prefix for environment variables, e.g.
  41. WASABI_LOG_FRIENDLY.
  42. timestamp (bool): Print a timestamp (default False).
  43. RETURNS (Printer): The initialized printer.
  44. """
  45. env_log_friendly = os.getenv("{}_LOG_FRIENDLY".format(env_prefix), False)
  46. env_no_pretty = os.getenv("{}_NO_PRETTY".format(env_prefix), False)
  47. self._counts = Counter()
  48. self.pretty = pretty and not env_no_pretty
  49. self.no_print = no_print
  50. self.show_color = supports_ansi() and not env_log_friendly
  51. self.hide_animation = hide_animation or env_log_friendly
  52. self.ignore_warnings = ignore_warnings
  53. self.line_max = line_max
  54. self.colors = dict(COLORS)
  55. self.icons = dict(ICONS)
  56. self.timestamp = timestamp
  57. if colors:
  58. self.colors.update(colors)
  59. if icons:
  60. self.icons.update(icons)
  61. self.anim = animation if can_render(animation) else animation_ascii
  62. @property
  63. def counts(self):
  64. """Get the counts of how often the special printers were fired,
  65. e.g. MESSAGES.GOOD. Can be used to print an overview like "X warnings".
  66. """
  67. return self._counts
  68. def good(self, title="", text="", show=True, spaced=False, exits=None):
  69. """Print a success message."""
  70. return self._get_msg(
  71. title, text, style=MESSAGES.GOOD, show=show, spaced=spaced, exits=exits
  72. )
  73. def fail(self, title="", text="", show=True, spaced=False, exits=None):
  74. """Print an error message."""
  75. return self._get_msg(
  76. title, text, style=MESSAGES.FAIL, show=show, spaced=spaced, exits=exits
  77. )
  78. def warn(self, title="", text="", show=True, spaced=False, exits=None):
  79. """Print a warning message."""
  80. return self._get_msg(
  81. title, text, style=MESSAGES.WARN, show=show, spaced=spaced, exits=exits
  82. )
  83. def info(self, title="", text="", show=True, spaced=False, exits=None):
  84. """Print an informational message."""
  85. return self._get_msg(
  86. title, text, style=MESSAGES.INFO, show=show, spaced=spaced, exits=exits
  87. )
  88. def text(
  89. self,
  90. title="",
  91. text="",
  92. color=None,
  93. icon=None,
  94. spaced=False,
  95. show=True,
  96. no_print=False,
  97. exits=None,
  98. ):
  99. """Print a message.
  100. title (unicode): The main text to print.
  101. text (unicode): Optional additional text to print.
  102. color (unicode / int): Foreground color.
  103. icon (unicode): Name of icon to add.
  104. spaced (unicode): Whether to add newlines around the output.
  105. show (bool): Whether to print or not. Can be used to only output
  106. messages under certain condition, e.g. if --verbose flag is set.
  107. no_print (bool): Don't actually print, just return.
  108. exits (int): Perform a system exit.
  109. """
  110. if not show:
  111. return
  112. if self.pretty:
  113. color = self.colors.get(color)
  114. icon = self.icons.get(icon)
  115. if icon:
  116. title = locale_escape("{} {}".format(icon, title)).strip()
  117. if self.show_color:
  118. title = _color(title, fg=color)
  119. title = wrap(title, indent=0)
  120. if text:
  121. title = "{}\n{}".format(title, wrap(text, indent=0))
  122. if self.timestamp:
  123. now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  124. title = "{}\t{}".format(now, title)
  125. if exits is not None or spaced:
  126. title = "\n{}\n".format(title)
  127. if not self.no_print and not no_print:
  128. print(title)
  129. if exits is not None:
  130. sys.stdout.flush()
  131. sys.stderr.flush()
  132. sys.exit(exits)
  133. if self.no_print or no_print:
  134. return title
  135. def divider(self, text="", char="=", show=True, icon=None):
  136. """Print a divider with a headline:
  137. ============================ Headline here ===========================
  138. text (unicode): Headline text. If empty, only the line is printed.
  139. char (unicode): Line character to repeat, e.g. =.
  140. show (bool): Whether to print or not.
  141. icon (unicode): Optional icon to display with title.
  142. """
  143. if len(char) != 1:
  144. raise ValueError(
  145. "Divider chars need to be one character long. "
  146. "Received: {}".format(char)
  147. )
  148. if self.pretty:
  149. icon = self.icons.get(icon)
  150. if icon:
  151. text = locale_escape("{} {}".format(icon, text)).strip()
  152. deco = char * (int(round((self.line_max - len(text))) / 2) - 2)
  153. text = " {} ".format(text) if text else ""
  154. text = _color(
  155. "\n{deco}{text}{deco}".format(deco=deco, text=text), bold=True
  156. )
  157. if len(text) < self.line_max:
  158. text = text + char * (self.line_max - len(text))
  159. if self.no_print:
  160. return text
  161. print(text)
  162. def table(self, data, **kwargs):
  163. """Print data as a table.
  164. data (iterable / dict): The data to render. Either a list of lists
  165. (one per row) or a dict for two-column tables.
  166. kwargs: Table settings. See tables.table for details.
  167. """
  168. title = kwargs.pop("title", None)
  169. text = table(data, **kwargs)
  170. if title:
  171. self.divider(title)
  172. if self.no_print:
  173. return text
  174. print(text)
  175. def row(self, data, **kwargs):
  176. """Print a table row.
  177. data (iterable): The individual columns to format.
  178. kwargs: Row settings. See tables.row for details.
  179. """
  180. text = row(data, **kwargs)
  181. if self.no_print:
  182. return text
  183. print(text)
  184. @contextmanager
  185. def loading(self, text="Loading..."):
  186. if self.no_print:
  187. yield
  188. elif self.hide_animation:
  189. print(text)
  190. yield
  191. else:
  192. sys.stdout.flush()
  193. t = Process(target=self._spinner, args=(text,))
  194. t.start()
  195. try:
  196. yield
  197. except Exception as e:
  198. # Handle exception inside the with block
  199. t.terminate()
  200. sys.stdout.write("\n")
  201. raise (e)
  202. t.terminate()
  203. sys.stdout.write("\r\x1b[2K") # erase line
  204. sys.stdout.flush()
  205. def _spinner(self, text="Loading..."):
  206. for char in itertools.cycle(self.anim):
  207. sys.stdout.write("\r{} {}".format(char, text))
  208. sys.stdout.flush()
  209. time.sleep(0.1)
  210. def _get_msg(self, title, text, style=None, show=None, spaced=False, exits=None):
  211. if self.ignore_warnings and style == MESSAGES.WARN:
  212. show = False
  213. self._counts[style] += 1
  214. return self.text(
  215. title, text, color=style, icon=style, show=show, spaced=spaced, exits=exits
  216. )