File: kunit_printer.py

package info (click to toggle)
linux 6.1.8-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,488,076 kB
  • sloc: ansic: 23,401,844; asm: 266,744; sh: 108,976; makefile: 49,705; python: 36,927; perl: 36,810; cpp: 6,044; yacc: 4,904; lex: 2,722; awk: 1,440; ruby: 25; sed: 5
file content (48 lines) | stat: -rw-r--r-- 1,209 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0
#
# Utilities for printing and coloring output.
#
# Copyright (C) 2022, Google LLC.
# Author: Daniel Latypov <dlatypov@google.com>

import datetime
import sys
import typing

_RESET = '\033[0;0m'

class Printer:
	"""Wraps a file object, providing utilities for coloring output, etc."""

	def __init__(self, output: typing.IO):
		self._output = output
		self._use_color = output.isatty()

	def print(self, message: str) -> None:
		print(message, file=self._output)

	def print_with_timestamp(self, message: str) -> None:
		ts = datetime.datetime.now().strftime('%H:%M:%S')
		self.print(f'[{ts}] {message}')

	def _color(self, code: str, text: str) -> str:
		if not self._use_color:
			return text
		return code + text + _RESET

	def red(self, text: str) -> str:
		return self._color('\033[1;31m', text)

	def yellow(self, text: str) -> str:
		return self._color('\033[1;33m', text)

	def green(self, text: str) -> str:
		return self._color('\033[1;32m', text)

	def color_len(self) -> int:
		"""Returns the length of the color escape codes."""
		return len(self.red(''))

# Provides a default instance that prints to stdout
stdout = Printer(sys.stdout)