forked from FaithLife-Community/LogosLinuxInstaller
-
Notifications
You must be signed in to change notification settings - Fork 0
/
msg.py
291 lines (239 loc) · 8.36 KB
/
msg.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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import gzip
import logging
from logging.handlers import RotatingFileHandler
import os
import signal
import shutil
import sys
import time
from pathlib import Path
import config
from gui import ask_question
from gui import show_error
logging.console_log = []
class GzippedRotatingFileHandler(RotatingFileHandler):
def doRollover(self):
super().doRollover()
if self.backupCount > 0:
for i in range(self.backupCount - 1, 0, -1):
source = f"{self.baseFilename}.{i}.gz"
destination = f"{self.baseFilename}.{i + 1}.gz"
if os.path.exists(source):
if os.path.exists(destination):
os.remove(destination)
os.rename(source, destination)
last_log = self.baseFilename + ".1"
gz_last_log = self.baseFilename + ".1.gz"
if os.path.exists(last_log) and os.path.getsize(last_log) > 0:
with open(last_log, 'rb') as f_in:
with gzip.open(gz_last_log, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
os.remove(last_log)
def get_log_level_name(level):
name = None
levels = {
"CRITICAL": logging.CRITICAL,
"ERROR": logging.ERROR,
"WARNING": logging.WARNING,
"INFO": logging.INFO,
"DEBUG": logging.DEBUG,
}
for k, v in levels.items():
if level == v:
name = k
break
return name
def initialize_logging(stderr_log_level):
'''
Log levels:
Level Value Description
CRITICAL 50 the program can't continue
ERROR 40 the program has not been able to do something
WARNING 30 something unexpected happened (maybe neg. effect)
INFO 20 confirmation that things are working as expected
DEBUG 10 detailed, dev-level information
NOTSET 0 all events are handled
'''
# Ensure log file parent folders exist.
log_parent = Path(config.LOGOS_LOG).parent
if not log_parent.is_dir():
log_parent.mkdir(parents=True)
# Define logging handlers.
file_h = GzippedRotatingFileHandler(config.LOGOS_LOG, maxBytes=10*1024*1024, backupCount=5, encoding='UTF8')
file_h.name = "logfile"
file_h.setLevel(logging.DEBUG)
# stdout_h = logging.StreamHandler(sys.stdout)
# stdout_h.setLevel(stdout_log_level)
stderr_h = logging.StreamHandler(sys.stderr)
stderr_h.name = "terminal"
stderr_h.setLevel(stderr_log_level)
handlers = [
file_h,
# stdout_h,
stderr_h,
]
# Set initial config.
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
handlers=handlers,
)
def initialize_curses_logging():
current_logger = logging.getLogger()
for h in current_logger.handlers:
if h.name == 'terminal':
break
def update_log_level(new_level):
# Update logging level from config.
for h in logging.getLogger().handlers:
if type(h) is logging.StreamHandler:
h.setLevel(new_level)
logging.info(f"Terminal log level set to {get_log_level_name(new_level)}")
def cli_msg(message, end='\n'):
'''Prints message to stdout regardless of log level.'''
print(message, end=end)
def logos_msg(message, end='\n'):
if config.DIALOG == 'curses':
pass
else:
cli_msg(message, end)
def logos_progress():
if config.DIALOG == 'curses':
pass
else:
sys.stdout.write('.')
sys.stdout.flush()
# i = 0
# spinner = "|/-\\"
# sys.stdout.write(f"\r{text} {spinner[i]}")
# sys.stdout.flush()
# i = (i + 1) % len(spinner)
# time.sleep(0.1)
def logos_warn(message):
if config.DIALOG == 'curses':
logging.warning(message)
else:
logos_msg(message)
# TODO: I think detail is doing the same thing as secondary.
def logos_error(message, secondary=None, detail=None, app=None, parent=None):
if detail is None:
detail = ''
logging.critical(message)
WIKI_LINK = "https://github.com/FaithLife-Community/LogosLinuxInstaller/wiki" # noqa: E501
TELEGRAM_LINK = "https://t.me/linux_logos"
MATRIX_LINK = "https://matrix.to/#/#logosbible:matrix.org"
help_message = f"If you need help, please consult:\n{WIKI_LINK}\n{TELEGRAM_LINK}\n{MATRIX_LINK}" # noqa: E501
if config.DIALOG == 'tk':
show_error(
message,
detail=f"{detail}\n\n{help_message}",
app=app,
parent=parent
)
elif config.DIALOG == 'curses':
if secondary != "info":
status(message)
status(help_message)
else:
logos_msg(message)
else:
logos_msg(message)
if secondary is None or secondary == "":
try:
os.remove("/tmp/LogosLinuxInstaller.pid")
except FileNotFoundError: # no pid file when testing functions
pass
os.kill(os.getpgid(os.getpid()), signal.SIGKILL)
if hasattr(app, 'destroy'):
app.destroy()
sys.exit(1)
def cli_question(question_text, secondary):
while True:
try:
cli_msg(secondary)
yn = input(f"{question_text} [Y/n]: ")
except KeyboardInterrupt:
print()
logos_error("Cancelled with Ctrl+C")
if yn.lower() == 'y' or yn == '': # defaults to "Yes"
return True
elif yn.lower() == 'n':
return False
else:
logos_msg("Type Y[es] or N[o].")
def cli_continue_question(question_text, no_text, secondary):
if not cli_question(question_text, secondary):
logos_error(no_text)
def gui_continue_question(question_text, no_text, secondary):
if ask_question(question_text, secondary) == 'no':
logos_error(no_text)
def cli_acknowledge_question(QUESTION_TEXT, NO_TEXT):
if not cli_question(QUESTION_TEXT):
logos_msg(NO_TEXT)
return False
else:
return True
def cli_ask_filepath(question_text):
try:
answer = input(f"{question_text} ")
except KeyboardInterrupt:
print()
logos_error("Cancelled with Ctrl+C")
return answer.strip('"').strip("'")
def logos_continue_question(question_text, no_text, secondary, app=None):
if config.DIALOG == 'tk':
gui_continue_question(question_text, no_text, secondary)
elif app is None:
cli_continue_question(question_text, no_text, secondary)
elif config.DIALOG == 'curses':
app.screen_q.put(
app.stack_confirm(
16,
app.confirm_q,
app.confirm_e,
question_text,
no_text,
secondary,
dialog=config.use_python_dialog
)
)
else:
logos_error(f"Unhandled question: {question_text}")
def logos_acknowledge_question(QUESTION_TEXT, NO_TEXT):
if config.DIALOG == 'curses':
pass
else:
return cli_acknowledge_question(QUESTION_TEXT, NO_TEXT)
def get_progress_str(percent):
length = 40
part_done = round(percent * length / 100)
part_left = length - part_done
return f"[{'*' * part_done}{'-' * part_left}]"
def progress(percent, app=None):
"""Updates progressbar values for TUI and GUI."""
if config.DIALOG == 'tk' and app:
app.progress_q.put(percent)
app.root.event_generate('<<UpdateProgress>>')
logging.info(f"Progress: {percent}%")
elif config.DIALOG == 'curses':
if app:
status(f"Progress: {percent}%", app)
else:
status(f"Progress: {get_progress_str(percent)}", app)
else:
logos_msg(get_progress_str(percent)) # provisional
def status(text, app=None):
timestamp = time.strftime("%Y-%m-%dT%H:%M:%S")
"""Handles status messages for both TUI and GUI."""
if app is not None:
if config.DIALOG == 'tk':
app.status_q.put(text)
app.root.event_generate('<<UpdateStatus>>')
elif config.DIALOG == 'curses':
app.status_q.put(f"{timestamp} {text}")
app.report_waiting(f"{app.status_q.get()}", dialog=config.use_python_dialog) # noqa: E501
logging.info(f"{text}")
else:
'''Prints message to stdout regardless of log level.'''
logos_msg(text)