-
Notifications
You must be signed in to change notification settings - Fork 108
/
msgs.py
68 lines (50 loc) · 1.68 KB
/
msgs.py
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#
# Copyright 2022, Proofcraft Pty Ltd
#
# SPDX-License-Identifier: BSD-2-Clause
#
"""Error, warning, and status message handling."""
import os
import sys
ANSI_RESET = "\033[0m"
ANSI_RED = "\033[31;1m"
ANSI_YELLOW = "\033[33m"
tty_status_line = [""]
def running_on_github():
"""Return True if we're running on GitHub Actions."""
return os.environ.get("GITHUB_REPOSITORY") != None
def output_color(color, s, github=running_on_github()):
"""Wrap the given string in the given colour."""
if sys.stderr.isatty() or github:
return color + s + ANSI_RESET
return s
def wipe_tty_status():
"""Clear the tty status line if it exists."""
if sys.stdout.isatty() and tty_status_line[0]:
print(" " * len(tty_status_line[0]) + "\r", end="")
sys.stdout.flush()
tty_status_line[0] = ""
def status(msg: str):
"""Print a status message to a tty status line or stdout."""
wipe_tty_status()
tty_status_line[0] = msg
end = "\r" if sys.stdout.isatty() else "\n"
print(tty_status_line[0], end=end)
sys.stdout.flush()
def pos_str(file, line):
"""Return a string indicating a file position."""
if file is None:
return ""
if line is None:
return f" [{file}]"
return f" [{file}:{line}]"
def warning(msg: str, file=None, line=None):
"""Print a warning message to stderr."""
wipe_tty_status()
w = output_color(ANSI_YELLOW, 'Warning:')
sys.stderr.write(f'{w} {msg}{pos_str(file,line)}\n')
def error(msg: str, file=None, line=None):
"""Print an error message to stderr."""
wipe_tty_status()
e = output_color(ANSI_RED, 'Fatal error:')
sys.stderr.write(f'{e} {msg}{pos_str(file,line)}\n')