-
-
Notifications
You must be signed in to change notification settings - Fork 891
Expand file tree
/
Copy pathcore.py
More file actions
820 lines (718 loc) · 27.2 KB
/
core.py
File metadata and controls
820 lines (718 loc) · 27.2 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
import errno
import inspect
import os
import sys
from collections.abc import Callable, MutableMapping, Sequence
from difflib import get_close_matches
from enum import Enum
from gettext import gettext as _
from typing import (
Any,
TextIO,
Union,
cast,
)
import click
import click.core
import click.formatting
import click.shell_completion
import click.types
import click.utils
from ._typing import Literal
from .utils import parse_boolean_env_var
MarkupMode = Literal["markdown", "rich", None]
MARKUP_MODE_KEY = "TYPER_RICH_MARKUP_MODE"
HAS_RICH = parse_boolean_env_var(os.getenv("TYPER_USE_RICH"), default=True)
if HAS_RICH:
DEFAULT_MARKUP_MODE: MarkupMode = "rich"
else:
DEFAULT_MARKUP_MODE = None
# Copy from click.parser._split_opt
def _split_opt(opt: str) -> tuple[str, str]:
first = opt[:1]
if first.isalnum():
return "", opt
if opt[1:2] == first:
return opt[:2], opt[2:]
return first, opt[1:]
def _typer_param_setup_autocompletion_compat(
self: click.Parameter,
*,
autocompletion: Callable[
[click.Context, list[str], str], list[tuple[str, str] | str]
]
| None = None,
) -> None:
if self._custom_shell_complete is not None:
import warnings
warnings.warn(
"In Typer, only the parameter 'autocompletion' is supported. "
"The support for 'shell_complete' is deprecated and will be removed in upcoming versions. ",
DeprecationWarning,
stacklevel=2,
)
if autocompletion is not None:
def compat_autocompletion(
ctx: click.Context, param: click.core.Parameter, incomplete: str
) -> list["click.shell_completion.CompletionItem"]:
from click.shell_completion import CompletionItem
out = []
for c in autocompletion(ctx, [], incomplete):
if isinstance(c, tuple):
use_completion = CompletionItem(c[0], help=c[1])
else:
assert isinstance(c, str)
use_completion = CompletionItem(c)
if use_completion.value.startswith(incomplete):
out.append(use_completion)
return out
self._custom_shell_complete = compat_autocompletion
def _get_default_string(
obj: Union["TyperArgument", "TyperOption"],
*,
ctx: click.Context,
show_default_is_str: bool,
default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any,
) -> str:
# Extracted from click.core.Option.get_help_record() to be reused by
# rich_utils avoiding RegEx hacks
if show_default_is_str:
default_string = f"({obj.show_default})"
elif isinstance(default_value, (list, tuple)):
default_string = ", ".join(
_get_default_string(
obj, ctx=ctx, show_default_is_str=show_default_is_str, default_value=d
)
for d in default_value
)
elif isinstance(default_value, Enum):
default_string = str(default_value.value)
elif inspect.isfunction(default_value):
default_string = _("(dynamic)")
elif isinstance(obj, TyperOption) and obj.is_bool_flag and obj.secondary_opts:
# For boolean flags that have distinct True/False opts,
# use the opt without prefix instead of the value.
# Typer override, original commented
# default_string = click.parser.split_opt(
# (self.opts if self.default else self.secondary_opts)[0]
# )[1]
if obj.default:
if obj.opts:
default_string = _split_opt(obj.opts[0])[1]
else:
default_string = str(default_value)
else:
default_string = _split_opt(obj.secondary_opts[0])[1]
# Typer override end
elif (
isinstance(obj, TyperOption)
and obj.is_bool_flag
and not obj.secondary_opts
and not default_value
):
default_string = ""
else:
default_string = str(default_value)
return default_string
def _extract_default_help_str(
obj: Union["TyperArgument", "TyperOption"], *, ctx: click.Context
) -> Any | Callable[[], Any] | None:
# Extracted from click.core.Option.get_help_record() to be reused by
# rich_utils avoiding RegEx hacks
# Temporarily enable resilient parsing to avoid type casting
# failing for the default. Might be possible to extend this to
# help formatting in general.
resilient = ctx.resilient_parsing
ctx.resilient_parsing = True
try:
default_value = obj.get_default(ctx, call=False)
finally:
ctx.resilient_parsing = resilient
return default_value
def _main(
self: click.Command,
*,
args: Sequence[str] | None = None,
prog_name: str | None = None,
complete_var: str | None = None,
standalone_mode: bool = True,
windows_expand_args: bool = True,
rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,
**extra: Any,
) -> Any:
# Typer override, duplicated from click.main() to handle custom rich exceptions
# Verify that the environment is configured correctly, or reject
# further execution to avoid a broken script.
if args is None:
args = sys.argv[1:]
# Covered in Click tests
if os.name == "nt" and windows_expand_args: # pragma: no cover
args = click.utils._expand_args(args)
else:
args = list(args)
if prog_name is None:
prog_name = click.utils._detect_program_name()
# Process shell completion requests and exit early.
self._main_shell_completion(extra, prog_name, complete_var)
try:
try:
with self.make_context(prog_name, args, **extra) as ctx:
rv = self.invoke(ctx)
if not standalone_mode:
return rv
# it's not safe to `ctx.exit(rv)` here!
# note that `rv` may actually contain data like "1" which
# has obvious effects
# more subtle case: `rv=[None, None]` can come out of
# chained commands which all returned `None` -- so it's not
# even always obvious that `rv` indicates success/failure
# by its truthiness/falsiness
ctx.exit()
except EOFError as e:
click.echo(file=sys.stderr)
raise click.Abort() from e
except KeyboardInterrupt as e:
raise click.exceptions.Exit(130) from e
except click.ClickException as e:
if not standalone_mode:
raise
# Typer override
if HAS_RICH and rich_markup_mode is not None:
from . import rich_utils
rich_utils.rich_format_error(e)
else:
e.show()
# Typer override end
sys.exit(e.exit_code)
except OSError as e:
if e.errno == errno.EPIPE:
sys.stdout = cast(TextIO, click.utils.PacifyFlushWrapper(sys.stdout))
sys.stderr = cast(TextIO, click.utils.PacifyFlushWrapper(sys.stderr))
sys.exit(1)
else:
raise
except click.exceptions.Exit as e:
if standalone_mode:
sys.exit(e.exit_code)
else:
# in non-standalone mode, return the exit code
# note that this is only reached if `self.invoke` above raises
# an Exit explicitly -- thus bypassing the check there which
# would return its result
# the results of non-standalone execution may therefore be
# somewhat ambiguous: if there are codepaths which lead to
# `ctx.exit(1)` and to `return 1`, the caller won't be able to
# tell the difference between the two
return e.exit_code
except click.Abort:
if not standalone_mode:
raise
# Typer override
if HAS_RICH and rich_markup_mode is not None:
from . import rich_utils
rich_utils.rich_abort_error()
else:
click.echo(_("Aborted!"), file=sys.stderr)
# Typer override end
sys.exit(1)
class TyperArgument(click.core.Argument):
def __init__(
self,
*,
# Parameter
param_decls: list[str],
type: Any | None = None,
required: bool | None = None,
default: Any | None = None,
callback: Callable[..., Any] | None = None,
nargs: int | None = None,
metavar: str | None = None,
expose_value: bool = True,
is_eager: bool = False,
envvar: str | list[str] | None = None,
# Note that shell_complete is not fully supported and will be removed in future versions
# TODO: Remove shell_complete in a future version (after 0.16.0)
shell_complete: Callable[
[click.Context, click.Parameter, str],
list["click.shell_completion.CompletionItem"] | list[str],
]
| None = None,
autocompletion: Callable[..., Any] | None = None,
# TyperArgument
show_default: bool | str = True,
show_choices: bool = True,
show_envvar: bool = True,
help: str | None = None,
hidden: bool = False,
# Rich settings
rich_help_panel: str | None = None,
):
self.help = help
self.show_default = show_default
self.show_choices = show_choices
self.show_envvar = show_envvar
self.hidden = hidden
self.rich_help_panel = rich_help_panel
super().__init__(
param_decls=param_decls,
type=type,
required=required,
default=default,
callback=callback,
nargs=nargs,
metavar=metavar,
expose_value=expose_value,
is_eager=is_eager,
envvar=envvar,
shell_complete=shell_complete,
)
_typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion)
def _get_default_string(
self,
*,
ctx: click.Context,
show_default_is_str: bool,
default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any,
) -> str:
return _get_default_string(
self,
ctx=ctx,
show_default_is_str=show_default_is_str,
default_value=default_value,
)
def _extract_default_help_str(
self, *, ctx: click.Context
) -> Any | Callable[[], Any] | None:
return _extract_default_help_str(self, ctx=ctx)
def get_help_record(self, ctx: click.Context) -> tuple[str, str] | None:
# Modified version of click.core.Option.get_help_record()
# to support Arguments
if self.hidden:
return None
name = self.make_metavar(ctx=ctx)
help = self.help or ""
extra = []
if self.show_envvar:
envvar = self.envvar
# allow_from_autoenv is currently not supported in Typer for CLI Arguments
if envvar is not None:
var_str = (
", ".join(str(d) for d in envvar)
if isinstance(envvar, (list, tuple))
else envvar
)
extra.append(f"env var: {var_str}")
# Typer override:
# Extracted to _extract_default_help_str() to allow re-using it in rich_utils
default_value = self._extract_default_help_str(ctx=ctx)
# Typer override end
show_default_is_str = isinstance(self.show_default, str)
if show_default_is_str or (
default_value is not None and (self.show_default or ctx.show_default)
):
# Typer override:
# Extracted to _get_default_string() to allow re-using it in rich_utils
default_string = self._get_default_string(
ctx=ctx,
show_default_is_str=show_default_is_str,
default_value=default_value,
)
# Typer override end
if default_string:
extra.append(_("default: {default}").format(default=default_string))
if self.required:
extra.append(_("required"))
if extra:
extra_str = "; ".join(extra)
extra_str = f"[{extra_str}]"
rich_markup_mode = None
if hasattr(ctx, "obj") and isinstance(ctx.obj, dict):
rich_markup_mode = ctx.obj.get(MARKUP_MODE_KEY, None)
if HAS_RICH and rich_markup_mode == "rich":
# This is needed for when we want to export to HTML
from . import rich_utils
extra_str = rich_utils.escape_before_html_export(extra_str)
help = f"{help} {extra_str}" if help else f"{extra_str}"
return name, help
def make_metavar(self, ctx: click.Context) -> str:
# Modified version of click.core.Argument.make_metavar()
# to include Argument name
if self.metavar is not None:
var = self.metavar
if not self.required and not var.startswith("["):
var = f"[{var}]"
return var
var = (self.name or "").upper()
if not self.required:
var = f"[{var}]"
type_var = self.type.get_metavar(self, ctx=ctx)
if type_var:
var += f":{type_var}"
if self.nargs != 1:
var += "..."
return var
def value_is_missing(self, value: Any) -> bool:
return _value_is_missing(self, value)
class TyperOption(click.core.Option):
def __init__(
self,
*,
# Parameter
param_decls: list[str],
type: click.types.ParamType | Any | None = None,
required: bool | None = None,
default: Any | None = None,
callback: Callable[..., Any] | None = None,
nargs: int | None = None,
metavar: str | None = None,
expose_value: bool = True,
is_eager: bool = False,
envvar: str | list[str] | None = None,
# Note that shell_complete is not fully supported and will be removed in future versions
# TODO: Remove shell_complete in a future version (after 0.16.0)
shell_complete: Callable[
[click.Context, click.Parameter, str],
list["click.shell_completion.CompletionItem"] | list[str],
]
| None = None,
autocompletion: Callable[..., Any] | None = None,
# Option
show_default: bool | str = False,
prompt: bool | str = False,
confirmation_prompt: bool | str = False,
prompt_required: bool = True,
hide_input: bool = False,
is_flag: bool | None = None,
multiple: bool = False,
count: bool = False,
allow_from_autoenv: bool = True,
help: str | None = None,
hidden: bool = False,
show_choices: bool = True,
show_envvar: bool = False,
# Rich settings
rich_help_panel: str | None = None,
):
super().__init__(
param_decls=param_decls,
type=type,
required=required,
default=default,
callback=callback,
nargs=nargs,
metavar=metavar,
expose_value=expose_value,
is_eager=is_eager,
envvar=envvar,
show_default=show_default,
prompt=prompt,
confirmation_prompt=confirmation_prompt,
hide_input=hide_input,
is_flag=is_flag,
multiple=multiple,
count=count,
allow_from_autoenv=allow_from_autoenv,
help=help,
hidden=hidden,
show_choices=show_choices,
show_envvar=show_envvar,
prompt_required=prompt_required,
shell_complete=shell_complete,
)
_typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion)
self.rich_help_panel = rich_help_panel
def _get_default_string(
self,
*,
ctx: click.Context,
show_default_is_str: bool,
default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any,
) -> str:
return _get_default_string(
self,
ctx=ctx,
show_default_is_str=show_default_is_str,
default_value=default_value,
)
def _extract_default_help_str(
self, *, ctx: click.Context
) -> Any | Callable[[], Any] | None:
return _extract_default_help_str(self, ctx=ctx)
def make_metavar(self, ctx: click.Context) -> str:
return super().make_metavar(ctx=ctx)
def get_help_record(self, ctx: click.Context) -> tuple[str, str] | None:
# Duplicate all of Click's logic only to modify a single line, to allow boolean
# flags with only names for False values as it's currently supported by Typer
# Ref: https://typer.tiangolo.com/tutorial/parameter-types/bool/#only-names-for-false
if self.hidden:
return None
any_prefix_is_slash = False
def _write_opts(opts: Sequence[str]) -> str:
nonlocal any_prefix_is_slash
rv, any_slashes = click.formatting.join_options(opts)
if any_slashes:
any_prefix_is_slash = True
if not self.is_flag and not self.count:
rv += f" {self.make_metavar(ctx=ctx)}"
return rv
rv = [_write_opts(self.opts)]
if self.secondary_opts:
rv.append(_write_opts(self.secondary_opts))
help = self.help or ""
extra = []
if self.show_envvar:
envvar = self.envvar
if envvar is None:
if (
self.allow_from_autoenv
and ctx.auto_envvar_prefix is not None
and self.name is not None
):
envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
if envvar is not None:
var_str = (
envvar
if isinstance(envvar, str)
else ", ".join(str(d) for d in envvar)
)
extra.append(_("env var: {var}").format(var=var_str))
# Typer override:
# Extracted to _extract_default() to allow re-using it in rich_utils
default_value = self._extract_default_help_str(ctx=ctx)
# Typer override end
show_default_is_str = isinstance(self.show_default, str)
if show_default_is_str or (
default_value is not None and (self.show_default or ctx.show_default)
):
# Typer override:
# Extracted to _get_default_string() to allow re-using it in rich_utils
default_string = self._get_default_string(
ctx=ctx,
show_default_is_str=show_default_is_str,
default_value=default_value,
)
# Typer override end
if default_string:
extra.append(_("default: {default}").format(default=default_string))
if isinstance(self.type, click.types._NumberRangeBase):
range_str = self.type._describe_range()
if range_str:
extra.append(range_str)
if self.required:
extra.append(_("required"))
if extra:
extra_str = "; ".join(extra)
extra_str = f"[{extra_str}]"
rich_markup_mode = None
if hasattr(ctx, "obj") and isinstance(ctx.obj, dict):
rich_markup_mode = ctx.obj.get(MARKUP_MODE_KEY, None)
if HAS_RICH and rich_markup_mode == "rich":
# This is needed for when we want to export to HTML
from . import rich_utils
extra_str = rich_utils.escape_before_html_export(extra_str)
help = f"{help} {extra_str}" if help else f"{extra_str}"
return ("; " if any_prefix_is_slash else " / ").join(rv), help
def value_is_missing(self, value: Any) -> bool:
return _value_is_missing(self, value)
def _value_is_missing(param: click.Parameter, value: Any) -> bool:
if value is None:
return True
# Click 8.3 and beyond
# if value is UNSET:
# return True
if (param.nargs != 1 or param.multiple) and value == ():
return True # pragma: no cover
return False
def _typer_format_options(
self: click.core.Command, *, ctx: click.Context, formatter: click.HelpFormatter
) -> None:
args = []
opts = []
for param in self.get_params(ctx):
rv = param.get_help_record(ctx)
if rv is not None:
if param.param_type_name == "argument":
args.append(rv)
elif param.param_type_name == "option":
opts.append(rv)
if args:
with formatter.section(_("Arguments")):
formatter.write_dl(args)
if opts:
with formatter.section(_("Options")):
formatter.write_dl(opts)
def _typer_main_shell_completion(
self: click.core.Command,
*,
ctx_args: MutableMapping[str, Any],
prog_name: str,
complete_var: str | None = None,
) -> None:
if complete_var is None:
complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper()
instruction = os.environ.get(complete_var)
if not instruction:
return
from .completion import shell_complete
rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)
sys.exit(rv)
class TyperCommand(click.core.Command):
def __init__(
self,
name: str | None,
*,
context_settings: dict[str, Any] | None = None,
callback: Callable[..., Any] | None = None,
params: list[click.Parameter] | None = None,
help: str | None = None,
epilog: str | None = None,
short_help: str | None = None,
options_metavar: str | None = "[OPTIONS]",
add_help_option: bool = True,
no_args_is_help: bool = False,
hidden: bool = False,
deprecated: bool = False,
# Rich settings
rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,
rich_help_panel: str | None = None,
) -> None:
super().__init__(
name=name,
context_settings=context_settings,
callback=callback,
params=params,
help=help,
epilog=epilog,
short_help=short_help,
options_metavar=options_metavar,
add_help_option=add_help_option,
no_args_is_help=no_args_is_help,
hidden=hidden,
deprecated=deprecated,
)
self.rich_markup_mode: MarkupMode = rich_markup_mode
self.rich_help_panel = rich_help_panel
def format_options(
self, ctx: click.Context, formatter: click.HelpFormatter
) -> None:
_typer_format_options(self, ctx=ctx, formatter=formatter)
def _main_shell_completion(
self,
ctx_args: MutableMapping[str, Any],
prog_name: str,
complete_var: str | None = None,
) -> None:
_typer_main_shell_completion(
self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var
)
def main(
self,
args: Sequence[str] | None = None,
prog_name: str | None = None,
complete_var: str | None = None,
standalone_mode: bool = True,
windows_expand_args: bool = True,
**extra: Any,
) -> Any:
return _main(
self,
args=args,
prog_name=prog_name,
complete_var=complete_var,
standalone_mode=standalone_mode,
windows_expand_args=windows_expand_args,
rich_markup_mode=self.rich_markup_mode,
**extra,
)
def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
if not HAS_RICH or self.rich_markup_mode is None:
if not hasattr(ctx, "obj") or ctx.obj is None:
ctx.ensure_object(dict)
if isinstance(ctx.obj, dict):
ctx.obj[MARKUP_MODE_KEY] = self.rich_markup_mode
return super().format_help(ctx, formatter)
from . import rich_utils
return rich_utils.rich_format_help(
obj=self,
ctx=ctx,
markup_mode=self.rich_markup_mode,
)
class TyperGroup(click.core.Group):
def __init__(
self,
*,
name: str | None = None,
commands: dict[str, click.Command] | Sequence[click.Command] | None = None,
# Rich settings
rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,
rich_help_panel: str | None = None,
suggest_commands: bool = True,
**attrs: Any,
) -> None:
super().__init__(name=name, commands=commands, **attrs)
self.rich_markup_mode: MarkupMode = rich_markup_mode
self.rich_help_panel = rich_help_panel
self.suggest_commands = suggest_commands
def format_options(
self, ctx: click.Context, formatter: click.HelpFormatter
) -> None:
_typer_format_options(self, ctx=ctx, formatter=formatter)
self.format_commands(ctx, formatter)
def _main_shell_completion(
self,
ctx_args: MutableMapping[str, Any],
prog_name: str,
complete_var: str | None = None,
) -> None:
_typer_main_shell_completion(
self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var
)
def resolve_command(
self, ctx: click.Context, args: list[str]
) -> tuple[str | None, click.Command | None, list[str]]:
try:
return super().resolve_command(ctx, args)
except click.UsageError as e:
if self.suggest_commands:
available_commands = list(self.commands.keys())
if available_commands and args:
typo = args[0]
matches = get_close_matches(typo, available_commands)
if matches:
suggestions = ", ".join(f"{m!r}" for m in matches)
message = e.message.rstrip(".")
e.message = f"{message}. Did you mean {suggestions}?"
raise
def main(
self,
args: Sequence[str] | None = None,
prog_name: str | None = None,
complete_var: str | None = None,
standalone_mode: bool = True,
windows_expand_args: bool = True,
**extra: Any,
) -> Any:
return _main(
self,
args=args,
prog_name=prog_name,
complete_var=complete_var,
standalone_mode=standalone_mode,
windows_expand_args=windows_expand_args,
rich_markup_mode=self.rich_markup_mode,
**extra,
)
def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
if not HAS_RICH or self.rich_markup_mode is None:
return super().format_help(ctx, formatter)
from . import rich_utils
return rich_utils.rich_format_help(
obj=self,
ctx=ctx,
markup_mode=self.rich_markup_mode,
)
def list_commands(self, ctx: click.Context) -> list[str]:
"""Returns a list of subcommand names.
Note that in Click's Group class, these are sorted.
In Typer, we wish to maintain the original order of creation (cf Issue #933)"""
return [n for n, c in self.commands.items()]