kunit_printer.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 <[email protected]>
  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, output: typing.IO):
  15. self._output = output
  16. self._use_color = output.isatty()
  17. def print(self, message: str) -> None:
  18. print(message, file=self._output)
  19. def print_with_timestamp(self, message: str) -> None:
  20. ts = datetime.datetime.now().strftime('%H:%M:%S')
  21. self.print(f'[{ts}] {message}')
  22. def _color(self, code: str, text: str) -> str:
  23. if not self._use_color:
  24. return text
  25. return code + text + _RESET
  26. def red(self, text: str) -> str:
  27. return self._color('\033[1;31m', text)
  28. def yellow(self, text: str) -> str:
  29. return self._color('\033[1;33m', text)
  30. def green(self, text: str) -> str:
  31. return self._color('\033[1;32m', text)
  32. def color_len(self) -> int:
  33. """Returns the length of the color escape codes."""
  34. return len(self.red(''))
  35. # Provides a default instance that prints to stdout
  36. stdout = Printer(sys.stdout)