kunit_printer.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0
  3. #
  4. # Utilities for printing and coloring output.
  5. #
  6. # Copyright (C) 2022, Google LLC.
  7. # Author: Daniel Latypov <dlatypov@google.com>
  8. import datetime
  9. import sys
  10. import typing
  11. _RESET = '\033[0;0m'
  12. class Printer:
  13. """Wraps a file object, providing utilities for coloring output, etc."""
  14. def __init__(self, print: bool=True, output: typing.IO[str]=sys.stdout):
  15. self._output = output
  16. self._print = print
  17. if print:
  18. self._use_color = output.isatty()
  19. else:
  20. self._use_color = False
  21. def print(self, message: str) -> None:
  22. if self._print:
  23. print(message, file=self._output)
  24. def print_with_timestamp(self, message: str) -> None:
  25. ts = datetime.datetime.now().strftime('%H:%M:%S')
  26. self.print(f'[{ts}] {message}')
  27. def _color(self, code: str, text: str) -> str:
  28. if not self._use_color:
  29. return text
  30. return code + text + _RESET
  31. def red(self, text: str) -> str:
  32. return self._color('\033[1;31m', text)
  33. def yellow(self, text: str) -> str:
  34. return self._color('\033[1;33m', text)
  35. def green(self, text: str) -> str:
  36. return self._color('\033[1;32m', text)
  37. def color_len(self) -> int:
  38. """Returns the length of the color escape codes."""
  39. return len(self.red(''))
  40. # Provides a default instance that prints to stdout
  41. stdout = Printer()
  42. null_printer = Printer(print=False)