Repository navigation
Expand file tree
/
Copy path__init__.py
More file actions
1229 lines (954 loc) · 35.4 KB
/
Copy path__init__.py
File metadata and controls
1229 lines (954 loc) · 35.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2024 Max Wiklund
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import difflib
import os
import re
import sys
import textwrap
from dataclasses import dataclass, field
from typing import Any, Callable, List, Tuple, Union
from clap_python.style import Style, _PrivateStyle
try:
import importlib.metadata
__version__ = importlib.metadata.version("clap_python")
except ImportError:
import importlib_metadata
__version__ = importlib_metadata.version("clap_python")
_ARG_PREFIX_RE = re.compile(r"^(-+)")
def color_text(text: str, style: int = 0, color: int = 37) -> str:
"""Color text with ANSI Escape Code.
Args:
text: Text to format.
style: Text style.
color: Color to set.
Returns:
Colored text.
"""
if not int(style) and color == 37:
return text
return f"\033[{style};{color}m{text}\033[0m"
class ClapPyException(Exception):
"""Exception to raise when parser fail."""
def __init__(self, msg: str, command: Union[_CommandPrivate, _ArgPrivate]):
super(ClapPyException, self).__init__(msg)
self.msg = msg
self.command = command
def _format_arg(
arg: Union[Arg, SubCommand, MutuallyExclusiveGroup], style: _PrivateStyle
) -> str:
"""Format arg for help message.
Args:
arg: Argument to format.
style: Style to use when formatting arg.
Returns:
Formatted arg as help string.
"""
if isinstance(arg, MutuallyExclusiveGroup):
return color_text(" | ".join([_format_arg(g_arg, style) for g_arg in arg]))
msg = f"{arg.private.long_name}" + (
f" {arg.private.short_name}" if arg.private.short_name else ""
)
msg = color_text(msg, style=style.flags.style, color=style.flags.color)
if isinstance(arg, SubCommand):
return msg
elif arg.private.choices and not arg.private.value_name:
args = f"{{{','.join(arg.private.choices)}}}"
if not arg.private.long_name.startswith("-"):
return args
msg += f" {args}"
elif arg.private.multiple_values:
msg += color_text(
f" [{arg.private.value_name.upper()} ...]",
style=style.value_names.style,
color=style.value_names.color,
)
elif arg.private.takes_value:
msg += color_text(
f" {arg.private.value_name.upper()}",
style=style.value_names.style,
color=style.value_names.color,
)
return msg
@dataclass()
class _ArgPrivate:
"""Class to hold business logic for ``Arg`` class."""
arg: Arg
long_name: str
short_name: str = ""
help_msg: str = ""
takes_value: bool = True
multiple_values: bool = False
required: bool = False
takes_values: bool = False
is_help_arg: bool = False
default_value = None
value_name: str = ""
tag: str = "Options"
group: MutuallyExclusiveGroup = None
value_parser: Callable[[str], Any] = str
# fmt: off
validate_callable: Callable[[Any, ], str] = lambda value: ""
# fmt: on
choices = None
parent: _CommandPrivate = None
def name(self) -> str:
"""Arg name.
Returns:
Long arg name.
"""
return _ARG_PREFIX_RE.sub("", self.long_name).replace("-", "_")
def get_style(self) -> _PrivateStyle:
root = self
while root.parent:
root = root.parent
return root.style
# pylint: disable=expression-not-assigned
def parse(
self,
argv: List[str],
visited: List[Union[_ArgPrivate, _CommandPrivate]],
) -> dict:
"""Parse values for arg.
Args:
argv: Remaining arguments to be parsed by parser.
visited: List of visited arguments.
Raises:
ClapPyException: Parsing failed.
Returns:
Dict with parsed values (argument name as key and parsed values
as values).
"""
exclusive_args = [
arg.private.long_name
for arg in (self.group or [])
if arg.private in visited
]
if exclusive_args:
style_class = self.get_style()
raise ClapPyException(
(
f"argument {color_text(self.long_name, style=style_class.flags.style, color=style_class.flags.color)} "
f"not allowed with argument {color_text(exclusive_args[0], style=style_class.error.style, color=style_class.error.color)}"
),
self.parent,
)
if not self.takes_value:
# The arg does not take any value.
return {self.name(): True}
arg_names = [_arg.private.long_name for _arg in self.parent.get_arguments()]
arg_names += [
_arg.private.short_name
for _arg in self.parent.get_arguments()
if _arg.private.short_name
]
# If no arguments are provided raise an exception
if not argv or argv[0] in arg_names:
message = (
"expected at least one argument"
if self.multiple_values
else "expected one argument"
)
raise ClapPyException(message, self.parent)
if not self.multiple_values:
value = self.value_parser(argv.pop(0))
self._validate_arg(value)
return {self.name(): value}
values = []
while argv and argv[0] not in arg_names:
values.append(self.value_parser(argv.pop(0)))
# Validate values.
[self._validate_arg(value) for value in values]
return {self.name(): values}
def _validate_arg(self, value: Any) -> None:
"""Validate argument value.
Args:
value: Value to validate.
Raises:
ClapPyException: User validation failed.
"""
error_msg = self.validate_callable(value)
if error_msg:
raise ClapPyException(error_msg, self.parent)
class Arg:
"""Argument class to define cli arguments.
**Example**::
from clap_python import Arg, App
args = (
App()
.about("Cli to change color space on images.")
.arg(Arg("images").multiple_values(True))
.arg(
Arg("--color-space")
.help("Color space to convert to.")
.choices(["Rec.709", "ACEScg"])
.default("Rec.709")
)
.arg(Arg("--output-dir").help("Directory to export converted images to"))
.arg(Arg("--fast").takes_value(False))
.parse_args()
)
"""
def __init__(self, long_name: str, short_name: str = ""):
self.private = _ArgPrivate(
arg=self,
long_name=long_name,
short_name=short_name,
required=not long_name.startswith("-"),
)
self.value_name(self.private.name())
def value_parser(self, parser: Callable[[Any], Any]) -> Arg:
"""Func to convert argument string into value.
Args:
parser: Callable object to cast parsed value into new. Default is ``str``.
Returns:
Self.
**Example**::
from clap_python import App, Arg
app = App().arg(Arg("--number").value_parser(int))
print(app.parse_args(["--number", "101"]))
{"number": 101}
"""
self.private.value_parser = parser
return self
def choices(self, choices: List[Union[float, int, str]]) -> Arg:
"""Specify values that are valid for the argument.
Args:
choices: Values that are valid.
Returns:
Self
"""
self.private.choices = choices
def validate(value: Any) -> str:
"""Validate that ``value`` matches choices.
Args:
value: Parsed value to validate.
Returns:
Error message if value not in choices else empty string.
"""
if value in self.private.choices:
return ""
options = ", ".join(f"'{opt}'" for opt in self.private.choices)
similar_values: List[str] = difflib.get_close_matches(
value, self.private.choices
)
error_msg = (
f"argument {self.private.long_name}: invalid choice: "
f"'{value}' (choose from {options})"
)
style = self.private.get_style()
if similar_values:
error_msg += (
f"\n\n{color_text('tip:', style=style.tip.style, color=style.tip.color)} "
f"a similar value exists: "
f"'{color_text(similar_values[0], style=style.tip.style, color=style.tip.color)}'"
)
return error_msg
self.private.validate_callable = validate
return self
def validate(self, callable_: Callable[[Any], str]) -> Arg:
"""Set callable object to validate arg value.
Args:
callable_: Callable object that returns error message if failed.
**Example**:
from typing import Any
from clap_python import Arg, App
def validate(value: str) -> str:
if value != "hello":
return "Invalid arg... 'hello' is only allowed."
return ""
args = App().arg(Arg("--abc").validate(validate)).parse_args()
Returns:
Self.
"""
self.private.validate_callable = callable_
return self
def default(self, value: Any) -> Arg:
"""Default value for arg. If specified argument is not required.
Args:
value: Default value.
Returns:
Self.
"""
self.private.default_value = value
return self
def value_name(self, text: str) -> Arg:
"""Set argument value name.
Args:
text: Argument value name.
Returns:
Self.
"""
self.private.value_name = text
return self
def help(self, text: str) -> Arg:
"""Add help text to argument.
Args:
text: Description what the arg does.
Returns:
Self.
"""
self.private.help_msg = text
return self
def takes_value(self, value: bool) -> Arg:
"""Configure whether arg requires value to be passed.
Args:
value: True if argument takes value else False.
Returns:
Self.
"""
self.private.takes_value = value
return self
def multiple_values(self, value: bool) -> Arg:
"""Set if arg takes multiple values.
Args:
value:
If True arg can consume multiple values and result of arg is
list.
Returns:
Self.
"""
self.private.multiple_values = value
return self
def required(self, value: bool) -> Arg:
"""Set enabled and not passed parser will fail.
Args:
value: If True and arg is missing parser will fail and exit.
Returns:
Self.
"""
# If the argument is positional it is always required.
self.private.required = value
return self
@dataclass()
class _GroupPrivate:
"""Class to hold business logic for ``MutuallyExclusiveGroup`` class."""
children: List[Union[SubCommand, Arg]] = field(default_factory=lambda: [])
required: bool = False
help_heading: str = ""
@property
def is_help_arg(self) -> bool:
"""Check if arg is help arg.
Returns:
False if argument is not a help arg.
"""
return False
class MutuallyExclusiveGroup:
"""Group to define group where only one command can be called."""
def __init__(self):
self.private = _GroupPrivate()
def required(self, value: bool) -> Arg:
"""Set enabled and not passed parser will fail.
Args:
value: If True and arg is missing parser will fail and exit.
Returns:
Self.
"""
# If the argument is positional it is always required.
self.private.required = value
return self
def help_heading(self, label: str) -> MutuallyExclusiveGroup:
"""Lets you organize the help message visually by adding a header above related options.
Args:
label: Name of header.
Returns:
Self.
"""
self.private.help_heading = label
return self
def arg(self, arg: Union[Arg, SubCommand]) -> MutuallyExclusiveGroup:
"""Add arg to group.
Args:
arg: Arg to add to mutually exclusive group.
Raises:
ValueError: Unsupported data type.
Returns:
Self.
"""
if not isinstance(arg, (Arg, SubCommand)):
raise ValueError(f"{type(self).__name__}.arg only supports Arg, SubCommand")
if isinstance(arg, Arg) and self.private.help_heading:
arg.private.tag = self.private.help_heading
arg.private.group = self
self.private.children.append(arg)
return self
def __iter__(self):
return iter(self.private.children)
@dataclass()
class _CommandPrivate:
"""Class to hold business logic for ``SubCommand`` class."""
command: SubCommand
long_name: str
short_name: str = ""
help_msg: str = ""
subcommand_required: bool = False
arg_else_show_help: bool = False
help_heading: str = ""
tag: str = "Commands"
group: MutuallyExclusiveGroup = None
arguments: List[Union[Arg, SubCommand, MutuallyExclusiveGroup]] = field(
default_factory=lambda: []
)
positional_args: List[Arg] = field(default_factory=lambda: [])
parent: _CommandPrivate = None
style: _PrivateStyle = field(default_factory=_PrivateStyle)
version: str = ""
width: int = 100
def get_style(self) -> _PrivateStyle:
"""Get app style."""
return self.get_app().style
def get_app(self) -> _CommandPrivate:
root = self
while root.parent:
root = root.parent
return root
def get_width(self) -> int:
return self.get_app().width
def name(self) -> str:
"""Name of command.
Returns:
Long command name.
"""
return _ARG_PREFIX_RE.sub("", self.long_name).replace("-", "_")
@property
def is_help_arg(self) -> bool:
"""Check if arg is help argument.
Returns:
True if arg is help arg else False.
"""
return False
def get_arguments(self) -> List[Union[SubCommand, Arg]]:
"""Unpack args (groups).
Returns:
List of unpacked args and subcommands.
"""
arguments = []
for arg in self.arguments:
if isinstance(arg, MutuallyExclusiveGroup):
for g_arg in arg:
arguments.append(g_arg)
else:
arguments.append(arg)
return arguments
def get_commands_and_options(self) -> Tuple[List[SubCommand], List[Arg]]:
"""Get commands and optional args.
Returns:
Subcommands and optional args.
"""
arguments = self.get_arguments()
command = [arg for arg in arguments if isinstance(arg, SubCommand)]
optional = [arg for arg in arguments if isinstance(arg, Arg)]
return command, optional
def arg_path_string(self) -> str:
"""Returns string of command that failed.
Returns:
App command or arg that failed e.g ``git clone``.
"""
path = []
node = self
while node:
path.insert(0, node.name())
node = node.parent
return " ".join(path)
def usage_string(self) -> str:
"""Usage text.
Returns:
Usage text e.g Usage:app [--add [ADD ...]]
"""
style = self.get_style()
usage_positional_args = " ".join(
[
color_text(
f"<{arg.private.long_name}>",
style=style.flags.style,
color=style.flags.color,
)
for arg in self.positional_args
if not arg.private.is_help_arg
]
)
commands = [arg for arg in self.arguments if isinstance(arg, SubCommand)]
optional_args = [
arg for arg in self.arguments if not isinstance(arg, SubCommand)
]
usage_optional_args = " ".join(
[
f"[{_format_arg(arg, style)}]"
for arg in optional_args
if not arg.private.is_help_arg
]
)
usage_commands = "<COMMAND>" if commands else ""
options = " ".join([usage_positional_args, usage_optional_args, usage_commands])
return f"{color_text('Usage:', style=style.usage.style, color=style.usage.color)} {options}"
def _print_version(self) -> None:
"""Print version info."""
sys.stdout.write(f"{os.path.basename(sys.argv[0])} {self.version}\n")
def print_help(self) -> None:
"""Print help message cli."""
style = self.get_style()
style_no_color = _PrivateStyle()
max_text_width = self.get_width()
msg = ""
if self.help_msg:
msg += f"{self.help_msg}\n"
msg += f"{self.usage_string()}\n"
max_width = max(
len(_format_arg(arg, style_no_color))
for arg in self.get_arguments() + self.positional_args
)
longest_str = min(50, max_width) + 4
indent = 2
grouped_args = {}
for arg in self.positional_args + self.get_arguments():
grouped_args.setdefault(arg.private.tag, []).append(arg)
default_options = ["Arguments", "Commands", "Options"]
order = default_options + list(set(grouped_args.keys()) - set(default_options))
for title in order:
arguments = grouped_args.get(title)
if not arguments:
continue
msg += color_text(
f"\n{title}:\n", style=style.headers.style, color=style.headers.color
)
for arg in arguments:
text = " " * indent + _format_arg(arg, style)
text_no_color = " " * indent + _format_arg(arg, style_no_color)
spaces = " " * (longest_str - len(text_no_color))
wrapper = textwrap.TextWrapper(
width=max_text_width, subsequent_indent=" " * (longest_str + 1)
)
line = f"{text}{spaces} {arg.private.help_msg}"
msg += f"{wrapper.fill(line)}\n"
sys.stdout.write(f"{msg}\n")
# pylint: disable=too-many-branches
def parse(
self,
args: List[str],
visited: List[Union[_ArgPrivate, _CommandPrivate]],
allow_unknown: bool,
) -> dict:
"""Parse cli args.
Args:
args: Args to parse.
visited: List of visited nodes.
allow_unknown:
If true allow parsing of unknown arguments separated by "--"
else raise exception.
Raises:
ClapPyException: Parsing failed.
Returns:
Dict with parsed result.
"""
style_class = self.get_style()
if not args and self.arg_else_show_help:
self.print_help()
sys.exit(0)
self._check_mutually_exclusive_args(visited, style_class)
# Populate with default data.
parsed_data = self._initialize_parsed_data()
self._skip_positional_args = False
while args:
arg_str = args.pop(0)
# Check for help or version argument
if self._parse_global_args(arg_str):
sys.exit(0)
if self._parse_positional_args(arg_str, args, visited, parsed_data):
continue
# Parse optional arguments or subcommands
self._parse_subcommands_and_options(
arg_str, args, visited, parsed_data, allow_unknown
)
self._validate_subcommands(visited)
self._validate_required_arguments(visited, style_class)
return {self.name(): parsed_data}
def _parse_positional_args(
self,
arg_str: str,
args: List[str],
visited: List[Union[_ArgPrivate, _CommandPrivate]],
parsed_data,
) -> bool:
"""Parse positional arguments.
Args:
arg_str: The current argument string to parse.
args: The remaining arguments to parse.
visited: List of arguments or commands that have already been visited during parsing.
parsed_data: Dict to store parsed argument data in.
Returns:
True if a positional argument was successfully parsed.
"""
if self._skip_positional_args:
return False
# Parse positional arguments
for arg in self.positional_args:
if arg_str.startswith("-"):
self._skip_positional_args = True
return False
if arg.private not in visited:
args.insert(0, arg_str)
parsed_data.update(arg.private.parse(args, visited))
visited.append(arg.private)
return True
return False
def _parse_subcommands_and_options(
self,
arg_str: str,
args: List[str],
visited: List[Union[_ArgPrivate, _CommandPrivate]],
parsed_data: dict,
allow_unknown: bool,
) -> None:
"""Parse optional arguments and subcommands.
Args:
arg_str: The current argument string to parse.
args: The remaining arguments to parse.
visited: List of arguments or commands that have already been visited during parsing.
parsed_data: Dict to store parsed argument data in.
allow_unknown: If True allow parsing of unknown arguments.
Raises:
ClapPyException: If an argument is unrecognized and `allow_unknown`
is `False`.
"""
# Parse optional arguments or subcommands
for arg in self.get_arguments():
if arg_str in (
arg.private.long_name,
arg.private.short_name,
):
if self._parse_global_args(arg.private.name()):
sys.exit(0)
kwargs = (
{
"args": args,
"visited": visited,
"allow_unknown": allow_unknown,
}
if isinstance(arg, SubCommand)
else {"argv": args, "visited": visited}
)
parsed_data.update(arg.private.parse(**kwargs))
visited.append(arg.private)
return
else:
# Handle unknown arguments
if arg_str == "--" and allow_unknown:
parsed_data.setdefault("unknown", []).extend(args)
args.clear() # All args that where left have
# been moved to unknown. Clear args to stop loop.
else:
style_class = self.get_style()
raise ClapPyException(
f"unrecognized arguments: {color_text(arg_str, style=style_class.error.style, color=style_class.error.color)}",
self,
)
def _parse_global_args(self, arg_str: str) -> bool:
"""Parse global args (help arg and version arg).
Args:
arg_str: Arg string to parse.
Returns:
True if global arg was parsed.
"""
# Check for help argument
if arg_str in ("-h", "--help"):
self.print_help()
return True
elif arg_str in ("-V", "--version") and self.version:
self._print_version()
return True
return False
def _initialize_parsed_data(self) -> dict:
"""Initialize the parsed data dictionary with default values."""
parsed_data = {}
# Populate with default data.
for arg in self.get_arguments():
if isinstance(arg, Arg) and arg.private.is_help_arg:
continue
if isinstance(arg, Arg) and arg.private.default_value is not None:
parsed_data[arg.private.name()] = arg.private.default_value
elif isinstance(arg, Arg) and not arg.private.takes_value:
parsed_data[arg.private.name()] = False
return parsed_data
def _check_mutually_exclusive_args(
self,
visited: List[Union[_ArgPrivate, _CommandPrivate]],
style_class: _PrivateStyle,
) -> None:
"""Check for mutually exclusive arguments in the visited list.
Args:
visited: List of arguments or commands that have already been visited during parsing.
style_class: Style object for error message.
Raises:
ClapPyException: If mutually exclusive arguments are found.
"""
active_args = [
arg.private.long_name
for arg in (self.group or [])
if arg.private in visited
]
if active_args:
raise ClapPyException(
f"argument {color_text(self.long_name, style=style_class.flags.style, color=style_class.flags.color)} "
f"not allowed with argument {color_text(active_args[0], style=style_class.error.style, color=style_class.error.color)}",
self.parent,
)
def _validate_required_arguments(
self,
visited: List[Union[_ArgPrivate, _CommandPrivate]],
style_class: _PrivateStyle,
) -> None:
"""Validate that all required arguments are provided.
Args:
visited: List of arguments or commands that have already been visited during parsing.
style_class: Style object for error message.
Raises:
ClapPyException: If required arguments or mutually exclusive groups
are missing from the `visited` list.
"""
# Gather required arguments
required_args = [
arg
for arg in self.positional_args + self.get_arguments()
if isinstance(arg, Arg) and arg.private.required
]
required_groups = [
arg
for arg in self.arguments
if isinstance(arg, MutuallyExclusiveGroup)
if arg.private.required
]
# Check for missing required arguments
missing_args = [
arg.private.long_name for arg in required_args if arg.private not in visited
]
if missing_args:
arg_text = color_text(
", ".join(missing_args),
style=style_class.flags.style,
color=style_class.flags.color,
)
raise ClapPyException(
f"the following arguments are required: {arg_text}",
self,
)
missing_group_args = [
group
for group in required_groups
if not any(arg.private in visited for arg in group)
]
if missing_group_args:
missing_args_text = " | ".join(
arg.private.long_name for arg in missing_group_args[0]
)
arg_text = color_text(
missing_args_text,
style=style_class.flags.style,
color=style_class.flags.color,
)
raise ClapPyException(
f"One of the following arguments are required: {arg_text}",
self,
)
def _validate_subcommands(
self, visited: List[Union[_ArgPrivate, _CommandPrivate]]
) -> None:
"""Validate that a required subcommand has been provided.
Args:
visited: List of arguments or commands that have already been visited during parsing.
Raises:
ClapPyException: If a required subcommand is missing.
"""
sub_commands, _ = self.get_commands_and_options()
if (
self.subcommand_required
and sub_commands
and not any(cmd for cmd in sub_commands if cmd.private in visited)
):
sub_commands_str = " | ".join(
[arg.private.long_name for arg in sub_commands]
)
help_msg = "requires a subcommand but one was not provided\n"
help_msg += f" [subcommands: {sub_commands_str}]\n\n"
help_msg += "For more information, try '--help'."
raise ClapPyException(help_msg, self)