devkitx 1.0.0__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.
@@ -0,0 +1,320 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import getpass
5
+ import threading
6
+ import time
7
+ from contextlib import contextmanager
8
+ from typing import Any, Iterator, TypeVar
9
+
10
+ from rich.console import Console
11
+ from rich.progress import Progress
12
+ from rich.table import Table
13
+ from rich.text import Text
14
+
15
+ T = TypeVar("T")
16
+
17
+
18
+ def parse_args(schema: dict[str, Any]) -> argparse.Namespace:
19
+ """
20
+ Tiny wrapper around argparse.
21
+ schema example:
22
+ {
23
+ "--input": str,
24
+ "--count": (int, 3),
25
+ "--verbose": bool,
26
+ }
27
+ """
28
+ parser = argparse.ArgumentParser()
29
+ for opt, spec in schema.items():
30
+ if isinstance(spec, tuple) and len(spec) == 2:
31
+ tp, default = spec
32
+ if tp is bool:
33
+ parser.add_argument(opt, action="store_true", default=bool(default))
34
+ else:
35
+ parser.add_argument(opt, type=tp, default=default)
36
+ else:
37
+ if spec is bool:
38
+ parser.add_argument(opt, action="store_true")
39
+ else:
40
+ parser.add_argument(opt, type=spec)
41
+ return parser.parse_args()
42
+
43
+
44
+ def confirm(prompt: str, default: bool = True) -> bool:
45
+ suffix = "[Y/n]" if default else "[y/N]"
46
+ while True:
47
+ resp = input(f"{prompt} {suffix} ").strip().lower()
48
+ if not resp:
49
+ return default
50
+ if resp in {"y", "yes"}:
51
+ return True
52
+ if resp in {"n", "no"}:
53
+ return False
54
+
55
+
56
+ def select(options: list[str], prompt: str = "Choose:") -> str:
57
+ if not options:
58
+ raise ValueError("options must not be empty")
59
+ for i, opt in enumerate(options, 1):
60
+ print(f"{i}) {opt}")
61
+ while True:
62
+ resp = input(f"{prompt} [1-{len(options)}] ").strip()
63
+ if resp.isdigit():
64
+ idx = int(resp)
65
+ if 1 <= idx <= len(options):
66
+ return options[idx - 1]
67
+
68
+
69
+ def password_prompt(prompt: str, confirm: bool = False) -> str:
70
+ """
71
+ Prompt for a password with optional confirmation.
72
+
73
+ Args:
74
+ prompt: The prompt message to display
75
+ confirm: Whether to ask for password confirmation
76
+
77
+ Returns:
78
+ The entered password
79
+
80
+ Raises:
81
+ ValueError: If confirmation passwords don't match
82
+
83
+ Example:
84
+ >>> password = password_prompt("Enter password:")
85
+ >>> password = password_prompt("Enter new password:", confirm=True)
86
+ """
87
+ password = getpass.getpass(f"{prompt} ")
88
+
89
+ if confirm:
90
+ confirm_password = getpass.getpass("Confirm password: ")
91
+ if password != confirm_password:
92
+ raise ValueError("Passwords do not match")
93
+
94
+ return password
95
+
96
+
97
+ def multi_select(options: list[str], prompt: str = "Select multiple:") -> list[str]:
98
+ """
99
+ Allow selection of multiple options from a list.
100
+
101
+ Args:
102
+ options: List of options to choose from
103
+ prompt: The prompt message to display
104
+
105
+ Returns:
106
+ List of selected options
107
+
108
+ Raises:
109
+ ValueError: If options list is empty
110
+
111
+ Example:
112
+ >>> selected = multi_select(["option1", "option2", "option3"])
113
+ >>> selected = multi_select(["red", "green", "blue"], "Pick colors:")
114
+ """
115
+ if not options:
116
+ raise ValueError("options must not be empty")
117
+
118
+ print(f"\n{prompt}")
119
+ print("Enter numbers separated by commas (e.g., 1,3,5) or 'all' for all options:")
120
+
121
+ for i, opt in enumerate(options, 1):
122
+ print(f"{i}) {opt}")
123
+
124
+ while True:
125
+ resp = input(f"Selection [1-{len(options)}]: ").strip().lower()
126
+
127
+ if resp == "all":
128
+ return options.copy()
129
+
130
+ if not resp:
131
+ continue
132
+
133
+ try:
134
+ # Parse comma-separated numbers
135
+ indices = [int(x.strip()) for x in resp.split(",") if x.strip()]
136
+
137
+ # Validate all indices are in range
138
+ if all(1 <= idx <= len(options) for idx in indices):
139
+ # Remove duplicates while preserving order
140
+ unique_indices = []
141
+ seen = set()
142
+ for idx in indices:
143
+ if idx not in seen:
144
+ unique_indices.append(idx)
145
+ seen.add(idx)
146
+
147
+ return [options[idx - 1] for idx in unique_indices]
148
+ else:
149
+ print(f"Please enter numbers between 1 and {len(options)}")
150
+
151
+ except ValueError:
152
+ print("Please enter valid numbers separated by commas")
153
+
154
+
155
+ def progress_bar(iterable: Iterator[T], desc: str = "", total: int | None = None) -> Iterator[T]:
156
+ """
157
+ Wrap an iterable with a progress bar.
158
+
159
+ Args:
160
+ iterable: The iterable to wrap
161
+ desc: Description to show with the progress bar
162
+ total: Total number of items (if known)
163
+
164
+ Yields:
165
+ Items from the original iterable
166
+
167
+ Example:
168
+ >>> for item in progress_bar(range(100), "Processing"):
169
+ ... # Do work with item
170
+ ... pass
171
+ """
172
+ console = Console()
173
+
174
+ # Convert to list if we need to determine length
175
+ if total is None:
176
+ try:
177
+ # Try to get length without consuming iterator
178
+ total = len(iterable) # type: ignore
179
+ except TypeError:
180
+ # If no length available, convert to list
181
+ items = list(iterable)
182
+ total = len(items)
183
+ iterable = iter(items)
184
+
185
+ with Progress(console=console) as progress:
186
+ task = progress.add_task(desc or "Processing...", total=total)
187
+
188
+ for item in iterable:
189
+ yield item
190
+ progress.advance(task)
191
+
192
+
193
+ @contextmanager
194
+ def spinner(message: str = "Processing..."):
195
+ """
196
+ Display a spinner while code is executing.
197
+
198
+ Args:
199
+ message: Message to display with the spinner
200
+
201
+ Example:
202
+ >>> with spinner("Loading data..."):
203
+ ... # Do some work
204
+ ... time.sleep(2)
205
+ """
206
+ console = Console()
207
+
208
+ # Simple spinner implementation using threading
209
+ stop_spinner = threading.Event()
210
+ spinner_chars = "|/-\\"
211
+
212
+ def spin():
213
+ idx = 0
214
+ while not stop_spinner.is_set():
215
+ console.print(f"\r{spinner_chars[idx % len(spinner_chars)]} {message}", end="")
216
+ idx += 1
217
+ time.sleep(0.1)
218
+ console.print(f"\r✓ {message}")
219
+
220
+ spinner_thread = threading.Thread(target=spin)
221
+ spinner_thread.daemon = True
222
+ spinner_thread.start()
223
+
224
+ try:
225
+ yield
226
+ finally:
227
+ stop_spinner.set()
228
+ spinner_thread.join(timeout=0.5)
229
+
230
+
231
+ def colored_text(text: str, color: str, bold: bool = False) -> str:
232
+ """
233
+ Return colored text for terminal output.
234
+
235
+ Args:
236
+ text: The text to color
237
+ color: Color name (red, green, blue, yellow, magenta, cyan, white, black)
238
+ bold: Whether to make the text bold
239
+
240
+ Returns:
241
+ Formatted text string
242
+
243
+ Example:
244
+ >>> print(colored_text("Success!", "green", bold=True))
245
+ >>> print(colored_text("Warning", "yellow"))
246
+ """
247
+ # Use console with force_terminal=True to ensure ANSI codes are included
248
+ console = Console(force_terminal=True, width=200)
249
+
250
+ style = color
251
+ if bold:
252
+ style = f"bold {color}"
253
+
254
+ # Create a Text object and render it to string
255
+ rich_text = Text(text, style=style)
256
+
257
+ # Use console to render the text with markup
258
+ with console.capture() as capture:
259
+ console.print(rich_text, end="")
260
+
261
+ return capture.get()
262
+
263
+
264
+ def table_format(data: list[dict[str, Any]], headers: list[str] | None = None) -> str:
265
+ """
266
+ Format data as a table.
267
+
268
+ Args:
269
+ data: List of dictionaries representing table rows
270
+ headers: Optional list of column headers (uses dict keys if not provided)
271
+
272
+ Returns:
273
+ Formatted table as string
274
+
275
+ Example:
276
+ >>> data = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
277
+ >>> print(table_format(data))
278
+ >>> print(table_format(data, headers=["Name", "Age"]))
279
+ """
280
+ if not data:
281
+ return ""
282
+
283
+ console = Console()
284
+
285
+ # Determine headers and create mapping
286
+ if headers is None:
287
+ headers = list(data[0].keys())
288
+ key_mapping = {h: h for h in headers}
289
+ else:
290
+ # If custom headers provided, map them to original keys
291
+ original_keys = list(data[0].keys())
292
+ key_mapping = {}
293
+ for i, header in enumerate(headers):
294
+ if i < len(original_keys):
295
+ key_mapping[header] = original_keys[i]
296
+ else:
297
+ key_mapping[header] = header
298
+
299
+ # Create table
300
+ table = Table()
301
+
302
+ # Add columns
303
+ for header in headers:
304
+ table.add_column(header, style="cyan")
305
+
306
+ # Add rows
307
+ for row in data:
308
+ row_values = []
309
+ for header in headers:
310
+ # Use the mapping to get the correct key from the data
311
+ data_key = key_mapping[header]
312
+ value = row.get(data_key, "")
313
+ row_values.append(str(value))
314
+ table.add_row(*row_values)
315
+
316
+ # Render table to string
317
+ with console.capture() as capture:
318
+ console.print(table)
319
+
320
+ return capture.get()