xulbux 1.6.7__tar.gz → 1.6.8__tar.gz

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.

Files changed (32) hide show
  1. {xulbux-1.6.7/src/xulbux.egg-info → xulbux-1.6.8}/PKG-INFO +8 -8
  2. {xulbux-1.6.7 → xulbux-1.6.8}/README.md +6 -6
  3. {xulbux-1.6.7 → xulbux-1.6.8}/pyproject.toml +45 -15
  4. {xulbux-1.6.7 → xulbux-1.6.8}/src/xulbux/__init__.py +1 -1
  5. {xulbux-1.6.7 → xulbux-1.6.8}/src/xulbux/xx_code.py +2 -3
  6. {xulbux-1.6.7 → xulbux-1.6.8}/src/xulbux/xx_console.py +92 -15
  7. {xulbux-1.6.7 → xulbux-1.6.8}/src/xulbux/xx_env_path.py +3 -15
  8. {xulbux-1.6.7 → xulbux-1.6.8}/src/xulbux/xx_file.py +2 -10
  9. {xulbux-1.6.7 → xulbux-1.6.8}/src/xulbux/xx_format_codes.py +43 -17
  10. {xulbux-1.6.7 → xulbux-1.6.8}/src/xulbux/xx_regex.py +1 -5
  11. {xulbux-1.6.7 → xulbux-1.6.8/src/xulbux.egg-info}/PKG-INFO +8 -8
  12. {xulbux-1.6.7 → xulbux-1.6.8}/LICENSE +0 -0
  13. {xulbux-1.6.7 → xulbux-1.6.8}/setup.cfg +0 -0
  14. {xulbux-1.6.7 → xulbux-1.6.8}/src/xulbux/_cli_.py +0 -0
  15. {xulbux-1.6.7 → xulbux-1.6.8}/src/xulbux/_consts_.py +0 -0
  16. {xulbux-1.6.7 → xulbux-1.6.8}/src/xulbux/xx_color.py +0 -0
  17. {xulbux-1.6.7 → xulbux-1.6.8}/src/xulbux/xx_data.py +0 -0
  18. {xulbux-1.6.7 → xulbux-1.6.8}/src/xulbux/xx_json.py +0 -0
  19. {xulbux-1.6.7 → xulbux-1.6.8}/src/xulbux/xx_path.py +0 -0
  20. {xulbux-1.6.7 → xulbux-1.6.8}/src/xulbux/xx_string.py +0 -0
  21. {xulbux-1.6.7 → xulbux-1.6.8}/src/xulbux/xx_system.py +0 -0
  22. {xulbux-1.6.7 → xulbux-1.6.8}/src/xulbux.egg-info/SOURCES.txt +0 -0
  23. {xulbux-1.6.7 → xulbux-1.6.8}/src/xulbux.egg-info/dependency_links.txt +0 -0
  24. {xulbux-1.6.7 → xulbux-1.6.8}/src/xulbux.egg-info/entry_points.txt +0 -0
  25. {xulbux-1.6.7 → xulbux-1.6.8}/src/xulbux.egg-info/requires.txt +0 -0
  26. {xulbux-1.6.7 → xulbux-1.6.8}/src/xulbux.egg-info/top_level.txt +0 -0
  27. {xulbux-1.6.7 → xulbux-1.6.8}/tests/test_color.py +0 -0
  28. {xulbux-1.6.7 → xulbux-1.6.8}/tests/test_color_types.py +0 -0
  29. {xulbux-1.6.7 → xulbux-1.6.8}/tests/test_console_info.py +0 -0
  30. {xulbux-1.6.7 → xulbux-1.6.8}/tests/test_data.py +0 -0
  31. {xulbux-1.6.7 → xulbux-1.6.8}/tests/test_env_vars.py +0 -0
  32. {xulbux-1.6.7 → xulbux-1.6.8}/tests/test_format_codes.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: xulbux
3
- Version: 1.6.7
3
+ Version: 1.6.8
4
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
@@ -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,constants,code,color,data,structures,env,environment,file,format,json,path,regex,string,system,operations,presets
34
+ Keywords: args,arguments,attributes,classes,cmd,client,code,codes,color,commands,console,consts,constants,convert,conversion,data,debug,easier,env,environment,error,file,format,formatting,functions,helper,hex,hexa,hsl,hsla,info,input,json,library,log,logging,methods,nice,operations,path,presets,pretty,printing,properties,python,re,regex,rgb,rgba,string,structures,system,tools,types,utility,warn,warning,xulbux
35
35
  Classifier: Intended Audience :: Developers
36
36
  Classifier: Programming Language :: Python :: 3
37
37
  Classifier: Programming Language :: Python :: 3.10
@@ -102,8 +102,8 @@ from xulbux import rgba, hsla, hexa
102
102
 
103
103
  ## Modules
104
104
 
105
- | | |
106
- | :--------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------- |
105
+ | Module | Short Description |
106
+ | :----------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------- |
107
107
  | <h3>[`xx_code`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_code)</h3> | advanced code-string operations (*changing the indent, finding function calls, ...*) |
108
108
  | <h3>[`xx_color`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_color)</h3> | everything around colors (*converting, blending, searching colors in strings, ...*) |
109
109
  | <h3>[`xx_console`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_console)</h3> | advanced actions related to the console (*pretty logging, advanced inputs, ...*) |
@@ -111,11 +111,11 @@ from xulbux import rgba, hsla, hexa
111
111
  | <h3>[`xx_env_path`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_env_path)</h3> | getting and editing the PATH variable (*get paths, check for paths, add paths, ...*) |
112
112
  | <h3>[`xx_file`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_file)</h3> | advanced working with files (*create files, rename file-extensions, ...*) |
113
113
  | <h3>[`xx_format_codes`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_format_codes)</h3> | easy pretty printing with custom format codes (*print, inputs, custom format codes to ANSI, ...*) |
114
- | <h3>`xx_json`</h3> | advanced working with json files (*read, create, update, ...*) |
115
- | <h3>`xx_path`</h3> | advanced path operations (*get paths, smart-extend relative paths, delete paths, ...*) |
116
- | <h3>`xx_regex`</h3> | generated regex pattern-templates (*match bracket- and quote pairs, match colors, ...*) |
114
+ | <h3>`xx_json`</h3> | advanced working with json files (*read, create, update, ...*) |
115
+ | <h3>`xx_path`</h3> | advanced path operations (*get paths, smart-extend relative paths, delete paths, ...*) |
116
+ | <h3>`xx_regex`</h3> | generated regex pattern-templates (*match bracket- and quote pairs, match colors, ...*) |
117
117
  | <h3>[`xx_string`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_string)</h3> | helpful actions when working with strings. (*normalize, escape, decompose, ...*) |
118
- | <h3>`xx_system`</h3> | advanced system actions (*restart with message, check installed Python libs, ...*) |
118
+ | <h3>`xx_system`</h3> | advanced system actions (*restart with message, check installed Python libs, ...*) |
119
119
 
120
120
  <br>
121
121
 
@@ -45,8 +45,8 @@ from xulbux import rgba, hsla, hexa
45
45
 
46
46
  ## Modules
47
47
 
48
- | | |
49
- | :--------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------- |
48
+ | Module | Short Description |
49
+ | :----------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------- |
50
50
  | <h3>[`xx_code`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_code)</h3> | advanced code-string operations (*changing the indent, finding function calls, ...*) |
51
51
  | <h3>[`xx_color`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_color)</h3> | everything around colors (*converting, blending, searching colors in strings, ...*) |
52
52
  | <h3>[`xx_console`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_console)</h3> | advanced actions related to the console (*pretty logging, advanced inputs, ...*) |
@@ -54,11 +54,11 @@ from xulbux import rgba, hsla, hexa
54
54
  | <h3>[`xx_env_path`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_env_path)</h3> | getting and editing the PATH variable (*get paths, check for paths, add paths, ...*) |
55
55
  | <h3>[`xx_file`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_file)</h3> | advanced working with files (*create files, rename file-extensions, ...*) |
56
56
  | <h3>[`xx_format_codes`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_format_codes)</h3> | easy pretty printing with custom format codes (*print, inputs, custom format codes to ANSI, ...*) |
57
- | <h3>`xx_json`</h3> | advanced working with json files (*read, create, update, ...*) |
58
- | <h3>`xx_path`</h3> | advanced path operations (*get paths, smart-extend relative paths, delete paths, ...*) |
59
- | <h3>`xx_regex`</h3> | generated regex pattern-templates (*match bracket- and quote pairs, match colors, ...*) |
57
+ | <h3>`xx_json`</h3> | advanced working with json files (*read, create, update, ...*) |
58
+ | <h3>`xx_path`</h3> | advanced path operations (*get paths, smart-extend relative paths, delete paths, ...*) |
59
+ | <h3>`xx_regex`</h3> | generated regex pattern-templates (*match bracket- and quote pairs, match colors, ...*) |
60
60
  | <h3>[`xx_string`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_string)</h3> | helpful actions when working with strings. (*normalize, escape, decompose, ...*) |
61
- | <h3>`xx_system`</h3> | advanced system actions (*restart with message, check installed Python libs, ...*) |
61
+ | <h3>`xx_system`</h3> | advanced system actions (*restart with message, check installed Python libs, ...*) |
62
62
 
63
63
  <br>
64
64
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "xulbux"
7
- version = "1.6.7"
7
+ version = "1.6.8"
8
8
  authors = [{ name = "XulbuX", email = "xulbux.real@gmail.com" }]
9
9
  description = "A Python library which includes lots of helpful classes, types and functions aiming to make common programming tasks simpler."
10
10
  readme = "README.md"
@@ -35,34 +35,64 @@ classifiers = [
35
35
  "Topic :: Software Development :: Libraries :: Python Modules",
36
36
  ]
37
37
  keywords = [
38
- "xulbux",
39
- "python",
40
- "library",
41
- "utility",
42
- "helper",
43
- "functions",
44
- "tools",
38
+ "args",
39
+ "arguments",
40
+ "attributes",
45
41
  "classes",
46
- "types",
47
- "methods",
48
42
  "cmd",
49
- "console",
50
- "constants",
43
+ "client",
51
44
  "code",
45
+ "codes",
52
46
  "color",
47
+ "commands",
48
+ "console",
49
+ "consts",
50
+ "constants",
51
+ "convert",
52
+ "conversion",
53
53
  "data",
54
- "structures",
54
+ "debug",
55
+ "easier",
55
56
  "env",
56
57
  "environment",
58
+ "error",
57
59
  "file",
58
60
  "format",
61
+ "formatting",
62
+ "functions",
63
+ "helper",
64
+ "hex",
65
+ "hexa",
66
+ "hsl",
67
+ "hsla",
68
+ "info",
69
+ "input",
59
70
  "json",
71
+ "library",
72
+ "log",
73
+ "logging",
74
+ "methods",
75
+ "nice",
76
+ "operations",
60
77
  "path",
78
+ "presets",
79
+ "pretty",
80
+ "printing",
81
+ "properties",
82
+ "python",
83
+ "re",
61
84
  "regex",
85
+ "rgb",
86
+ "rgba",
62
87
  "string",
88
+ "structures",
63
89
  "system",
64
- "operations",
65
- "presets",
90
+ "tools",
91
+ "types",
92
+ "utility",
93
+ "warn",
94
+ "warning",
95
+ "xulbux",
66
96
  ]
67
97
 
68
98
  [project.urls]
@@ -19,7 +19,7 @@
19
19
  • REGEX PATTERN TEMPLATES xx.Regex
20
20
  """
21
21
 
22
- __version__ = "1.6.7"
22
+ __version__ = "1.6.8"
23
23
  __author__ = "XulbuX"
24
24
  __email__ = "xulbux.real@gmail.com"
25
25
  __license__ = "MIT"
@@ -21,14 +21,13 @@ class Code:
21
21
  non_zero_indents = [i for i in indents if i > 0]
22
22
  return min(non_zero_indents) if non_zero_indents else 0
23
23
 
24
- @staticmethod
25
- def change_tab_size(code: str, new_tab_size: int, remove_empty_lines: bool = False) -> str:
24
+ def change_tab_size(self, code: str, new_tab_size: int, remove_empty_lines: bool = False) -> str:
26
25
  """Replaces all tabs with `new_tab_size` spaces.\n
27
26
  ----------------------------------------------------------------------------------
28
27
  If `remove_empty_lines` is `True`, empty lines will be removed in the process."""
29
28
  code_lines = String.get_lines(code, remove_empty_lines=True)
30
29
  lines = code_lines if remove_empty_lines else String.get_lines(code)
31
- tab_spaces = Code.get_tab_spaces(code)
30
+ tab_spaces = self.get_tab_spaces(code)
32
31
  if (tab_spaces == new_tab_size) or tab_spaces == 0:
33
32
  if remove_empty_lines:
34
33
  return "\n".join(code_lines)
@@ -46,14 +46,39 @@ class ArgResult:
46
46
  def __init__(self, exists: bool, value: any):
47
47
  self.exists = exists
48
48
  self.value = value
49
+ def __bool__(self):
50
+ return self.exists
49
51
 
50
52
  class Args:
51
- """Stores arguments under their aliases with their results."""
53
+ """Stores found command arguments under their aliases with their results."""
52
54
  def __init__(self, **kwargs):
53
55
  for key, value in kwargs.items():
54
56
  if not key.isidentifier():
55
57
  raise TypeError(f"Argument alias '{key}' is invalid. It must be a valid Python variable name.")
56
58
  setattr(self, key, ArgResult(**value))
59
+ def __len__(self):
60
+ return len(vars(self))
61
+ def __contains__(self, key):
62
+ return hasattr(self, key)
63
+ def __getitem__(self, key):
64
+ if isinstance(key, int):
65
+ return list(self.__iter__())[key]
66
+ return getattr(self, key)
67
+ def __iter__(self):
68
+ for key, value in vars(self).items():
69
+ yield (key, {"exists": value.exists, "value": value.value})
70
+ def dict(self) -> dict[str, dict[str, any]]:
71
+ """Returns the arguments as a dictionary."""
72
+ return {k: {"exists": v.exists, "value": v.value} for k, v in vars(self).items()}
73
+ def keys(self):
74
+ """Returns the argument aliases as `dict_keys([...])`."""
75
+ return vars(self).keys()
76
+ def values(self):
77
+ """Returns the argument results as `dict_values([...])`."""
78
+ return vars(self).values()
79
+ def items(self):
80
+ """Returns the argument aliases and results as `dict_items([...])`."""
81
+ return vars(self).items()
57
82
  # YAPF: enable
58
83
 
59
84
 
@@ -70,7 +95,7 @@ class Console:
70
95
  """The name of the current user."""
71
96
 
72
97
  @staticmethod
73
- def get_args(find_args: dict[str, list[str] | tuple[str, ...]]) -> Args:
98
+ def get_args(find_args: dict[str, list[str] | tuple[str, ...]], allow_spaces: bool = False) -> Args:
74
99
  """Will search for the specified arguments in the command line
75
100
  arguments and return the results as a special `Args` object.\n
76
101
  ----------------------------------------------------------------
@@ -96,20 +121,39 @@ class Console:
96
121
  - `Args.<arg_alias>.exists` is `True` if any of the specified
97
122
  args were found and `False` if not
98
123
  - `Args.<arg_alias>.value` the value from behind the found arg,
99
- `None` if no value was found"""
124
+ `None` if no value was found\n
125
+ ----------------------------------------------------------------
126
+ Normally if `allow_spaces` is false, it will take a space as
127
+ the end of an args value. If it is true, it will take spaces as
128
+ part of the value until the next arg is found.
129
+ (Multiple spaces will become one space in the value.)"""
100
130
  args = _sys.argv[1:]
101
- results = {}
131
+ args_len = len(args)
132
+ arg_lookup = {}
102
133
  for arg_key, arg_group in find_args.items():
103
- value = None
104
- exists = False
105
134
  for arg in arg_group:
106
- if arg in args:
107
- exists = True
108
- arg_index = args.index(arg)
109
- if arg_index + 1 < len(args) and not args[arg_index + 1].startswith("-"):
110
- value = String.to_type(args[arg_index + 1])
111
- break
112
- results[arg_key] = {"exists": exists, "value": value}
135
+ arg_lookup[arg] = arg_key
136
+ results = {key: {"exists": False, "value": None} for key in find_args}
137
+ i = 0
138
+ while i < args_len:
139
+ arg = args[i]
140
+ arg_key = arg_lookup.get(arg)
141
+ if arg_key:
142
+ results[arg_key]["exists"] = True
143
+ if i + 1 < args_len and not args[i + 1].startswith("-"):
144
+ if not allow_spaces:
145
+ results[arg_key]["value"] = String.to_type(args[i + 1])
146
+ i += 1
147
+ else:
148
+ value_parts = []
149
+ j = i + 1
150
+ while j < args_len and not args[j].startswith("-"):
151
+ value_parts.append(args[j])
152
+ j += 1
153
+ if value_parts:
154
+ results[arg_key]["value"] = String.to_type(" ".join(value_parts))
155
+ i = j - 1
156
+ i += 1
113
157
  return Args(**results)
114
158
 
115
159
  @staticmethod
@@ -166,9 +210,10 @@ class Console:
166
210
  title_len, tab_len = len(title) + 4, _console_tabsize - ((len(title) + 4) % _console_tabsize)
167
211
  title_color = "_color" if not title_bg_color else Color.text_color_for_on_bg(title_bg_color)
168
212
  if format_linebreaks:
169
- prompt_lst = (String.split_count(l, Console.w - (title_len + tab_len)) for l in str(prompt).splitlines())
213
+ clean_prompt, removals = FormatCodes.remove_formatting(str(prompt), get_removals=True)
214
+ prompt_lst = (String.split_count(l, Console.w - (title_len + tab_len)) for l in str(clean_prompt).splitlines())
170
215
  prompt_lst = (item for lst in prompt_lst for item in (lst if isinstance(lst, list) else [lst]))
171
- prompt = f"\n{' ' * title_len}\t".join(prompt_lst)
216
+ prompt = f"\n{' ' * title_len}\t".join(Console.__add_back_removed_parts(list(prompt_lst), removals))
172
217
  else:
173
218
  prompt = str(prompt)
174
219
  if title == "":
@@ -185,6 +230,38 @@ class Console:
185
230
  end=end,
186
231
  )
187
232
 
233
+ @staticmethod
234
+ def __add_back_removed_parts(split_string: list[str], removals: tuple[tuple[int, str], ...]) -> list[str]:
235
+ """Adds back the removed parts into the split string parts at their original positions."""
236
+ lengths, cumulative_pos = [len(s) for s in split_string], [0]
237
+ for length in lengths:
238
+ cumulative_pos.append(cumulative_pos[-1] + length)
239
+ result, offset_adjusts = split_string.copy(), [0] * len(split_string)
240
+ last_idx, total_length = len(split_string) - 1, cumulative_pos[-1]
241
+
242
+ def find_string_part(pos: int) -> int:
243
+ left, right = 0, len(cumulative_pos) - 1
244
+ while left < right:
245
+ mid = (left + right) // 2
246
+ if cumulative_pos[mid] <= pos < cumulative_pos[mid + 1]:
247
+ return mid
248
+ elif pos < cumulative_pos[mid]:
249
+ right = mid
250
+ else:
251
+ left = mid + 1
252
+ return left
253
+
254
+ for pos, removal in removals:
255
+ if pos >= total_length:
256
+ result[last_idx] = result[last_idx] + removal
257
+ continue
258
+ i = find_string_part(pos)
259
+ adjusted_pos = (pos - cumulative_pos[i]) + offset_adjusts[i]
260
+ parts = [result[i][:adjusted_pos], removal, result[i][adjusted_pos:]]
261
+ result[i] = ''.join(parts)
262
+ offset_adjusts[i] += len(removal)
263
+ return result
264
+
188
265
  @staticmethod
189
266
  def debug(
190
267
  prompt: object = "Point in program reached.",
@@ -29,33 +29,21 @@ class EnvPath:
29
29
  return _os.path.normpath(path) in [_os.path.normpath(p) for p in paths]
30
30
 
31
31
  @staticmethod
32
- def add_path(
33
- path: str = None,
34
- cwd: bool = False,
35
- base_dir: bool = False,
36
- ) -> None:
32
+ def add_path(path: str = None, cwd: bool = False, base_dir: bool = False) -> None:
37
33
  """Add a path to the PATH environment variable."""
38
34
  path = EnvPath.__get(path, cwd, base_dir)
39
35
  if not EnvPath.has_path(path):
40
36
  EnvPath.__persistent(path, add=True)
41
37
 
42
38
  @staticmethod
43
- def remove_path(
44
- path: str = None,
45
- cwd: bool = False,
46
- base_dir: bool = False,
47
- ) -> None:
39
+ def remove_path(path: str = None, cwd: bool = False, base_dir: bool = False) -> None:
48
40
  """Remove a path from the PATH environment variable."""
49
41
  path = EnvPath.__get(path, cwd, base_dir)
50
42
  if EnvPath.has_path(path):
51
43
  EnvPath.__persistent(path, remove=True)
52
44
 
53
45
  @staticmethod
54
- def __get(
55
- path: str = None,
56
- cwd: bool = False,
57
- base_dir: bool = False,
58
- ) -> list:
46
+ def __get(path: str = None, cwd: bool = False, base_dir: bool = False) -> list:
59
47
  """Get and/or normalize the paths.\n
60
48
  ------------------------------------------------------------------------------------
61
49
  Raise an error if no path is provided and neither `cwd` or `base_dir` is `True`."""
@@ -11,11 +11,7 @@ class SameContentFileExistsError(FileExistsError):
11
11
  class File:
12
12
 
13
13
  @staticmethod
14
- def rename_extension(
15
- file: str,
16
- new_extension: str,
17
- camel_case_filename: bool = False,
18
- ) -> str:
14
+ def rename_extension(file: str, new_extension: str, camel_case_filename: bool = False) -> str:
19
15
  """Rename the extension of a file.\n
20
16
  --------------------------------------------------------------------------
21
17
  If the `camel_case_filename` parameter is true, the filename will be made
@@ -27,11 +23,7 @@ class File:
27
23
  return _os.path.join(directory, f"{filename}{new_extension}")
28
24
 
29
25
  @staticmethod
30
- def create(
31
- file: str,
32
- content: str = "",
33
- force: bool = False,
34
- ) -> str:
26
+ def create(file: str, content: str = "", force: bool = False) -> str:
35
27
  """Create a file with ot without content.\n
36
28
  ----------------------------------------------------------------------
37
29
  The function will throw a `FileExistsError` if a file with the same
@@ -182,6 +182,8 @@ _COMPILED: dict[str, Pattern] = { # PRECOMPILE REGULAR EXPRESSIONS
182
182
  + Regex.brackets("(", ")", is_group=True, strip_spaces=False, ignore_in_strings=False)
183
183
  + r")?"
184
184
  ),
185
+ "escape_char": _re.compile(r"(\s*)(\/|\\)"),
186
+ "escape_char_cond": _re.compile(r"(\s*\[\s*)(\/|\\)(?!\2+)"),
185
187
  "bg?_default": _re.compile(r"(?i)((?:" + _PREFIX_RX["BG"] + r")?)\s*default"),
186
188
  "bg_default": _re.compile(r"(?i)" + _PREFIX_RX["BG"] + r"\s*default"),
187
189
  "modifier": _re.compile(
@@ -265,9 +267,11 @@ class FormatCodes:
265
267
  return color in ANSI.color_map or Color.is_valid_rgba(color) or Color.is_valid_hexa(color)
266
268
 
267
269
  def replace_keys(match: _re.Match) -> str:
268
- formats = match.group(1)
269
- escaped = match.group(2)
270
+ _formats = formats = match.group(1)
271
+ auto_reset_escaped = match.group(2)
270
272
  auto_reset_txt = match.group(3)
273
+ if formats_escaped := bool(_COMPILED["escape_char_cond"].match(match.group(0))):
274
+ _formats = formats = _COMPILED["escape_char"].sub(r"\1", formats) # REMOVE / OR \\
271
275
  if auto_reset_txt and auto_reset_txt.count("[") > 0 and auto_reset_txt.count("]") > 0:
272
276
  auto_reset_txt = FormatCodes.to_ansi(auto_reset_txt, default_color, brightness_steps, False)
273
277
  if not formats:
@@ -279,7 +283,7 @@ class FormatCodes:
279
283
  r if (r := FormatCodes.__get_replacement(k, default_color, brightness_steps)) != k else f"[{k}]"
280
284
  for k in format_keys
281
285
  ]
282
- if auto_reset_txt and not escaped:
286
+ if auto_reset_txt and not auto_reset_escaped:
283
287
  reset_keys = []
284
288
  for k in format_keys:
285
289
  k_lower = k.lower()
@@ -308,17 +312,20 @@ class FormatCodes:
308
312
  else:
309
313
  ansi_resets = []
310
314
  if not (len(ansi_formats) == 1 and ansi_formats[0].count(f"{ANSI.char}{ANSI.start}") >= 1) and not all(
311
- f.startswith(f"{ANSI.char}{ANSI.start}") for f in ansi_formats):
315
+ f.startswith(f"{ANSI.char}{ANSI.start}") for f in ansi_formats): # FORMATTING WAS INVALID
312
316
  return match.group(0)
313
- return (
314
- "".join(ansi_formats) + (
315
- f"({FormatCodes.to_ansi(auto_reset_txt, default_color, brightness_steps, False)})"
316
- if escaped and auto_reset_txt else auto_reset_txt if auto_reset_txt else ""
317
- ) + ("" if escaped else "".join(ansi_resets))
318
- )
317
+ elif formats_escaped: # FORMATTING WAS VALID BUT ESCAPED
318
+ return f"[{_formats}]({auto_reset_txt})" if auto_reset_txt else f"[{_formats}]"
319
+ else:
320
+ return (
321
+ "".join(ansi_formats) + (
322
+ f"({FormatCodes.to_ansi(auto_reset_txt, default_color, brightness_steps, False)})"
323
+ if auto_reset_escaped and auto_reset_txt else auto_reset_txt if auto_reset_txt else ""
324
+ ) + ("" if auto_reset_escaped else "".join(ansi_resets))
325
+ )
319
326
 
320
327
  string = "\n".join(_COMPILED["formatting"].sub(replace_keys, line) for line in string.split("\n"))
321
- return (FormatCodes.__get_default_ansi(default_color) if _default_start else "") + string if use_default else string
328
+ return ((FormatCodes.__get_default_ansi(default_color) if _default_start else "") + string) if use_default else string
322
329
 
323
330
  @staticmethod
324
331
  def escape_ansi(ansi_string: str) -> str:
@@ -326,14 +333,33 @@ class FormatCodes:
326
333
  return ansi_string.replace(ANSI.char, ANSI.escaped_char)
327
334
 
328
335
  @staticmethod
329
- def remove_ansi(ansi_string: str) -> str:
330
- """Removes all ANSI codes from the string."""
331
- return _COMPILED["ansi_seq"].sub("", ansi_string)
336
+ def remove_ansi(ansi_string: str, get_removals: bool = False) -> str | tuple[str, tuple[tuple[int, str], ...]]:
337
+ """Removes all ANSI codes from the string.\n
338
+ --------------------------------------------------------------------------------------------------
339
+ If `get_removals` is true, additionally to the cleaned string, a list of tuples will be returned.
340
+ Each tuple contains the position of the removed ansi code and the removed ansi code."""
341
+ if get_removals:
342
+ removals = []
343
+
344
+ def replacement(match: _re.Match) -> str:
345
+ start_pos = match.start() - sum(len(removed) for _, removed in removals)
346
+ if removals and removals[-1][0] == start_pos:
347
+ start_pos = removals[-1][0]
348
+ removals.append((start_pos, match.group()))
349
+ return ""
350
+
351
+ clean_string = _COMPILED["ansi_seq"].sub(replacement, ansi_string)
352
+ return clean_string, tuple(removals)
353
+ else:
354
+ return _COMPILED["ansi_seq"].sub("", ansi_string)
332
355
 
333
356
  @staticmethod
334
- def remove_formatting(string: str) -> str:
335
- """Removes all formatting codes from the string."""
336
- return _COMPILED["ansi_seq"].sub("", FormatCodes.to_ansi(string))
357
+ def remove_formatting(string: str, get_removals: bool = False) -> str | tuple[str, tuple[tuple[int, str], ...]]:
358
+ """Removes all formatting codes from the string.\n
359
+ ----------------------------------------------------------------------------------------------------
360
+ If `get_removals` is true, additionally to the cleaned string, a list of tuples will be returned.
361
+ Each tuple contains the position of the removed formatting code and the removed formatting code."""
362
+ return FormatCodes.remove_ansi(FormatCodes.to_ansi(string), get_removals=get_removals)
337
363
 
338
364
  @staticmethod
339
365
  def __config_console() -> None:
@@ -55,11 +55,7 @@ class Regex:
55
55
  return rf'(?<!["\'])(?:{pattern})(?!["\'])'
56
56
 
57
57
  @staticmethod
58
- def all_except(
59
- disallowed_pattern: str,
60
- ignore_pattern: str = "",
61
- is_group: bool = False,
62
- ) -> str:
58
+ def all_except(disallowed_pattern: str, ignore_pattern: str = "", is_group: bool = False) -> str:
63
59
  """Matches everything except `disallowed_pattern`, unless the `disallowed_pattern`
64
60
  is found inside a string (`'...'` or `"..."`).\n
65
61
  ------------------------------------------------------------------------------------
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: xulbux
3
- Version: 1.6.7
3
+ Version: 1.6.8
4
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
@@ -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,constants,code,color,data,structures,env,environment,file,format,json,path,regex,string,system,operations,presets
34
+ Keywords: args,arguments,attributes,classes,cmd,client,code,codes,color,commands,console,consts,constants,convert,conversion,data,debug,easier,env,environment,error,file,format,formatting,functions,helper,hex,hexa,hsl,hsla,info,input,json,library,log,logging,methods,nice,operations,path,presets,pretty,printing,properties,python,re,regex,rgb,rgba,string,structures,system,tools,types,utility,warn,warning,xulbux
35
35
  Classifier: Intended Audience :: Developers
36
36
  Classifier: Programming Language :: Python :: 3
37
37
  Classifier: Programming Language :: Python :: 3.10
@@ -102,8 +102,8 @@ from xulbux import rgba, hsla, hexa
102
102
 
103
103
  ## Modules
104
104
 
105
- | | |
106
- | :--------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------- |
105
+ | Module | Short Description |
106
+ | :----------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------- |
107
107
  | <h3>[`xx_code`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_code)</h3> | advanced code-string operations (*changing the indent, finding function calls, ...*) |
108
108
  | <h3>[`xx_color`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_color)</h3> | everything around colors (*converting, blending, searching colors in strings, ...*) |
109
109
  | <h3>[`xx_console`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_console)</h3> | advanced actions related to the console (*pretty logging, advanced inputs, ...*) |
@@ -111,11 +111,11 @@ from xulbux import rgba, hsla, hexa
111
111
  | <h3>[`xx_env_path`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_env_path)</h3> | getting and editing the PATH variable (*get paths, check for paths, add paths, ...*) |
112
112
  | <h3>[`xx_file`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_file)</h3> | advanced working with files (*create files, rename file-extensions, ...*) |
113
113
  | <h3>[`xx_format_codes`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_format_codes)</h3> | easy pretty printing with custom format codes (*print, inputs, custom format codes to ANSI, ...*) |
114
- | <h3>`xx_json`</h3> | advanced working with json files (*read, create, update, ...*) |
115
- | <h3>`xx_path`</h3> | advanced path operations (*get paths, smart-extend relative paths, delete paths, ...*) |
116
- | <h3>`xx_regex`</h3> | generated regex pattern-templates (*match bracket- and quote pairs, match colors, ...*) |
114
+ | <h3>`xx_json`</h3> | advanced working with json files (*read, create, update, ...*) |
115
+ | <h3>`xx_path`</h3> | advanced path operations (*get paths, smart-extend relative paths, delete paths, ...*) |
116
+ | <h3>`xx_regex`</h3> | generated regex pattern-templates (*match bracket- and quote pairs, match colors, ...*) |
117
117
  | <h3>[`xx_string`](https://github.com/XulbuX/PythonLibraryXulbuX/wiki/xx_string)</h3> | helpful actions when working with strings. (*normalize, escape, decompose, ...*) |
118
- | <h3>`xx_system`</h3> | advanced system actions (*restart with message, check installed Python libs, ...*) |
118
+ | <h3>`xx_system`</h3> | advanced system actions (*restart with message, check installed Python libs, ...*) |
119
119
 
120
120
  <br>
121
121
 
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes