falyx 0.1.26__py3-none-any.whl → 0.1.28__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.
- falyx/action/__init__.py +2 -0
- falyx/action/action_factory.py +11 -2
- falyx/action/menu_action.py +4 -0
- falyx/action/user_input_action.py +94 -0
- falyx/argparse.py +596 -0
- falyx/command.py +35 -4
- falyx/exceptions.py +4 -0
- falyx/execution_registry.py +1 -1
- falyx/falyx.py +95 -43
- falyx/parsers.py +7 -1
- falyx/protocols.py +8 -2
- falyx/signals.py +14 -0
- falyx/utils.py +1 -0
- falyx/version.py +1 -1
- {falyx-0.1.26.dist-info → falyx-0.1.28.dist-info}/METADATA +1 -1
- {falyx-0.1.26.dist-info → falyx-0.1.28.dist-info}/RECORD +19 -17
- {falyx-0.1.26.dist-info → falyx-0.1.28.dist-info}/LICENSE +0 -0
- {falyx-0.1.26.dist-info → falyx-0.1.28.dist-info}/WHEEL +0 -0
- {falyx-0.1.26.dist-info → falyx-0.1.28.dist-info}/entry_points.txt +0 -0
falyx/argparse.py
ADDED
@@ -0,0 +1,596 @@
|
|
1
|
+
# Falyx CLI Framework — (c) 2025 rtj.dev LLC — MIT Licensed
|
2
|
+
from copy import deepcopy
|
3
|
+
from dataclasses import dataclass
|
4
|
+
from enum import Enum
|
5
|
+
from typing import Any, Iterable
|
6
|
+
|
7
|
+
from rich.console import Console
|
8
|
+
from rich.table import Table
|
9
|
+
|
10
|
+
from falyx.exceptions import CommandArgumentError
|
11
|
+
from falyx.signals import HelpSignal
|
12
|
+
|
13
|
+
|
14
|
+
class ArgumentAction(Enum):
|
15
|
+
"""Defines the action to be taken when the argument is encountered."""
|
16
|
+
|
17
|
+
STORE = "store"
|
18
|
+
STORE_TRUE = "store_true"
|
19
|
+
STORE_FALSE = "store_false"
|
20
|
+
APPEND = "append"
|
21
|
+
EXTEND = "extend"
|
22
|
+
COUNT = "count"
|
23
|
+
HELP = "help"
|
24
|
+
|
25
|
+
|
26
|
+
@dataclass
|
27
|
+
class Argument:
|
28
|
+
"""Represents a command-line argument."""
|
29
|
+
|
30
|
+
flags: list[str]
|
31
|
+
dest: str # Destination name for the argument
|
32
|
+
action: ArgumentAction = (
|
33
|
+
ArgumentAction.STORE
|
34
|
+
) # Action to be taken when the argument is encountered
|
35
|
+
type: Any = str # Type of the argument (e.g., str, int, float) or callable
|
36
|
+
default: Any = None # Default value if the argument is not provided
|
37
|
+
choices: list[str] | None = None # List of valid choices for the argument
|
38
|
+
required: bool = False # True if the argument is required
|
39
|
+
help: str = "" # Help text for the argument
|
40
|
+
nargs: int | str = 1 # int, '?', '*', '+'
|
41
|
+
positional: bool = False # True if no leading - or -- in flags
|
42
|
+
|
43
|
+
|
44
|
+
class CommandArgumentParser:
|
45
|
+
"""
|
46
|
+
Custom argument parser for Falyx Commands.
|
47
|
+
It is used to create a command-line interface for Falyx
|
48
|
+
commands, allowing users to specify options and arguments
|
49
|
+
when executing commands.
|
50
|
+
It is not intended to be a full-featured replacement for
|
51
|
+
argparse, but rather a lightweight alternative for specific use
|
52
|
+
cases within the Falyx framework.
|
53
|
+
|
54
|
+
Features:
|
55
|
+
- Customizable argument parsing.
|
56
|
+
- Type coercion for arguments.
|
57
|
+
- Support for positional and keyword arguments.
|
58
|
+
- Support for default values.
|
59
|
+
- Support for boolean flags.
|
60
|
+
- Exception handling for invalid arguments.
|
61
|
+
- Render Help using Rich library.
|
62
|
+
"""
|
63
|
+
|
64
|
+
def __init__(self) -> None:
|
65
|
+
"""Initialize the CommandArgumentParser."""
|
66
|
+
self.command_description: str = ""
|
67
|
+
self._arguments: list[Argument] = []
|
68
|
+
self._flag_map: dict[str, Argument] = {}
|
69
|
+
self._dest_set: set[str] = set()
|
70
|
+
self._add_help()
|
71
|
+
self.console = Console(color_system="auto")
|
72
|
+
|
73
|
+
def _add_help(self):
|
74
|
+
"""Add help argument to the parser."""
|
75
|
+
self.add_argument(
|
76
|
+
"--help",
|
77
|
+
"-h",
|
78
|
+
action=ArgumentAction.HELP,
|
79
|
+
help="Show this help message and exit.",
|
80
|
+
dest="help",
|
81
|
+
)
|
82
|
+
|
83
|
+
def _is_positional(self, flags: tuple[str, ...]) -> bool:
|
84
|
+
"""Check if the flags are positional."""
|
85
|
+
positional = False
|
86
|
+
if any(not flag.startswith("-") for flag in flags):
|
87
|
+
positional = True
|
88
|
+
|
89
|
+
if positional and len(flags) > 1:
|
90
|
+
raise CommandArgumentError("Positional arguments cannot have multiple flags")
|
91
|
+
return positional
|
92
|
+
|
93
|
+
def _get_dest_from_flags(
|
94
|
+
self, flags: tuple[str, ...], dest: str | None
|
95
|
+
) -> str | None:
|
96
|
+
"""Convert flags to a destination name."""
|
97
|
+
if dest:
|
98
|
+
if not dest.replace("_", "").isalnum():
|
99
|
+
raise CommandArgumentError(
|
100
|
+
"dest must be a valid identifier (letters, digits, and underscores only)"
|
101
|
+
)
|
102
|
+
if dest[0].isdigit():
|
103
|
+
raise CommandArgumentError("dest must not start with a digit")
|
104
|
+
return dest
|
105
|
+
dest = None
|
106
|
+
for flag in flags:
|
107
|
+
if flag.startswith("--"):
|
108
|
+
dest = flag.lstrip("-").replace("-", "_").lower()
|
109
|
+
break
|
110
|
+
elif flag.startswith("-"):
|
111
|
+
dest = flag.lstrip("-").replace("-", "_").lower()
|
112
|
+
else:
|
113
|
+
dest = flag.replace("-", "_").lower()
|
114
|
+
assert dest is not None, "dest should not be None"
|
115
|
+
if not dest.replace("_", "").isalnum():
|
116
|
+
raise CommandArgumentError(
|
117
|
+
"dest must be a valid identifier (letters, digits, and underscores only)"
|
118
|
+
)
|
119
|
+
if dest[0].isdigit():
|
120
|
+
raise CommandArgumentError("dest must not start with a digit")
|
121
|
+
return dest
|
122
|
+
|
123
|
+
def _determine_required(
|
124
|
+
self, required: bool, positional: bool, nargs: int | str
|
125
|
+
) -> bool:
|
126
|
+
"""Determine if the argument is required."""
|
127
|
+
if required:
|
128
|
+
return True
|
129
|
+
if positional:
|
130
|
+
if isinstance(nargs, int):
|
131
|
+
return nargs > 0
|
132
|
+
elif isinstance(nargs, str):
|
133
|
+
if nargs in ("+"):
|
134
|
+
return True
|
135
|
+
elif nargs in ("*", "?"):
|
136
|
+
return False
|
137
|
+
else:
|
138
|
+
raise CommandArgumentError(f"Invalid nargs value: {nargs}")
|
139
|
+
|
140
|
+
return required
|
141
|
+
|
142
|
+
def _validate_nargs(self, nargs: int | str) -> int | str:
|
143
|
+
allowed_nargs = ("?", "*", "+")
|
144
|
+
if isinstance(nargs, int):
|
145
|
+
if nargs <= 0:
|
146
|
+
raise CommandArgumentError("nargs must be a positive integer")
|
147
|
+
elif isinstance(nargs, str):
|
148
|
+
if nargs not in allowed_nargs:
|
149
|
+
raise CommandArgumentError(f"Invalid nargs value: {nargs}")
|
150
|
+
else:
|
151
|
+
raise CommandArgumentError(f"nargs must be an int or one of {allowed_nargs}")
|
152
|
+
return nargs
|
153
|
+
|
154
|
+
def _normalize_choices(self, choices: Iterable, expected_type: Any) -> list[Any]:
|
155
|
+
if choices is not None:
|
156
|
+
if isinstance(choices, dict):
|
157
|
+
raise CommandArgumentError("choices cannot be a dict")
|
158
|
+
try:
|
159
|
+
choices = list(choices)
|
160
|
+
except TypeError:
|
161
|
+
raise CommandArgumentError(
|
162
|
+
"choices must be iterable (like list, tuple, or set)"
|
163
|
+
)
|
164
|
+
else:
|
165
|
+
choices = []
|
166
|
+
for choice in choices:
|
167
|
+
if not isinstance(choice, expected_type):
|
168
|
+
try:
|
169
|
+
expected_type(choice)
|
170
|
+
except Exception:
|
171
|
+
raise CommandArgumentError(
|
172
|
+
f"Invalid choice {choice!r}: not coercible to {expected_type.__name__}"
|
173
|
+
)
|
174
|
+
return choices
|
175
|
+
|
176
|
+
def _validate_default_type(
|
177
|
+
self, default: Any, expected_type: type, dest: str
|
178
|
+
) -> None:
|
179
|
+
"""Validate the default value type."""
|
180
|
+
if default is not None and not isinstance(default, expected_type):
|
181
|
+
try:
|
182
|
+
expected_type(default)
|
183
|
+
except Exception:
|
184
|
+
raise CommandArgumentError(
|
185
|
+
f"Default value {default!r} for '{dest}' cannot be coerced to {expected_type.__name__}"
|
186
|
+
)
|
187
|
+
|
188
|
+
def _validate_default_list_type(
|
189
|
+
self, default: list[Any], expected_type: type, dest: str
|
190
|
+
) -> None:
|
191
|
+
if isinstance(default, list):
|
192
|
+
for item in default:
|
193
|
+
if not isinstance(item, expected_type):
|
194
|
+
try:
|
195
|
+
expected_type(item)
|
196
|
+
except Exception:
|
197
|
+
raise CommandArgumentError(
|
198
|
+
f"Default list value {default!r} for '{dest}' cannot be coerced to {expected_type.__name__}"
|
199
|
+
)
|
200
|
+
|
201
|
+
def _resolve_default(
|
202
|
+
self, action: ArgumentAction, default: Any, nargs: str | int
|
203
|
+
) -> Any:
|
204
|
+
"""Get the default value for the argument."""
|
205
|
+
if default is None:
|
206
|
+
if action == ArgumentAction.STORE_TRUE:
|
207
|
+
return False
|
208
|
+
elif action == ArgumentAction.STORE_FALSE:
|
209
|
+
return True
|
210
|
+
elif action == ArgumentAction.COUNT:
|
211
|
+
return 0
|
212
|
+
elif action in (ArgumentAction.APPEND, ArgumentAction.EXTEND):
|
213
|
+
return []
|
214
|
+
elif nargs in ("+", "*"):
|
215
|
+
return []
|
216
|
+
else:
|
217
|
+
return None
|
218
|
+
return default
|
219
|
+
|
220
|
+
def _validate_flags(self, flags: tuple[str, ...]) -> None:
|
221
|
+
"""Validate the flags provided for the argument."""
|
222
|
+
if not flags:
|
223
|
+
raise CommandArgumentError("No flags provided")
|
224
|
+
for flag in flags:
|
225
|
+
if not isinstance(flag, str):
|
226
|
+
raise CommandArgumentError(f"Flag '{flag}' must be a string")
|
227
|
+
if flag.startswith("--") and len(flag) < 3:
|
228
|
+
raise CommandArgumentError(
|
229
|
+
f"Flag '{flag}' must be at least 3 characters long"
|
230
|
+
)
|
231
|
+
if flag.startswith("-") and not flag.startswith("--") and len(flag) > 2:
|
232
|
+
raise CommandArgumentError(
|
233
|
+
f"Flag '{flag}' must be a single character or start with '--'"
|
234
|
+
)
|
235
|
+
|
236
|
+
def add_argument(self, *flags, **kwargs):
|
237
|
+
"""Add an argument to the parser.
|
238
|
+
Args:
|
239
|
+
name or flags: Either a name or prefixed flags (e.g. 'faylx', '-f', '--falyx').
|
240
|
+
action: The action to be taken when the argument is encountered.
|
241
|
+
nargs: The number of arguments expected.
|
242
|
+
default: The default value if the argument is not provided.
|
243
|
+
type: The type to which the command-line argument should be converted.
|
244
|
+
choices: A container of the allowable values for the argument.
|
245
|
+
required: Whether or not the argument is required.
|
246
|
+
help: A brief description of the argument.
|
247
|
+
dest: The name of the attribute to be added to the object returned by parse_args().
|
248
|
+
"""
|
249
|
+
self._validate_flags(flags)
|
250
|
+
positional = self._is_positional(flags)
|
251
|
+
dest = self._get_dest_from_flags(flags, kwargs.get("dest"))
|
252
|
+
if dest in self._dest_set:
|
253
|
+
raise CommandArgumentError(
|
254
|
+
f"Destination '{dest}' is already defined.\n"
|
255
|
+
"Merging multiple arguments into the same dest (e.g. positional + flagged) "
|
256
|
+
"is not supported. Define a unique 'dest' for each argument."
|
257
|
+
)
|
258
|
+
self._dest_set.add(dest)
|
259
|
+
action = kwargs.get("action", ArgumentAction.STORE)
|
260
|
+
if not isinstance(action, ArgumentAction):
|
261
|
+
try:
|
262
|
+
action = ArgumentAction(action)
|
263
|
+
except ValueError:
|
264
|
+
raise CommandArgumentError(
|
265
|
+
f"Invalid action '{action}' is not a valid ArgumentAction"
|
266
|
+
)
|
267
|
+
flags = list(flags)
|
268
|
+
nargs = self._validate_nargs(kwargs.get("nargs", 1))
|
269
|
+
default = self._resolve_default(action, kwargs.get("default"), nargs)
|
270
|
+
expected_type = kwargs.get("type", str)
|
271
|
+
if (
|
272
|
+
action in (ArgumentAction.STORE, ArgumentAction.APPEND, ArgumentAction.EXTEND)
|
273
|
+
and default is not None
|
274
|
+
):
|
275
|
+
if isinstance(default, list):
|
276
|
+
self._validate_default_list_type(default, expected_type, dest)
|
277
|
+
else:
|
278
|
+
self._validate_default_type(default, expected_type, dest)
|
279
|
+
choices = self._normalize_choices(kwargs.get("choices"), expected_type)
|
280
|
+
if default is not None and choices and default not in choices:
|
281
|
+
raise CommandArgumentError(
|
282
|
+
f"Default value '{default}' not in allowed choices: {choices}"
|
283
|
+
)
|
284
|
+
required = self._determine_required(
|
285
|
+
kwargs.get("required", False), positional, nargs
|
286
|
+
)
|
287
|
+
argument = Argument(
|
288
|
+
flags=flags,
|
289
|
+
dest=dest,
|
290
|
+
action=action,
|
291
|
+
type=expected_type,
|
292
|
+
default=default,
|
293
|
+
choices=choices,
|
294
|
+
required=required,
|
295
|
+
help=kwargs.get("help", ""),
|
296
|
+
nargs=nargs,
|
297
|
+
positional=positional,
|
298
|
+
)
|
299
|
+
for flag in flags:
|
300
|
+
if flag in self._flag_map:
|
301
|
+
existing = self._flag_map[flag]
|
302
|
+
raise CommandArgumentError(
|
303
|
+
f"Flag '{flag}' is already used by argument '{existing.dest}'"
|
304
|
+
)
|
305
|
+
self._flag_map[flag] = argument
|
306
|
+
self._arguments.append(argument)
|
307
|
+
|
308
|
+
def get_argument(self, dest: str) -> Argument | None:
|
309
|
+
return next((a for a in self._arguments if a.dest == dest), None)
|
310
|
+
|
311
|
+
def _consume_nargs(
|
312
|
+
self, args: list[str], start: int, spec: Argument
|
313
|
+
) -> tuple[list[str], int]:
|
314
|
+
values = []
|
315
|
+
i = start
|
316
|
+
if isinstance(spec.nargs, int):
|
317
|
+
# assert i + spec.nargs <= len(
|
318
|
+
# args
|
319
|
+
# ), "Not enough arguments provided: shouldn't happen"
|
320
|
+
values = args[i : i + spec.nargs]
|
321
|
+
return values, i + spec.nargs
|
322
|
+
elif spec.nargs == "+":
|
323
|
+
if i >= len(args):
|
324
|
+
raise CommandArgumentError(
|
325
|
+
f"Expected at least one value for '{spec.dest}'"
|
326
|
+
)
|
327
|
+
while i < len(args) and not args[i].startswith("-"):
|
328
|
+
values.append(args[i])
|
329
|
+
i += 1
|
330
|
+
assert values, "Expected at least one value for '+' nargs: shouldn't happen"
|
331
|
+
return values, i
|
332
|
+
elif spec.nargs == "*":
|
333
|
+
while i < len(args) and not args[i].startswith("-"):
|
334
|
+
values.append(args[i])
|
335
|
+
i += 1
|
336
|
+
return values, i
|
337
|
+
elif spec.nargs == "?":
|
338
|
+
if i < len(args) and not args[i].startswith("-"):
|
339
|
+
return [args[i]], i + 1
|
340
|
+
return [], i
|
341
|
+
else:
|
342
|
+
assert False, "Invalid nargs value: shouldn't happen"
|
343
|
+
|
344
|
+
def _consume_all_positional_args(
|
345
|
+
self,
|
346
|
+
args: list[str],
|
347
|
+
result: dict[str, Any],
|
348
|
+
positional_args: list[Argument],
|
349
|
+
consumed_positional_indicies: set[int],
|
350
|
+
) -> int:
|
351
|
+
remaining_positional_args = [
|
352
|
+
(j, spec)
|
353
|
+
for j, spec in enumerate(positional_args)
|
354
|
+
if j not in consumed_positional_indicies
|
355
|
+
]
|
356
|
+
i = 0
|
357
|
+
|
358
|
+
for j, spec in remaining_positional_args:
|
359
|
+
# estimate how many args the remaining specs might need
|
360
|
+
is_last = j == len(positional_args) - 1
|
361
|
+
remaining = len(args) - i
|
362
|
+
min_required = 0
|
363
|
+
for next_spec in positional_args[j + 1 :]:
|
364
|
+
if isinstance(next_spec.nargs, int):
|
365
|
+
min_required += next_spec.nargs
|
366
|
+
elif next_spec.nargs == "+":
|
367
|
+
min_required += 1
|
368
|
+
elif next_spec.nargs == "?":
|
369
|
+
min_required += 0
|
370
|
+
elif next_spec.nargs == "*":
|
371
|
+
min_required += 0
|
372
|
+
else:
|
373
|
+
assert False, "Invalid nargs value: shouldn't happen"
|
374
|
+
|
375
|
+
slice_args = args[i:] if is_last else args[i : i + (remaining - min_required)]
|
376
|
+
values, new_i = self._consume_nargs(slice_args, 0, spec)
|
377
|
+
i += new_i
|
378
|
+
|
379
|
+
try:
|
380
|
+
typed = [spec.type(v) for v in values]
|
381
|
+
except Exception:
|
382
|
+
raise CommandArgumentError(
|
383
|
+
f"Invalid value for '{spec.dest}': expected {spec.type.__name__}"
|
384
|
+
)
|
385
|
+
|
386
|
+
if spec.action == ArgumentAction.APPEND:
|
387
|
+
assert result.get(spec.dest) is not None, "dest should not be None"
|
388
|
+
if spec.nargs in (None, 1):
|
389
|
+
result[spec.dest].append(typed[0])
|
390
|
+
else:
|
391
|
+
result[spec.dest].append(typed)
|
392
|
+
elif spec.action == ArgumentAction.EXTEND:
|
393
|
+
assert result.get(spec.dest) is not None, "dest should not be None"
|
394
|
+
result[spec.dest].extend(typed)
|
395
|
+
elif spec.nargs in (None, 1, "?"):
|
396
|
+
result[spec.dest] = typed[0] if len(typed) == 1 else typed
|
397
|
+
else:
|
398
|
+
result[spec.dest] = typed
|
399
|
+
|
400
|
+
if spec.nargs not in ("*", "+"):
|
401
|
+
consumed_positional_indicies.add(j)
|
402
|
+
|
403
|
+
if i < len(args):
|
404
|
+
raise CommandArgumentError(f"Unexpected positional argument: {args[i:]}")
|
405
|
+
|
406
|
+
return i
|
407
|
+
|
408
|
+
def parse_args(self, args: list[str] | None = None) -> dict[str, Any]:
|
409
|
+
"""Parse Falyx Command arguments."""
|
410
|
+
if args is None:
|
411
|
+
args = []
|
412
|
+
|
413
|
+
result = {arg.dest: deepcopy(arg.default) for arg in self._arguments}
|
414
|
+
positional_args = [arg for arg in self._arguments if arg.positional]
|
415
|
+
consumed_positional_indices: set[int] = set()
|
416
|
+
|
417
|
+
consumed_indices: set[int] = set()
|
418
|
+
i = 0
|
419
|
+
while i < len(args):
|
420
|
+
token = args[i]
|
421
|
+
if token in self._flag_map:
|
422
|
+
spec = self._flag_map[token]
|
423
|
+
action = spec.action
|
424
|
+
|
425
|
+
if action == ArgumentAction.HELP:
|
426
|
+
self.render_help()
|
427
|
+
raise HelpSignal()
|
428
|
+
elif action == ArgumentAction.STORE_TRUE:
|
429
|
+
result[spec.dest] = True
|
430
|
+
consumed_indices.add(i)
|
431
|
+
i += 1
|
432
|
+
elif action == ArgumentAction.STORE_FALSE:
|
433
|
+
result[spec.dest] = False
|
434
|
+
consumed_indices.add(i)
|
435
|
+
i += 1
|
436
|
+
elif action == ArgumentAction.COUNT:
|
437
|
+
result[spec.dest] = result.get(spec.dest, 0) + 1
|
438
|
+
consumed_indices.add(i)
|
439
|
+
i += 1
|
440
|
+
elif action == ArgumentAction.APPEND:
|
441
|
+
assert result.get(spec.dest) is not None, "dest should not be None"
|
442
|
+
values, new_i = self._consume_nargs(args, i + 1, spec)
|
443
|
+
try:
|
444
|
+
typed_values = [spec.type(value) for value in values]
|
445
|
+
except ValueError:
|
446
|
+
raise CommandArgumentError(
|
447
|
+
f"Invalid value for '{spec.dest}': expected {spec.type.__name__}"
|
448
|
+
)
|
449
|
+
if spec.nargs in (None, 1):
|
450
|
+
try:
|
451
|
+
result[spec.dest].append(spec.type(values[0]))
|
452
|
+
except ValueError:
|
453
|
+
raise CommandArgumentError(
|
454
|
+
f"Invalid value for '{spec.dest}': expected {spec.type.__name__}"
|
455
|
+
)
|
456
|
+
else:
|
457
|
+
result[spec.dest].append(typed_values)
|
458
|
+
consumed_indices.update(range(i, new_i))
|
459
|
+
i = new_i
|
460
|
+
elif action == ArgumentAction.EXTEND:
|
461
|
+
assert result.get(spec.dest) is not None, "dest should not be None"
|
462
|
+
values, new_i = self._consume_nargs(args, i + 1, spec)
|
463
|
+
try:
|
464
|
+
typed_values = [spec.type(value) for value in values]
|
465
|
+
except ValueError:
|
466
|
+
raise CommandArgumentError(
|
467
|
+
f"Invalid value for '{spec.dest}': expected {spec.type.__name__}"
|
468
|
+
)
|
469
|
+
result[spec.dest].extend(typed_values)
|
470
|
+
consumed_indices.update(range(i, new_i))
|
471
|
+
i = new_i
|
472
|
+
else:
|
473
|
+
values, new_i = self._consume_nargs(args, i + 1, spec)
|
474
|
+
try:
|
475
|
+
typed_values = [spec.type(v) for v in values]
|
476
|
+
except ValueError:
|
477
|
+
raise CommandArgumentError(
|
478
|
+
f"Invalid value for '{spec.dest}': expected {spec.type.__name__}"
|
479
|
+
)
|
480
|
+
if (
|
481
|
+
spec.nargs in (None, 1, "?")
|
482
|
+
and spec.action != ArgumentAction.APPEND
|
483
|
+
):
|
484
|
+
result[spec.dest] = (
|
485
|
+
typed_values[0] if len(typed_values) == 1 else typed_values
|
486
|
+
)
|
487
|
+
else:
|
488
|
+
result[spec.dest] = typed_values
|
489
|
+
consumed_indices.update(range(i, new_i))
|
490
|
+
i = new_i
|
491
|
+
else:
|
492
|
+
# Get the next flagged argument index if it exists
|
493
|
+
next_flagged_index = -1
|
494
|
+
for index, arg in enumerate(args[i:], start=i):
|
495
|
+
if arg.startswith("-"):
|
496
|
+
next_flagged_index = index
|
497
|
+
break
|
498
|
+
if next_flagged_index == -1:
|
499
|
+
next_flagged_index = len(args)
|
500
|
+
|
501
|
+
args_consumed = self._consume_all_positional_args(
|
502
|
+
args[i:next_flagged_index],
|
503
|
+
result,
|
504
|
+
positional_args,
|
505
|
+
consumed_positional_indices,
|
506
|
+
)
|
507
|
+
i += args_consumed
|
508
|
+
|
509
|
+
# Required validation
|
510
|
+
for spec in self._arguments:
|
511
|
+
if spec.dest == "help":
|
512
|
+
continue
|
513
|
+
if spec.required and not result.get(spec.dest):
|
514
|
+
raise CommandArgumentError(f"Missing required argument: {spec.dest}")
|
515
|
+
|
516
|
+
if spec.choices and result.get(spec.dest) not in spec.choices:
|
517
|
+
raise CommandArgumentError(
|
518
|
+
f"Invalid value for {spec.dest}: must be one of {spec.choices}"
|
519
|
+
)
|
520
|
+
|
521
|
+
if isinstance(spec.nargs, int) and spec.nargs > 1:
|
522
|
+
if not isinstance(result.get(spec.dest), list):
|
523
|
+
raise CommandArgumentError(
|
524
|
+
f"Invalid value for {spec.dest}: expected a list"
|
525
|
+
)
|
526
|
+
if spec.action == ArgumentAction.APPEND:
|
527
|
+
if not isinstance(result[spec.dest], list):
|
528
|
+
raise CommandArgumentError(
|
529
|
+
f"Invalid value for {spec.dest}: expected a list"
|
530
|
+
)
|
531
|
+
for group in result[spec.dest]:
|
532
|
+
if len(group) % spec.nargs != 0:
|
533
|
+
raise CommandArgumentError(
|
534
|
+
f"Invalid number of values for {spec.dest}: expected a multiple of {spec.nargs}"
|
535
|
+
)
|
536
|
+
elif spec.action == ArgumentAction.EXTEND:
|
537
|
+
if not isinstance(result[spec.dest], list):
|
538
|
+
raise CommandArgumentError(
|
539
|
+
f"Invalid value for {spec.dest}: expected a list"
|
540
|
+
)
|
541
|
+
if len(result[spec.dest]) % spec.nargs != 0:
|
542
|
+
raise CommandArgumentError(
|
543
|
+
f"Invalid number of values for {spec.dest}: expected a multiple of {spec.nargs}"
|
544
|
+
)
|
545
|
+
elif len(result[spec.dest]) != spec.nargs:
|
546
|
+
raise CommandArgumentError(
|
547
|
+
f"Invalid number of values for {spec.dest}: expected {spec.nargs}, got {len(result[spec.dest])}"
|
548
|
+
)
|
549
|
+
|
550
|
+
result.pop("help", None)
|
551
|
+
return result
|
552
|
+
|
553
|
+
def parse_args_split(self, args: list[str]) -> tuple[tuple[Any, ...], dict[str, Any]]:
|
554
|
+
"""
|
555
|
+
Returns:
|
556
|
+
tuple[args, kwargs] - Positional arguments in defined order,
|
557
|
+
followed by keyword argument mapping.
|
558
|
+
"""
|
559
|
+
parsed = self.parse_args(args)
|
560
|
+
args_list = []
|
561
|
+
kwargs_dict = {}
|
562
|
+
for arg in self._arguments:
|
563
|
+
if arg.dest == "help":
|
564
|
+
continue
|
565
|
+
if arg.positional:
|
566
|
+
args_list.append(parsed[arg.dest])
|
567
|
+
else:
|
568
|
+
kwargs_dict[arg.dest] = parsed[arg.dest]
|
569
|
+
return tuple(args_list), kwargs_dict
|
570
|
+
|
571
|
+
def render_help(self):
|
572
|
+
table = Table(title=f"{self.command_description} Help")
|
573
|
+
table.add_column("Flags")
|
574
|
+
table.add_column("Help")
|
575
|
+
for arg in self._arguments:
|
576
|
+
if arg.dest == "help":
|
577
|
+
continue
|
578
|
+
flag_str = ", ".join(arg.flags) if not arg.positional else arg.dest
|
579
|
+
table.add_row(flag_str, arg.help or "")
|
580
|
+
table.add_section()
|
581
|
+
arg = self.get_argument("help")
|
582
|
+
flag_str = ", ".join(arg.flags) if not arg.positional else arg.dest
|
583
|
+
table.add_row(flag_str, arg.help or "")
|
584
|
+
self.console.print(table)
|
585
|
+
|
586
|
+
def __str__(self) -> str:
|
587
|
+
positional = sum(arg.positional for arg in self._arguments)
|
588
|
+
required = sum(arg.required for arg in self._arguments)
|
589
|
+
return (
|
590
|
+
f"CommandArgumentParser(args={len(self._arguments)}, "
|
591
|
+
f"flags={len(self._flag_map)}, dests={len(self._dest_set)}, "
|
592
|
+
f"required={required}, positional={positional})"
|
593
|
+
)
|
594
|
+
|
595
|
+
def __repr__(self) -> str:
|
596
|
+
return str(self)
|
falyx/command.py
CHANGED
@@ -18,6 +18,7 @@ in building robust interactive menus.
|
|
18
18
|
"""
|
19
19
|
from __future__ import annotations
|
20
20
|
|
21
|
+
import shlex
|
21
22
|
from functools import cached_property
|
22
23
|
from typing import Any, Callable
|
23
24
|
|
@@ -28,18 +29,20 @@ from rich.tree import Tree
|
|
28
29
|
|
29
30
|
from falyx.action.action import Action, ActionGroup, BaseAction, ChainedAction
|
30
31
|
from falyx.action.io_action import BaseIOAction
|
32
|
+
from falyx.argparse import CommandArgumentParser
|
31
33
|
from falyx.context import ExecutionContext
|
32
34
|
from falyx.debug import register_debug_hooks
|
33
|
-
from falyx.exceptions import FalyxError
|
34
35
|
from falyx.execution_registry import ExecutionRegistry as er
|
35
36
|
from falyx.hook_manager import HookManager, HookType
|
36
37
|
from falyx.logger import logger
|
37
38
|
from falyx.options_manager import OptionsManager
|
38
39
|
from falyx.prompt_utils import confirm_async, should_prompt_user
|
40
|
+
from falyx.protocols import ArgParserProtocol
|
39
41
|
from falyx.retry import RetryPolicy
|
40
42
|
from falyx.retry_utils import enable_retries_recursively
|
43
|
+
from falyx.signals import CancelSignal
|
41
44
|
from falyx.themes import OneColors
|
42
|
-
from falyx.utils import
|
45
|
+
from falyx.utils import ensure_async
|
43
46
|
|
44
47
|
console = Console(color_system="auto")
|
45
48
|
|
@@ -98,7 +101,7 @@ class Command(BaseModel):
|
|
98
101
|
|
99
102
|
key: str
|
100
103
|
description: str
|
101
|
-
action: BaseAction | Callable[[], Any]
|
104
|
+
action: BaseAction | Callable[[], Any]
|
102
105
|
args: tuple = ()
|
103
106
|
kwargs: dict[str, Any] = Field(default_factory=dict)
|
104
107
|
hidden: bool = False
|
@@ -121,11 +124,24 @@ class Command(BaseModel):
|
|
121
124
|
logging_hooks: bool = False
|
122
125
|
requires_input: bool | None = None
|
123
126
|
options_manager: OptionsManager = Field(default_factory=OptionsManager)
|
127
|
+
arg_parser: CommandArgumentParser = Field(default_factory=CommandArgumentParser)
|
128
|
+
custom_parser: ArgParserProtocol | None = None
|
129
|
+
custom_help: Callable[[], str | None] | None = None
|
124
130
|
|
125
131
|
_context: ExecutionContext | None = PrivateAttr(default=None)
|
126
132
|
|
127
133
|
model_config = ConfigDict(arbitrary_types_allowed=True)
|
128
134
|
|
135
|
+
def parse_args(self, raw_args: list[str] | str) -> tuple[tuple, dict]:
|
136
|
+
if self.custom_parser:
|
137
|
+
if isinstance(raw_args, str):
|
138
|
+
raw_args = shlex.split(raw_args)
|
139
|
+
return self.custom_parser(raw_args)
|
140
|
+
|
141
|
+
if isinstance(raw_args, str):
|
142
|
+
raw_args = shlex.split(raw_args)
|
143
|
+
return self.arg_parser.parse_args_split(raw_args)
|
144
|
+
|
129
145
|
@field_validator("action", mode="before")
|
130
146
|
@classmethod
|
131
147
|
def wrap_callable_as_async(cls, action: Any) -> Any:
|
@@ -137,6 +153,9 @@ class Command(BaseModel):
|
|
137
153
|
|
138
154
|
def model_post_init(self, _: Any) -> None:
|
139
155
|
"""Post-initialization to set up the action and hooks."""
|
156
|
+
if isinstance(self.arg_parser, CommandArgumentParser):
|
157
|
+
self.arg_parser.command_description = self.description
|
158
|
+
|
140
159
|
if self.retry and isinstance(self.action, Action):
|
141
160
|
self.action.enable_retry()
|
142
161
|
elif self.retry_policy and isinstance(self.action, Action):
|
@@ -205,7 +224,7 @@ class Command(BaseModel):
|
|
205
224
|
await self.preview()
|
206
225
|
if not await confirm_async(self.confirmation_prompt):
|
207
226
|
logger.info("[Command:%s] ❌ Cancelled by user.", self.key)
|
208
|
-
raise
|
227
|
+
raise CancelSignal(f"[Command:{self.key}] Cancelled by confirmation.")
|
209
228
|
|
210
229
|
context.start_timer()
|
211
230
|
|
@@ -269,6 +288,18 @@ class Command(BaseModel):
|
|
269
288
|
if self._context:
|
270
289
|
self._context.log_summary()
|
271
290
|
|
291
|
+
def show_help(self) -> bool:
|
292
|
+
"""Display the help message for the command."""
|
293
|
+
if self.custom_help:
|
294
|
+
output = self.custom_help()
|
295
|
+
if output:
|
296
|
+
console.print(output)
|
297
|
+
return True
|
298
|
+
if isinstance(self.arg_parser, CommandArgumentParser):
|
299
|
+
self.arg_parser.render_help()
|
300
|
+
return True
|
301
|
+
return False
|
302
|
+
|
272
303
|
async def preview(self) -> None:
|
273
304
|
label = f"[{OneColors.GREEN_b}]Command:[/] '{self.key}' — {self.description}"
|
274
305
|
|