formatter.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import logging
  2. from shutil import get_terminal_size
  3. import texttable
  4. from compose.cli import colors
  5. def get_tty_width():
  6. try:
  7. # get_terminal_size can't determine the size if compose is piped
  8. # to another command. But in such case it doesn't make sense to
  9. # try format the output by terminal size as this output is consumed
  10. # by another command. So let's pretend we have a huge terminal so
  11. # output is single-lined
  12. width, _ = get_terminal_size(fallback=(999, 0))
  13. return int(width)
  14. except OSError:
  15. return 0
  16. class Formatter:
  17. """Format tabular data for printing."""
  18. @staticmethod
  19. def table(headers, rows):
  20. table = texttable.Texttable(max_width=get_tty_width())
  21. table.set_cols_dtype(['t' for h in headers])
  22. table.add_rows([headers] + rows)
  23. table.set_deco(table.HEADER)
  24. table.set_chars(['-', '|', '+', '-'])
  25. return table.draw()
  26. class ConsoleWarningFormatter(logging.Formatter):
  27. """A logging.Formatter which prints WARNING and ERROR messages with
  28. a prefix of the log level colored appropriate for the log level.
  29. """
  30. def get_level_message(self, record):
  31. separator = ': '
  32. if record.levelno >= logging.ERROR:
  33. return colors.red(record.levelname) + separator
  34. if record.levelno >= logging.WARNING:
  35. return colors.yellow(record.levelname) + separator
  36. return ''
  37. def format(self, record):
  38. if isinstance(record.msg, bytes):
  39. record.msg = record.msg.decode('utf-8')
  40. message = super().format(record)
  41. return '{}{}'.format(self.get_level_message(record), message)