formatter.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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(object):
  15. """Format tabular data for printing."""
  16. def table(self, headers, rows):
  17. table = texttable.Texttable(max_width=get_tty_width())
  18. table.set_cols_dtype(['t' for h in headers])
  19. table.add_rows([headers] + rows)
  20. table.set_deco(table.HEADER)
  21. table.set_chars(['-', '|', '+', '-'])
  22. return table.draw()
  23. class ConsoleWarningFormatter(logging.Formatter):
  24. """A logging.Formatter which prints WARNING and ERROR messages with
  25. a prefix of the log level colored appropriate for the log level.
  26. """
  27. def get_level_message(self, record):
  28. separator = ': '
  29. if record.levelno == logging.WARNING:
  30. return colors.yellow(record.levelname) + separator
  31. if record.levelno == logging.ERROR:
  32. return colors.red(record.levelname) + separator
  33. return ''
  34. def format(self, record):
  35. if isinstance(record.msg, six.binary_type):
  36. record.msg = record.msg.decode('utf-8')
  37. message = super(ConsoleWarningFormatter, self).format(record)
  38. return '{0}{1}'.format(self.get_level_message(record), message)