-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.py
160 lines (127 loc) · 4.06 KB
/
helpers.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
"""
Helpers
====================================
Helper classes and functions
"""
import os
import shlex
from subprocess import run
from enum import Enum
from yachalk import chalk
from rich.console import Console
from rich.table import Table
class ReturnCode(Enum):
OK = 0
class Executor:
"""
Class to execute shell commands
"""
@classmethod
def success(cls, command: str, env: dict = None) -> bool:
ret, _ = cls.__run(command, env=env)
return ret == ReturnCode.OK.value
@classmethod
def run(cls, command: str, env: dict = None) -> str:
_, output = cls.__run(command, env=env)
return cls.__handle_output(output)
@classmethod
def __run(cls, command: str, env: dict = None) -> tuple[int, str]:
"""
Runs a shell command with the default environment.
If env is given it is _UPDATED_ to the default environment.
"""
_env = os.environ.copy()
if env:
_env.update(env)
p = run(shlex.split(command), capture_output=True, env=_env)
return p.returncode, cls.__handle_output(p.stdout.decode())
@classmethod
def __handle_output(cls, output: str) -> str:
# We remove the last \n
return output.rstrip("\n")
class Message:
"""
Class to output colored messages to the console
"""
@classmethod
def info(cls, message):
print(chalk.green_bright.bold(message))
@classmethod
def warn(cls, message):
print(chalk.yellow_bright.bold(message))
@classmethod
def error(cls, message):
print(chalk.red_bright.bold(message))
@classmethod
def debug(cls, message):
print(chalk.blue_bright.bold(message))
class TableOutput:
"""
Class to output text in table format
"""
console = Console()
@classmethod
def out(
cls,
data: str | list,
sep: str = "#",
headers: tuple[str] = None,
show_lines=False,
):
table = Table(
show_header=(headers is not None), show_lines=show_lines, show_edge=False
)
if headers:
for header in headers:
table.add_column(header)
if isinstance(data, str):
data = data.split("\n")
for line in data:
if isinstance(line, str):
table.add_row(*line.split(sep))
elif isinstance(line, list):
table.add_row(*line)
cls.console.print(table)
####################
# OLD CODE
####################
# class Interactive():
# """
# Execute a command interactively with pseudo terminal
# found at https://stackoverflow.com/questions/41542960/run-interactive-bash-with-popen-and-a-dedicated-tty-python
# """
# def __init__(self, command: str = '/bin/bash', env: dict = None):
# self.command = command
# self.env = os.environ.copy()
# if env:
# self.env.update(env)
# self.process = None
# def run(self):
# old_tty = termios.tcgetattr(sys.stdin)
# tty.setraw(sys.stdin.fileno())
# master, slave = pty.openpty()
# try:
# self.process = Popen(
# shlex.split(self.command),
# preexec_fn=os.setsid,
# stdin=slave,
# stdout=slave,
# stderr=slave,
# env=self.env)
# while True:
# r, _, _ = select.select([sys.stdin, master], [], [])
# if sys.stdin in r:
# d = os.read(sys.stdin.fileno(), 10240)
# os.write(master, d)
# elif master in r:
# o = os.read(master, 10240)
# if o:
# os.write(sys.stdout.fileno(), o)
# if self.process.poll() is not None:
# sys.stdout.flush()
# break
# else:
# sleep(0.1)
# finally:
# # restore tty settings back
# termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)