xulbux 1.6.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of xulbux might be problematic. Click here for more details.

xulbux/xx_console.py ADDED
@@ -0,0 +1,378 @@
1
+ """
2
+ Functions for logging and other small actions within the console:
3
+ - `Console.get_args()`
4
+ - `Console.user()`
5
+ - `Console.is_admin()`
6
+ - `Console.pause_exit()`
7
+ - `Console.cls()`
8
+ - `Console.log()`
9
+ - `Console.debug()`
10
+ - `Console.info()`
11
+ - `Console.done()`
12
+ - `Console.warn()`
13
+ - `Console.fail()`
14
+ - `Console.exit()`
15
+ - `Console.confirm()`
16
+ - `Console.restricted_input()`
17
+ - `Console.pwd_input()`\n
18
+ ------------------------------------------------------------------------------------------------------
19
+ You can also use special formatting codes directly inside the log message to change their appearance.
20
+ For more detailed information about formatting codes, see the the `xx_format_codes` description.
21
+ """
22
+
23
+ from ._consts_ import DEFAULT, CHARS
24
+ from .xx_format_codes import FormatCodes
25
+ from .xx_string import String
26
+ from .xx_color import *
27
+
28
+ from contextlib import suppress
29
+ import pyperclip as _pyperclip
30
+ import keyboard as _keyboard
31
+ import getpass as _getpass
32
+ import ctypes as _ctypes
33
+ import shutil as _shutil
34
+ import mouse as _mouse
35
+ import sys as _sys
36
+ import os as _os
37
+
38
+
39
+ class Console:
40
+
41
+ @staticmethod
42
+ def get_args(find_args: dict) -> dict[str, dict[str, any]]:
43
+ args = _sys.argv[1:]
44
+ results = {}
45
+ for arg_key, arg_group in find_args.items():
46
+ value = None
47
+ exists = False
48
+ for arg in arg_group:
49
+ if arg in args:
50
+ exists = True
51
+ arg_index = args.index(arg)
52
+ if arg_index + 1 < len(args) and not args[arg_index + 1].startswith("-"):
53
+ value = String.to_type(args[arg_index + 1])
54
+ break
55
+ results[arg_key] = {"exists": exists, "value": value}
56
+ return results
57
+
58
+ def w() -> int:
59
+ return getattr(_shutil.get_terminal_size(), "columns", 80)
60
+
61
+ def h() -> int:
62
+ return getattr(_shutil.get_terminal_size(), "lines", 24)
63
+
64
+ def wh() -> tuple[int, int]:
65
+ return Console.w(), Console.h()
66
+
67
+ def user() -> str:
68
+ return _os.getenv("USER") or _os.getenv("USERNAME") or _getpass.getuser()
69
+
70
+ def is_admin() -> bool:
71
+ try:
72
+ if _os.name == "nt":
73
+ return _ctypes.windll.shell32.IsUserAnAdmin() != 0
74
+ elif _os.name == "posix":
75
+ return _os.geteuid() == 0
76
+ else:
77
+ return False
78
+ except Exception:
79
+ return False
80
+
81
+ @staticmethod
82
+ def pause_exit(
83
+ pause: bool = False,
84
+ exit: bool = False,
85
+ prompt: object = "",
86
+ exit_code: int = 0,
87
+ reset_ansi: bool = False,
88
+ ) -> None:
89
+ """Will print the `last_prompt` and then pause the program if `pause` is set
90
+ to `True` and after the pause, exit the program if `exit` is set to `True`."""
91
+ print(prompt, end="", flush=True)
92
+ if reset_ansi:
93
+ FormatCodes.print("[_]", end="")
94
+ if pause:
95
+ _keyboard.read_event()
96
+ if exit:
97
+ _sys.exit(exit_code)
98
+
99
+ def cls() -> None:
100
+ """Will clear the console in addition to completely resetting the ANSI formats."""
101
+ if _shutil.which("cls"):
102
+ _os.system("cls")
103
+ elif _shutil.which("clear"):
104
+ _os.system("clear")
105
+ print("\033[0m", end="", flush=True)
106
+
107
+ @staticmethod
108
+ def log(
109
+ title: str,
110
+ prompt: object = "",
111
+ start: str = "",
112
+ end: str = "\n",
113
+ title_bg_color: hexa | rgba = None,
114
+ default_color: hexa | rgba = None,
115
+ ) -> None:
116
+ """Will print a formatted log message:
117
+ - `title` -⠀the title of the log message (e.g. `DEBUG`, `WARN`, `FAIL`, etc.)
118
+ - `prompt` -⠀the log message
119
+ - `start` -⠀something to print before the log is printed
120
+ - `end` -⠀something to print after the log is printed (e.g. `\\n\\n`)
121
+ - `title_bg_color` -⠀the background color of the `title`
122
+ - `default_color` -⠀the default text color of the `prompt`\n
123
+ --------------------------------------------------------------------------------
124
+ The log message supports special formatting codes. For more detailed
125
+ information about formatting codes, see `xx_format_codes` class description."""
126
+ title_color = "_color" if not title_bg_color else Color.text_color_for_on_bg(title_bg_color)
127
+ if title:
128
+ FormatCodes.print(
129
+ f'{start} [bold][{title_color}]{f"[BG:{title_bg_color}]" if title_bg_color else ""} {title.upper()}: [_]\t{f"[{default_color}]" if default_color else ""}{str(prompt)}[_]',
130
+ default_color=default_color,
131
+ end=end,
132
+ )
133
+ else:
134
+ FormatCodes.print(
135
+ f'{start} {f"[{default_color}]" if default_color else ""}{str(prompt)}[_]',
136
+ default_color=default_color,
137
+ end=end,
138
+ )
139
+
140
+ @staticmethod
141
+ def debug(
142
+ prompt: object = "Point in program reached.",
143
+ active: bool = True,
144
+ start: str = "\n",
145
+ end: str = "\n\n",
146
+ title_bg_color: hexa | rgba = DEFAULT.color["yellow"],
147
+ default_color: hexa | rgba = DEFAULT.text_color,
148
+ pause: bool = False,
149
+ exit: bool = False,
150
+ ) -> None:
151
+ """A preset for `log()`: `DEBUG` log message with the options to pause
152
+ at the message and exit the program after the message was printed."""
153
+ if active:
154
+ Console.log("DEBUG", prompt, start, end, title_bg_color, default_color)
155
+ Console.pause_exit(pause, exit)
156
+
157
+ @staticmethod
158
+ def info(
159
+ prompt: object = "Program running.",
160
+ start: str = "\n",
161
+ end: str = "\n\n",
162
+ title_bg_color: hexa | rgba = DEFAULT.color["blue"],
163
+ default_color: hexa | rgba = DEFAULT.text_color,
164
+ pause: bool = False,
165
+ exit: bool = False,
166
+ ) -> None:
167
+ """A preset for `log()`: `INFO` log message with the options to pause
168
+ at the message and exit the program after the message was printed."""
169
+ Console.log("INFO", prompt, start, end, title_bg_color, default_color)
170
+ Console.pause_exit(pause, exit)
171
+
172
+ @staticmethod
173
+ def done(
174
+ prompt: object = "Program finished.",
175
+ start: str = "\n",
176
+ end: str = "\n\n",
177
+ title_bg_color: hexa | rgba = DEFAULT.color["teal"],
178
+ default_color: hexa | rgba = DEFAULT.text_color,
179
+ pause: bool = False,
180
+ exit: bool = False,
181
+ ) -> None:
182
+ """A preset for `log()`: `DONE` log message with the options to pause
183
+ at the message and exit the program after the message was printed."""
184
+ Console.log("DONE", prompt, start, end, title_bg_color, default_color)
185
+ Console.pause_exit(pause, exit)
186
+
187
+ @staticmethod
188
+ def warn(
189
+ prompt: object = "Important message.",
190
+ start: str = "\n",
191
+ end: str = "\n\n",
192
+ title_bg_color: hexa | rgba = DEFAULT.color["orange"],
193
+ default_color: hexa | rgba = DEFAULT.text_color,
194
+ pause: bool = False,
195
+ exit: bool = False,
196
+ ) -> None:
197
+ """A preset for `log()`: `WARN` log message with the options to pause
198
+ at the message and exit the program after the message was printed."""
199
+ Console.log("WARN", prompt, start, end, title_bg_color, default_color)
200
+ Console.pause_exit(pause, exit)
201
+
202
+ @staticmethod
203
+ def fail(
204
+ prompt: object = "Program error.",
205
+ start: str = "\n",
206
+ end: str = "\n\n",
207
+ title_bg_color: hexa | rgba = DEFAULT.color["red"],
208
+ default_color: hexa | rgba = DEFAULT.text_color,
209
+ pause: bool = False,
210
+ exit: bool = True,
211
+ reset_ansi=True,
212
+ ) -> None:
213
+ """A preset for `log()`: `FAIL` log message with the options to pause
214
+ at the message and exit the program after the message was printed."""
215
+ Console.log("FAIL", prompt, start, end, title_bg_color, default_color)
216
+ Console.pause_exit(pause, exit, reset_ansi=reset_ansi)
217
+
218
+ @staticmethod
219
+ def exit(
220
+ prompt: object = "Program ended.",
221
+ start: str = "\n",
222
+ end: str = "\n\n",
223
+ title_bg_color: hexa | rgba = DEFAULT.color["magenta"],
224
+ default_color: hexa | rgba = DEFAULT.text_color,
225
+ pause: bool = False,
226
+ exit: bool = True,
227
+ reset_ansi=True,
228
+ ) -> None:
229
+ """A preset for `log()`: `EXIT` log message with the options to pause
230
+ at the message and exit the program after the message was printed."""
231
+ Console.log("EXIT", prompt, start, end, title_bg_color, default_color)
232
+ Console.pause_exit(pause, exit, reset_ansi=reset_ansi)
233
+
234
+ @staticmethod
235
+ def confirm(
236
+ prompt: object = "Do you want to continue?",
237
+ start="\n",
238
+ end="\n",
239
+ default_color: hexa | rgba = DEFAULT.color["cyan"],
240
+ default_is_yes: bool = True,
241
+ ) -> bool:
242
+ """Ask a yes/no question.\n
243
+ -------------------------------------------------------------------------------
244
+ The question can be formatted with special formatting codes. For more detailed
245
+ information about formatting codes, see the `xx_format_codes` description."""
246
+ confirmed = input(
247
+ FormatCodes.to_ansi(
248
+ f'{start} {str(prompt)} [_|dim](({"Y" if default_is_yes else "y"}/{"n" if default_is_yes else "N"}): )',
249
+ default_color,
250
+ )
251
+ ).strip().lower() in (("", "y", "yes") if default_is_yes else ("y", "yes"))
252
+ if end:
253
+ Console.log("", end, end="")
254
+ return confirmed
255
+
256
+ @staticmethod
257
+ def restricted_input(
258
+ prompt: object = "",
259
+ allowed_chars: str = CHARS.all,
260
+ min_len: int = None,
261
+ max_len: int = None,
262
+ mask_char: str = None,
263
+ reset_ansi: bool = True,
264
+ ) -> str | None:
265
+ """Acts like a standard Python `input()` with the advantage, that you can specify:
266
+ - what text characters the user is allowed to type and
267
+ - the minimum and/or maximum length of the users input
268
+ - optional mask character (hide user input, e.g. for passwords)
269
+ - reset the ANSI formatting codes after the user continues\n
270
+ -----------------------------------------------------------------------------------
271
+ The input can be formatted with special formatting codes. For more detailed
272
+ information about formatting codes, see the `xx_format_codes` description."""
273
+ FormatCodes.print(prompt, end="", flush=True)
274
+ result = ""
275
+ select_all = False
276
+ last_line_count = 1
277
+ last_console_width = 0
278
+
279
+ def update_display(console_width: int) -> None:
280
+ nonlocal select_all, last_line_count, last_console_width
281
+ lines = String.split_count(
282
+ str(prompt) + (mask_char * len(result) if mask_char else result),
283
+ console_width,
284
+ )
285
+ line_count = len(lines)
286
+ if (line_count > 1 or line_count < last_line_count) and not last_line_count == 1:
287
+ if last_console_width > console_width:
288
+ line_count *= 2
289
+ for _ in range(
290
+ line_count
291
+ if line_count < last_line_count and not line_count > last_line_count
292
+ else (line_count - 2 if line_count > last_line_count else line_count - 1)
293
+ ):
294
+ _sys.stdout.write("\033[2K\r\033[A")
295
+ prompt_len = len(str(prompt)) if prompt else 0
296
+ prompt_str, input_str = lines[0][:prompt_len], (
297
+ lines[0][prompt_len:] if len(lines) == 1 else "\n".join([lines[0][prompt_len:]] + lines[1:])
298
+ ) # SEPARATE THE PROMPT AND THE INPUT
299
+ _sys.stdout.write(
300
+ "\033[2K\r" + FormatCodes.to_ansi(prompt_str) + ("\033[7m" if select_all else "") + input_str + "\033[27m"
301
+ )
302
+ last_line_count, last_console_width = line_count, console_width
303
+
304
+ def handle_enter():
305
+ if min_len is not None and len(result) < min_len:
306
+ return False
307
+ FormatCodes.print("[_]" if reset_ansi else "", flush=True)
308
+ return True
309
+
310
+ def handle_backspace_delete():
311
+ nonlocal result, select_all
312
+ if select_all:
313
+ result, select_all = "", False
314
+ elif result and event.name == "backspace":
315
+ result = result[:-1]
316
+ update_display(Console.w())
317
+
318
+ def handle_paste():
319
+ nonlocal result, select_all
320
+ if select_all:
321
+ result, select_all = "", False
322
+ filtered_text = "".join(char for char in _pyperclip.paste() if allowed_chars == CHARS.all or char in allowed_chars)
323
+ if max_len is None or len(result) + len(filtered_text) <= max_len:
324
+ result += filtered_text
325
+ update_display(Console.w())
326
+
327
+ def handle_select_all():
328
+ nonlocal select_all
329
+ select_all = True
330
+ update_display(Console.w())
331
+
332
+ def handle_copy():
333
+ nonlocal select_all
334
+ with suppress(KeyboardInterrupt):
335
+ select_all = False
336
+ update_display(Console.w())
337
+ _pyperclip.copy(result)
338
+
339
+ def handle_character_input():
340
+ nonlocal result
341
+ if (allowed_chars == CHARS.all or event.name in allowed_chars) and (max_len is None or len(result) < max_len):
342
+ result += event.name
343
+ update_display(Console.w())
344
+
345
+ while True:
346
+ event = _keyboard.read_event()
347
+ if event.event_type == "down":
348
+ if event.name == "enter" and handle_enter():
349
+ return result.rstrip("\n")
350
+ elif event.name in ("backspace", "delete", "entf"):
351
+ handle_backspace_delete()
352
+ elif (event.name == "v" and _keyboard.is_pressed("ctrl")) or _mouse.is_pressed("right"):
353
+ handle_paste()
354
+ elif event.name == "a" and _keyboard.is_pressed("ctrl"):
355
+ handle_select_all()
356
+ elif event.name == "c" and _keyboard.is_pressed("ctrl") and select_all:
357
+ handle_copy()
358
+ elif event.name == "esc":
359
+ return None
360
+ elif event.name == "space":
361
+ handle_character_input()
362
+ elif len(event.name) == 1:
363
+ handle_character_input()
364
+ else:
365
+ select_all = False
366
+ update_display(Console.w())
367
+
368
+ @staticmethod
369
+ def pwd_input(
370
+ prompt: object = "Password: ",
371
+ allowed_chars: str = CHARS.standard_ascii,
372
+ min_len: int = None,
373
+ max_len: int = None,
374
+ _reset_ansi: bool = True,
375
+ ) -> str:
376
+ """Password input (preset for `Console.restricted_input()`)
377
+ that always masks the entered characters with asterisks."""
378
+ return Console.restricted_input(prompt, allowed_chars, min_len, max_len, "*", _reset_ansi)