bear-utils 0.9.0__py3-none-any.whl → 0.9.3__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.
- bear_utils/_internal/_version.py +1 -0
- bear_utils/_internal/cli.py +55 -9
- bear_utils/_internal/debug.py +19 -4
- bear_utils/cli/_get_version.py +207 -0
- bear_utils/constants/__init__.py +6 -2
- bear_utils/constants/_exit_code.py +1 -1
- bear_utils/constants/_http_status_code.py +1 -1
- bear_utils/constants/_meta.py +107 -16
- bear_utils/extras/__init__.py +6 -0
- bear_utils/extras/_tools.py +11 -119
- bear_utils/extras/_zapper.py +399 -0
- bear_utils/graphics/font/_utils.py +188 -0
- bear_utils/graphics/font/block_font.py +68 -7
- bear_utils/logger_manager/_log_level.py +14 -14
- {bear_utils-0.9.0.dist-info → bear_utils-0.9.3.dist-info}/METADATA +3 -2
- {bear_utils-0.9.0.dist-info → bear_utils-0.9.3.dist-info}/RECORD +17 -13
- {bear_utils-0.9.0.dist-info → bear_utils-0.9.3.dist-info}/WHEEL +0 -0
bear_utils/extras/_tools.py
CHANGED
@@ -1,15 +1,13 @@
|
|
1
1
|
import asyncio
|
2
2
|
from asyncio.subprocess import PIPE
|
3
3
|
from collections import deque
|
4
|
-
from functools import cached_property
|
5
4
|
import shutil
|
6
5
|
from typing import TYPE_CHECKING
|
7
6
|
|
8
|
-
from rich.console import Console
|
9
|
-
|
10
7
|
from bear_utils.cli.shell._base_command import BaseShellCommand as ShellCommand
|
11
8
|
from bear_utils.cli.shell._base_shell import AsyncShellSession
|
12
9
|
from bear_utils.extras.platform_utils import OS, get_platform
|
10
|
+
from bear_utils.graphics.font._utils import ascii_header
|
13
11
|
|
14
12
|
if TYPE_CHECKING:
|
15
13
|
from subprocess import CompletedProcess
|
@@ -175,119 +173,13 @@ async def clear_clipboard_async() -> int:
|
|
175
173
|
return await clipboard_manager.clear()
|
176
174
|
|
177
175
|
|
178
|
-
|
179
|
-
|
180
|
-
|
181
|
-
|
182
|
-
|
183
|
-
|
184
|
-
|
185
|
-
|
186
|
-
|
187
|
-
|
188
|
-
right_sep: str = "<",
|
189
|
-
bottom_sep: str = "#",
|
190
|
-
length: int = 60,
|
191
|
-
s1: str = "bold red",
|
192
|
-
s2: str = "bold blue",
|
193
|
-
return_txt: bool = False,
|
194
|
-
) -> str:
|
195
|
-
"""Generate a header string with customizable separators for each line.
|
196
|
-
|
197
|
-
Args:
|
198
|
-
title: The title text to display
|
199
|
-
top_sep: Character(s) for the top separator line
|
200
|
-
left_sep: Character(s) for the left side of title line
|
201
|
-
right_sep: Character(s) for the right side of title line
|
202
|
-
bottom_sep: Character(s) for the bottom separator line
|
203
|
-
length: Total width of each line
|
204
|
-
s1: Style for the title text
|
205
|
-
s2: Style for the entire header block
|
206
|
-
return_txt: If True, return the text instead of printing
|
207
|
-
"""
|
208
|
-
# Top line: all top_sep characters
|
209
|
-
top_line: str = top_sep * length
|
210
|
-
|
211
|
-
# Bottom line: all bottom_sep characters
|
212
|
-
bottom_line: str = bottom_sep * length
|
213
|
-
|
214
|
-
# Title line: left_sep chars + title + right_sep chars
|
215
|
-
title_with_spaces = f" {title} "
|
216
|
-
styled_title = f"[{s1}]{title}[/{s1}]"
|
217
|
-
|
218
|
-
# Calculate padding needed on each side
|
219
|
-
title_length = len(title_with_spaces)
|
220
|
-
remaining_space = length - title_length
|
221
|
-
left_padding = remaining_space // 2
|
222
|
-
right_padding = remaining_space - left_padding
|
223
|
-
|
224
|
-
# Build the title line with different left and right separators
|
225
|
-
title_line = (
|
226
|
-
(left_sep * left_padding) + title_with_spaces.replace(title, styled_title) + (right_sep * right_padding)
|
227
|
-
)
|
228
|
-
|
229
|
-
# Assemble the complete header
|
230
|
-
output_text: str = f"\n{top_line}\n{title_line}\n{bottom_line}\n"
|
231
|
-
|
232
|
-
if not return_txt:
|
233
|
-
self.local_console.print(output_text, style=s2)
|
234
|
-
return output_text
|
235
|
-
|
236
|
-
|
237
|
-
def ascii_header(
|
238
|
-
title: str,
|
239
|
-
top_sep: str = "#",
|
240
|
-
left_sep: str = ">",
|
241
|
-
right_sep: str = "<",
|
242
|
-
bottom_sep: str = "#",
|
243
|
-
length: int = 60,
|
244
|
-
style1: str = "bold red",
|
245
|
-
style2: str = "bold blue",
|
246
|
-
print_out: bool = True,
|
247
|
-
) -> str:
|
248
|
-
"""Generate a header string for visual tests.
|
249
|
-
|
250
|
-
Args:
|
251
|
-
title (str): The title to display in the header.
|
252
|
-
top_sep (str): The character to use for the top separator line. Defaults to '#'.
|
253
|
-
left_sep (str): The character to use for the left side of title line. Defaults to '>'.
|
254
|
-
right_sep (str): The character to use for the right side of title line. Defaults to '<'.
|
255
|
-
bottom_sep (str): The character to use for the bottom separator line. Defaults to '#'.
|
256
|
-
length (int): The total length of the header line. Defaults to 60.
|
257
|
-
style1 (str): The style for the title text. Defaults to 'bold red'.
|
258
|
-
style2 (str): The style for the separator text. Defaults to 'bold blue'.
|
259
|
-
print_out (bool): Whether to print the header or just return it. Defaults to True.
|
260
|
-
"""
|
261
|
-
text_helper = TextHelper()
|
262
|
-
if print_out:
|
263
|
-
text_helper.print_header(
|
264
|
-
title=title,
|
265
|
-
top_sep=top_sep,
|
266
|
-
left_sep=left_sep,
|
267
|
-
right_sep=right_sep,
|
268
|
-
bottom_sep=bottom_sep,
|
269
|
-
length=length,
|
270
|
-
s1=style1,
|
271
|
-
s2=style2,
|
272
|
-
return_txt=False,
|
273
|
-
)
|
274
|
-
return ""
|
275
|
-
return text_helper.print_header(
|
276
|
-
title=title,
|
277
|
-
top_sep=top_sep,
|
278
|
-
left_sep=left_sep,
|
279
|
-
right_sep=right_sep,
|
280
|
-
bottom_sep=bottom_sep,
|
281
|
-
length=length,
|
282
|
-
s1=style1,
|
283
|
-
s2=style2,
|
284
|
-
return_txt=True,
|
285
|
-
)
|
286
|
-
|
287
|
-
|
288
|
-
if __name__ == "__main__":
|
289
|
-
# Example usage of the TextHelper
|
290
|
-
text_helper = TextHelper()
|
291
|
-
text_helper.print_header("My Title", top_sep="#", bottom_sep="#")
|
292
|
-
text_helper.print_header("My Title", top_sep="=", left_sep=">", right_sep="<", bottom_sep="=")
|
293
|
-
text_helper.print_header("My Title", top_sep="-", left_sep="[", right_sep="]", bottom_sep="-")
|
176
|
+
__all__ = [
|
177
|
+
"ClipboardManager",
|
178
|
+
"ascii_header",
|
179
|
+
"clear_clipboard",
|
180
|
+
"clear_clipboard_async",
|
181
|
+
"copy_to_clipboard",
|
182
|
+
"copy_to_clipboard_async",
|
183
|
+
"paste_from_clipboard",
|
184
|
+
"paste_from_clipboard_async",
|
185
|
+
]
|
@@ -0,0 +1,399 @@
|
|
1
|
+
from collections.abc import Callable
|
2
|
+
import re
|
3
|
+
from typing import Any, Literal, Self
|
4
|
+
|
5
|
+
|
6
|
+
class Zapper[T]:
|
7
|
+
"""A class to remove specified symbols from a source string."""
|
8
|
+
|
9
|
+
def __init__(
|
10
|
+
self,
|
11
|
+
str_input: str | tuple[str, ...],
|
12
|
+
src: str,
|
13
|
+
replace: str = "",
|
14
|
+
expected_unpack: int = 0,
|
15
|
+
sep: str = ".",
|
16
|
+
atomic: bool = False,
|
17
|
+
unpack_strict: bool = True,
|
18
|
+
regex: bool = False,
|
19
|
+
filter_start: bool = False, # Will filter out any separators at the start of the string
|
20
|
+
filter_end: bool = False, # Will filter out any separators at the end of the string
|
21
|
+
sorting: Literal["length", "order"] = "length",
|
22
|
+
func: Callable[[str], T] = str,
|
23
|
+
) -> None:
|
24
|
+
"""Initialize the Zapper with symbols, source string, and optional parameters."""
|
25
|
+
self.src: str = src
|
26
|
+
self.replace: str = replace
|
27
|
+
self.expected_unpack: int = expected_unpack
|
28
|
+
self.sep: str = sep
|
29
|
+
self.func: Callable[[str], T] = func
|
30
|
+
self.atomic: bool = atomic
|
31
|
+
self.unpack_strict: bool = unpack_strict
|
32
|
+
self.regex_enabled: bool = regex
|
33
|
+
self.filter_start: bool = filter_start
|
34
|
+
self.filter_end: bool = filter_end
|
35
|
+
self.sorting: Literal["length", "order"] = sorting
|
36
|
+
self.input: list[str] = self._process_input(str_input)
|
37
|
+
self.dst: str = ""
|
38
|
+
self.result: tuple[Any, ...] | None = None
|
39
|
+
|
40
|
+
@staticmethod
|
41
|
+
def _get_chars(str_input: str) -> list[str]:
|
42
|
+
"""Get a list of characters from the input string."""
|
43
|
+
return [char for char in str_input if char if char != ""]
|
44
|
+
|
45
|
+
@staticmethod
|
46
|
+
def _get_strs(str_input: tuple[str, ...]) -> list[str]:
|
47
|
+
"""Get a list of strings from the input tuple."""
|
48
|
+
return [item for item in str_input if item if item != ""]
|
49
|
+
|
50
|
+
@staticmethod
|
51
|
+
def _de_dupe(strings: list[str], atomic: bool, sorting: Literal["length", "order"]) -> list[str]:
|
52
|
+
"""Remove duplicates from the input list based on the sorting method."""
|
53
|
+
if atomic and sorting == "length":
|
54
|
+
return sorted(set(strings), key=lambda x: len(x), reverse=True)
|
55
|
+
seen = set()
|
56
|
+
ordered_result = []
|
57
|
+
for item in strings:
|
58
|
+
if item not in seen:
|
59
|
+
seen.add(item)
|
60
|
+
ordered_result.append(item)
|
61
|
+
return ordered_result
|
62
|
+
|
63
|
+
def _process_input(self, str_input: str | tuple[str, ...]) -> list[str]:
|
64
|
+
"""Process the input symbols based on whether they are multi-input or single."""
|
65
|
+
is_tuple = isinstance(str_input, tuple)
|
66
|
+
is_string = isinstance(str_input, str)
|
67
|
+
if str_input == "":
|
68
|
+
return []
|
69
|
+
strings_to_replace = []
|
70
|
+
if is_string and not self.atomic:
|
71
|
+
# If a single string is passed, treat each char as a string to replace
|
72
|
+
chars: list[str] = self._get_chars(str_input)
|
73
|
+
strings_to_replace.extend(chars)
|
74
|
+
elif is_string and self.atomic:
|
75
|
+
# If a single string is passed and self.atomic is True, treat it as a single string to replace
|
76
|
+
strings_to_replace.append(str_input)
|
77
|
+
elif is_tuple and not self.atomic:
|
78
|
+
# If a tuple is passed while atomic is false, treat each char as a string to replace
|
79
|
+
for item in str_input:
|
80
|
+
chars = self._get_chars(item)
|
81
|
+
strings_to_replace.extend(chars)
|
82
|
+
elif is_tuple and self.atomic:
|
83
|
+
# If a tuple is passed and atomic is True, treat each string as a thing to replace
|
84
|
+
strings: list[str] = self._get_strs(str_input)
|
85
|
+
strings_to_replace.extend(strings)
|
86
|
+
return self._de_dupe(strings_to_replace, self.atomic, self.sorting)
|
87
|
+
|
88
|
+
# region Zap Related
|
89
|
+
|
90
|
+
@staticmethod
|
91
|
+
def _re_sub(src: str, pattern: str, replacement: str) -> str:
|
92
|
+
"""Perform a regex substitution on the source string."""
|
93
|
+
return re.sub(pattern, replacement, src)
|
94
|
+
|
95
|
+
@property
|
96
|
+
def value(self) -> str:
|
97
|
+
"""Return the modified source string."""
|
98
|
+
return self.dst
|
99
|
+
|
100
|
+
def _zap(self) -> str:
|
101
|
+
"""Remove specified symbols from the source string."""
|
102
|
+
temp_str = self.src
|
103
|
+
for to_replace in self.input:
|
104
|
+
if self.regex_enabled:
|
105
|
+
temp_str = self._re_sub(temp_str, to_replace, self.replace)
|
106
|
+
else:
|
107
|
+
temp_str = temp_str.replace(to_replace, self.replace)
|
108
|
+
if self.filter_start and temp_str.startswith(self.sep):
|
109
|
+
temp_str = temp_str[len(self.sep) :]
|
110
|
+
if self.filter_end and temp_str.endswith(self.sep):
|
111
|
+
temp_str = temp_str[: -len(self.sep)]
|
112
|
+
if self.unpack_strict:
|
113
|
+
temp_str = temp_str.replace(self.sep * 2, self.sep) # Remove double separators
|
114
|
+
self.dst = temp_str
|
115
|
+
return self.dst
|
116
|
+
|
117
|
+
def zap(self) -> Self:
|
118
|
+
"""Remove specified symbols from the source string."""
|
119
|
+
self.dst = self._zap()
|
120
|
+
return self
|
121
|
+
|
122
|
+
# endregion
|
123
|
+
# region Zap Get Related
|
124
|
+
|
125
|
+
def _zap_get(self) -> tuple[str, ...]:
|
126
|
+
"""Remove specified symbols and return a tuple of unpacked values."""
|
127
|
+
result: list[str] = self._zap().split(self.sep)[: self.expected_unpack]
|
128
|
+
if self.unpack_strict and len(result) != self.expected_unpack:
|
129
|
+
raise ValueError(f"Expected {self.expected_unpack} items, got {len(result)}: {result}")
|
130
|
+
self.result = tuple(result)
|
131
|
+
return self.result
|
132
|
+
|
133
|
+
def zap_get(self) -> Self:
|
134
|
+
"""Remove specified symbols and return a tuple of unpacked values."""
|
135
|
+
self.result = self._zap_get()
|
136
|
+
if self.unpack_strict and len(self.result) != self.expected_unpack:
|
137
|
+
raise ValueError(f"Expected {self.expected_unpack} items, got {len(self.result)}: {self.result}")
|
138
|
+
return self
|
139
|
+
|
140
|
+
@property
|
141
|
+
def unpacked(self) -> tuple[Any, ...]:
|
142
|
+
"""Return the unpacked values as a tuple."""
|
143
|
+
if isinstance(self.result, tuple):
|
144
|
+
return self.result
|
145
|
+
raise ValueError("Result is not unpacked yet. Call zap_get() first.")
|
146
|
+
|
147
|
+
# endregion
|
148
|
+
# region Zap As Related
|
149
|
+
|
150
|
+
def _zap_as(self) -> tuple[T, ...]:
|
151
|
+
"""Convert the result in self.result to the specified type."""
|
152
|
+
temp_list: list[Any] = []
|
153
|
+
if self.result is None:
|
154
|
+
raise ValueError("No result to convert. Call zap_get() first.")
|
155
|
+
for item in self.result:
|
156
|
+
temp_list.append(self.func(item))
|
157
|
+
self.result = tuple(temp_list)
|
158
|
+
return self.result
|
159
|
+
|
160
|
+
def zap_as(self) -> Self:
|
161
|
+
"""Convert the result in self.result to the specified type."""
|
162
|
+
if not self.result:
|
163
|
+
raise ValueError("No result to convert. Call zap_get() first.")
|
164
|
+
self._zap_as()
|
165
|
+
return self
|
166
|
+
|
167
|
+
# endregion
|
168
|
+
|
169
|
+
|
170
|
+
def zap_multi(
|
171
|
+
*sym: str,
|
172
|
+
src: str,
|
173
|
+
replace: str = "",
|
174
|
+
atomic: bool = True,
|
175
|
+
) -> str:
|
176
|
+
"""Remove specified symbols from the source string.
|
177
|
+
|
178
|
+
Args:
|
179
|
+
*sym: A variable number of strings containing symbols to remove from src (e.g., "?!" or "!?")
|
180
|
+
src (str): The source string from which to remove the symbols
|
181
|
+
replace (str, optional): The string to replace the removed symbols with (default is an empty string).
|
182
|
+
|
183
|
+
Returns:
|
184
|
+
str: The modified source string with specified symbols removed.
|
185
|
+
|
186
|
+
Example:
|
187
|
+
>>> zap_multi("!?*", "Hello!? World! *", "")
|
188
|
+
'Hello World '
|
189
|
+
>>> zap_multi("!?*", "Hello!? World! *", "-")
|
190
|
+
'Hello- World- -'
|
191
|
+
"""
|
192
|
+
zapper = Zapper(sym, src, replace, atomic=atomic)
|
193
|
+
return zapper.zap().value
|
194
|
+
|
195
|
+
|
196
|
+
def zap(sym: str, src: str, replace: str = "") -> str:
|
197
|
+
"""Remove specified symbols from the source string.
|
198
|
+
|
199
|
+
Args:
|
200
|
+
sym (str): A string containing symbols to remove from src (e.g., "?!" or "!?")
|
201
|
+
src (str): The source string from which to remove the symbols
|
202
|
+
replace (str, optional): The string to replace the removed symbols with (default is an empty string).
|
203
|
+
|
204
|
+
Returns:
|
205
|
+
str: The modified source string with specified symbols removed.
|
206
|
+
|
207
|
+
Example:
|
208
|
+
>>> zap("!?*", "Hello!? World! *", "")
|
209
|
+
'Hello World '
|
210
|
+
>>> zap("!?*", "Hello!? World! *", "-")
|
211
|
+
'Hello- World- -'
|
212
|
+
"""
|
213
|
+
zapper = Zapper(sym, src, replace, unpack_strict=False)
|
214
|
+
return zapper.zap().value
|
215
|
+
|
216
|
+
|
217
|
+
def zap_get_multi(
|
218
|
+
*sym: str,
|
219
|
+
src: str,
|
220
|
+
unpack_val: int,
|
221
|
+
replace: str = "",
|
222
|
+
sep: str = ".",
|
223
|
+
) -> tuple[str, ...]:
|
224
|
+
"""Remove specified symbols from the source string and return a tuple of unpacked values.
|
225
|
+
|
226
|
+
Args:
|
227
|
+
*sym: A variable number of strings containing symbols to remove from src (e.g., "?!" or "!?")
|
228
|
+
src (str): The source string from which to remove the symbols
|
229
|
+
unpack_val (int): The expected number of items to unpack from the result
|
230
|
+
replace (str, optional): The string to replace the removed symbols with (default is an empty string).
|
231
|
+
sep (str, optional): The separator used to split the modified source string (default is ".").
|
232
|
+
|
233
|
+
Returns:
|
234
|
+
tuple[str, ...]: A tuple of unpacked values from the modified source string.
|
235
|
+
|
236
|
+
Raises:
|
237
|
+
ValueError: If the number of items in the result does not match unpack_val.
|
238
|
+
"""
|
239
|
+
zapper = Zapper(sym, src, replace, expected_unpack=unpack_val, sep=sep, unpack_strict=True)
|
240
|
+
try:
|
241
|
+
return zapper.zap_get().unpacked
|
242
|
+
except Exception as e:
|
243
|
+
raise ValueError(f"Error unpacking values: {e}") from e
|
244
|
+
|
245
|
+
|
246
|
+
def zap_get(sym: str, src: str, unpack_val: int, replace: str = "", sep: str = ".") -> tuple[str, ...]:
|
247
|
+
"""Remove specified symbols from the source string and return a tuple of unpacked values.
|
248
|
+
|
249
|
+
Args:
|
250
|
+
sym (str): A string containing symbols to remove from src (e.g., "?!" or "!?")
|
251
|
+
src (str): The source string from which to remove the symbols
|
252
|
+
unpack_val (int): The expected number of items to unpack from the result
|
253
|
+
replace (str, optional): The string to replace the removed symbols with (default is an empty string).
|
254
|
+
sep (str, optional): The separator used to split the modified source string (default is ".").
|
255
|
+
|
256
|
+
Returns:
|
257
|
+
tuple[str, ...]: A tuple of unpacked values from the modified source string.
|
258
|
+
|
259
|
+
Raises:
|
260
|
+
ValueError: If the number of items in the result does not match unpack_val.
|
261
|
+
"""
|
262
|
+
zapper = Zapper(sym, src, replace, expected_unpack=unpack_val, sep=sep, unpack_strict=True)
|
263
|
+
try:
|
264
|
+
return zapper.zap_get().unpacked
|
265
|
+
except Exception as e:
|
266
|
+
raise ValueError(f"Error unpacking values: {e}") from e
|
267
|
+
|
268
|
+
|
269
|
+
def zap_take(sym: str, src: str, unpack_val: int, replace: str = "", sep: str = ".") -> tuple[str, ...]:
|
270
|
+
"""Remove specified symbols from the source string and return a tuple of unpacked values.
|
271
|
+
|
272
|
+
This function is similar to zap_get but does not raise an error if the number of items does not match unpack_val.
|
273
|
+
Instead, it returns as many items as possible.
|
274
|
+
|
275
|
+
Args:
|
276
|
+
sym (str): A string containing symbols to remove from src (e.g., "?!" or "!?")
|
277
|
+
src (str): The source string from which to remove the symbols
|
278
|
+
unpack_val (int): The expected number of items to unpack from the result
|
279
|
+
replace (str, optional): The string to replace the removed symbols with (default is an empty string).
|
280
|
+
sep (str, optional): The separator used to split the modified source string (default is ".").
|
281
|
+
|
282
|
+
Returns:
|
283
|
+
tuple[str, ...]: A tuple of unpacked values from the modified source string.
|
284
|
+
"""
|
285
|
+
zapper = Zapper(sym, src, replace, expected_unpack=unpack_val, sep=sep, unpack_strict=False)
|
286
|
+
return zapper.zap_get().unpacked
|
287
|
+
|
288
|
+
|
289
|
+
def zap_as_multi[T](
|
290
|
+
*sym,
|
291
|
+
src: str,
|
292
|
+
unpack_val: int,
|
293
|
+
replace: str = "",
|
294
|
+
sep: str | None = None,
|
295
|
+
func: Callable[[str], T] = str,
|
296
|
+
strict: bool = True,
|
297
|
+
regex: bool = False,
|
298
|
+
atomic: bool = True,
|
299
|
+
filter_start: bool = False, # Will filter out any separators at the start of the string
|
300
|
+
filter_end: bool = False, # Will filter out any separators at the end of the string
|
301
|
+
sorting: Literal["length", "order"] = "length", # Will sort the input symbols by length in descending order
|
302
|
+
) -> tuple[T, ...]:
|
303
|
+
"""Remove specified symbols from the source string, unpack the result, and convert it to a specified type.
|
304
|
+
|
305
|
+
Args:
|
306
|
+
*sym: A variable number of strings containing symbols to remove from src (e.g., "?!" or "!?")
|
307
|
+
src (str): The source string from which to remove the symbols
|
308
|
+
unpack_val (int): The expected number of items to unpack from the result
|
309
|
+
replace (str, optional): The string to replace the removed symbols with (default is an empty string).
|
310
|
+
sep (str, optional): The separator used to split the modified source string (default is ".").
|
311
|
+
func (type, optional): The type of the result to cast/convert to (default is str).
|
312
|
+
|
313
|
+
Returns:
|
314
|
+
Zapper: An instance of the Zapper class configured with the provided parameters.
|
315
|
+
"""
|
316
|
+
if sep is None:
|
317
|
+
sep = replace
|
318
|
+
|
319
|
+
zapper: Zapper[T] = Zapper(
|
320
|
+
str_input=sym,
|
321
|
+
src=src,
|
322
|
+
replace=replace,
|
323
|
+
expected_unpack=unpack_val,
|
324
|
+
sep=sep,
|
325
|
+
func=func,
|
326
|
+
unpack_strict=strict,
|
327
|
+
regex=regex,
|
328
|
+
atomic=atomic,
|
329
|
+
filter_start=filter_start,
|
330
|
+
filter_end=filter_end,
|
331
|
+
sorting=sorting,
|
332
|
+
)
|
333
|
+
try:
|
334
|
+
return zapper.zap_get().zap_as().unpacked
|
335
|
+
except Exception as e:
|
336
|
+
raise ValueError(f"Error converting values: {e}") from e
|
337
|
+
|
338
|
+
|
339
|
+
def zap_as[T](
|
340
|
+
sym: str,
|
341
|
+
src: str,
|
342
|
+
unpack_val: int,
|
343
|
+
replace: str = "",
|
344
|
+
sep: str | None = None,
|
345
|
+
func: Callable[[str], T] = str,
|
346
|
+
strict: bool = True,
|
347
|
+
regex: bool = False,
|
348
|
+
filter_start: bool = False, # Will filter out any separators at the start of the string
|
349
|
+
filter_end: bool = False, # Will filter out any separators at the end of the string
|
350
|
+
atomic: bool = False, # If True, treat the input symbols as a single string to replace
|
351
|
+
sorting: Literal["length", "order"] = "length", # length ordering or by the order of input
|
352
|
+
) -> tuple[T, ...]:
|
353
|
+
"""Remove specified symbols from the source string, unpack the result, and convert it to a specified type.
|
354
|
+
|
355
|
+
Args:
|
356
|
+
sym (str): A string containing symbols to remove from src (e.g., "?!" or "!?")
|
357
|
+
src (str): The source string from which to remove the symbols
|
358
|
+
unpack_val (int): The expected number of items to unpack from the result
|
359
|
+
replace (str, optional): The string to replace the removed symbols with (default is an empty string).
|
360
|
+
sep (str, optional): The separator used to split the modified source string (default is ".").
|
361
|
+
func (type, optional): The type of the result to cast/convert to (default is str).
|
362
|
+
|
363
|
+
Returns:
|
364
|
+
Zapper: An instance of the Zapper class configured with the provided parameters.
|
365
|
+
"""
|
366
|
+
if sep is None:
|
367
|
+
sep = replace
|
368
|
+
|
369
|
+
zapper: Zapper[T] = Zapper(
|
370
|
+
str_input=sym,
|
371
|
+
src=src,
|
372
|
+
replace=replace,
|
373
|
+
expected_unpack=unpack_val,
|
374
|
+
sep=sep,
|
375
|
+
func=func,
|
376
|
+
unpack_strict=strict,
|
377
|
+
regex=regex,
|
378
|
+
filter_start=filter_start,
|
379
|
+
filter_end=filter_end,
|
380
|
+
atomic=atomic,
|
381
|
+
sorting=sorting,
|
382
|
+
)
|
383
|
+
try:
|
384
|
+
return zapper.zap_get().zap_as().unpacked
|
385
|
+
except Exception as e:
|
386
|
+
raise ValueError(f"Error converting values: {e}") from e
|
387
|
+
|
388
|
+
|
389
|
+
if __name__ == "__main__":
|
390
|
+
# # Example usage
|
391
|
+
# result = zap_as_multi("()", "(", ")", src="(a)(b)(c)", unpack_val=3, replace="|", atomic=False)
|
392
|
+
# print(result)
|
393
|
+
# assert result == ("a", "b", "c")
|
394
|
+
|
395
|
+
version_string = "v1.2.3-beta+build"
|
396
|
+
result = zap_as_multi(
|
397
|
+
"v", "-", "+", src=version_string, unpack_val=3, replace=".", func=int, strict=True, filter_start=True
|
398
|
+
)
|
399
|
+
print(result)
|