formatter.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import logging
  4. import os
  5. import six
  6. import texttable
  7. from compose.cli import colors
  8. def get_tty_width():
  9. tty_size = os.popen('stty size 2> /dev/null', 'r').read().split()
  10. if len(tty_size) != 2:
  11. return 0
  12. _, width = tty_size
  13. return int(width)
  14. class Formatter:
  15. """Format tabular data for printing."""
  16. @staticmethod
  17. def table(headers, rows):
  18. table = texttable.Texttable(max_width=get_tty_width())
  19. table.set_cols_dtype(['t' for h in headers])
  20. table.add_rows([headers] + rows)
  21. table.set_deco(table.HEADER)
  22. table.set_chars(['-', '|', '+', '-'])
  23. return table.draw()
  24. class ConsoleWarningFormatter(logging.Formatter):
  25. """A logging.Formatter which prints WARNING and ERROR messages with
  26. a prefix of the log level colored appropriate for the log level.
  27. """
  28. def get_level_message(self, record):
  29. separator = ': '
  30. if record.levelno == logging.WARNING:
  31. return colors.yellow(record.levelname) + separator
  32. if record.levelno == logging.ERROR:
  33. return colors.red(record.levelname) + separator
  34. return ''
  35. def format(self, record):
  36. if isinstance(record.msg, six.binary_type):
  37. record.msg = record.msg.decode('utf-8')
  38. message = super(ConsoleWarningFormatter, self).format(record)
  39. return '{0}{1}'.format(self.get_level_message(record), message)