xulbux 1.6.6__py3-none-any.whl → 1.6.7__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/__init__.py +1 -1
- xulbux/_consts_.py +31 -8
- xulbux/xx_console.py +86 -39
- xulbux/xx_data.py +13 -16
- xulbux/xx_env_path.py +2 -2
- xulbux/xx_file.py +10 -4
- xulbux/xx_path.py +30 -20
- xulbux/xx_system.py +11 -6
- {xulbux-1.6.6.dist-info → xulbux-1.6.7.dist-info}/METADATA +90 -13
- xulbux-1.6.7.dist-info/RECORD +21 -0
- {xulbux-1.6.6.dist-info → xulbux-1.6.7.dist-info}/WHEEL +1 -1
- xulbux-1.6.6.dist-info/RECORD +0 -21
- {xulbux-1.6.6.dist-info → xulbux-1.6.7.dist-info}/LICENSE +0 -0
- {xulbux-1.6.6.dist-info → xulbux-1.6.7.dist-info}/entry_points.txt +0 -0
- {xulbux-1.6.6.dist-info → xulbux-1.6.7.dist-info}/top_level.txt +0 -0
xulbux/__init__.py
CHANGED
xulbux/_consts_.py
CHANGED
|
@@ -3,13 +3,16 @@ from typing import TypeAlias
|
|
|
3
3
|
|
|
4
4
|
|
|
5
5
|
FormattableString: TypeAlias = str
|
|
6
|
+
"""A `str` object that is made to be formatted with the `.format()` method."""
|
|
6
7
|
|
|
7
8
|
|
|
8
9
|
@dataclass
|
|
9
10
|
class COLOR:
|
|
10
|
-
"""Color presets used in the
|
|
11
|
+
"""Color presets used in the `xulbux` library."""
|
|
11
12
|
|
|
12
13
|
text = "#A5D6FF"
|
|
14
|
+
"""The default text color used in the `xulbux` library."""
|
|
15
|
+
|
|
13
16
|
white = "#F1F2FF"
|
|
14
17
|
lightgray = "#B6B7C0"
|
|
15
18
|
gray = "#7B7C8D"
|
|
@@ -21,6 +24,7 @@ class COLOR:
|
|
|
21
24
|
tangerine = "#FF9962"
|
|
22
25
|
gold = "#FFAF60"
|
|
23
26
|
yellow = "#FFD260"
|
|
27
|
+
lime = "#C9F16E"
|
|
24
28
|
green = "#7EE787"
|
|
25
29
|
teal = "#50EAAF"
|
|
26
30
|
cyan = "#3EDEE6"
|
|
@@ -40,50 +44,67 @@ class _AllTextCharacters:
|
|
|
40
44
|
|
|
41
45
|
@dataclass
|
|
42
46
|
class CHARS:
|
|
43
|
-
"""
|
|
47
|
+
"""Text character sets."""
|
|
44
48
|
|
|
45
|
-
# CODE TO SIGNAL, ALL CHARACTERS ARE ALLOWED
|
|
46
49
|
all = _AllTextCharacters
|
|
50
|
+
"""Code to signal that all characters are allowed."""
|
|
47
51
|
|
|
48
|
-
# DIGIT SETS
|
|
49
52
|
digits: str = "0123456789"
|
|
53
|
+
"""Digits: `0`-`9`"""
|
|
50
54
|
float_digits: str = digits + "."
|
|
55
|
+
"""Digits: `0`-`9` with decimal point `.`"""
|
|
51
56
|
hex_digits: str = digits + "#abcdefABCDEF"
|
|
57
|
+
"""Digits: `0`-`9` Letters: `a`-`f` `A`-`F` and a hashtag `#`"""
|
|
52
58
|
|
|
53
|
-
# LETTER CATEGORIES
|
|
54
59
|
lowercase: str = "abcdefghijklmnopqrstuvwxyz"
|
|
60
|
+
"""Lowercase letters `a`-`z`"""
|
|
55
61
|
lowercase_extended: str = lowercase + "äëïöüÿàèìòùáéíóúýâêîôûãñõåæç"
|
|
62
|
+
"""Lowercase letters `a`-`z` with all lowercase diacritic letters."""
|
|
56
63
|
uppercase: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
64
|
+
"""Uppercase letters `A`-`Z`"""
|
|
57
65
|
uppercase_extended: str = uppercase + "ÄËÏÖÜÀÈÌÒÙÁÉÍÓÚÝÂÊÎÔÛÃÑÕÅÆÇß"
|
|
66
|
+
"""Uppercase letters `A`-`Z` with all uppercase diacritic letters."""
|
|
58
67
|
|
|
59
|
-
# COMBINED LETTER SETS
|
|
60
68
|
letters: str = lowercase + uppercase
|
|
69
|
+
"""Lowercase and uppercase letters `a`-`z` and `A`-`Z`"""
|
|
61
70
|
letters_extended: str = lowercase_extended + uppercase_extended
|
|
71
|
+
"""Lowercase and uppercase letters `a`-`z` `A`-`Z` and all diacritic letters."""
|
|
62
72
|
|
|
63
|
-
# ASCII sets
|
|
64
73
|
special_ascii: str = " !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
|
|
74
|
+
"""All ASCII special characters."""
|
|
65
75
|
special_ascii_extended: str = special_ascii + "ø£Ø×ƒªº¿®¬½¼¡«»░▒▓│┤©╣║╗╝¢¥┐└┴┬├─┼╚╔╩╦╠═╬¤ðÐı┘┌█▄¦▀µþÞ¯´≡±‗¾¶§÷¸°¨·¹³²■ "
|
|
76
|
+
"""All ASCII special characters with the extended ASCII special characters."""
|
|
66
77
|
standard_ascii: str = special_ascii + digits + letters
|
|
78
|
+
"""All standard ASCII characters."""
|
|
67
79
|
full_ascii: str = special_ascii_extended + digits + letters_extended
|
|
80
|
+
"""All characters in the ASCII table."""
|
|
68
81
|
|
|
69
82
|
|
|
70
83
|
class ANSI:
|
|
71
84
|
"""Constants and class-methods for use of ANSI escape codes."""
|
|
72
85
|
|
|
73
86
|
escaped_char: str = "\\x1b"
|
|
87
|
+
"""The printable ANSI escape character."""
|
|
74
88
|
CHAR = char = "\x1b"
|
|
89
|
+
"""The ANSI escape character."""
|
|
75
90
|
START = start = "["
|
|
91
|
+
"""The start of an ANSI escape sequence."""
|
|
76
92
|
SEP = sep = ";"
|
|
93
|
+
"""The separator between ANSI escape sequence parts."""
|
|
77
94
|
END = end = "m"
|
|
95
|
+
"""The end of an ANSI escape sequence."""
|
|
78
96
|
default_color_modifiers: dict[str, str] = {"lighten": "+l", "darken": "-d"}
|
|
97
|
+
"""Characters to modify the lightness of the default color with."""
|
|
79
98
|
|
|
80
99
|
@classmethod
|
|
81
|
-
def seq(cls, parts: int = 1) ->
|
|
100
|
+
def seq(cls, parts: int = 1) -> FormattableString:
|
|
82
101
|
"""Generate an ANSI sequence with `parts` amount of placeholders."""
|
|
83
102
|
return cls.CHAR + cls.START + cls.SEP.join(["{}" for _ in range(parts)]) + cls.END
|
|
84
103
|
|
|
85
104
|
seq_color: FormattableString = CHAR + START + "38" + SEP + "2" + SEP + "{}" + SEP + "{}" + SEP + "{}" + END
|
|
105
|
+
"""The ANSI escape sequence for setting the text RGB color."""
|
|
86
106
|
seq_bg_color: FormattableString = CHAR + START + "48" + SEP + "2" + SEP + "{}" + SEP + "{}" + SEP + "{}" + END
|
|
107
|
+
"""The ANSI escape sequence for setting the background RGB color."""
|
|
87
108
|
|
|
88
109
|
color_map: list[str] = [
|
|
89
110
|
########### DEFAULT CONSOLE COLOR NAMES ############
|
|
@@ -96,6 +117,7 @@ class ANSI:
|
|
|
96
117
|
"cyan",
|
|
97
118
|
"white",
|
|
98
119
|
]
|
|
120
|
+
"""The console default color names."""
|
|
99
121
|
|
|
100
122
|
codes_map: dict[str | tuple[str, ...], int] = {
|
|
101
123
|
################# SPECIFIC RESETS ##################
|
|
@@ -156,3 +178,4 @@ class ANSI:
|
|
|
156
178
|
"bg:br:cyan": 106,
|
|
157
179
|
"bg:br:white": 107,
|
|
158
180
|
}
|
|
181
|
+
"""All custom format keys and their corresponding ANSI format number codes."""
|
xulbux/xx_console.py
CHANGED
|
@@ -39,18 +39,64 @@ class _ConsoleSize:
|
|
|
39
39
|
class _ConsoleUser:
|
|
40
40
|
def __get__(self, obj, owner=None):
|
|
41
41
|
return _os.getenv("USER") or _os.getenv("USERNAME") or _getpass.getuser()
|
|
42
|
+
|
|
43
|
+
class ArgResult:
|
|
44
|
+
"""Exists: if the argument was found or not\n
|
|
45
|
+
Value: the value from behind the found argument"""
|
|
46
|
+
def __init__(self, exists: bool, value: any):
|
|
47
|
+
self.exists = exists
|
|
48
|
+
self.value = value
|
|
49
|
+
|
|
50
|
+
class Args:
|
|
51
|
+
"""Stores arguments under their aliases with their results."""
|
|
52
|
+
def __init__(self, **kwargs):
|
|
53
|
+
for key, value in kwargs.items():
|
|
54
|
+
if not key.isidentifier():
|
|
55
|
+
raise TypeError(f"Argument alias '{key}' is invalid. It must be a valid Python variable name.")
|
|
56
|
+
setattr(self, key, ArgResult(**value))
|
|
42
57
|
# YAPF: enable
|
|
43
58
|
|
|
44
59
|
|
|
45
60
|
class Console:
|
|
46
61
|
|
|
47
62
|
w: int = _ConsoleWidth()
|
|
63
|
+
"""The width of the console in characters."""
|
|
48
64
|
h: int = _ConsoleHeight()
|
|
65
|
+
"""The height of the console in lines."""
|
|
49
66
|
wh: tuple[int, int] = _ConsoleSize()
|
|
67
|
+
"""A tuple with the width and height of
|
|
68
|
+
the console in characters and lines."""
|
|
50
69
|
usr: str = _ConsoleUser()
|
|
70
|
+
"""The name of the current user."""
|
|
51
71
|
|
|
52
72
|
@staticmethod
|
|
53
|
-
def get_args(find_args: dict
|
|
73
|
+
def get_args(find_args: dict[str, list[str] | tuple[str, ...]]) -> Args:
|
|
74
|
+
"""Will search for the specified arguments in the command line
|
|
75
|
+
arguments and return the results as a special `Args` object.\n
|
|
76
|
+
----------------------------------------------------------------
|
|
77
|
+
The `find_args` dictionary should have the following structure:
|
|
78
|
+
```python
|
|
79
|
+
find_args={
|
|
80
|
+
"arg1_alias": ["-a1", "--arg1", "--argument-1"],
|
|
81
|
+
"arg2_alias": ("-a2", "--arg2", "--argument-2"),
|
|
82
|
+
...
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
And if the script is called via the command line:\n
|
|
86
|
+
`python script.py -a1 "argument value" --arg2`\n
|
|
87
|
+
...it would return the following `Args` object:
|
|
88
|
+
```python
|
|
89
|
+
Args(
|
|
90
|
+
arg1_alias=ArgResult(exists=True, value="argument value"),
|
|
91
|
+
arg2_alias=ArgResult(exists=True, value=None),
|
|
92
|
+
...
|
|
93
|
+
)
|
|
94
|
+
```
|
|
95
|
+
...which can be accessed like this:\n
|
|
96
|
+
- `Args.<arg_alias>.exists` is `True` if any of the specified
|
|
97
|
+
args were found and `False` if not
|
|
98
|
+
- `Args.<arg_alias>.value` the value from behind the found arg,
|
|
99
|
+
`None` if no value was found"""
|
|
54
100
|
args = _sys.argv[1:]
|
|
55
101
|
results = {}
|
|
56
102
|
for arg_key, arg_group in find_args.items():
|
|
@@ -64,7 +110,7 @@ class Console:
|
|
|
64
110
|
value = String.to_type(args[arg_index + 1])
|
|
65
111
|
break
|
|
66
112
|
results[arg_key] = {"exists": exists, "value": value}
|
|
67
|
-
return results
|
|
113
|
+
return Args(**results)
|
|
68
114
|
|
|
69
115
|
@staticmethod
|
|
70
116
|
def pause_exit(
|
|
@@ -111,7 +157,8 @@ class Console:
|
|
|
111
157
|
- `start` -⠀something to print before the log is printed
|
|
112
158
|
- `end` -⠀something to print after the log is printed (e.g. `\\n`)
|
|
113
159
|
- `title_bg_color` -⠀the background color of the `title`
|
|
114
|
-
- `default_color` -⠀the default text color of the `prompt
|
|
160
|
+
- `default_color` -⠀the default text color of the `prompt`
|
|
161
|
+
- `_console_tabsize` -⠀the tab size of the console (default is 8)\n
|
|
115
162
|
-----------------------------------------------------------------------------------
|
|
116
163
|
The log message can be formatted with special formatting codes. For more detailed
|
|
117
164
|
information about formatting codes, see `xx_format_codes` module documentation."""
|
|
@@ -253,7 +300,7 @@ class Console:
|
|
|
253
300
|
- `*values` -⠀the box content (each value is on a new line)
|
|
254
301
|
- `start` -⠀something to print before the log box is printed
|
|
255
302
|
- `end` -⠀something to print after the log box is printed (e.g. `\\n`)
|
|
256
|
-
- `box_bg_color` -⠀the
|
|
303
|
+
- `box_bg_color` -⠀the background color of the box
|
|
257
304
|
- `default_color` -⠀the default text color of the `*values`
|
|
258
305
|
- `w_padding` -⠀the horizontal padding (in chars) to the box content
|
|
259
306
|
- `w_full` -⠀whether to make the box be the full console width or not\n
|
|
@@ -300,6 +347,41 @@ class Console:
|
|
|
300
347
|
Console.log("", end, end="")
|
|
301
348
|
return confirmed
|
|
302
349
|
|
|
350
|
+
@staticmethod
|
|
351
|
+
def multiline_input(
|
|
352
|
+
prompt: object = "",
|
|
353
|
+
start="",
|
|
354
|
+
end="\n",
|
|
355
|
+
default_color: hexa | rgba = COLOR.cyan,
|
|
356
|
+
show_keybindings=True,
|
|
357
|
+
input_prefix=" ⤷ ",
|
|
358
|
+
reset_ansi=True,
|
|
359
|
+
) -> str:
|
|
360
|
+
"""An input where users can input (and paste) text over multiple lines.\n
|
|
361
|
+
-----------------------------------------------------------------------------------
|
|
362
|
+
- `prompt` -⠀the input prompt
|
|
363
|
+
- `start` -⠀something to print before the input
|
|
364
|
+
- `end` -⠀something to print after the input (e.g. `\\n`)
|
|
365
|
+
- `default_color` -⠀the default text color of the `prompt`
|
|
366
|
+
- `show_keybindings` -⠀whether to show the special keybindings or not
|
|
367
|
+
- `input_prefix` -⠀the prefix of the input line
|
|
368
|
+
- `reset_ansi` -⠀whether to reset the ANSI codes after the input or not
|
|
369
|
+
-----------------------------------------------------------------------------------
|
|
370
|
+
The input prompt can be formatted with special formatting codes. For more detailed
|
|
371
|
+
information about formatting codes, see `xx_format_codes` module documentation."""
|
|
372
|
+
kb = KeyBindings()
|
|
373
|
+
|
|
374
|
+
@kb.add("c-d", eager=True) # CTRL+D
|
|
375
|
+
def _(event):
|
|
376
|
+
event.app.exit(result=event.app.current_buffer.document.text)
|
|
377
|
+
|
|
378
|
+
FormatCodes.print(start + prompt, default_color=default_color)
|
|
379
|
+
if show_keybindings:
|
|
380
|
+
FormatCodes.print("[dim][[b](CTRL+D)[dim] : end of input][_dim]")
|
|
381
|
+
input_string = _prompt_toolkit.prompt(input_prefix, multiline=True, wrap_lines=True, key_bindings=kb)
|
|
382
|
+
FormatCodes.print("[_]" if reset_ansi else "", end=end[1:] if end.startswith("\n") else end)
|
|
383
|
+
return input_string
|
|
384
|
+
|
|
303
385
|
@staticmethod
|
|
304
386
|
def restricted_input(
|
|
305
387
|
prompt: object = "",
|
|
@@ -417,38 +499,3 @@ class Console:
|
|
|
417
499
|
"""Password input (preset for `Console.restricted_input()`)
|
|
418
500
|
that always masks the entered characters with asterisks."""
|
|
419
501
|
return Console.restricted_input(prompt, start, end, default_color, allowed_chars, min_len, max_len, "*", reset_ansi)
|
|
420
|
-
|
|
421
|
-
@staticmethod
|
|
422
|
-
def multiline_input(
|
|
423
|
-
prompt: object = "",
|
|
424
|
-
start="",
|
|
425
|
-
end="\n",
|
|
426
|
-
default_color: hexa | rgba = COLOR.cyan,
|
|
427
|
-
show_keybindings=True,
|
|
428
|
-
input_prefix=" ⤷ ",
|
|
429
|
-
reset_ansi=True,
|
|
430
|
-
) -> str:
|
|
431
|
-
"""An input where users can input (and paste) text over multiple lines.\n
|
|
432
|
-
-----------------------------------------------------------------------------------
|
|
433
|
-
- `prompt` -⠀the input prompt
|
|
434
|
-
- `start` -⠀something to print before the input
|
|
435
|
-
- `end` -⠀something to print after the input (e.g. `\\n`)
|
|
436
|
-
- `default_color` -⠀the default text color of the `prompt`
|
|
437
|
-
- `show_keybindings` -⠀whether to show the special keybindings or not
|
|
438
|
-
- `input_prefix` -⠀the prefix of the input line
|
|
439
|
-
- `reset_ansi` -⠀whether to reset the ANSI codes after the input or not
|
|
440
|
-
-----------------------------------------------------------------------------------
|
|
441
|
-
The input prompt can be formatted with special formatting codes. For more detailed
|
|
442
|
-
information about formatting codes, see `xx_format_codes` module documentation."""
|
|
443
|
-
kb = KeyBindings()
|
|
444
|
-
|
|
445
|
-
@kb.add("c-d", eager=True) # CTRL+D
|
|
446
|
-
def _(event):
|
|
447
|
-
event.app.exit(result=event.app.current_buffer.document.text)
|
|
448
|
-
|
|
449
|
-
FormatCodes.print(start + prompt, default_color=default_color)
|
|
450
|
-
if show_keybindings:
|
|
451
|
-
FormatCodes.print("[dim][[b](CTRL+D)[dim] : end of input][_dim]")
|
|
452
|
-
input_string = _prompt_toolkit.prompt(input_prefix, multiline=True, wrap_lines=True, key_bindings=kb)
|
|
453
|
-
FormatCodes.print("[_]" if reset_ansi else "", end=end[1:] if end.startswith("\n") else end)
|
|
454
|
-
return input_string
|
xulbux/xx_data.py
CHANGED
|
@@ -63,8 +63,7 @@ class Data:
|
|
|
63
63
|
v if not isinstance(v,
|
|
64
64
|
(list, tuple, set, frozenset, dict)) else Data.remove_empty_items(v, spaces_are_empty)
|
|
65
65
|
)
|
|
66
|
-
for k, v in data.items()
|
|
67
|
-
if not String.is_empty(v, spaces_are_empty)
|
|
66
|
+
for k, v in data.items() if not String.is_empty(v, spaces_are_empty)
|
|
68
67
|
}
|
|
69
68
|
if isinstance(data, (list, tuple, set, frozenset)):
|
|
70
69
|
return type(data)(
|
|
@@ -166,8 +165,7 @@ class Data:
|
|
|
166
165
|
if isinstance(item, dict):
|
|
167
166
|
return {
|
|
168
167
|
k: v
|
|
169
|
-
for k, v in ((process_item(key), process_item(value)) for key, value in item.items())
|
|
170
|
-
if k is not None
|
|
168
|
+
for k, v in ((process_item(key), process_item(value)) for key, value in item.items()) if k is not None
|
|
171
169
|
}
|
|
172
170
|
if isinstance(item, (list, tuple, set, frozenset)):
|
|
173
171
|
processed = (v for v in map(process_item, item) if v is not None)
|
|
@@ -379,8 +377,7 @@ class Data:
|
|
|
379
377
|
|
|
380
378
|
if isinstance(update_values, str):
|
|
381
379
|
update_values = [update_values]
|
|
382
|
-
valid_entries = [(parts[0].strip(), parts[1])
|
|
383
|
-
for update_value in update_values
|
|
380
|
+
valid_entries = [(parts[0].strip(), parts[1]) for update_value in update_values
|
|
384
381
|
if len(parts := update_value.split(str(sep).strip())) == 2]
|
|
385
382
|
if not valid_entries:
|
|
386
383
|
raise ValueError(f"No valid update_values found: {update_values}")
|
|
@@ -493,14 +490,14 @@ class Data:
|
|
|
493
490
|
if not d or compactness == 2:
|
|
494
491
|
return (
|
|
495
492
|
punct["{"]
|
|
496
|
-
+ sep.join(f"{format_value(k)}{punct[':']} {format_value(v, current_indent)}"
|
|
497
|
-
|
|
493
|
+
+ sep.join(f"{format_value(k)}{punct[':']} {format_value(v, current_indent)}"
|
|
494
|
+
for k, v in d.items()) + punct["}"]
|
|
498
495
|
)
|
|
499
496
|
if not should_expand(d.values()):
|
|
500
497
|
return (
|
|
501
498
|
punct["{"]
|
|
502
|
-
+ sep.join(f"{format_value(k)}{punct[':']} {format_value(v, current_indent)}"
|
|
503
|
-
|
|
499
|
+
+ sep.join(f"{format_value(k)}{punct[':']} {format_value(v, current_indent)}"
|
|
500
|
+
for k, v in d.items()) + punct["}"]
|
|
504
501
|
)
|
|
505
502
|
items = []
|
|
506
503
|
for k, val in d.items():
|
|
@@ -530,7 +527,7 @@ class Data:
|
|
|
530
527
|
else:
|
|
531
528
|
return f"{punct['(']}\n{formatted_items}\n{' ' * current_indent}{punct[')']}"
|
|
532
529
|
|
|
533
|
-
return format_dict(data, 0) if isinstance(data, dict) else format_sequence(data, 0)
|
|
530
|
+
return _re.sub(r"\s+(?=\n)", "", format_dict(data, 0) if isinstance(data, dict) else format_sequence(data, 0))
|
|
534
531
|
|
|
535
532
|
@staticmethod
|
|
536
533
|
def print(
|
|
@@ -559,11 +556,11 @@ class Data:
|
|
|
559
556
|
part. The formatting can be changed by simply adding the key with the new
|
|
560
557
|
value inside the `syntax_highlighting` dictionary.\n
|
|
561
558
|
The keys with their default values are:
|
|
562
|
-
- `str: COLOR.
|
|
563
|
-
- `number: COLOR.
|
|
564
|
-
- `literal: COLOR.
|
|
565
|
-
- `type: "i|" + COLOR.
|
|
566
|
-
- `punctuation: COLOR.
|
|
559
|
+
- `str: COLOR.blue`
|
|
560
|
+
- `number: COLOR.magenta`
|
|
561
|
+
- `literal: COLOR.cyan`
|
|
562
|
+
- `type: "i|" + COLOR.lightblue`
|
|
563
|
+
- `punctuation: COLOR.darkgray`\n
|
|
567
564
|
For no syntax highlighting, set `syntax_highlighting` to `False` or `None`.\n
|
|
568
565
|
------------------------------------------------------------------------------
|
|
569
566
|
For more detailed information about formatting codes, see `xx_format_codes`
|
xulbux/xx_env_path.py
CHANGED
|
@@ -22,7 +22,7 @@ class EnvPath:
|
|
|
22
22
|
if cwd:
|
|
23
23
|
path = _os.getcwd()
|
|
24
24
|
elif base_dir:
|
|
25
|
-
path = Path.
|
|
25
|
+
path = Path.script_dir
|
|
26
26
|
elif path is None:
|
|
27
27
|
raise ValueError("A path must be provided or either 'cwd' or 'base_dir' must be True.")
|
|
28
28
|
paths = EnvPath.paths(as_list=True)
|
|
@@ -62,7 +62,7 @@ class EnvPath:
|
|
|
62
62
|
if cwd:
|
|
63
63
|
path = _os.getcwd()
|
|
64
64
|
elif base_dir:
|
|
65
|
-
path = Path.
|
|
65
|
+
path = Path.script_dir
|
|
66
66
|
elif path is None:
|
|
67
67
|
raise ValueError("A path must be provided or either 'cwd' or 'base_dir' must be True.")
|
|
68
68
|
return _os.path.normpath(path)
|
xulbux/xx_file.py
CHANGED
|
@@ -4,6 +4,10 @@ from .xx_path import Path
|
|
|
4
4
|
import os as _os
|
|
5
5
|
|
|
6
6
|
|
|
7
|
+
class SameContentFileExistsError(FileExistsError):
|
|
8
|
+
pass
|
|
9
|
+
|
|
10
|
+
|
|
7
11
|
class File:
|
|
8
12
|
|
|
9
13
|
@staticmethod
|
|
@@ -29,14 +33,16 @@ class File:
|
|
|
29
33
|
force: bool = False,
|
|
30
34
|
) -> str:
|
|
31
35
|
"""Create a file with ot without content.\n
|
|
32
|
-
|
|
33
|
-
The function will throw a `FileExistsError` if
|
|
36
|
+
----------------------------------------------------------------------
|
|
37
|
+
The function will throw a `FileExistsError` if a file with the same
|
|
38
|
+
name already exists and a `SameContentFileExistsError` if a file with
|
|
39
|
+
the same name and content already exists.
|
|
34
40
|
To always overwrite the file, set the `force` parameter to `True`."""
|
|
35
41
|
if _os.path.exists(file) and not force:
|
|
36
42
|
with open(file, "r", encoding="utf-8") as existing_file:
|
|
37
43
|
existing_content = existing_file.read()
|
|
38
44
|
if existing_content == content:
|
|
39
|
-
raise
|
|
45
|
+
raise SameContentFileExistsError("Already created this file. (nothing changed)")
|
|
40
46
|
raise FileExistsError("File already exists.")
|
|
41
47
|
with open(file, "w", encoding="utf-8") as f:
|
|
42
48
|
f.write(content)
|
|
@@ -62,4 +68,4 @@ class File:
|
|
|
62
68
|
try:
|
|
63
69
|
return Path.extend(file, search_in, raise_error=True, correct_path=correct_paths)
|
|
64
70
|
except FileNotFoundError:
|
|
65
|
-
return _os.path.join(Path.
|
|
71
|
+
return _os.path.join(Path.script_dir, file) if prefer_base_dir else _os.path.join(_os.getcwd(), file)
|
xulbux/xx_path.py
CHANGED
|
@@ -6,27 +6,37 @@ import sys as _sys
|
|
|
6
6
|
import os as _os
|
|
7
7
|
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
# YAPF: disable
|
|
10
|
+
class ProcessNotFoundError(Exception):
|
|
11
|
+
pass
|
|
10
12
|
|
|
11
|
-
|
|
12
|
-
def
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
13
|
+
class _Cwd:
|
|
14
|
+
def __get__(self, obj, owner=None):
|
|
15
|
+
return _os.getcwd()
|
|
16
|
+
|
|
17
|
+
class _ScriptDir:
|
|
18
|
+
def __get__(self, obj, owner=None):
|
|
19
|
+
if getattr(_sys, "frozen", False):
|
|
20
|
+
base_path = _os.path.dirname(_sys.executable)
|
|
21
|
+
else:
|
|
22
|
+
main_module = _sys.modules["__main__"]
|
|
23
|
+
if hasattr(main_module, "__file__"):
|
|
24
|
+
base_path = _os.path.dirname(_os.path.abspath(main_module.__file__))
|
|
25
|
+
elif (hasattr(main_module, "__spec__") and main_module.__spec__
|
|
26
|
+
and getattr(main_module.__spec__, "origin", None)):
|
|
27
|
+
base_path = _os.path.dirname(_os.path.abspath(main_module.__spec__.origin))
|
|
19
28
|
else:
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
29
|
+
raise RuntimeError("Can only get base directory if accessed from a file.")
|
|
30
|
+
return base_path
|
|
31
|
+
# YAPF: enable
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Path:
|
|
35
|
+
|
|
36
|
+
cwd: str = _Cwd()
|
|
37
|
+
"""The path to the current working directory."""
|
|
38
|
+
script_dir: str = _ScriptDir()
|
|
39
|
+
"""The path to the directory of the current script."""
|
|
30
40
|
|
|
31
41
|
@staticmethod
|
|
32
42
|
def extend(path: str, search_in: str | list[str] = None, raise_error: bool = False, correct_path: bool = False) -> str:
|
|
@@ -68,7 +78,7 @@ class Path:
|
|
|
68
78
|
search_dirs = (drive + _os.sep) if drive else [_os.sep]
|
|
69
79
|
else:
|
|
70
80
|
rel_path = path.lstrip(_os.sep)
|
|
71
|
-
base_dir = Path.
|
|
81
|
+
base_dir = Path.script_dir
|
|
72
82
|
search_dirs = (
|
|
73
83
|
_os.getcwd(),
|
|
74
84
|
base_dir,
|
xulbux/xx_system.py
CHANGED
|
@@ -7,15 +7,12 @@ import sys as _sys
|
|
|
7
7
|
import os as _os
|
|
8
8
|
|
|
9
9
|
|
|
10
|
+
# YAPF: disable
|
|
10
11
|
class ProcessNotFoundError(Exception):
|
|
11
12
|
pass
|
|
12
13
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
@staticmethod
|
|
17
|
-
def is_elevated() -> bool:
|
|
18
|
-
"""Returns `True` if the current user is an admin and `False` otherwise."""
|
|
14
|
+
class _IsElevated:
|
|
15
|
+
def __get__(self, obj, owner=None):
|
|
19
16
|
try:
|
|
20
17
|
if _os.name == "nt":
|
|
21
18
|
return _ctypes.windll.shell32.IsUserAnAdmin() != 0
|
|
@@ -24,6 +21,14 @@ class System:
|
|
|
24
21
|
except Exception:
|
|
25
22
|
pass
|
|
26
23
|
return False
|
|
24
|
+
# YAPF: enable
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class System:
|
|
28
|
+
|
|
29
|
+
is_elevated: bool = _IsElevated()
|
|
30
|
+
"""Is `True` if the current process has
|
|
31
|
+
elevated privileges and `False` otherwise."""
|
|
27
32
|
|
|
28
33
|
@staticmethod
|
|
29
34
|
def restart(prompt: object = None, wait: int = 0, continue_program: bool = False, force: bool = False) -> None:
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.2
|
|
2
2
|
Name: xulbux
|
|
3
|
-
Version: 1.6.
|
|
4
|
-
Summary: A library which includes
|
|
3
|
+
Version: 1.6.7
|
|
4
|
+
Summary: A Python library which includes lots of helpful classes, types and functions aiming to make common programming tasks simpler.
|
|
5
5
|
Author-email: XulbuX <xulbux.real@gmail.com>
|
|
6
6
|
License: MIT License
|
|
7
7
|
|
|
@@ -31,7 +31,7 @@ Project-URL: Documentation, https://github.com/XulbuX/PythonLibraryXulbuX/wiki
|
|
|
31
31
|
Project-URL: Homepage, https://github.com/XulbuX/PythonLibraryXulbuX
|
|
32
32
|
Project-URL: License, https://github.com/XulbuX/PythonLibraryXulbuX/blob/main/LICENSE
|
|
33
33
|
Project-URL: Source Code, https://github.com/XulbuX/PythonLibraryXulbuX/tree/main/src
|
|
34
|
-
Keywords: xulbux,python,library,utility,helper,functions,tools,classes,types,methods,cmd,console,code,color,data,structures,env,environment,file,format,json,path,regex,string,system,operations,presets
|
|
34
|
+
Keywords: xulbux,python,library,utility,helper,functions,tools,classes,types,methods,cmd,console,constants,code,color,data,structures,env,environment,file,format,json,path,regex,string,system,operations,presets
|
|
35
35
|
Classifier: Intended Audience :: Developers
|
|
36
36
|
Classifier: Programming Language :: Python :: 3
|
|
37
37
|
Classifier: Programming Language :: Python :: 3.10
|
|
@@ -57,38 +57,50 @@ Requires-Dist: flake8-pyproject>=1.2.3; extra == "dev"
|
|
|
57
57
|
|
|
58
58
|
# **$\color{#8085FF}\Huge\textsf{XulbuX}$**
|
|
59
59
|
|
|
60
|
-
**$\color{#8085FF}\textsf{XulbuX}$** is
|
|
60
|
+
**$\color{#8085FF}\textsf{XulbuX}$** is library that contains many useful classes, types, and functions,
|
|
61
|
+
ranging from console logging and working with colors to file management and system operations.
|
|
62
|
+
The library is designed to simplify common programming tasks and improve code readability through its collection of tools.
|
|
61
63
|
|
|
62
|
-
For precise information about the library, see the library's [
|
|
63
|
-
For the libraries latest changes, see the [change log](https://github.com/XulbuX/PythonLibraryXulbuX/blob/main/CHANGELOG.md).
|
|
64
|
+
For precise information about the library, see the library's [wiki page](https://github.com/XulbuX/PythonLibraryXulbuX/wiki).<br>
|
|
65
|
+
For the libraries latest changes and updates, see the [change log](https://github.com/XulbuX/PythonLibraryXulbuX/blob/main/CHANGELOG.md).
|
|
64
66
|
|
|
67
|
+
<br>
|
|
65
68
|
|
|
66
69
|
## Installation
|
|
67
70
|
|
|
68
|
-
|
|
69
|
-
|
|
71
|
+
Run the following commands in a console with administrator privileges, so the actions take effect for all users.
|
|
72
|
+
|
|
73
|
+
Install the library and all its dependencies with the command:
|
|
74
|
+
```console
|
|
70
75
|
pip install xulbux
|
|
71
76
|
```
|
|
72
77
|
|
|
73
|
-
|
|
74
|
-
```
|
|
78
|
+
Upgrade the library and all its dependencies to their latest available version with the command:
|
|
79
|
+
```console
|
|
75
80
|
pip install --upgrade xulbux
|
|
76
81
|
```
|
|
77
82
|
|
|
83
|
+
<br>
|
|
78
84
|
|
|
79
85
|
## Usage
|
|
80
86
|
|
|
81
|
-
Import the full library under the alias `xx`, so
|
|
87
|
+
Import the full library under the alias `xx`, so its constants, classes, methods and types are accessible with `xx.CONSTANT.value`, `xx.Class.method()`, `xx.type()`:
|
|
82
88
|
```python
|
|
83
89
|
import xulbux as xx
|
|
84
90
|
```
|
|
85
|
-
So you don't have to
|
|
91
|
+
So you don't have to import the full library under an alias, you can also import only certain parts of the library's contents:
|
|
86
92
|
```python
|
|
93
|
+
# CONSTANTS
|
|
94
|
+
from xulbux import COLOR, CHARS, ANSI
|
|
95
|
+
# Classes
|
|
96
|
+
from xulbux import Code, Color, Console, ...
|
|
97
|
+
# types
|
|
87
98
|
from xulbux import rgba, hsla, hexa
|
|
88
99
|
```
|
|
89
100
|
|
|
101
|
+
<br>
|
|
90
102
|
|
|
91
|
-
|
|
103
|
+
## Modules
|
|
92
104
|
|
|
93
105
|
| | |
|
|
94
106
|
| :--------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------- |
|
|
@@ -105,7 +117,72 @@ from xulbux import rgba, hsla, hexa
|
|
|
105
117
|
| <h3>[`xx_string`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_string)</h3> | helpful actions when working with strings. (*normalize, escape, decompose, ...*) |
|
|
106
118
|
| <h3>`xx_system`</h3> | advanced system actions (*restart with message, check installed Python libs, ...*) |
|
|
107
119
|
|
|
120
|
+
<br>
|
|
121
|
+
|
|
122
|
+
## Example Usage
|
|
108
123
|
|
|
124
|
+
This is what it could look like using this library for a simple but very nice looking color converter:
|
|
125
|
+
```python
|
|
126
|
+
from xulbux import COLOR # CONSTANTS
|
|
127
|
+
from xulbux import FormatCodes, Console # Classes
|
|
128
|
+
from xulbux import hexa # types
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def main() -> None:
|
|
132
|
+
|
|
133
|
+
# LET THE USER ENTER A HEXA COLOR IN ANY HEXA FORMAT
|
|
134
|
+
input_clr = FormatCodes.input(
|
|
135
|
+
"\n[b](Enter a HEXA color in any format) [dim](>) "
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
# ANNOUNCE INDEXING THE INPUT COLOR
|
|
139
|
+
Console.log(
|
|
140
|
+
"INDEX",
|
|
141
|
+
"Indexing the input HEXA color...",
|
|
142
|
+
start="\n",
|
|
143
|
+
title_bg_color=COLOR.blue,
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
try:
|
|
147
|
+
# TRY TO CONVERT THE INPUT COLOR INTO A hexa() COLOR
|
|
148
|
+
hexa_color = hexa(input_clr)
|
|
149
|
+
|
|
150
|
+
except ValueError:
|
|
151
|
+
# ANNOUNCE THE ERROR AND EXIT THE PROGRAM
|
|
152
|
+
Console.fail(
|
|
153
|
+
"The input HEXA color is invalid.",
|
|
154
|
+
end="\n\n",
|
|
155
|
+
exit=True,
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
# ANNOUNCE STARTING THE CONVERSION
|
|
159
|
+
Console.log(
|
|
160
|
+
"CONVERT",
|
|
161
|
+
"Converting the HEXA color into different types...",
|
|
162
|
+
title_bg_color=COLOR.tangerine,
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
# CONVERT THE HEXA COLOR INTO THE TWO OTHER COLOR TYPES
|
|
166
|
+
rgba_color = hexa_color.to_rgba()
|
|
167
|
+
hsla_color = hexa_color.to_hsla()
|
|
168
|
+
|
|
169
|
+
# ANNOUNCE THE SUCCESSFUL CONVERSION
|
|
170
|
+
Console.done(
|
|
171
|
+
"Successfully converted color into different types.",
|
|
172
|
+
end="\n\n",
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
# PRETTY PRINT THE COLOR IN DIFFERENT TYPES
|
|
176
|
+
FormatCodes.print(f"[b](HEXA:) [i|white]({hexa_color})")
|
|
177
|
+
FormatCodes.print(f"[b](RGBA:) [i|white]({rgba_color})")
|
|
178
|
+
FormatCodes.print(f"[b](HSLA:) [i|white]({hsla_color})\n")
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
if __name__ == "__main__":
|
|
182
|
+
main()
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
<br>
|
|
109
186
|
<br>
|
|
110
187
|
|
|
111
188
|
--------------------------------------------------------------
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
xulbux/__init__.py,sha256=UpA3daxpIqjsDltsQawhVZWD5ggQAHl9L8YVurs_LgQ,1654
|
|
2
|
+
xulbux/_cli_.py,sha256=I1TieHnX60mlRvMaTQnon-VRuf_70dkP7sOU1aHthQY,3470
|
|
3
|
+
xulbux/_consts_.py,sha256=b85O5sePS18z7CJgrVw0V7v88PIG9qnQ7G2bJL71odk,6287
|
|
4
|
+
xulbux/xx_code.py,sha256=dY2HRXIDXHN3KTzzUkQVBacFDExNVwH8flREshwi4vk,5288
|
|
5
|
+
xulbux/xx_color.py,sha256=nwcd5_4JIRfZ99JqbCXMl4RWpic_-M361AA5zEa9Nuw,44846
|
|
6
|
+
xulbux/xx_console.py,sha256=X5Xw-Sd-0aOPqIhdddTyXyEELsnlOP8QFOmBED4cbJg,22175
|
|
7
|
+
xulbux/xx_data.py,sha256=5MIEKDgbRLGkZi9Yd35XhzrWZY09oXyVLGs0BgTTHFA,30219
|
|
8
|
+
xulbux/xx_env_path.py,sha256=pdFyfZgOgCQ440thNdUKzhb1JVxefeTLp7rj6YHYrpk,4305
|
|
9
|
+
xulbux/xx_file.py,sha256=sVUj50vT0wpc2C8Kkg1MlqDUFauCvLGQx6ZEh1gMm5k,3316
|
|
10
|
+
xulbux/xx_format_codes.py,sha256=abR9TWtnBLF0L08oyRjDYXx9VCtun9kjGVPmkv44emU,20359
|
|
11
|
+
xulbux/xx_json.py,sha256=dw2AiqMErdjW0ot4pICDBdTL6j03IrYJWJz-Lw21d4Q,5149
|
|
12
|
+
xulbux/xx_path.py,sha256=trDke1N9ewbkQmAIqjeB9gfbTuAlzqFY2mtPtlK2Ks0,4639
|
|
13
|
+
xulbux/xx_regex.py,sha256=gvnDel8xVmf11kvhc0iIjSj1dFW3OLnXNDlaJsUxXU4,7952
|
|
14
|
+
xulbux/xx_string.py,sha256=nJBXAVNknhTE9N_4yOyCVwSSIwOyHCRlZe_D7LOgrOY,5450
|
|
15
|
+
xulbux/xx_system.py,sha256=4WuItIeVF5cU3u3-cu3XqhtxBcap9YDJiQKTZuWsUyM,6494
|
|
16
|
+
xulbux-1.6.7.dist-info/LICENSE,sha256=6NflEcvzFEe8_JFVNCPVwZBwBhlLLd4vqQi8WiX_Xk4,1084
|
|
17
|
+
xulbux-1.6.7.dist-info/METADATA,sha256=QDBNVRyIAIrMBzSHxJ1u-cIX2QiU-f9HxcudiCr5of4,9295
|
|
18
|
+
xulbux-1.6.7.dist-info/WHEEL,sha256=nn6H5-ilmfVryoAQl3ZQ2l8SH5imPWFpm1A5FgEuFV4,91
|
|
19
|
+
xulbux-1.6.7.dist-info/entry_points.txt,sha256=a3womfLIMZKnOFiyy-xnVb4g2qkZsHR5FbKKkljcGns,94
|
|
20
|
+
xulbux-1.6.7.dist-info/top_level.txt,sha256=FkK4EZajwfP36fnlrPaR98OrEvZpvdEOdW1T5zTj6og,7
|
|
21
|
+
xulbux-1.6.7.dist-info/RECORD,,
|
xulbux-1.6.6.dist-info/RECORD
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
xulbux/__init__.py,sha256=kGUOl7SiyAMqKsEZfZODjJILWaFVVRnzAkT5WrwmHMQ,1654
|
|
2
|
-
xulbux/_cli_.py,sha256=I1TieHnX60mlRvMaTQnon-VRuf_70dkP7sOU1aHthQY,3470
|
|
3
|
-
xulbux/_consts_.py,sha256=aQyWSJ5_Spqot1HHWKbYj1j-6YSakIqG89Olv7rp7Ms,4886
|
|
4
|
-
xulbux/xx_code.py,sha256=dY2HRXIDXHN3KTzzUkQVBacFDExNVwH8flREshwi4vk,5288
|
|
5
|
-
xulbux/xx_color.py,sha256=nwcd5_4JIRfZ99JqbCXMl4RWpic_-M361AA5zEa9Nuw,44846
|
|
6
|
-
xulbux/xx_console.py,sha256=pwB1gLuwTj9V2FhcK-kNTfK7eK3Mb-fbsD59Cua-XTM,20078
|
|
7
|
-
xulbux/xx_data.py,sha256=fkJKArU7TTmXTk90vG_s4BHIor6NRqUP_gqypyv3v9U,30254
|
|
8
|
-
xulbux/xx_env_path.py,sha256=e5r47g-dLIo_J9RM9teqLM1rTzNsI0w9U0xjjcK6nro,4321
|
|
9
|
-
xulbux/xx_file.py,sha256=MGGrPDyvgVQJrdcRSGE_jiB_aQz6zo5I0m6_5pKYIo8,3123
|
|
10
|
-
xulbux/xx_format_codes.py,sha256=abR9TWtnBLF0L08oyRjDYXx9VCtun9kjGVPmkv44emU,20359
|
|
11
|
-
xulbux/xx_json.py,sha256=dw2AiqMErdjW0ot4pICDBdTL6j03IrYJWJz-Lw21d4Q,5149
|
|
12
|
-
xulbux/xx_path.py,sha256=KjSurQ9SHqcdhyTo1vzZn2qGXaQr3T1eDr-E_PVdyXo,4537
|
|
13
|
-
xulbux/xx_regex.py,sha256=gvnDel8xVmf11kvhc0iIjSj1dFW3OLnXNDlaJsUxXU4,7952
|
|
14
|
-
xulbux/xx_string.py,sha256=nJBXAVNknhTE9N_4yOyCVwSSIwOyHCRlZe_D7LOgrOY,5450
|
|
15
|
-
xulbux/xx_system.py,sha256=izDmmrh3o66drAp-LkqsA5AruAdHprq5p_CuseT1OJI,6399
|
|
16
|
-
xulbux-1.6.6.dist-info/LICENSE,sha256=6NflEcvzFEe8_JFVNCPVwZBwBhlLLd4vqQi8WiX_Xk4,1084
|
|
17
|
-
xulbux-1.6.6.dist-info/METADATA,sha256=s2U6Uel8qNsGjnL8Czi8nxzXcOy_sByZCSd_dLAg-w4,6979
|
|
18
|
-
xulbux-1.6.6.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
|
|
19
|
-
xulbux-1.6.6.dist-info/entry_points.txt,sha256=a3womfLIMZKnOFiyy-xnVb4g2qkZsHR5FbKKkljcGns,94
|
|
20
|
-
xulbux-1.6.6.dist-info/top_level.txt,sha256=FkK4EZajwfP36fnlrPaR98OrEvZpvdEOdW1T5zTj6og,7
|
|
21
|
-
xulbux-1.6.6.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|