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/context.py
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
"""
|
|
2
|
+
CLI Action Context
|
|
3
|
+
"""
|
|
4
|
+
import sys
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextlib
|
|
7
|
+
from contextvars import ContextVar
|
|
8
|
+
from types import TracebackType
|
|
9
|
+
from typing import (
|
|
10
|
+
Any, AsyncGenerator, Awaitable, BinaryIO, Callable, Dict, Generator,
|
|
11
|
+
List, Literal, Optional, TextIO, Type, TypeVar, Union, cast, overload)
|
|
12
|
+
from typing_extensions import Annotated, get_origin, get_args
|
|
13
|
+
|
|
14
|
+
from . import T
|
|
15
|
+
from .style import Styling, AnsiTermStyle
|
|
16
|
+
|
|
17
|
+
#** Variables **#
|
|
18
|
+
__all__ = [
|
|
19
|
+
'AnyIO',
|
|
20
|
+
'MISSING',
|
|
21
|
+
|
|
22
|
+
'new_context',
|
|
23
|
+
'new_context_async',
|
|
24
|
+
'get_current_context',
|
|
25
|
+
|
|
26
|
+
'Context',
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
SyncCtx = TypeVar('SyncCtx', bound=contextlib.AbstractContextManager)
|
|
30
|
+
AsyncCtx = TypeVar('AsyncCtx', bound=contextlib.AbstractAsyncContextManager)
|
|
31
|
+
|
|
32
|
+
AnyIO = Union[TextIO, BinaryIO]
|
|
33
|
+
|
|
34
|
+
SyncExitFunc = Callable[[
|
|
35
|
+
Optional[Type[Exception]],
|
|
36
|
+
Optional[Exception],
|
|
37
|
+
Optional[TracebackType],
|
|
38
|
+
], Optional[bool]]
|
|
39
|
+
|
|
40
|
+
AsyncExitFunc = Callable[[
|
|
41
|
+
Optional[Type[Exception]],
|
|
42
|
+
Optional[Exception],
|
|
43
|
+
Optional[TracebackType],
|
|
44
|
+
], Awaitable[Optional[bool]]]
|
|
45
|
+
|
|
46
|
+
ExitFunc = Union[AsyncExitFunc, SyncExitFunc]
|
|
47
|
+
|
|
48
|
+
context_stack: ContextVar[List['Context']] = ContextVar('context_stack')
|
|
49
|
+
|
|
50
|
+
#** Functions **#
|
|
51
|
+
|
|
52
|
+
@contextlib.contextmanager
|
|
53
|
+
def new_context(
|
|
54
|
+
parsed: 'ParsedCmd', **kwargs) -> Generator['Context', None, None]:
|
|
55
|
+
"""
|
|
56
|
+
start new context object stack for the current cli job
|
|
57
|
+
"""
|
|
58
|
+
close = kwargs.get('loop') is None
|
|
59
|
+
context = Context(parsed, **kwargs)
|
|
60
|
+
token = context_stack.set([context])
|
|
61
|
+
try:
|
|
62
|
+
yield context
|
|
63
|
+
context.close(None, None, None)
|
|
64
|
+
except Exception as e:
|
|
65
|
+
context.close(e.__class__, e, e.__traceback__)
|
|
66
|
+
raise e
|
|
67
|
+
finally:
|
|
68
|
+
context_stack.reset(token)
|
|
69
|
+
if close:
|
|
70
|
+
context.loop.close()
|
|
71
|
+
|
|
72
|
+
@contextlib.asynccontextmanager
|
|
73
|
+
async def new_context_async(
|
|
74
|
+
parsed: 'ParsedCmd', **kwargs) -> AsyncGenerator['Context', None]:
|
|
75
|
+
"""
|
|
76
|
+
asyncly start new context object stack for the current cli job
|
|
77
|
+
"""
|
|
78
|
+
kwargs.setdefault('loop', asyncio.get_running_loop())
|
|
79
|
+
context = Context(parsed, **kwargs)
|
|
80
|
+
token = context_stack.set([context])
|
|
81
|
+
try:
|
|
82
|
+
yield context
|
|
83
|
+
await context.close_async(None, None, None)
|
|
84
|
+
except Exception as e:
|
|
85
|
+
await context.close_async(e.__class__, e, e.__traceback__)
|
|
86
|
+
raise e
|
|
87
|
+
finally:
|
|
88
|
+
context_stack.reset(token)
|
|
89
|
+
|
|
90
|
+
@overload
|
|
91
|
+
def get_current_context(silent: Literal[False] = False) -> 'Context':
|
|
92
|
+
...
|
|
93
|
+
|
|
94
|
+
@overload
|
|
95
|
+
def get_current_context(silent: Literal[True] = True) -> Optional['Context']:
|
|
96
|
+
...
|
|
97
|
+
|
|
98
|
+
def get_current_context(silent: bool = False) -> Optional['Context']:
|
|
99
|
+
"""
|
|
100
|
+
retrieve last stack from context-stack of current job
|
|
101
|
+
"""
|
|
102
|
+
try:
|
|
103
|
+
return context_stack.get()[-1]
|
|
104
|
+
except LookupError as e:
|
|
105
|
+
if silent: return None
|
|
106
|
+
raise e
|
|
107
|
+
|
|
108
|
+
def typecheck(value: Any, typedef: Type) -> bool:
|
|
109
|
+
"""
|
|
110
|
+
guarded isinstance check that handles specialized typedefs
|
|
111
|
+
"""
|
|
112
|
+
origin = get_origin(typedef)
|
|
113
|
+
args = get_args(typedef)
|
|
114
|
+
if origin in (list, dict, set, tuple):
|
|
115
|
+
typedef = origin
|
|
116
|
+
elif origin is Union:
|
|
117
|
+
return any(typecheck(value, a) for a in args)
|
|
118
|
+
elif origin is Annotated:
|
|
119
|
+
typedef = args[0]
|
|
120
|
+
return isinstance(value, typedef)
|
|
121
|
+
|
|
122
|
+
def get_dict(dict: Dict[str, Any], name: str, ctype: Optional[Type[T]]) -> T:
|
|
123
|
+
"""
|
|
124
|
+
retrieve a value from a dictionarry and validate its type if given
|
|
125
|
+
"""
|
|
126
|
+
value = dict[name]
|
|
127
|
+
if ctype is not None and not typecheck(value, ctype):
|
|
128
|
+
t1 = type(value).__name__
|
|
129
|
+
t2 = ctype.__name__
|
|
130
|
+
raise TypeError(f'{name!r} ({t1}) is not a {t2}')
|
|
131
|
+
return value
|
|
132
|
+
|
|
133
|
+
#** Classes **#
|
|
134
|
+
|
|
135
|
+
class MISSING:
|
|
136
|
+
pass
|
|
137
|
+
|
|
138
|
+
class Context:
|
|
139
|
+
"""
|
|
140
|
+
CLI Command Action Runtime Context
|
|
141
|
+
"""
|
|
142
|
+
__slots__ = ('parsed', 'command', 'args', 'flags', 'parent',
|
|
143
|
+
'extra', 'stdout', 'stderr', 'suggest', 'styling', 'help',
|
|
144
|
+
'closed', 'closers', 'standalone_mode', 'loop', 'run_async')
|
|
145
|
+
|
|
146
|
+
extra: Dict[str, Any]
|
|
147
|
+
stdout: AnyIO
|
|
148
|
+
stderr: AnyIO
|
|
149
|
+
styling: Styling
|
|
150
|
+
closers: List[ExitFunc]
|
|
151
|
+
loop: asyncio.AbstractEventLoop
|
|
152
|
+
|
|
153
|
+
def __init__(self,
|
|
154
|
+
parsed: 'ParsedCmd',
|
|
155
|
+
parent: Optional['Context'] = None,
|
|
156
|
+
help: Optional['Help'] = None,
|
|
157
|
+
stdout: Optional[AnyIO] = None,
|
|
158
|
+
stderr: Optional[AnyIO] = None,
|
|
159
|
+
suggest: Optional['SuggestorCLS'] = None,
|
|
160
|
+
styling: Optional[Styling] = None,
|
|
161
|
+
extra: Optional[Dict[str, Any]] = None,
|
|
162
|
+
|
|
163
|
+
loop: Optional[asyncio.AbstractEventLoop] = None,
|
|
164
|
+
standalone_mode: bool = True,
|
|
165
|
+
run_async: bool = False,
|
|
166
|
+
):
|
|
167
|
+
"""
|
|
168
|
+
:param parsed: parsed command contents
|
|
169
|
+
:param parent: parent context of parent action
|
|
170
|
+
:param help: help formatter object
|
|
171
|
+
:param stdout: standard output file
|
|
172
|
+
:param stderr: standard error output file
|
|
173
|
+
:param suggest: auto-complete suggestion handler type
|
|
174
|
+
:param styling: format styling object
|
|
175
|
+
:param extra: extra data
|
|
176
|
+
:param standalone_mode: label if actions are running in standalone
|
|
177
|
+
:param loop: event-loop to use for action/callback processing
|
|
178
|
+
:param run_async: label context of runtime as within async loop
|
|
179
|
+
"""
|
|
180
|
+
self.parsed = parsed
|
|
181
|
+
self.command = parsed.source
|
|
182
|
+
self.args = parsed.args
|
|
183
|
+
self.flags = parsed.flags
|
|
184
|
+
self.parent = parent
|
|
185
|
+
self.extra = extra or (parent.extra if parent else {})
|
|
186
|
+
self.stdout = stdout or sys.stdout
|
|
187
|
+
self.stderr = stderr or sys.stderr
|
|
188
|
+
self.suggest = suggest or Suggestor
|
|
189
|
+
self.styling = styling or AnsiTermStyle()
|
|
190
|
+
self.help = help or Help(styling)
|
|
191
|
+
self.closed = False
|
|
192
|
+
self.closers = []
|
|
193
|
+
|
|
194
|
+
self.standalone_mode = standalone_mode
|
|
195
|
+
self.run_async = run_async
|
|
196
|
+
self.loop = loop or (parent.loop if parent else asyncio.new_event_loop())
|
|
197
|
+
|
|
198
|
+
def __repr__(self) -> str:
|
|
199
|
+
return f'Context(args={self.args}, flags={self.flags}, extra={self.extra})'
|
|
200
|
+
|
|
201
|
+
@property
|
|
202
|
+
def path(self) -> List['Command']:
|
|
203
|
+
"""
|
|
204
|
+
retrieve heigharchical path of commands executed
|
|
205
|
+
"""
|
|
206
|
+
path: List[Command] = []
|
|
207
|
+
ctx: Optional[Context] = self
|
|
208
|
+
while ctx is not None:
|
|
209
|
+
path.insert(0, ctx.command)
|
|
210
|
+
ctx = ctx.parent if ctx else None
|
|
211
|
+
return path
|
|
212
|
+
|
|
213
|
+
@property
|
|
214
|
+
def invoked_subcommands(self) -> Optional[List[str]]:
|
|
215
|
+
"""
|
|
216
|
+
retrieve list of subcommands to be invoked next
|
|
217
|
+
"""
|
|
218
|
+
commands = list(self.parsed.commands.keys())
|
|
219
|
+
return commands if commands else None
|
|
220
|
+
|
|
221
|
+
def suggestor(self) -> 'Suggestor':
|
|
222
|
+
"""
|
|
223
|
+
generate auto-complete suggestor instance
|
|
224
|
+
"""
|
|
225
|
+
return self.suggest(self.path[0], self.extra)
|
|
226
|
+
|
|
227
|
+
def exit(self, exit_code: int = 0):
|
|
228
|
+
"""
|
|
229
|
+
force exit command execution early
|
|
230
|
+
"""
|
|
231
|
+
raise Exit(exit_code)
|
|
232
|
+
|
|
233
|
+
def on_close(self, closer: ExitFunc):
|
|
234
|
+
"""
|
|
235
|
+
add exit function to be triggered on cleanup (LIFO queue)
|
|
236
|
+
"""
|
|
237
|
+
self.closers.insert(0, closer)
|
|
238
|
+
|
|
239
|
+
def with_resource(self, manager: SyncCtx) -> SyncCtx:
|
|
240
|
+
"""
|
|
241
|
+
bind context-manager to context to ensure closing on exit
|
|
242
|
+
"""
|
|
243
|
+
manager.__enter__()
|
|
244
|
+
self.on_close(manager.__exit__)
|
|
245
|
+
return manager
|
|
246
|
+
|
|
247
|
+
async def with_async_resource(self, manager: AsyncCtx) -> AsyncCtx:
|
|
248
|
+
"""
|
|
249
|
+
bind async context-manager to context to ensure closing on exit
|
|
250
|
+
"""
|
|
251
|
+
await manager.__aenter__()
|
|
252
|
+
self.on_close(manager.__aexit__)
|
|
253
|
+
return manager
|
|
254
|
+
|
|
255
|
+
def close(self,
|
|
256
|
+
exc_type: Optional[Type[Exception]],
|
|
257
|
+
exc_val: Optional[Exception],
|
|
258
|
+
exc_tb: Optional[TracebackType],
|
|
259
|
+
):
|
|
260
|
+
"""
|
|
261
|
+
run all configured closers
|
|
262
|
+
"""
|
|
263
|
+
if self.closed:
|
|
264
|
+
return
|
|
265
|
+
for closer in self.closers:
|
|
266
|
+
co = closer(exc_type, exc_val, exc_tb)
|
|
267
|
+
call_async(co, loop=self.loop)
|
|
268
|
+
self.closed = True
|
|
269
|
+
|
|
270
|
+
async def close_async(self,
|
|
271
|
+
exc_type: Optional[Type[Exception]],
|
|
272
|
+
exc_val: Optional[Exception],
|
|
273
|
+
exc_tb: Optional[TracebackType],
|
|
274
|
+
):
|
|
275
|
+
"""
|
|
276
|
+
run all configured closers asyncly
|
|
277
|
+
"""
|
|
278
|
+
if self.closed:
|
|
279
|
+
return
|
|
280
|
+
for closer in self.closers:
|
|
281
|
+
func = wrap_async(closer)
|
|
282
|
+
await func(exc_type, exc_val, exc_tb)
|
|
283
|
+
self.closed = True
|
|
284
|
+
|
|
285
|
+
def get(self, name: str,
|
|
286
|
+
ctype: Optional[Type[T]] = None, default: Any = MISSING) -> T:
|
|
287
|
+
"""
|
|
288
|
+
retrieve a value from the first relevant context and valdiate its type
|
|
289
|
+
|
|
290
|
+
heigharchy: arguments -> flags -> extra -> default
|
|
291
|
+
|
|
292
|
+
:param name: name of value to retrieve
|
|
293
|
+
:param ctype: type to validate
|
|
294
|
+
:param default: default value if value is missing
|
|
295
|
+
"""
|
|
296
|
+
value = self.args.get(name, MISSING)
|
|
297
|
+
value = self.flags.get(name, MISSING) if value is MISSING else value
|
|
298
|
+
value = self.extra.get(name, MISSING) if value is MISSING else value
|
|
299
|
+
value = default if value is MISSING else value
|
|
300
|
+
if value is MISSING:
|
|
301
|
+
if ctype is not None and issubclass(ctype, self.__class__):
|
|
302
|
+
return cast(T, self)
|
|
303
|
+
raise KeyError(name)
|
|
304
|
+
if ctype is not None and not typecheck(value, ctype):
|
|
305
|
+
t1 = type(value).__name__
|
|
306
|
+
t2 = ctype.__name__
|
|
307
|
+
raise TypeError(f'{name!r} ({t1}) is not a {t2}')
|
|
308
|
+
return value
|
|
309
|
+
|
|
310
|
+
def get_arg(self, name: str, ctype: Optional[Type[T]] = None) -> T:
|
|
311
|
+
"""
|
|
312
|
+
retrieve argument value of a specific name and validate type
|
|
313
|
+
|
|
314
|
+
:param name: name of argument
|
|
315
|
+
:param ctype: type annotation/validation
|
|
316
|
+
"""
|
|
317
|
+
return get_dict(self.args, name, ctype)
|
|
318
|
+
|
|
319
|
+
def get_flag(self, name: str, ctype: Type[T]) -> T:
|
|
320
|
+
"""
|
|
321
|
+
retrieve flag/option value of a specific name and validate type
|
|
322
|
+
|
|
323
|
+
:param name: name of flag/option
|
|
324
|
+
:param ctype: type annotation/validation
|
|
325
|
+
"""
|
|
326
|
+
return get_dict(self.flags, name, ctype)
|
|
327
|
+
|
|
328
|
+
def get_extra(self, name: str, ctype: Type[T]) -> T:
|
|
329
|
+
"""
|
|
330
|
+
retrieve extra value of a specific name and validate type
|
|
331
|
+
|
|
332
|
+
:param name: name of extra value
|
|
333
|
+
:param ctype: type annotation/validation
|
|
334
|
+
"""
|
|
335
|
+
return get_dict(self.extra, name, ctype)
|
|
336
|
+
|
|
337
|
+
def stack(self, parsed: 'ParsedCmd') -> 'Context':
|
|
338
|
+
"""
|
|
339
|
+
generate child context object using parsed context
|
|
340
|
+
"""
|
|
341
|
+
context = self.__class__(
|
|
342
|
+
parsed=parsed,
|
|
343
|
+
parent=self,
|
|
344
|
+
stdout=self.stdout,
|
|
345
|
+
stderr=self.stderr,
|
|
346
|
+
suggest=self.suggest,
|
|
347
|
+
styling=self.styling,
|
|
348
|
+
help=self.help)
|
|
349
|
+
context_stack.get().append(context)
|
|
350
|
+
|
|
351
|
+
close = context.close_async \
|
|
352
|
+
if self.run_async is None else context.close
|
|
353
|
+
self.on_close(close)
|
|
354
|
+
return context
|
|
355
|
+
|
|
356
|
+
#** Imports **#
|
|
357
|
+
from .cmd import Command
|
|
358
|
+
from .help import Help
|
|
359
|
+
from .errors import Exit
|
|
360
|
+
from .parser import ParsedCmd
|
|
361
|
+
from .suggest import Suggestor, SuggestorCLS
|
|
362
|
+
from .wraps import call_async, wrap_async
|
cli/errors.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""
|
|
2
|
+
CLI Parser/Runtime Exception Implementations
|
|
3
|
+
"""
|
|
4
|
+
from typing import ClassVar, Dict, List, NamedTuple, Optional, Union
|
|
5
|
+
|
|
6
|
+
from .arg import Arg
|
|
7
|
+
from .cmd import Command
|
|
8
|
+
from .flag import Flag
|
|
9
|
+
from .help import Help
|
|
10
|
+
from .parser import ParseCtx
|
|
11
|
+
|
|
12
|
+
#** Variables **#
|
|
13
|
+
__all__ = [
|
|
14
|
+
'InvalidDict',
|
|
15
|
+
'InvalidRef',
|
|
16
|
+
|
|
17
|
+
'Exit',
|
|
18
|
+
'CliError',
|
|
19
|
+
|
|
20
|
+
'HelpError',
|
|
21
|
+
'CommandRequired',
|
|
22
|
+
'NoCommandChain',
|
|
23
|
+
'InvalidCommand',
|
|
24
|
+
'Missing',
|
|
25
|
+
'MissingValue',
|
|
26
|
+
'Invalid',
|
|
27
|
+
'Unexpected',
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
InvalidDict = Dict[Union[Arg, Flag], 'InvalidRef']
|
|
31
|
+
|
|
32
|
+
#** Classes **#
|
|
33
|
+
|
|
34
|
+
class Exit(RuntimeError):
|
|
35
|
+
"""
|
|
36
|
+
Custom Exception for Early Exit of CLI Actions
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(self, exit_code: int = 0):
|
|
40
|
+
self.exit_code = exit_code
|
|
41
|
+
|
|
42
|
+
class CliError(Exception):
|
|
43
|
+
"""
|
|
44
|
+
Baseclass for CLI Exceptions
|
|
45
|
+
"""
|
|
46
|
+
exit_code: ClassVar[int] = 1
|
|
47
|
+
|
|
48
|
+
def __init__(self, ctx: ParseCtx, *args):
|
|
49
|
+
super().__init__(ctx, *args)
|
|
50
|
+
self.ctx = ctx
|
|
51
|
+
self.message = self.__class__.__name__
|
|
52
|
+
|
|
53
|
+
def format_message(self, help: Help) -> str:
|
|
54
|
+
"""
|
|
55
|
+
format the error message as part of the help-display
|
|
56
|
+
"""
|
|
57
|
+
return self.message
|
|
58
|
+
|
|
59
|
+
def show(self, help: Optional[Help] = None) -> str:
|
|
60
|
+
"""
|
|
61
|
+
show the help-page associated with this error
|
|
62
|
+
"""
|
|
63
|
+
help = help or Help()
|
|
64
|
+
return help.styling.wrap_color('red', 'error:') \
|
|
65
|
+
+ help.space \
|
|
66
|
+
+ self.format_message(help) \
|
|
67
|
+
+ help.newline \
|
|
68
|
+
+ help.err_suffix(self.ctx)
|
|
69
|
+
|
|
70
|
+
class HelpError(CliError):
|
|
71
|
+
"""
|
|
72
|
+
Internal Exception used when Help Command should be raised.
|
|
73
|
+
"""
|
|
74
|
+
exit_code: ClassVar[int] = 0
|
|
75
|
+
|
|
76
|
+
def __init__(self, ctx: ParseCtx, command: Command):
|
|
77
|
+
super().__init__(ctx, command)
|
|
78
|
+
self.ctx = ctx
|
|
79
|
+
self.command = command
|
|
80
|
+
|
|
81
|
+
def show(self, help: Optional[Help] = None) -> str:
|
|
82
|
+
help = help or Help()
|
|
83
|
+
return help.help(self.ctx, self.command)
|
|
84
|
+
|
|
85
|
+
class UsageError(CliError):
|
|
86
|
+
"""
|
|
87
|
+
Generic Usage Error Exception
|
|
88
|
+
"""
|
|
89
|
+
exit_code: ClassVar[int] = 2
|
|
90
|
+
|
|
91
|
+
def __init__(self, ctx: ParseCtx, *args):
|
|
92
|
+
super().__init__(ctx, *args)
|
|
93
|
+
if args and isinstance(args[0], str):
|
|
94
|
+
self.message = args[0]
|
|
95
|
+
|
|
96
|
+
class InvalidCommand(UsageError):
|
|
97
|
+
def __init__(self, ctx: ParseCtx, command: str):
|
|
98
|
+
super().__init__(ctx, command)
|
|
99
|
+
self.command = command
|
|
100
|
+
self.message = 'unrecognized subcommand'
|
|
101
|
+
|
|
102
|
+
def format_message(self, help: Help) -> str:
|
|
103
|
+
return self.message + help.space \
|
|
104
|
+
+ help.styling.wrap_color('yellow', repr(self.command))
|
|
105
|
+
|
|
106
|
+
class CommandRequired(UsageError):
|
|
107
|
+
def __init__(self, ctx: ParseCtx, commands: List[Command]):
|
|
108
|
+
super().__init__(ctx, commands)
|
|
109
|
+
self.commands = commands
|
|
110
|
+
self.message = 'requires a subcommand but one was not provided'
|
|
111
|
+
|
|
112
|
+
def format_message(self, help: Help) -> str:
|
|
113
|
+
commands = self.ctx.command.visible_commands()
|
|
114
|
+
name = help.styling.wrap_color('yellow', repr(self.ctx.command.name))
|
|
115
|
+
cmds = [help.styling.wrap_color('green', c.name) for c in commands]
|
|
116
|
+
return f'{name} {self.message}' \
|
|
117
|
+
+ help.newline \
|
|
118
|
+
+ help.indent \
|
|
119
|
+
+ f'[subcommands: {", ".join(cmds)}]'
|
|
120
|
+
|
|
121
|
+
class NoCommandChain(UsageError):
|
|
122
|
+
def __init__(self, ctx: ParseCtx, commands: List[Command]):
|
|
123
|
+
super().__init__(ctx, commands)
|
|
124
|
+
self.commands = commands
|
|
125
|
+
self.message = 'command chaining is not allowed'
|
|
126
|
+
|
|
127
|
+
def format_message(self, help: Help):
|
|
128
|
+
cmds = [help.styling.wrap_color('green', c.name) for c in self.commands]
|
|
129
|
+
name = help.styling.wrap_color('yellow', repr(self.ctx.command.name))
|
|
130
|
+
return f'{name} {self.message}' \
|
|
131
|
+
+ help.newline \
|
|
132
|
+
+ help.indent \
|
|
133
|
+
+ f'[used: {", ".join(cmds)}]'
|
|
134
|
+
|
|
135
|
+
class Missing(UsageError):
|
|
136
|
+
def __init__(self, ctx: ParseCtx, missing: List[Union[Arg, Flag]]):
|
|
137
|
+
super().__init__(ctx, missing)
|
|
138
|
+
self.missing = missing
|
|
139
|
+
self.message = 'the following required arguments were not provided'
|
|
140
|
+
self.missing.sort(key=lambda m: isinstance(m, Flag))
|
|
141
|
+
|
|
142
|
+
def format_message(self, help: Help) -> str:
|
|
143
|
+
elems = []
|
|
144
|
+
for elem in self.missing:
|
|
145
|
+
line = help.usage(self.ctx, elem)
|
|
146
|
+
elems.append(help.indent + help.styling.wrap_color('green', line))
|
|
147
|
+
return f'{self.message}:' \
|
|
148
|
+
+ help.newline \
|
|
149
|
+
+ help.newline.join(elems)
|
|
150
|
+
|
|
151
|
+
class MissingValue(UsageError):
|
|
152
|
+
def __init__(self, ctx: ParseCtx, missing: List[Flag]):
|
|
153
|
+
super().__init__(ctx, missing)
|
|
154
|
+
self.missing = missing
|
|
155
|
+
self.message = 'following flag(s) are missing values'
|
|
156
|
+
|
|
157
|
+
def format_message(self, help: Help) -> str:
|
|
158
|
+
items = []
|
|
159
|
+
for flag in self.missing:
|
|
160
|
+
line = help.flag_usage(self.ctx, flag)
|
|
161
|
+
prefix, value = line.rsplit(help.space, 1)
|
|
162
|
+
value = help.styling.wrap_color('yellow', value)
|
|
163
|
+
line = prefix + help.space + value
|
|
164
|
+
items.append(help.indent + line)
|
|
165
|
+
return f'{self.message}:' \
|
|
166
|
+
+ help.newline \
|
|
167
|
+
+ help.newline.join(items)
|
|
168
|
+
|
|
169
|
+
class InvalidRef(NamedTuple):
|
|
170
|
+
value: str
|
|
171
|
+
error: str
|
|
172
|
+
|
|
173
|
+
class Invalid(UsageError):
|
|
174
|
+
def __init__(self, ctx: ParseCtx, invalid: InvalidDict):
|
|
175
|
+
super().__init__(ctx, invalid)
|
|
176
|
+
self.invalid = invalid
|
|
177
|
+
self.message = 'invalid arguments present'
|
|
178
|
+
|
|
179
|
+
def format_message(self, help: Help) -> str:
|
|
180
|
+
invalid = list(self.invalid.items())
|
|
181
|
+
invalid.sort(key=lambda i: isinstance(i[0], Arg))
|
|
182
|
+
return f'{self.message}:' \
|
|
183
|
+
+ help.newline \
|
|
184
|
+
+ help.buffer(
|
|
185
|
+
items=invalid,
|
|
186
|
+
left=lambda items: help.usage(self.ctx, items[0]),
|
|
187
|
+
right=lambda items: help.styling.wrap_color('yellow', items[1].error),
|
|
188
|
+
).rstrip()
|
|
189
|
+
|
|
190
|
+
class Unexpected(UsageError):
|
|
191
|
+
def __init__(self, ctx: ParseCtx, unexpected: List[str]):
|
|
192
|
+
super().__init__(ctx, unexpected)
|
|
193
|
+
self.unexpected = unexpected
|
|
194
|
+
self.message = 'unexpected argument'
|
|
195
|
+
|
|
196
|
+
def format_message(self, help: Help) -> str:
|
|
197
|
+
items = [help.styling.wrap_color('yellow', repr(u))
|
|
198
|
+
for u in self.unexpected]
|
|
199
|
+
return f'{self.message}(s) {", ".join(items)} found'
|
cli/flag.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""
|
|
2
|
+
CLI Flag Implementation
|
|
3
|
+
"""
|
|
4
|
+
from typing import (
|
|
5
|
+
Any, Callable, Generic, List, Literal, Optional, Tuple, Type,
|
|
6
|
+
cast, get_args)
|
|
7
|
+
|
|
8
|
+
from . import T, OptSuggest, get_type, get_suggestor, get_validator
|
|
9
|
+
|
|
10
|
+
#** Variables **#
|
|
11
|
+
__all__ = ['Flag', 'Flags']
|
|
12
|
+
|
|
13
|
+
Flags = List['Flag']
|
|
14
|
+
Short = Literal[
|
|
15
|
+
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
|
|
16
|
+
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
|
|
17
|
+
|
|
18
|
+
#** Functions **#
|
|
19
|
+
|
|
20
|
+
def flag_default(type: Type[T], value: Any) -> Optional[T]:
|
|
21
|
+
"""
|
|
22
|
+
determine default based on type and value
|
|
23
|
+
"""
|
|
24
|
+
if type is bool and value is None:
|
|
25
|
+
return cast(T, False)
|
|
26
|
+
return value
|
|
27
|
+
|
|
28
|
+
def parse_short(name: str) -> Tuple[str, Optional[Short]]:
|
|
29
|
+
"""
|
|
30
|
+
parse short included with name (if specified)
|
|
31
|
+
|
|
32
|
+
example: `name, n` = (long=name, short=n)
|
|
33
|
+
"""
|
|
34
|
+
comma = name.count(',')
|
|
35
|
+
if comma > 1:
|
|
36
|
+
raise ValueError(f'Invalid flag name: {name!r}')
|
|
37
|
+
if comma == 0:
|
|
38
|
+
return (name, None)
|
|
39
|
+
long, short = name.split(',', 1)
|
|
40
|
+
long, short = long.strip(), short.strip()
|
|
41
|
+
if short not in get_args(Short):
|
|
42
|
+
raise ValueError(f'Invalid short flag: {short!r}')
|
|
43
|
+
return (long, cast(Short, short))
|
|
44
|
+
|
|
45
|
+
#** Classes **#
|
|
46
|
+
|
|
47
|
+
class Flag(Generic[T]):
|
|
48
|
+
"""
|
|
49
|
+
Command Flag/Option Configuration Setting
|
|
50
|
+
"""
|
|
51
|
+
type: Type[T]
|
|
52
|
+
suggestor: OptSuggest
|
|
53
|
+
|
|
54
|
+
def __init__(self,
|
|
55
|
+
name: str,
|
|
56
|
+
about: Optional[str] = None,
|
|
57
|
+
default: Optional[T] = None,
|
|
58
|
+
required: bool = False,
|
|
59
|
+
repeat: bool = False,
|
|
60
|
+
short: Optional[Short] = None,
|
|
61
|
+
long: Optional[str] = None,
|
|
62
|
+
hidden: bool = False,
|
|
63
|
+
validators: Optional[List[Callable[[Any], T]]] = None,
|
|
64
|
+
suggestor: OptSuggest = None,
|
|
65
|
+
type: Optional[Type[T]] = None,
|
|
66
|
+
):
|
|
67
|
+
"""
|
|
68
|
+
:param name: name of flag
|
|
69
|
+
:param about: description of flag
|
|
70
|
+
:param default: default value assigned to flag
|
|
71
|
+
:param required: label if flag is required during parsing
|
|
72
|
+
:param repeat: allow flag to be repeated
|
|
73
|
+
:param short: flag short variant
|
|
74
|
+
:param long: flag long variant
|
|
75
|
+
:param hidden: hide flag in help if true
|
|
76
|
+
:param validators: validators used to process flag value
|
|
77
|
+
:param suggestor: flag auto-complete suggestion function
|
|
78
|
+
:param type: flag type assignment
|
|
79
|
+
"""
|
|
80
|
+
name, name_short = parse_short(name)
|
|
81
|
+
self.name = name
|
|
82
|
+
self.about = about or ''
|
|
83
|
+
self.default = default
|
|
84
|
+
self.required = required
|
|
85
|
+
self.repeat = repeat
|
|
86
|
+
self.short = short or name_short
|
|
87
|
+
self.long = long or name
|
|
88
|
+
self.hidden = hidden
|
|
89
|
+
self.validators = validators.copy() if validators else []
|
|
90
|
+
self.suggestor = suggestor
|
|
91
|
+
self._set_type(type)
|
|
92
|
+
|
|
93
|
+
def _set_type(self, typedef: Optional[Type]):
|
|
94
|
+
"""
|
|
95
|
+
type assignment and all related attributes that pull from type
|
|
96
|
+
"""
|
|
97
|
+
newtype, meta = get_type(self, typedef)
|
|
98
|
+
self.type = newtype
|
|
99
|
+
self.repeat = self.repeat or meta.repeat
|
|
100
|
+
self.suggestor = get_suggestor(self.type, self.suggestor)
|
|
101
|
+
self.validators = get_validator(self.type, self.validators)
|
|
102
|
+
self.default = flag_default(self.type, self.default)
|
|
103
|
+
|
|
104
|
+
def __repr__(self) -> str:
|
|
105
|
+
attrs = {'name': self.name, 'short': self.short, 'long': self.long}
|
|
106
|
+
items = ', '.join(f'{k}={v}' for k,v in attrs.items() if v)
|
|
107
|
+
return f'Flag({items})'
|
|
108
|
+
|
|
109
|
+
@classmethod
|
|
110
|
+
def __class_getitem__(cls, value: Type):
|
|
111
|
+
func = getattr(super(), '__class_getitem__')
|
|
112
|
+
instance = func(value)
|
|
113
|
+
instance.type = value
|
|
114
|
+
return instance
|
|
115
|
+
|
|
116
|
+
def _requires_value(self) -> bool:
|
|
117
|
+
"""
|
|
118
|
+
return if flag requires a value or not based on type
|
|
119
|
+
"""
|
|
120
|
+
return self.type is not bool
|
|
121
|
+
|
|
122
|
+
def variants(self) -> List[str]:
|
|
123
|
+
"""
|
|
124
|
+
short and long flag variants of this flag
|
|
125
|
+
"""
|
|
126
|
+
names = [f'--{self.long}']
|
|
127
|
+
if self.short is not None:
|
|
128
|
+
names.insert(0, f'-{self.short}')
|
|
129
|
+
return names
|