cli3 2.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.
- cli/__init__.py +168 -0
- cli/arg.py +69 -0
- cli/cmd.py +473 -0
- cli/context.py +362 -0
- cli/errors.py +199 -0
- cli/flag.py +129 -0
- cli/help.py +228 -0
- cli/parser.py +440 -0
- cli/py.typed +0 -0
- cli/style.py +180 -0
- cli/suggest.py +256 -0
- cli/tests/__init__.py +15 -0
- cli/tests/_apps/__init__.py +19 -0
- cli/tests/_apps/v1.py +61 -0
- cli/tests/_apps/v2.py +76 -0
- cli/tests/parser.py +294 -0
- cli/tests/suggest.py +77 -0
- cli/utils.py +374 -0
- cli/validate.py +171 -0
- cli/wraps.py +371 -0
- cli3-2.0.0.dist-info/METADATA +218 -0
- cli3-2.0.0.dist-info/RECORD +25 -0
- cli3-2.0.0.dist-info/WHEEL +5 -0
- cli3-2.0.0.dist-info/licenses/LICENSE +21 -0
- cli3-2.0.0.dist-info/top_level.txt +1 -0
cli/__init__.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Command-Line-Interface Parsing Library
|
|
3
|
+
"""
|
|
4
|
+
from enum import Enum
|
|
5
|
+
from typing import (
|
|
6
|
+
Callable, Iterable, List, Literal, NamedTuple, Optional,
|
|
7
|
+
Tuple, Type, TypeVar, Union, cast)
|
|
8
|
+
from typing_extensions import Annotated, get_args, get_origin, get_type_hints
|
|
9
|
+
|
|
10
|
+
#DONE: handle ValueError exceptions on data-type issues
|
|
11
|
+
#DONE: functions: cli.group/cli.context/cli.echo
|
|
12
|
+
#DONE: decorators: cli.argument/cli.flag/cli.pass_context to override/enhance parsed details
|
|
13
|
+
|
|
14
|
+
#DONE: pass `Context` with annotation present or @cli.pass_context wrapper
|
|
15
|
+
#DONE: moar unit-tests for parser
|
|
16
|
+
# - extra arg / missing arg / invalid arg / arg repeat
|
|
17
|
+
# - extra flag / missing flag / invalid flag / missing flag value / invalid flag value / flag repeat
|
|
18
|
+
# - repeated command
|
|
19
|
+
# - group / command tree (subcmd-required difference)
|
|
20
|
+
|
|
21
|
+
#DONE: docs
|
|
22
|
+
# - simple hello world
|
|
23
|
+
# - `Context.extra` and pass via function args
|
|
24
|
+
|
|
25
|
+
#DONE: suggestor unit-tests
|
|
26
|
+
#DONE: controls on stripping/ignoring styling when writing to file instead of tty
|
|
27
|
+
#DONE: help-page implementation (with colors)
|
|
28
|
+
|
|
29
|
+
#DONE: docstrings for all functions
|
|
30
|
+
|
|
31
|
+
#DONE: command chaining rules
|
|
32
|
+
# enable/disable chaining with `chain: bool = False`
|
|
33
|
+
# command also has `repeat: bool = False`
|
|
34
|
+
# - repeat configures whether command can be chained on itself
|
|
35
|
+
# - chain configures if subcommands are allowed in combination.
|
|
36
|
+
|
|
37
|
+
#DONE: allow returning values from actions (when standalone is disabled)
|
|
38
|
+
|
|
39
|
+
#TODO: give indexing another shot (but count down rather than up)
|
|
40
|
+
#TODO: errors should be more precisce -> double flag, extra arg, etc...
|
|
41
|
+
|
|
42
|
+
#TODO: command categories does nothing
|
|
43
|
+
#TODO: authors will never be displayed ever in help
|
|
44
|
+
#TODO: version will never be displayed ever (maybe add version flag with support for more info?)
|
|
45
|
+
|
|
46
|
+
#** Variables **#
|
|
47
|
+
__all__ = [
|
|
48
|
+
'echo',
|
|
49
|
+
'style',
|
|
50
|
+
'secho',
|
|
51
|
+
'argument',
|
|
52
|
+
'extra',
|
|
53
|
+
'option',
|
|
54
|
+
'command',
|
|
55
|
+
'group',
|
|
56
|
+
'get_current_context',
|
|
57
|
+
|
|
58
|
+
'Arg',
|
|
59
|
+
'Command',
|
|
60
|
+
'Context',
|
|
61
|
+
'Flag',
|
|
62
|
+
|
|
63
|
+
'CliError',
|
|
64
|
+
'Extra',
|
|
65
|
+
'Validate',
|
|
66
|
+
'Suggest',
|
|
67
|
+
|
|
68
|
+
'Help',
|
|
69
|
+
'Parser',
|
|
70
|
+
'ParseCtx',
|
|
71
|
+
'ParsedCmd',
|
|
72
|
+
'Suggestor',
|
|
73
|
+
]
|
|
74
|
+
|
|
75
|
+
E = TypeVar('E', bound=Enum)
|
|
76
|
+
T = TypeVar('T')
|
|
77
|
+
|
|
78
|
+
SuggestFunc = Callable[[str], Iterable[str]]
|
|
79
|
+
OptSuggest = Union['SuggestFunc', Literal[False], None]
|
|
80
|
+
|
|
81
|
+
#** Classes **#
|
|
82
|
+
|
|
83
|
+
class _Meta(NamedTuple):
|
|
84
|
+
repeat: bool = False
|
|
85
|
+
|
|
86
|
+
#** Functions **#
|
|
87
|
+
|
|
88
|
+
def get_type(self, ftype: Optional[Type[T]]) -> Tuple[Type[T], _Meta]:
|
|
89
|
+
"""
|
|
90
|
+
retrieve real type associated with arg/flag and update the relevant attrs
|
|
91
|
+
|
|
92
|
+
:param ftype: type annotation assignment
|
|
93
|
+
:return: (true type, option metadata)
|
|
94
|
+
"""
|
|
95
|
+
ftype = ftype or getattr(self, 'type', None)
|
|
96
|
+
if ftype is not None:
|
|
97
|
+
origin = get_origin(ftype)
|
|
98
|
+
args = get_args(ftype)
|
|
99
|
+
if origin is None or origin is Annotated:
|
|
100
|
+
return ftype, _Meta()
|
|
101
|
+
if origin in (list, set):
|
|
102
|
+
return args[0], _Meta(repeat=True)
|
|
103
|
+
if origin is Union and len(args) == 2 and args[1] is type(None):
|
|
104
|
+
return get_type(self, args[0])
|
|
105
|
+
raise TypeError(ftype)
|
|
106
|
+
default = getattr(self, 'default', None)
|
|
107
|
+
if default is not None:
|
|
108
|
+
return type(self.default), _Meta()
|
|
109
|
+
validators = getattr(self, 'validators', None)
|
|
110
|
+
if validators:
|
|
111
|
+
for validator in validators[::-1]:
|
|
112
|
+
hints = get_type_hints(validator)
|
|
113
|
+
if 'return' in hints:
|
|
114
|
+
return hints['return']
|
|
115
|
+
return cast(Type, str), _Meta()
|
|
116
|
+
|
|
117
|
+
def get_suggestor(typedef: Type, suggest: OptSuggest) -> OptSuggest:
|
|
118
|
+
"""
|
|
119
|
+
get suggestor function or configuration based on type
|
|
120
|
+
|
|
121
|
+
:param type: arg/flag type
|
|
122
|
+
:param suggest: suggestion setting
|
|
123
|
+
:return: suggestion
|
|
124
|
+
"""
|
|
125
|
+
if suggest is not None:
|
|
126
|
+
return suggest
|
|
127
|
+
origin = get_origin(typedef)
|
|
128
|
+
if origin is Annotated:
|
|
129
|
+
for arg in get_args(typedef):
|
|
130
|
+
if isinstance(arg, Suggest):
|
|
131
|
+
return arg.suggestor
|
|
132
|
+
if origin is None and issubclass(typedef, Enum):
|
|
133
|
+
return suggest_static([opt.value for opt in typedef])
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
def get_validator(type: Type,
|
|
137
|
+
validators: List['ValidatorFunc']) -> List['ValidatorFunc']:
|
|
138
|
+
"""
|
|
139
|
+
retrieve validators based on arg/flag configuration
|
|
140
|
+
|
|
141
|
+
:param type: type assignment for arg/flag
|
|
142
|
+
:param validators: list of established validators
|
|
143
|
+
:return: complete list of validators
|
|
144
|
+
"""
|
|
145
|
+
validator = DEFAULT_VALIDATORS.get(type)
|
|
146
|
+
if validator is not None:
|
|
147
|
+
validators.append(validator)
|
|
148
|
+
return validators
|
|
149
|
+
if get_origin(type) is Annotated:
|
|
150
|
+
for arg in get_args(type):
|
|
151
|
+
if isinstance(arg, Validate):
|
|
152
|
+
validators.append(arg.validator)
|
|
153
|
+
if not validators and type is not str:
|
|
154
|
+
return [type]
|
|
155
|
+
return validators
|
|
156
|
+
|
|
157
|
+
#** Imports **#
|
|
158
|
+
from .arg import Arg
|
|
159
|
+
from .cmd import Command
|
|
160
|
+
from .context import Context, get_current_context
|
|
161
|
+
from .errors import CliError
|
|
162
|
+
from .flag import Flag
|
|
163
|
+
from .help import Help
|
|
164
|
+
from .parser import Parser, ParsedCmd, ParseCtx
|
|
165
|
+
from .suggest import Suggest, Suggestor, suggest_static
|
|
166
|
+
from .utils import echo, style, secho, argument, extra, option, command, group
|
|
167
|
+
from .validate import DEFAULT_VALIDATORS, Validate, ValidatorFunc
|
|
168
|
+
from .wraps import Extra
|
cli/arg.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""
|
|
2
|
+
CLI Argument Implementation and DataType Parsers
|
|
3
|
+
"""
|
|
4
|
+
from typing import Any, Callable, Generic, List, Optional, Type
|
|
5
|
+
|
|
6
|
+
from . import T, OptSuggest, get_type, get_suggestor, get_validator
|
|
7
|
+
|
|
8
|
+
#** Variables **#
|
|
9
|
+
__all__ = ['Arg', 'Args']
|
|
10
|
+
|
|
11
|
+
Args = List['Arg']
|
|
12
|
+
|
|
13
|
+
#** Classes **#
|
|
14
|
+
|
|
15
|
+
class Arg(Generic[T]):
|
|
16
|
+
"""
|
|
17
|
+
Command Argument Configuration Setting
|
|
18
|
+
"""
|
|
19
|
+
type: Type[T]
|
|
20
|
+
suggestor: OptSuggest
|
|
21
|
+
|
|
22
|
+
def __init__(self,
|
|
23
|
+
name: str,
|
|
24
|
+
about: Optional[str] = None,
|
|
25
|
+
default: Optional[T] = None,
|
|
26
|
+
required: Optional[bool] = None,
|
|
27
|
+
repeat: bool = False,
|
|
28
|
+
validators: Optional[List[Callable[[Any], T]]] = None,
|
|
29
|
+
suggestor: OptSuggest = None,
|
|
30
|
+
type: Optional[Type[T]] = None,
|
|
31
|
+
):
|
|
32
|
+
"""
|
|
33
|
+
:param name: name of argument
|
|
34
|
+
:param about: description of argument
|
|
35
|
+
:param default: default value assigned to argument
|
|
36
|
+
:param required: label if argument is required during parsing
|
|
37
|
+
:param repeat: allow argument to be repeated
|
|
38
|
+
:param validators: validators used to process argument value
|
|
39
|
+
:param suggestor: argument auto-complete suggestion function
|
|
40
|
+
:param type: argument type assignment
|
|
41
|
+
"""
|
|
42
|
+
self.name = name
|
|
43
|
+
self.about = about
|
|
44
|
+
self.default = default
|
|
45
|
+
self.required = self.default is None if required is None else required
|
|
46
|
+
self.repeat = repeat
|
|
47
|
+
self.validators = validators or []
|
|
48
|
+
self.suggestor = suggestor
|
|
49
|
+
self._set_type(type)
|
|
50
|
+
|
|
51
|
+
def _set_type(self, typedef: Optional[Type]):
|
|
52
|
+
"""
|
|
53
|
+
type assignment and all related attributes that pull from type
|
|
54
|
+
"""
|
|
55
|
+
newtype, meta = get_type(self, typedef)
|
|
56
|
+
self.type = newtype
|
|
57
|
+
self.repeat = self.repeat or meta.repeat
|
|
58
|
+
self.suggestor = get_suggestor(self.type, self.suggestor)
|
|
59
|
+
self.validators = get_validator(self.type, self.validators)
|
|
60
|
+
|
|
61
|
+
def __repr__(self) -> str:
|
|
62
|
+
return f'Arg(name={self.name}, default={self.default})'
|
|
63
|
+
|
|
64
|
+
@classmethod
|
|
65
|
+
def __class_getitem__(cls, value: Type):
|
|
66
|
+
func = getattr(super(), '__class_getitem__')
|
|
67
|
+
instance = func(value)
|
|
68
|
+
instance.type = value
|
|
69
|
+
return instance
|
cli/cmd.py
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
1
|
+
"""
|
|
2
|
+
CLI Command Implementation
|
|
3
|
+
"""
|
|
4
|
+
import sys
|
|
5
|
+
import asyncio
|
|
6
|
+
from collections import UserList
|
|
7
|
+
from typing import (
|
|
8
|
+
Any, Awaitable, Callable, Dict, List, Literal, Optional, Type,
|
|
9
|
+
TypeVar, Union, overload)
|
|
10
|
+
from typing_extensions import NoReturn, TypedDict, Unpack
|
|
11
|
+
|
|
12
|
+
from .arg import Args
|
|
13
|
+
from .flag import Flags
|
|
14
|
+
from .style import Styling
|
|
15
|
+
|
|
16
|
+
#** Variables **#
|
|
17
|
+
__all__ = ['Action', 'Command', 'Commands']
|
|
18
|
+
|
|
19
|
+
C = TypeVar('C', bound='Command')
|
|
20
|
+
Commands = List['Command']
|
|
21
|
+
|
|
22
|
+
SyncAction = Callable[..., Any]
|
|
23
|
+
AsyncAction = Callable[..., Awaitable[Any]]
|
|
24
|
+
Action = Union[SyncAction, AsyncAction]
|
|
25
|
+
|
|
26
|
+
RunArgs = Optional[List[str]]
|
|
27
|
+
|
|
28
|
+
#** Classes **#
|
|
29
|
+
|
|
30
|
+
class RunKwargs(TypedDict, total=False):
|
|
31
|
+
help: 'Help'
|
|
32
|
+
parser: Type['Parser']
|
|
33
|
+
stdout: 'AnyIO'
|
|
34
|
+
stderr: 'AnyIO'
|
|
35
|
+
suggest: 'SuggestorCLS'
|
|
36
|
+
styling: Styling
|
|
37
|
+
extra: Dict[str, Any]
|
|
38
|
+
loop: asyncio.AbstractEventLoop
|
|
39
|
+
|
|
40
|
+
class ResultList(UserList):
|
|
41
|
+
"""
|
|
42
|
+
Special list subtype to denote a result collection
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
class Results:
|
|
46
|
+
"""
|
|
47
|
+
Command Return Result Accumulator
|
|
48
|
+
"""
|
|
49
|
+
__slots__ = ('results', )
|
|
50
|
+
|
|
51
|
+
def __init__(self):
|
|
52
|
+
self.results = ResultList()
|
|
53
|
+
|
|
54
|
+
def add_result(self, result: Any):
|
|
55
|
+
"""
|
|
56
|
+
add a new result to the collection
|
|
57
|
+
"""
|
|
58
|
+
if result is None:
|
|
59
|
+
return
|
|
60
|
+
if isinstance(result, ResultList):
|
|
61
|
+
self.results.extend(result)
|
|
62
|
+
else:
|
|
63
|
+
self.results.append(result)
|
|
64
|
+
|
|
65
|
+
def result(self) -> Any:
|
|
66
|
+
"""
|
|
67
|
+
return finalized result from collection
|
|
68
|
+
"""
|
|
69
|
+
if not self.results:
|
|
70
|
+
return
|
|
71
|
+
if len(self.results) == 1:
|
|
72
|
+
return self.results[0]
|
|
73
|
+
return self.results
|
|
74
|
+
|
|
75
|
+
class Command:
|
|
76
|
+
"""
|
|
77
|
+
CLI Command Configuration Object
|
|
78
|
+
"""
|
|
79
|
+
__slots__ = (
|
|
80
|
+
'name', 'about', 'version', 'authors', 'category', 'hidden',
|
|
81
|
+
'suggest', 'args', 'flags', 'commands', 'aliases', 'action',
|
|
82
|
+
'chain', 'repeat', 'invoke_without_command',)
|
|
83
|
+
|
|
84
|
+
def __init__(self,
|
|
85
|
+
name: str,
|
|
86
|
+
about: Optional[str] = None,
|
|
87
|
+
version: Optional[str] = None,
|
|
88
|
+
authors: Optional[List[str]] = None,
|
|
89
|
+
category: Optional[str] = None,
|
|
90
|
+
hidden: bool = False,
|
|
91
|
+
suggest: bool = True,
|
|
92
|
+
args: Optional[Args] = None,
|
|
93
|
+
flags: Optional[Flags] = None,
|
|
94
|
+
commands: Optional[Commands] = None,
|
|
95
|
+
aliases: Optional[List[str]] = None,
|
|
96
|
+
action: Optional[Action] = None,
|
|
97
|
+
chain: bool = False,
|
|
98
|
+
repeat: bool = False,
|
|
99
|
+
invoke_without_command: bool = False,
|
|
100
|
+
):
|
|
101
|
+
"""
|
|
102
|
+
:param name: namme of command
|
|
103
|
+
:param about: description of command
|
|
104
|
+
:param version: version of command
|
|
105
|
+
:param authors: authors of command / program
|
|
106
|
+
:param category: category linked to command
|
|
107
|
+
:param hidden: hide command if true
|
|
108
|
+
:param suggest: allow inclusion for suggestion
|
|
109
|
+
:param args: configured command arguments
|
|
110
|
+
:param flags: configured command options/flags
|
|
111
|
+
:param commands: configured sub-commands
|
|
112
|
+
:param aliases: aliases of the command
|
|
113
|
+
:param action: function to call on command
|
|
114
|
+
:param chain: allow chaining subcommands
|
|
115
|
+
:param repeat: allow repeating the same command (in chain)
|
|
116
|
+
:param invoke_without_command: allow command to run without subcommand
|
|
117
|
+
"""
|
|
118
|
+
self.name = name
|
|
119
|
+
self.about = about
|
|
120
|
+
self.version = version
|
|
121
|
+
self.authors = authors
|
|
122
|
+
self.category = category or '*'
|
|
123
|
+
self.hidden = hidden
|
|
124
|
+
self.suggest = suggest
|
|
125
|
+
self.args = args or []
|
|
126
|
+
self.flags = flags or []
|
|
127
|
+
self.commands = commands or []
|
|
128
|
+
self.aliases = aliases or []
|
|
129
|
+
self.action = action
|
|
130
|
+
self.chain = chain
|
|
131
|
+
self.repeat = repeat
|
|
132
|
+
self.invoke_without_command = invoke_without_command
|
|
133
|
+
|
|
134
|
+
def __repr__(self) -> str:
|
|
135
|
+
return f'Command(name={self.name}, aliases={self.aliases!r})'
|
|
136
|
+
|
|
137
|
+
@overload
|
|
138
|
+
def __call__(self,
|
|
139
|
+
args: RunArgs = None,
|
|
140
|
+
*,
|
|
141
|
+
standalone_mode: Literal[True] = True,
|
|
142
|
+
**kwargs: Unpack[RunKwargs]
|
|
143
|
+
) -> NoReturn:
|
|
144
|
+
...
|
|
145
|
+
|
|
146
|
+
@overload
|
|
147
|
+
def __call__(self,
|
|
148
|
+
args: RunArgs = None,
|
|
149
|
+
*,
|
|
150
|
+
standalone_mode: Literal[False] = False,
|
|
151
|
+
**kwargs: Unpack[RunKwargs]
|
|
152
|
+
) -> Any:
|
|
153
|
+
...
|
|
154
|
+
|
|
155
|
+
def __call__(self,
|
|
156
|
+
args: RunArgs = None,
|
|
157
|
+
*,
|
|
158
|
+
standalone_mode: bool = True,
|
|
159
|
+
**kwargs: Unpack[RunKwargs]
|
|
160
|
+
):
|
|
161
|
+
return self.run(args, #type: ignore[call-overload]
|
|
162
|
+
standalone_mode=standalone_mode, **kwargs)
|
|
163
|
+
|
|
164
|
+
def variants(self) -> List[str]:
|
|
165
|
+
"""
|
|
166
|
+
list of name and aliases of command
|
|
167
|
+
"""
|
|
168
|
+
return [self.name, *self.aliases]
|
|
169
|
+
|
|
170
|
+
@property
|
|
171
|
+
def categories(self) -> Dict[str, List['Command']]:
|
|
172
|
+
"""
|
|
173
|
+
Organize sub-commands into categories
|
|
174
|
+
|
|
175
|
+
:return: dictionary of category names associated w/ sub-commands
|
|
176
|
+
"""
|
|
177
|
+
categories: Dict[str, List[Command]] = {}
|
|
178
|
+
for cmd in self.commands:
|
|
179
|
+
categories.setdefault(cmd.category, [])
|
|
180
|
+
categories[cmd.category].append(cmd)
|
|
181
|
+
return categories
|
|
182
|
+
|
|
183
|
+
def visible_flags(self) -> Flags:
|
|
184
|
+
"""
|
|
185
|
+
Retrieve visable flags
|
|
186
|
+
|
|
187
|
+
:return: all non hidden flags attached to this command
|
|
188
|
+
"""
|
|
189
|
+
return [f for f in self.flags if not f.hidden]
|
|
190
|
+
|
|
191
|
+
def visible_commands(self, category: Optional[str] = None) -> Commands:
|
|
192
|
+
"""
|
|
193
|
+
Retrieve visable commands (of given category if specified)
|
|
194
|
+
|
|
195
|
+
:param category: only return commands of the given category if specified
|
|
196
|
+
:return: commands not hidden
|
|
197
|
+
"""
|
|
198
|
+
commands = [c for c in self.commands if not c.hidden]
|
|
199
|
+
if category is not None:
|
|
200
|
+
commands = [c for c in commands if c.category == category]
|
|
201
|
+
return commands
|
|
202
|
+
|
|
203
|
+
def visible_categories(self) -> List[str]:
|
|
204
|
+
"""
|
|
205
|
+
retrieve category names
|
|
206
|
+
"""
|
|
207
|
+
return [category for category in self.categories.keys()]
|
|
208
|
+
|
|
209
|
+
@overload
|
|
210
|
+
def command(self,
|
|
211
|
+
name: Optional[str] = None,
|
|
212
|
+
about: Optional[str] = None,
|
|
213
|
+
category: Optional[str] = None,
|
|
214
|
+
hidden: bool = False,
|
|
215
|
+
chain: bool = False,
|
|
216
|
+
repeat: bool = False,
|
|
217
|
+
cls: None = None,
|
|
218
|
+
) -> Callable[[Callable], 'Command']:
|
|
219
|
+
...
|
|
220
|
+
|
|
221
|
+
@overload
|
|
222
|
+
def command(self,
|
|
223
|
+
name: Optional[str] = None,
|
|
224
|
+
about: Optional[str] = None,
|
|
225
|
+
category: Optional[str] = None,
|
|
226
|
+
hidden: bool = False,
|
|
227
|
+
chain: bool = False,
|
|
228
|
+
repeat: bool = False,
|
|
229
|
+
*, cls: Type[C],
|
|
230
|
+
) -> Callable[[Callable], C]:
|
|
231
|
+
...
|
|
232
|
+
|
|
233
|
+
@overload
|
|
234
|
+
def command(self, name: Callable) -> 'Command':
|
|
235
|
+
...
|
|
236
|
+
|
|
237
|
+
def command(self,
|
|
238
|
+
name: Union[str, Action, None] = None,
|
|
239
|
+
about: Optional[str] = None,
|
|
240
|
+
category: Optional[str] = None,
|
|
241
|
+
hidden: bool = False,
|
|
242
|
+
chain: bool = False,
|
|
243
|
+
repeat: bool = False,
|
|
244
|
+
cls: Optional[Type[C]] = None,
|
|
245
|
+
) -> Union[Callable[[Action], 'Command'], C, 'Command']:
|
|
246
|
+
"""
|
|
247
|
+
subcommand function wrapper
|
|
248
|
+
|
|
249
|
+
:param name: name of command
|
|
250
|
+
:param about: description of command
|
|
251
|
+
:param category: category linked to command
|
|
252
|
+
:param hidden: hide this command if true
|
|
253
|
+
:param chain: allow chaining subcommands
|
|
254
|
+
:param repeat: allow repeating the same command (in chain)
|
|
255
|
+
:param cls: command subclass type
|
|
256
|
+
"""
|
|
257
|
+
cname = name if isinstance(name, str) else None
|
|
258
|
+
def wrapper(action: Action) -> Command:
|
|
259
|
+
cmd = into_command(action, cls or Command)
|
|
260
|
+
cmd.name = cname or cmd.name
|
|
261
|
+
cmd.about = about or cmd.about
|
|
262
|
+
cmd.category = category or cmd.category
|
|
263
|
+
cmd.hidden = hidden or cmd.hidden
|
|
264
|
+
cmd.chain = chain or cmd.chain
|
|
265
|
+
cmd.repeat = repeat or cmd.repeat
|
|
266
|
+
self.commands.append(cmd)
|
|
267
|
+
return cmd
|
|
268
|
+
return wrapper(name) if callable(name) else wrapper
|
|
269
|
+
|
|
270
|
+
def _validate_args(self):
|
|
271
|
+
"""
|
|
272
|
+
validate arguments and their configuration in command
|
|
273
|
+
"""
|
|
274
|
+
reserved = set()
|
|
275
|
+
repeated = None
|
|
276
|
+
for n, arg in enumerate(self.args, 0):
|
|
277
|
+
if arg.repeat:
|
|
278
|
+
if repeated is not None:
|
|
279
|
+
raise ValueError(
|
|
280
|
+
f'{self.name} arg({n}) cannot also be repeated.')
|
|
281
|
+
repeated = arg.name
|
|
282
|
+
if arg.name not in reserved:
|
|
283
|
+
reserved.add(arg.name)
|
|
284
|
+
continue
|
|
285
|
+
raise ValueError(
|
|
286
|
+
f'{self.name} arg({n}) has duplicate argument {arg.name!r}')
|
|
287
|
+
|
|
288
|
+
def _validate_flags(self):
|
|
289
|
+
"""
|
|
290
|
+
validate flags and their configuration in command
|
|
291
|
+
"""
|
|
292
|
+
reserved = set()
|
|
293
|
+
for n, flag in enumerate(self.flags, 0):
|
|
294
|
+
if flag.name in reserved:
|
|
295
|
+
raise ValueError(
|
|
296
|
+
f'{self.name} flag({n}) has duplicate name {flag.name!r}')
|
|
297
|
+
reserved.add(flag.name)
|
|
298
|
+
for var in flag.variants():
|
|
299
|
+
if var in reserved:
|
|
300
|
+
raise ValueError(
|
|
301
|
+
f'{self.name} flag({n}) has duplicate flag {var!r}')
|
|
302
|
+
reserved.add(var)
|
|
303
|
+
|
|
304
|
+
def _validate_commands(self):
|
|
305
|
+
"""
|
|
306
|
+
validate subcommands and their configuration in command
|
|
307
|
+
"""
|
|
308
|
+
reserved = set()
|
|
309
|
+
for n, cmd in enumerate(self.commands, 0):
|
|
310
|
+
if cmd.name in reserved:
|
|
311
|
+
raise ValueError(
|
|
312
|
+
f'{self.name} command({n}) has duplicate name {cmd.name!r}')
|
|
313
|
+
reserved.add(cmd.name)
|
|
314
|
+
for alias in cmd.aliases:
|
|
315
|
+
if alias in reserved:
|
|
316
|
+
raise ValueError(
|
|
317
|
+
f'{self.name} command({n}) has duplicate alias {alias!r}')
|
|
318
|
+
reserved.add(alias)
|
|
319
|
+
|
|
320
|
+
def validate(self):
|
|
321
|
+
"""
|
|
322
|
+
validate this command and its configuration
|
|
323
|
+
"""
|
|
324
|
+
self._validate_args()
|
|
325
|
+
self._validate_flags()
|
|
326
|
+
self._validate_commands()
|
|
327
|
+
|
|
328
|
+
def parse(self,
|
|
329
|
+
args: RunArgs = None,
|
|
330
|
+
*,
|
|
331
|
+
standalone_mode: bool = True,
|
|
332
|
+
**kwargs: Unpack[RunKwargs]
|
|
333
|
+
) -> 'ParsedCmd':
|
|
334
|
+
"""
|
|
335
|
+
parse the given arguments and return the parsed context object
|
|
336
|
+
|
|
337
|
+
:param args: arguments to parse
|
|
338
|
+
:param standalone_mode: exit after completion if true
|
|
339
|
+
:param kwargs: additional contextual arguments
|
|
340
|
+
:return: parsed command structure
|
|
341
|
+
"""
|
|
342
|
+
help = kwargs.get('help') or Help()
|
|
343
|
+
parser = kwargs.get('parser') or Parser
|
|
344
|
+
engine = (parser or Parser)(self, help=help)
|
|
345
|
+
try:
|
|
346
|
+
return engine.parse(args or sys.argv[1:], extra=kwargs.get('extra'))
|
|
347
|
+
except CliError as err:
|
|
348
|
+
if not standalone_mode:
|
|
349
|
+
raise err
|
|
350
|
+
stderr = kwargs.get('stderr') or sys.stderr
|
|
351
|
+
echo(err.show(help), file=stderr)
|
|
352
|
+
sys.exit(err.exit_code)
|
|
353
|
+
|
|
354
|
+
def _check_run(self, context: 'Context') -> bool:
|
|
355
|
+
"""
|
|
356
|
+
check if the next command action should run
|
|
357
|
+
"""
|
|
358
|
+
is_group = len(self.commands) > 0
|
|
359
|
+
if is_group:
|
|
360
|
+
return self.invoke_without_command \
|
|
361
|
+
or len(context.parsed.commands) > 0
|
|
362
|
+
return True
|
|
363
|
+
|
|
364
|
+
def run_with(self, context: 'Context', action: Optional[SyncAction] = None):
|
|
365
|
+
"""
|
|
366
|
+
run this command with the specified context/action
|
|
367
|
+
|
|
368
|
+
:param context: command runtime context
|
|
369
|
+
:param action: command action override
|
|
370
|
+
"""
|
|
371
|
+
act = action or self.action
|
|
372
|
+
result = Results()
|
|
373
|
+
if act is not None:
|
|
374
|
+
if self._check_run(context):
|
|
375
|
+
func = wrap_ctx(act)
|
|
376
|
+
co = func(context)
|
|
377
|
+
ret = call_async(co, loop=context.loop)
|
|
378
|
+
result.add_result(ret)
|
|
379
|
+
for plist in context.parsed.commands.values():
|
|
380
|
+
for parsed in plist:
|
|
381
|
+
context = context.stack(parsed)
|
|
382
|
+
ret = context.command.run_with(context)
|
|
383
|
+
result.add_result(ret)
|
|
384
|
+
return result.result()
|
|
385
|
+
|
|
386
|
+
async def run_with_async(self,
|
|
387
|
+
context: 'Context', action: Optional[AsyncAction] = None):
|
|
388
|
+
"""
|
|
389
|
+
run this command with the specified context/action asyncly
|
|
390
|
+
|
|
391
|
+
:param context: command runtime context
|
|
392
|
+
:param action: command action override
|
|
393
|
+
"""
|
|
394
|
+
act = action or self.action
|
|
395
|
+
result = Results()
|
|
396
|
+
if act is not None:
|
|
397
|
+
if self._check_run(context):
|
|
398
|
+
async_act = wrap_async(act)
|
|
399
|
+
ret = await wrap_ctx(async_act)(context)
|
|
400
|
+
result.add_result(ret)
|
|
401
|
+
for plist in context.parsed.commands.values():
|
|
402
|
+
for parsed in plist:
|
|
403
|
+
context = context.stack(parsed)
|
|
404
|
+
ret = await context.command.run_with_async(context)
|
|
405
|
+
result.add_result(ret)
|
|
406
|
+
return result.result()
|
|
407
|
+
|
|
408
|
+
@overload
|
|
409
|
+
def run(self,
|
|
410
|
+
args: RunArgs = None,
|
|
411
|
+
*,
|
|
412
|
+
standalone_mode: Literal[True] = True,
|
|
413
|
+
**kwargs: Unpack[RunKwargs]
|
|
414
|
+
) -> NoReturn:
|
|
415
|
+
...
|
|
416
|
+
|
|
417
|
+
@overload
|
|
418
|
+
def run(self,
|
|
419
|
+
args: RunArgs = None,
|
|
420
|
+
*,
|
|
421
|
+
standalone_mode: Literal[False] = False,
|
|
422
|
+
**kwargs: Unpack[RunKwargs]
|
|
423
|
+
) -> Any:
|
|
424
|
+
...
|
|
425
|
+
|
|
426
|
+
def run(self,
|
|
427
|
+
args: RunArgs = None,
|
|
428
|
+
*,
|
|
429
|
+
standalone_mode: bool = True,
|
|
430
|
+
**kwargs: Unpack[RunKwargs]
|
|
431
|
+
) -> Any:
|
|
432
|
+
"""
|
|
433
|
+
parse the given arguments and run the relevant command actions
|
|
434
|
+
|
|
435
|
+
:param args: arguments to parse
|
|
436
|
+
:param standalone_mode: exit after completion if true
|
|
437
|
+
"""
|
|
438
|
+
code = 0
|
|
439
|
+
parsed = self.parse(args, standalone_mode=standalone_mode, **kwargs)
|
|
440
|
+
result = None
|
|
441
|
+
with new_context(parsed,
|
|
442
|
+
standalone_mode=standalone_mode, **kwargs) as context:
|
|
443
|
+
try:
|
|
444
|
+
result = self.run_with(context)
|
|
445
|
+
except Exit as err:
|
|
446
|
+
if not standalone_mode:
|
|
447
|
+
raise err
|
|
448
|
+
code = err.exit_code
|
|
449
|
+
if standalone_mode:
|
|
450
|
+
sys.exit(code)
|
|
451
|
+
return result
|
|
452
|
+
|
|
453
|
+
async def run_async(self,
|
|
454
|
+
args: RunArgs = None, **kwargs: Unpack[RunKwargs]) -> Any:
|
|
455
|
+
"""
|
|
456
|
+
parse the given arguments and run the relevant command actions asyncly
|
|
457
|
+
|
|
458
|
+
:param args: arguments to parse
|
|
459
|
+
:param standalone_mode: exit after completion if true
|
|
460
|
+
"""
|
|
461
|
+
parsed = self.parse(args, standalone_mode=False, **kwargs)
|
|
462
|
+
async with new_context_async(parsed,
|
|
463
|
+
standalone_mode=False, run_async=True, **kwargs) as context:
|
|
464
|
+
return await self.run_with_async(context)
|
|
465
|
+
|
|
466
|
+
#** Imports **#
|
|
467
|
+
from .context import AnyIO, Context, new_context, new_context_async
|
|
468
|
+
from .errors import CliError, Exit
|
|
469
|
+
from .help import Help
|
|
470
|
+
from .parser import Parser, ParsedCmd
|
|
471
|
+
from .suggest import SuggestorCLS
|
|
472
|
+
from .wraps import call_async, into_command, wrap_ctx, wrap_async
|
|
473
|
+
from .utils import echo
|