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/help.py ADDED
@@ -0,0 +1,228 @@
1
+ """
2
+ Help Page Generation
3
+ """
4
+ import functools
5
+ from typing import Callable, List, Optional, Union
6
+
7
+ from . import T
8
+ from .arg import Arg
9
+ from .cmd import Command
10
+ from .flag import Flag
11
+ from .style import AnsiTermStyle, Styling
12
+
13
+ #** Variables **#
14
+ __all__ = ['Help']
15
+
16
+ #** Functions **#
17
+
18
+ @functools.lru_cache()
19
+ def help_flag() -> Flag:
20
+ return Flag[bool]('help', 'Print help', suggestor=False)
21
+
22
+ @functools.lru_cache()
23
+ def help_command() -> Command:
24
+ return Command(
25
+ name='help',
26
+ about='Print this message or the help of the given subcommand(s)',
27
+ suggest=False)
28
+
29
+ #** Classes **#
30
+
31
+ class Help:
32
+ """
33
+ Help Page Generation Class
34
+ """
35
+ __slots__ = ('styling', 'indent', 'space', 'newline', 'flag', 'command')
36
+
37
+ def __init__(self,
38
+ styling: Optional[Styling] = None,
39
+ indent: str = ' ',
40
+ space: str = ' ',
41
+ newline: str = '\n',
42
+ ):
43
+ """
44
+ :param styling: styling used during help-page generation
45
+ :param indent: character(s) used for indent in help generation
46
+ :param space: character(s) used for space in help generation
47
+ :param newline: character(s) used for newline in help generation
48
+ """
49
+ self.styling = styling or AnsiTermStyle()
50
+ self.indent = indent
51
+ self.space = space
52
+ self.newline = newline
53
+ self.flag = help_flag()
54
+ self.command = help_command()
55
+
56
+ def apply_helpers(self, command: Command):
57
+ """
58
+ apply help flag/command to the given command (if not already)
59
+ """
60
+ if self.flag not in command.flags:
61
+ command.flags.append(self.flag)
62
+ if command.commands and self.command not in command.commands:
63
+ command.commands.append(self.command)
64
+
65
+ def buffer(self,
66
+ items: List[T],
67
+ left: Callable[[T], str],
68
+ right: Callable[[T], str],
69
+ threshold: int = 80,
70
+ prefix: Optional[str] = None,
71
+ ) -> str:
72
+ """
73
+ write two columns with each row equidistant from each other
74
+
75
+ :param items: source of content to generate columns
76
+ :param left: function used to generate left column
77
+ :param right: function used to generate right column
78
+ :param threshold: max width allowed for row
79
+ :param prefix: prefix added to each row
80
+ """
81
+ r1 = []
82
+ r2 = []
83
+ for item in items:
84
+ r1.append(left(item))
85
+ r2.append(right(item))
86
+
87
+ buffer = 0
88
+ prefix = prefix or self.indent
89
+ for a, b in zip(r1, r2):
90
+ line = self.indent + a
91
+ if (len(prefix) + len(line) + len(b)) > threshold:
92
+ buffer = None #type: ignore[assignment]
93
+ break
94
+ buffer = len(line) if buffer < len(line) else buffer
95
+
96
+ lines = []
97
+ if buffer is None:
98
+ for a, b in zip(r1, r2):
99
+ line = a + self.newline + (self.indent * 2) + b
100
+ lines.append(prefix + line)
101
+ else:
102
+ for a, b in zip(r1, r2):
103
+ buf = self.space * (buffer - len(a) + 1)
104
+ lines.append(prefix + a + buf + b)
105
+ return self.newline.join(lines) + self.newline
106
+
107
+ def about(self, item: Union[Arg, Flag]) -> str:
108
+ """
109
+ generate an about string for both argument/flag
110
+ """
111
+ if isinstance(item, Flag) and not item._requires_value():
112
+ return item.about
113
+ if item.default is not None:
114
+ default = item.default
115
+ if isinstance(default, bool):
116
+ default = int(default)
117
+ return f'{item.about} [default: {default}]'
118
+ return item.about or ''
119
+
120
+ def arg_usage(self, ctx: 'ParseCtx', arg: Arg) -> str:
121
+ """
122
+ generate usage string for an argument
123
+ """
124
+ if arg.required:
125
+ return f'<{arg.name.upper()}>'
126
+ return f'[{arg.name.upper()}]'
127
+
128
+ def flag_usage(self, ctx: 'ParseCtx', flag: Flag, short: bool = False) -> str:
129
+ """
130
+ generate usage string for a flag
131
+ """
132
+ if not flag._requires_value():
133
+ value = ''
134
+ elif flag.default is not None:
135
+ value = f'[{flag.name.upper()}]'
136
+ else:
137
+ value = f'<{flag.name.upper()}>'
138
+
139
+ if short:
140
+ if flag.short is not None:
141
+ return f'-{flag.short} --{flag.long} {value}'
142
+ return self.space * 4 + f'--{flag.long} {value}'
143
+ return f'--{flag.long} {value}'
144
+
145
+ def command_usage(self, ctx: 'ParseCtx', cmd: Command) -> str:
146
+ """
147
+ generate usage string for a command
148
+ """
149
+ path = [*ctx.path[:-1], cmd]
150
+ usage = []
151
+ for c in path:
152
+ usage.append(c.name)
153
+ for arg in c.args:
154
+ usage.append(self.arg_usage(ctx, arg))
155
+
156
+ flags = [f for f in c.visible_flags() if f != self.flag]
157
+ required = [f for f in flags if f.required]
158
+ for flag in required:
159
+ usage.append(self.flag_usage(ctx, flag))
160
+ if len(required) < len(flags):
161
+ usage.append('<OPTIONS>')
162
+
163
+ if cmd.visible_commands():
164
+ command = '[COMMAND]' if cmd.invoke_without_command else '<COMMAND>'
165
+ usage.append(command)
166
+ return self.space.join(usage)
167
+
168
+ def usage(self, ctx: 'ParseCtx', item: Union[Arg, Command, Flag]) -> str:
169
+ """
170
+ generate usage string for any argument/flag/command
171
+ """
172
+ if isinstance(item, Arg):
173
+ return self.arg_usage(ctx, item)
174
+ elif isinstance(item, Flag):
175
+ return self.flag_usage(ctx, item)
176
+ return self.command_usage(ctx, item)
177
+
178
+ def err_suffix(self, ctx: 'ParseCtx') -> str:
179
+ """
180
+ generate standard help page suffix for an error message
181
+ """
182
+ return self.newline \
183
+ + self.styling.wrap_style('underline', 'Usage:') \
184
+ + self.space \
185
+ + self.command_usage(ctx, ctx.command) \
186
+ + self.newline * 2 \
187
+ + "For more information, try: '--help'."
188
+
189
+ def help(self, ctx: 'ParseCtx', cmd: Command) -> str:
190
+ """
191
+ generate a complete help-page for the specified command
192
+ """
193
+ help = self.styling.wrap_style('underline', 'Usage:') \
194
+ + self.space \
195
+ + self.command_usage(ctx, cmd) \
196
+ + self.newline
197
+ if cmd.args:
198
+ help += self.newline \
199
+ + self.styling.wrap_style('underline', 'Arguments:') \
200
+ + self.newline \
201
+ + self.buffer(
202
+ items=cmd.args,
203
+ left=lambda arg: self.arg_usage(ctx, arg),
204
+ right=self.about,
205
+ )
206
+ if cmd.visible_commands():
207
+ help += self.newline \
208
+ + self.styling.wrap_style('underline', 'Commands:') \
209
+ + self.newline \
210
+ + self.buffer(
211
+ items=cmd.visible_commands(),
212
+ left=lambda c: c.name,
213
+ right=lambda c: c.about or '',
214
+ )
215
+ if cmd.visible_flags():
216
+ short = any(f.short is not None for f in cmd.flags)
217
+ help += self.newline \
218
+ + self.styling.wrap_style('underline', 'Options:') \
219
+ + self.newline \
220
+ + self.buffer(
221
+ items=cmd.visible_flags(),
222
+ left=lambda f: self.flag_usage(ctx, f, short),
223
+ right=self.about,
224
+ )
225
+ return help
226
+
227
+ #** Imports **#
228
+ from .parser import ParseCtx
cli/parser.py ADDED
@@ -0,0 +1,440 @@
1
+ """
2
+ CLI Argument Parser
3
+ """
4
+ from collections import OrderedDict
5
+ from typing import Any, Dict, List, Optional, Tuple, Type, Union, cast
6
+ from typing_extensions import NamedTuple
7
+
8
+ from . import T
9
+ from .arg import Arg
10
+ from .cmd import Command
11
+ from .flag import Flag
12
+ from .context import MISSING, get_dict
13
+ from .help import Help
14
+
15
+ #** Variables **#
16
+ __all__ = ['Parser', 'ParsedCmd']
17
+
18
+ ArgValue = Union[str, None, Type[MISSING]]
19
+ FlagValues = Union[List[Optional[str]], Type[MISSING]]
20
+
21
+ #** Functions **#
22
+
23
+ def index_flags(flags: List[Flag], args: List[str]) -> List[Tuple[int, Flag]]:
24
+ """
25
+ retrieve list of indexes for each flag found in the arguments
26
+
27
+ :param flags: list of flags to find indexes of
28
+ :param args: list of arguments to parse flags from
29
+ """
30
+ flags = flags.copy()
31
+ indexes = []
32
+ for arg_idx, arg in enumerate(args, 0):
33
+ if arg == '--':
34
+ break
35
+ for flag_idx, flag in enumerate(flags, 0):
36
+ if arg not in flag.variants():
37
+ continue
38
+ indexes.append((arg_idx, flag))
39
+ if not flag.repeat:
40
+ flags.pop(flag_idx)
41
+ break
42
+ return indexes
43
+
44
+ def index_commands(
45
+ commands: List[Command], args: List[str]) -> List[Tuple[int, Command]]:
46
+ """
47
+ retrieve list of indexes for each command found in the arguments
48
+
49
+ :param commands: list of commands to find indexes of
50
+ :param args: list of arguments to parse commands from
51
+ """
52
+ commands = commands.copy()
53
+ indexes = []
54
+ for arg_idx, arg in enumerate(args, 0):
55
+ if arg == '--':
56
+ break
57
+ for cmd_idx, command in enumerate(commands, 0):
58
+ if command.name != arg and arg not in command.aliases:
59
+ continue
60
+ indexes.append((arg_idx, command))
61
+ if not command.repeat:
62
+ commands.pop(cmd_idx)
63
+ break
64
+ return indexes
65
+
66
+ #** Classes **#
67
+
68
+ class ParsedCmd(NamedTuple):
69
+ """
70
+ Parse Completion Command Details
71
+ """
72
+ source: Command
73
+ args: Dict[str, Any]
74
+ commands: Dict[str, List['ParsedCmd']]
75
+ flags: Dict[str, Any]
76
+
77
+ class ParseCtx:
78
+ """
79
+ Parsing shared context object
80
+ """
81
+ __slots__ = ('path', 'extra',
82
+ 'missing', 'missing_v', 'invalid', 'unexpected', 'disallowed')
83
+
84
+ path: List[Command]
85
+ extra: Dict[str, Any]
86
+
87
+ missing: List[Union[Arg, Flag, Command]]
88
+ missing_v: List[Flag]
89
+ disallowed: List[Command]
90
+ invalid: 'InvalidDict'
91
+ unexpected: List[str]
92
+
93
+ def __init__(self, path: List[Command], extra: Dict[str, Any]):
94
+ self.path = path
95
+ self.extra = extra
96
+ self.missing = []
97
+ self.missing_v = []
98
+ self.invalid = {}
99
+ self.disallowed = []
100
+ self.unexpected = []
101
+
102
+ def __repr__(self) -> str:
103
+ return f'ParseCtx(path={[c.name for c in self.path]})'
104
+
105
+ @property
106
+ def command(self) -> Command:
107
+ """
108
+ retrieve latest command in parsing stack
109
+ """
110
+ return self.path[-1]
111
+
112
+ def stack(self, command: Command) -> 'ParseCtx':
113
+ """
114
+ generate new child context with next command
115
+ """
116
+ return self.__class__([*self.path, command], self.extra)
117
+
118
+ def splice_args(self, array: List[T],
119
+ index: int, length: Optional[int] = None) -> List[T]:
120
+ """
121
+ splice a subsection of an array and remove it from the existing one
122
+
123
+ :param array: array to splice entries from
124
+ :param index: index to begin splicing from
125
+ :param length: length of items to splice (defaults to end)
126
+ :return: subsection spliced out
127
+ """
128
+ end = (index + length) if length is not None else len(array)
129
+ splice = array[index:end]
130
+ array[index:end] = []
131
+ return splice
132
+
133
+ def get_extra(self, name: str, ctype: Type[T]) -> T:
134
+ """
135
+ retrieve extra value of a specific name and validate type
136
+
137
+ :param name: name of extra value
138
+ :param ctype: type annotation/validation
139
+ """
140
+ if name not in self.extra:
141
+ if issubclass(ctype, self.__class__):
142
+ return cast(T, self)
143
+ return get_dict(self.extra, name, ctype)
144
+
145
+ def add_missing(self, *missing: Union[Arg, Flag, Command]):
146
+ """
147
+ log a missing argument/flag/command during parsing
148
+ """
149
+ self.missing.extend(missing)
150
+
151
+ def add_missing_value(self, *missing: Flag):
152
+ """
153
+ log a missing flag value during parsing
154
+ """
155
+ self.missing_v.extend(missing)
156
+
157
+ def add_disallowed(self, commands: List[Command]):
158
+ """
159
+ log disallowed command chain
160
+ """
161
+ self.disallowed.extend(commands)
162
+
163
+ def add_invalid(self, invalid: Union[Arg, Flag], value: str, error: str):
164
+ """
165
+ log an invalid argument/flag value during parsing
166
+ """
167
+ self.invalid[invalid] = InvalidRef(value, error)
168
+
169
+ def add_unexpected(self, *unexpected: str):
170
+ """
171
+ log an unexpected argument during parsing
172
+ """
173
+ self.unexpected.extend(unexpected)
174
+
175
+ def finalize(self):
176
+ """
177
+ raise an exception if any items were logged during parsing
178
+ """
179
+ if self.unexpected:
180
+ raise Unexpected(self, self.unexpected)
181
+ if self.invalid:
182
+ raise Invalid(self, self.invalid)
183
+ if self.disallowed:
184
+ raise NoCommandChain(self, self.disallowed)
185
+ if self.missing_v:
186
+ raise MissingValue(self, self.missing_v)
187
+ if self.missing:
188
+ command = [m for m in self.missing if isinstance(m, Command)]
189
+ if command:
190
+ raise CommandRequired(self, command[0].commands)
191
+ raise Missing(self, cast(List[Union[Arg, Flag]], self.missing))
192
+
193
+ class Parser:
194
+ """
195
+ CLI Raw Argument Parser Implementation
196
+ """
197
+ __slots__ = ('command', 'complete', 'help')
198
+
199
+ def __init__(self,
200
+ command: Command,
201
+ help: Optional[Help] = None,
202
+ complete: Optional[Command] = None,
203
+ ):
204
+ """
205
+ :param command: command definition to parse from
206
+ :param help: help-page generator
207
+ :param complete: auto-completion command (if any)
208
+ """
209
+ self.help = help or Help()
210
+ self.command = command
211
+ self.complete = complete or autocomplete_cmd()
212
+ self._init()
213
+
214
+ def _init(self):
215
+ """
216
+ append help and auto-complete flags/commands
217
+ """
218
+ command = self.command
219
+ self.help.apply_helpers(command)
220
+ if self.complete not in command.commands:
221
+ command.commands.append(self.complete)
222
+ #NOTE: dont force autocomplete command usage
223
+ if len(command.commands) == 1:
224
+ command.invoke_without_command = True
225
+ command.validate()
226
+
227
+ def validate_arg(self,
228
+ ctx: ParseCtx, arg: Arg, value: ArgValue, error_flags: bool) -> Any:
229
+ """
230
+ validate the given value matches an arguments configuration
231
+
232
+ :param ctx: parsing context
233
+ :param arg: command argument definition
234
+ :param value: value to parse
235
+ :param error_flags: raise an exception on flag prefix if true
236
+ """
237
+ if value is MISSING:
238
+ return ctx.add_missing(arg) if arg.required else arg.default
239
+
240
+ if error_flags and isinstance(value, str) and value.startswith('-'):
241
+ return ctx.add_unexpected(value)
242
+
243
+ for raw_validator in arg.validators:
244
+ validator = wrap_validator(raw_validator)
245
+ try:
246
+ value = validator(ctx, value)
247
+ except ValueError as e:
248
+ value = cast(str, value)
249
+ return ctx.add_invalid(arg, value, e.args[0])
250
+ return value
251
+
252
+ def validate_flag(self, ctx: ParseCtx, flag: Flag, values: FlagValues) -> Any:
253
+ """
254
+ validate the given value matches a flags configuration
255
+
256
+ :param ctx: parsing context
257
+ :param flag: command flag/option definition
258
+ :param values: values assigned to flag
259
+ """
260
+ if values is MISSING:
261
+ return ctx.add_missing(flag) if flag.required else flag.default
262
+
263
+ values = cast(List[Optional[str]], values)
264
+ if flag._requires_value() and any(v is None for v in values):
265
+ return ctx.add_missing_value(flag)
266
+
267
+ parsed = []
268
+ for value in values:
269
+ if value is None:
270
+ parsed.append(flag.default if flag._requires_value() else True)
271
+ continue
272
+ for raw_validator in flag.validators:
273
+ validator = wrap_validator(raw_validator)
274
+ try:
275
+ value = validator(ctx, value)
276
+ except ValueError as e:
277
+ return ctx.add_invalid(flag, value, e.args[0])
278
+ parsed.insert(0, value)
279
+ return parsed if flag.repeat else parsed[0]
280
+
281
+ def split_args(self, ctx: ParseCtx,
282
+ cmdargs: List[Arg], args: List[str]) -> Dict[str, Any]:
283
+ """
284
+ split command arguments from the raw argument list
285
+
286
+ :param ctx: parsing context
287
+ :param cmdargs: command arguments to parse and validate against
288
+ :param args: raw arguments to parse from
289
+ :return: map of parsed/validated argument values
290
+ """
291
+ values = {} #type: Dict[str, Any]
292
+ cmdargs = cmdargs.copy()
293
+ error_flags = True
294
+ while cmdargs and args:
295
+ cmdarg = cmdargs[0]
296
+ value = args.pop(0) if args else MISSING
297
+ if value == '--' and error_flags:
298
+ error_flags = False
299
+ continue
300
+
301
+ val = self.validate_arg(ctx, cmdarg, value, error_flags)
302
+ if cmdarg.repeat:
303
+ val = val if isinstance(val, (list, tuple, set)) else [val]
304
+ values.setdefault(cmdarg.name, [])
305
+ values[cmdarg.name].extend(val)
306
+ else:
307
+ values[cmdarg.name] = val
308
+ cmdargs.pop(0)
309
+
310
+ remaining = []
311
+ for arg in cmdargs:
312
+ if arg.name in values:
313
+ continue
314
+ if arg.default is not None:
315
+ values[arg.name] = arg.default
316
+ continue
317
+ if arg.required:
318
+ remaining.append(arg)
319
+
320
+ ctx.add_missing(*remaining)
321
+ ctx.add_unexpected(*args)
322
+ return values
323
+
324
+ def split_flags(self, ctx: ParseCtx,
325
+ flags: List[Flag], args: List[str]) -> Dict[str, Any]:
326
+ """
327
+ split flags from the raw argument list
328
+
329
+ :param ctx: parsing context
330
+ :param flags: command flags to parse and validate against
331
+ :param args: raw arguments to parse from
332
+ :return: map of parsed/validated flag values
333
+ """
334
+ indexes = index_flags(flags, args)
335
+
336
+ values: Dict[str, List[Optional[str]]] = {}
337
+ indexes.reverse()
338
+ for idx, flag in indexes:
339
+ ctx.splice_args(args, idx, 1)
340
+ has_value = not any(i == idx + 1 for i, _ in indexes) \
341
+ and idx + 1 <= len(args) and flag._requires_value()
342
+ value = ctx.splice_args(args, idx, 1)[0] if has_value else None
343
+ values.setdefault(flag.name, [])
344
+ values[flag.name].append(value)
345
+
346
+ parsed = {}
347
+ for flag in flags:
348
+ fvalue = values.get(flag.name, MISSING)
349
+ parsed[flag.name] = self.validate_flag(ctx, flag, fvalue)
350
+ return parsed
351
+
352
+ def split_commands(self, ctx: ParseCtx, commands: List[Command],
353
+ args: List[str]) -> Dict[str, List[ParsedCmd]]:
354
+ """
355
+ split sub-commands from the raw argument list
356
+
357
+ :param ctx: parsing contxt
358
+ :param commands: subcommands to parse and validate against
359
+ :param args: raw arguments to parse from
360
+ :return: map of parsed/validated commands
361
+ """
362
+ indexes = index_commands(commands, args)
363
+
364
+ parsed: Dict[str, List[ParsedCmd]] = OrderedDict()
365
+ indexes.reverse()
366
+ for idx, command in indexes:
367
+ c_ctx = ctx.stack(command)
368
+ c_args = c_ctx.splice_args(args, idx)[1:]
369
+ c_commands = self.split_commands(c_ctx, command.commands, c_args)
370
+ c_flags = self.split_flags(c_ctx, command.flags, c_args)
371
+ c_params = self.split_args(c_ctx, command.args, c_args)
372
+ c_ctx.finalize()
373
+ parsed.setdefault(command.name, [])
374
+ parsed[command.name].insert(0,
375
+ ParsedCmd(command, c_params, c_commands, c_flags))
376
+
377
+ if not parsed and commands \
378
+ and not ctx.command.invoke_without_command:
379
+ ctx.add_missing(ctx.command)
380
+
381
+ if len(parsed) > 1 and not ctx.command.chain:
382
+ ctx.add_disallowed([c for c in commands if c.name in parsed])
383
+
384
+ return OrderedDict(reversed(parsed.items()))
385
+
386
+ def split_help(self, ctx: ParseCtx, args: List[str]):
387
+ """
388
+ check for the presence of the help command/flag and raise error
389
+
390
+ :param ctx: parsing context
391
+ :param args: raw arguments to compare against
392
+ """
393
+ for variant in self.help.flag.variants():
394
+ if variant in args:
395
+ raise HelpError(ctx, self.command)
396
+
397
+ variants = self.help.command.variants()
398
+ for idx, arg in enumerate(args, 0):
399
+ if arg not in variants:
400
+ continue
401
+
402
+ cmd = self.command
403
+ path = args[idx+1:]
404
+ for item in path:
405
+ vars = {v:c for c in cmd.commands for v in c.variants()}
406
+ if item not in vars:
407
+ raise InvalidCommand(ctx, item)
408
+ cmd = vars[item]
409
+ raise HelpError(ctx, cmd)
410
+
411
+ def parse(self, args: List[str],
412
+ extra: Optional[Dict[str, Any]] = None) -> ParsedCmd:
413
+ """
414
+ parse the specified arguments against the command defintion
415
+
416
+ :param args: raw arguments to parse from
417
+ :return: parsed command values
418
+ """
419
+ args = args.copy()
420
+ nargs = len(args)
421
+ ctx = ParseCtx([self.command], extra or {})
422
+ self.split_help(ctx, args)
423
+
424
+ try:
425
+ commands = self.split_commands(ctx, self.command.commands, args)
426
+ flags = self.split_flags(ctx, self.command.flags, args)
427
+ params = self.split_args(ctx, self.command.args, args)
428
+ ctx.finalize()
429
+ except CliError as err:
430
+ if nargs == 0:
431
+ raise HelpError(ctx, self.command) from None
432
+ raise err
433
+ return ParsedCmd(self.command, params, commands, flags)
434
+
435
+ #** Imports **#
436
+ from .errors import (
437
+ CliError, CommandRequired, HelpError, Invalid, InvalidCommand,
438
+ InvalidDict, InvalidRef, Missing, MissingValue, NoCommandChain, Unexpected)
439
+ from .suggest import autocomplete_cmd
440
+ from .wraps import wrap_validator
cli/py.typed ADDED
File without changes