Debian Codegraph @

cloup/_commands.py

raw
1 """
2 This module contains Cloup command classes and decorators.
3
4 Note that Cloup commands *are* Click commands. Apart from supporting more
5 features, Cloup command decorators have detailed type hints and are generics so
6 that type checkers can precisely infer the type of the returned command based on
7 the ``cls`` argument.
8
9 Why did you overload all decorators?
10 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
11 I wanted that the return type of decorators depended from the ``cls`` argument
12 but MyPy doesn't allow you to set a default value on a generic argument, see:
13 https://github.com/python/mypy/issues/3737.
14 So I had to resort to a workaround using @overload which makes things more
15 verbose. '`@overload`` is on the ``cls`` argument:
16
17 - in one signature, ``cls`` has type ``None`` and it's set to ``None``; in this
18 case the type of the instantiated command is ``cloup.Command`` for ``@command``
19 and ``cloup.Group`` for ``@group``
20 - in the other signature, there's ``cls: C`` without a default, where ``C`` is
21 a type variable; in this case the type of the instantiated command is ``C``.
22
23 When and if the MyPy issue is resolved, the overloads will be removed.
24 """
25 import inspect
26 from typing import (
27 Any, Callable, Dict, Iterable, List, NamedTuple, Optional, Sequence, Tuple,
28 Type, TypeVar, Union, cast, overload, MutableMapping, Mapping,
29 )
30
31 import click
32
33 import cloup
34 from ._context import Context
35 from ._option_groups import OptionGroupMixin
36 from ._sections import Section, SectionMixin
37 from ._util import click_version_ge_8_1, first_bool, reindent
38 from .constraints import ConstraintMixin
39 from .styling import DEFAULT_THEME
40 from .typing import AnyCallable
41
42 # Generic types of ``cls`` args of ``@command`` and ``@group``
43 C = TypeVar('C', bound=click.Command)
44 G = TypeVar('G', bound=click.Group)
45
46
47 class Command(ConstraintMixin, OptionGroupMixin, click.Command):
48 """A ``click.Command`` supporting option groups and constraints.
49
50 Refer to superclasses for the documentation of all accepted parameters:
51
52 - :class:`ConstraintMixin`
53 - :class:`OptionGroupMixin`
54 - :class:`click.Command`
55
56 Besides other things, this class also:
57
58 * adds a ``formatter_settings`` instance attribute.
59
60 Refer to :class:`click.Command` for the documentation of all parameters.
61
62 .. versionadded:: 0.8.0
63 """
64 context_class: Type[Context] = Context
65
66 def __init__(
67 self, *args: Any,
68 aliases: Optional[Iterable[str]] = None,
69 formatter_settings: Optional[Dict[str, Any]] = None,
70 **kwargs: Any,
71 ):
72 super().__init__(*args, **kwargs)
73 #: HelpFormatter options that are merged with ``Context.formatter_settings``
74 #: (eventually overriding some values).
75 self.aliases: List[str] = [] if aliases is None else list(aliases)
76 self.formatter_settings: Dict[str, Any] = (
77 {} if formatter_settings is None else formatter_settings)
78
79 def get_normalized_epilog(self) -> str:
80 if self.epilog and click_version_ge_8_1:
81 return inspect.cleandoc(self.epilog)
82 return self.epilog or ""
83
84 # Differently from Click, this doesn't indent the epilog.
85 def format_epilog(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
86 if self.epilog:
87 assert isinstance(formatter, cloup.HelpFormatter)
88 epilog = self.get_normalized_epilog()
89 formatter.write_paragraph()
90 formatter.write_epilog(epilog)
91
92 def format_help_text(
93 self, ctx: click.Context, formatter: click.HelpFormatter
94 ) -> None:
95 assert isinstance(formatter, cloup.HelpFormatter)
96 formatter.write_command_help_text(self)
97
98 def format_aliases(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
99 if not self.aliases:
100 return
101 assert isinstance(formatter, cloup.HelpFormatter)
102 formatter.write_aliases(self.aliases)
103
104 def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
105 self.format_usage(ctx, formatter)
106 self.format_aliases(ctx, formatter)
107 self.format_help_text(ctx, formatter)
108 self.format_params(ctx, formatter)
109 if self.must_show_constraints(ctx):
110 self.format_constraints(ctx, formatter) # type: ignore
111 # We use hasattr() in place of isinstance(..., MultiCommand) because
112 # MultiCommand is not a valid type since Click 8.2, which merged MultiCommand
113 # with Group and deprecated it. Since then, MultiCommand returns a
114 # _MultiCommand(Group) fake class through a module-level __getattr__, and mypy
115 # complains that MultiCommand is not a type. This check can be eventually
116 # replaced by isinstance(self, click.Group) when we drop support for Click 8.1.
117 if hasattr(self, "format_commands"):
118 self.format_commands(ctx, formatter)
119 self.format_epilog(ctx, formatter)
120
121
122 class Group(SectionMixin, Command, click.Group):
123 """
124 A ``click.Group`` that allows to organize its subcommands in multiple help
125 sections and whose subcommands are, by default, of type :class:`cloup.Command`.
126
127 Refer to superclasses for the documentation of all accepted parameters:
128
129 - :class:`SectionMixin`
130 - :class:`Command`
131 - :class:`click.Group`
132
133 Apart from superclasses arguments, the following is the only additional parameter:
134
135 ``show_subcommand_aliases``: ``Optional[bool] = None``
136 whether to show subcommand aliases; aliases are shown by default and
137 can be disabled using this argument or the homonym context setting.
138
139 .. versionchanged:: 0.14.0
140 this class now supports option groups and constraints.
141
142 .. versionadded:: 0.10.0
143 the "command aliases" feature, including the ``show_subcommand_aliases``
144 parameter/attribute.
145
146 .. versionchanged:: 0.8.0
147 this class now inherits from :class:`cloup.BaseCommand`.
148 """
149 SHOW_SUBCOMMAND_ALIASES: bool = False
150
151 def __init__(
152 self, *args: Any,
153 show_subcommand_aliases: Optional[bool] = None,
154 commands: Optional[
155 Union[MutableMapping[str, click.Command], Sequence[click.Command]]
156 ] = None,
157 **kwargs: Any
158 ):
159 super().__init__(*args, **kwargs)
160 self.show_subcommand_aliases = show_subcommand_aliases
161 """Whether to show subcommand aliases."""
162
163 self.alias2name: Dict[str, str] = {}
164 """Dictionary mapping each alias to a command name."""
165
166 if commands:
167 self.add_multiple_commands(commands)
168
169 def add_multiple_commands(
170 self, commands: Union[Mapping[str, click.Command], Sequence[click.Command]]
171 ) -> None:
172 if isinstance(commands, Mapping):
173 for name, cmd in commands.items():
174 self.add_command(cmd, name=name)
175 else:
176 for cmd in commands:
177 self.add_command(cmd)
178
179 def add_command(
180 self, cmd: click.Command,
181 name: Optional[str] = None,
182 section: Optional[Section] = None,
183 fallback_to_default_section: bool = True,
184 ) -> None:
185 super().add_command(cmd, name, section, fallback_to_default_section)
186 name = cast(str, cmd.name) if name is None else name
187 aliases = getattr(cmd, 'aliases', [])
188 for alias in aliases:
189 self.alias2name[alias] = name
190
191 def resolve_command_name(self, ctx: click.Context, name: str) -> Optional[str]:
192 """Map a string supposed to be a command name or an alias to a normalized
193 command name. If no match is found, it returns ``None``."""
194 if ctx.token_normalize_func:
195 name = ctx.token_normalize_func(name)
196 if name in self.commands:
197 return name
198 return self.alias2name.get(name)
199
200 def resolve_command(
201 self, ctx: click.Context, args: List[str]
202 ) -> Tuple[Optional[str], Optional[click.Command], List[str]]:
203 normalized_name = self.resolve_command_name(ctx, args[0])
204 if normalized_name:
205 # Replacing this string ensures that super().resolve_command() returns a
206 # normalized command name rather than an alias. The technique described in
207 # Click's docs doesn't work if the subcommand is added using Group.group
208 # passing the "name" argument.
209 args[0] = normalized_name
210 try:
211 return super().resolve_command(ctx, args)
212 except click.UsageError as error:
213 new_error = self.handle_bad_command_name(
214 bad_name=args[0],
215 valid_names=[*self.commands, *self.alias2name],
216 error=error
217 )
218 raise new_error
219
220 def handle_bad_command_name(
221 self, bad_name: str, valid_names: List[str], error: click.UsageError
222 ) -> click.UsageError:
223 """This method is called when a command name cannot be resolved.
224 Useful to implement the "Did you mean <x>?" feature.
225
226 :param bad_name: the command name that could not be resolved.
227 :param valid_names: the list of valid command names, including aliases.
228 :param error: the original error coming from Click.
229 :return: the original error or a new one.
230 """
231 import difflib
232 matches = difflib.get_close_matches(bad_name, valid_names)
233 if not matches:
234 return error
235 elif len(matches) == 1:
236 extra_msg = f"Did you mean '{matches[0]}'?"
237 else:
238 matches_list = "\n".join(" " + match for match in matches)
239 extra_msg = 'Did you mean one of these?\n' + matches_list
240
241 error_msg = str(error) + " " + extra_msg
242 return click.exceptions.UsageError(error_msg, error.ctx)
243
244 def must_show_subcommand_aliases(self, ctx: click.Context) -> bool:
245 return first_bool(
246 self.show_subcommand_aliases,
247 getattr(ctx, 'show_subcommand_aliases', None),
248 Group.SHOW_SUBCOMMAND_ALIASES,
249 )
250
251 def format_subcommand_name(
252 self, ctx: click.Context, name: str, cmd: click.Command
253 ) -> str:
254 aliases = getattr(cmd, 'aliases', None)
255 if aliases and self.must_show_subcommand_aliases(ctx):
256 assert isinstance(ctx, cloup.Context)
257 theme = cast(
258 cloup.HelpTheme, ctx.formatter_settings.get("theme", DEFAULT_THEME)
259 )
260 alias_list = self.format_subcommand_aliases(aliases, theme)
261 return f"{name} {alias_list}"
262 return name
263
264 @staticmethod
265 def format_subcommand_aliases(aliases: Sequence[str], theme: cloup.HelpTheme) -> str:
266 secondary_style = theme.alias_secondary
267 if secondary_style is None or secondary_style == theme.alias:
268 return theme.alias(f"({', '.join(aliases)})")
269 else:
270 return (
271 secondary_style("(")
272 + secondary_style(", ").join(theme.alias(alias) for alias in aliases)
273 + secondary_style(")")
274 )
275
276 # MyPy complains because "Signature of "group" incompatible with supertype".
277 # The supertype signature is (*args, **kwargs), which is compatible with
278 # this provided that you pass all arguments (expect "name") as keyword arg.
279 @overload # type: ignore
280 def command( # Why overloading? Refer to module docstring.
281 self, name: Optional[str] = None,
282 *,
283 aliases: Optional[Iterable[str]] = None,
284 cls: None = None, # default to Group.command_class or cloup.Command
285 section: Optional[Section] = None,
286 context_settings: Optional[Dict[str, Any]] = None,
287 formatter_settings: Optional[Dict[str, Any]] = None,
288 help: Optional[str] = None,
289 epilog: Optional[str] = None,
290 short_help: Optional[str] = None,
291 options_metavar: Optional[str] = "[OPTIONS]",
292 add_help_option: bool = True,
293 no_args_is_help: bool = False,
294 hidden: bool = False,
295 deprecated: bool = False,
296 align_option_groups: Optional[bool] = None,
297 show_constraints: Optional[bool] = None,
298 params: Optional[List[click.Parameter]] = None,
299 ) -> Callable[[AnyCallable], click.Command]:
300 ...
301
302 @overload
303 def command( # Why overloading? Refer to module docstring.
304 self, name: Optional[str] = None,
305 *,
306 aliases: Optional[Iterable[str]] = None,
307 cls: Type[C],
308 section: Optional[Section] = None,
309 context_settings: Optional[Dict[str, Any]] = None,
310 help: Optional[str] = None,
311 epilog: Optional[str] = None,
312 short_help: Optional[str] = None,
313 options_metavar: Optional[str] = "[OPTIONS]",
314 add_help_option: bool = True,
315 no_args_is_help: bool = False,
316 hidden: bool = False,
317 deprecated: bool = False,
318 params: Optional[List[click.Parameter]] = None,
319 **kwargs: Any,
320 ) -> Callable[[AnyCallable], C]:
321 ...
322
323 def command(
324 self, name: Optional[str] = None, *,
325 aliases: Optional[Iterable[str]] = None,
326 cls: Optional[Type[C]] = None,
327 section: Optional[Section] = None,
328 **kwargs: Any
329 ) -> Callable[[AnyCallable], Union[click.Command, C]]:
330 """Return a decorator that creates a new subcommand of this ``Group``
331 using the decorated function as callback.
332
333 It takes the same arguments of :func:`command` plus:
334
335 ``section``: ``Optional[Section]``
336 if provided, put the subcommand in this section.
337
338 .. versionchanged:: 0.10.0
339 all arguments but ``name`` are now keyword-only.
340 """
341 make_command = command(
342 name=name, cls=(self.command_class if cls is None else cls),
343 aliases=aliases, **kwargs
344 )
345
346 def decorator(f: AnyCallable) -> click.Command:
347 cmd = make_command(f)
348 self.add_command(cmd, section=section)
349 return cmd
350
351 return decorator
352
353 # MyPy complains: "signature of "group" incompatible with supertype".
354 # The supertype signature is (*args, **kwargs), which is compatible with
355 # this provided that you pass all arguments (expect "name") as keyword arg.
356 @overload # type: ignore
357 def group( # Why overloading? Refer to module docstring.
358 self, name: Optional[str] = None,
359 *,
360 aliases: Optional[Iterable[str]] = None,
361 cls: None = None, # cls not provided
362 section: Optional[Section] = None,
363 sections: Iterable[Section] = (),
364 align_sections: Optional[bool] = None,
365 invoke_without_command: bool = False,
366 no_args_is_help: bool = False,
367 context_settings: Optional[Dict[str, Any]] = None,
368 formatter_settings: Dict[str, Any] = {},
369 help: Optional[str] = None,
370 epilog: Optional[str] = None,
371 short_help: Optional[str] = None,
372 options_metavar: Optional[str] = "[OPTIONS]",
373 subcommand_metavar: Optional[str] = None,
374 add_help_option: bool = True,
375 chain: bool = False,
376 hidden: bool = False,
377 deprecated: bool = False,
378 show_subcommand_aliases: bool = False,
379 ) -> Callable[[AnyCallable], click.Group]:
380 ...
381
382 @overload
383 def group( # Why overloading? Refer to module docstring.
384 self, name: Optional[str] = None, *,
385 aliases: Optional[Iterable[str]] = None,
386 cls: Optional[Type[G]] = None,
387 section: Optional[Section] = None,
388 invoke_without_command: bool = False,
389 no_args_is_help: bool = False,
390 context_settings: Optional[Dict[str, Any]] = None,
391 help: Optional[str] = None,
392 epilog: Optional[str] = None,
393 short_help: Optional[str] = None,
394 options_metavar: Optional[str] = "[OPTIONS]",
395 subcommand_metavar: Optional[str] = None,
396 add_help_option: bool = True,
397 chain: bool = False,
398 hidden: bool = False,
399 deprecated: bool = False,
400 params: Optional[List[click.Parameter]] = None,
401 **kwargs: Any
402 ) -> Callable[[AnyCallable], G]:
403 ...
404
405 def group( # type: ignore
406 self, name: Optional[None] = None,
407 *,
408 cls: Optional[Type[G]] = None,
409 aliases: Optional[Iterable[str]] = None,
410 section: Optional[Section] = None,
411 **kwargs: Any
412 ) -> Callable[[AnyCallable], Union[click.Group, G]]:
413 """Return a decorator that creates a new subcommand of this ``Group``
414 using the decorated function as callback.
415
416 It takes the same argument of :func:`group` plus:
417
418 ``section``: ``Optional[Section]``
419 if provided, put the subcommand in this section.
420
421 .. versionchanged:: 0.10.0
422 all arguments but ``name`` are now keyword-only.
423 """
424 make_group = group(
425 name=name, cls=cls or self._default_group_class(), aliases=aliases, **kwargs
426 )
427
428 def decorator(f: AnyCallable) -> Union[click.Group, G]:
429 cmd = make_group(f)
430 self.add_command(cmd, section=section)
431 return cmd
432
433 return decorator
434
435 @classmethod
436 def _default_group_class(cls) -> Optional[Type[click.Group]]:
437 if cls.group_class is None:
438 return None
439 if cls.group_class is type:
440 return cls
441 else:
442 return cast(Type[click.Group], cls.group_class)
443
444
445 # Why overloading? Refer to module docstring.
446 @overload # In this overload: "cls: None = None"
447 def command(
448 name: Optional[str] = None,
449 *,
450 aliases: Optional[Iterable[str]] = None,
451 cls: None = None,
452 context_settings: Optional[Dict[str, Any]] = None,
453 formatter_settings: Optional[Dict[str, Any]] = None,
454 help: Optional[str] = None,
455 short_help: Optional[str] = None,
456 epilog: Optional[str] = None,
457 options_metavar: Optional[str] = "[OPTIONS]",
458 add_help_option: bool = True,
459 no_args_is_help: bool = False,
460 hidden: bool = False,
461 deprecated: bool = False,
462 align_option_groups: Optional[bool] = None,
463 show_constraints: Optional[bool] = None,
464 params: Optional[List[click.Parameter]] = None,
465 ) -> Callable[[AnyCallable], Command]:
466 ...
467
468
469 @overload
470 def command( # In this overload: "cls: ClickCommand"
471 name: Optional[str] = None,
472 *,
473 aliases: Optional[Iterable[str]] = None,
474 cls: Type[C],
475 context_settings: Optional[Dict[str, Any]] = None,
476 help: Optional[str] = None,
477 short_help: Optional[str] = None,
478 epilog: Optional[str] = None,
479 options_metavar: Optional[str] = "[OPTIONS]",
480 add_help_option: bool = True,
481 no_args_is_help: bool = False,
482 hidden: bool = False,
483 deprecated: bool = False,
484 params: Optional[List[click.Parameter]] = None,
485 **kwargs: Any
486 ) -> Callable[[AnyCallable], C]:
487 ...
488
489
490 # noinspection PyIncorrectDocstring
491 def command(
492 name: Optional[str] = None, *,
493 aliases: Optional[Iterable[str]] = None,
494 cls: Optional[Type[C]] = None,
495 **kwargs: Any
496 ) -> Callable[[AnyCallable], Union[Command, C]]:
497 """
498 Return a decorator that creates a new command using the decorated function
499 as callback.
500
501 The only differences with respect to ``click.command`` are:
502
503 - the default command class is :class:`cloup.Command`
504 - supports constraints, provided that ``cls`` inherits from ``ConstraintMixin``
505 like ``cloup.Command`` (the default)
506 - this function has detailed type hints and uses generics for the ``cls``
507 argument and return type.
508
509 Note that the following arguments are about Cloup-specific features and are
510 not supported by all ``click.Command``, so if you provide a custom ``cls``
511 make sure you don't set these:
512
513 - ``formatter_settings``
514 - ``align_option_groups`` (``cls`` needs to inherit from ``OptionGroupMixin``)
515 - ``show_constraints`` (``cls`` needs to inherit ``ConstraintMixin``).
516
517 .. versionchanged:: 0.10.0
518 this function is now generic: the return type depends on what you provide
519 as ``cls`` argument.
520
521 .. versionchanged:: 0.9.0
522 all arguments but ``name`` are now keyword-only arguments.
523
524 :param name:
525 the name of the command to use unless a group overrides it.
526 :param aliases:
527 alternative names for this command. If ``cls`` is not a Cloup command class,
528 aliases will be stored in the instantiated command by monkey-patching
529 and aliases won't be documented in the help page of the command.
530 :param cls:
531 the command class to instantiate.
532 :param context_settings:
533 an optional dictionary with defaults that are passed to the context object.
534 :param formatter_settings:
535 arguments for the formatter; you can use :meth:`HelpFormatter.settings`
536 to build this dictionary.
537 :param help:
538 the help string to use for this command.
539 :param epilog:
540 like the help string but it's printed at the end of the help page after
541 everything else.
542 :param short_help:
543 the short help to use for this command. This is shown on the command
544 listing of the parent command.
545 :param options_metavar:
546 metavar for options shown in the command's usage string.
547 :param add_help_option:
548 by default each command registers a ``--help`` option.
549 This can be disabled by this parameter.
550 :param no_args_is_help:
551 this controls what happens if no arguments are provided. This option is
552 disabled by default. If enabled this will add ``--help`` as argument if
553 no arguments are passed
554 :param hidden:
555 hide this command from help outputs.
556 :param deprecated:
557 issues a message indicating that the command is deprecated.
558 :param align_option_groups:
559 whether to align the columns of all option groups' help sections.
560 This is also available as a context setting having a lower priority
561 than this attribute. Given that this setting should be consistent
562 across all you commands, you should probably use the context
563 setting only.
564 :param show_constraints:
565 whether to include a "Constraint" section in the command help. This
566 is also available as a context setting having a lower priority than
567 this attribute.
568 :param params:
569 **(click >= 8.1.0)** a list of parameters (:class:`Argument` and
570 :class:`Option` instances). Params added with ``@option`` and ``@argument``
571 are appended to the end of the list if given.
572 :param kwargs:
573 any other argument accepted by the instantiated command class (``cls``).
574 """
575 if callable(name):
576 raise Exception(
577 f"you forgot parenthesis in the command decorator for `{name.__name__}`. "
578 f"While parenthesis are optional in Click >= 8.1, they are required in Cloup."
579 )
580
581 def decorator(f: AnyCallable) -> C:
582 if hasattr(f, '__cloup_constraints__'):
583 if cls and not issubclass(cls, ConstraintMixin):
584 raise TypeError(
585 f"a `Command` must inherit from `cloup.ConstraintMixin` to support "
586 f"constraints; `{cls}` doesn't")
587 constraints = tuple(reversed(f.__cloup_constraints__))
588 del f.__cloup_constraints__
589 kwargs['constraints'] = constraints
590
591 cmd_cls = cast(Type[Command], cls if cls is not None else Command)
592 try:
593 cmd = cast(C, click.command(name, cls=cmd_cls, **kwargs)(f))
594 if aliases:
595 cmd.aliases = list(aliases) # type: ignore
596 return cmd
597 except TypeError as error:
598 raise _process_unexpected_kwarg_error(error, _ARGS_INFO, cmd_cls)
599
600 return decorator
601
602
603 @overload # Why overloading? Refer to module docstring.
604 def group(
605 name: Optional[str] = None,
606 *,
607 cls: None = None,
608 aliases: Optional[Iterable[str]] = None,
609 sections: Iterable[Section] = (),
610 align_sections: Optional[bool] = None,
611 invoke_without_command: bool = False,
612 no_args_is_help: bool = False,
613 context_settings: Optional[Dict[str, Any]] = None,
614 formatter_settings: Dict[str, Any] = {},
615 help: Optional[str] = None,
616 short_help: Optional[str] = None,
617 epilog: Optional[str] = None,
618 options_metavar: Optional[str] = "[OPTIONS]",
619 subcommand_metavar: Optional[str] = None,
620 add_help_option: bool = True,
621 chain: bool = False,
622 hidden: bool = False,
623 deprecated: bool = False,
624 params: Optional[List[click.Parameter]] = None,
625 show_subcommand_aliases: bool = False,
626 ) -> Callable[[AnyCallable], Group]:
627 ...
628
629
630 @overload
631 def group(
632 name: Optional[str] = None,
633 *,
634 cls: Type[G],
635 aliases: Optional[Iterable[str]] = None,
636 invoke_without_command: bool = False,
637 no_args_is_help: bool = False,
638 context_settings: Optional[Dict[str, Any]] = None,
639 help: Optional[str] = None,
640 short_help: Optional[str] = None,
641 epilog: Optional[str] = None,
642 options_metavar: Optional[str] = "[OPTIONS]",
643 subcommand_metavar: Optional[str] = None,
644 add_help_option: bool = True,
645 chain: bool = False,
646 hidden: bool = False,
647 deprecated: bool = False,
648 params: Optional[List[click.Parameter]] = None,
649 **kwargs: Any
650 ) -> Callable[[AnyCallable], G]:
651 ...
652
653
654 def group(
655 name: Optional[str] = None, *, cls: Optional[Type[G]] = None, **kwargs: Any
656 ) -> Callable[[AnyCallable], click.Group]:
657 """
658 Return a decorator that instantiates a ``Group`` (or a subclass of it)
659 using the decorated function as callback.
660
661 .. versionchanged:: 0.10.0
662 the ``cls`` argument can now be any ``click.Group`` (previously had to
663 be a ``cloup.Group``) and the type of the instantiated command matches
664 it (previously, the type was ``cloup.Group`` even if ``cls`` was a subclass
665 of it).
666
667 .. versionchanged:: 0.9.0
668 all arguments but ``name`` are now keyword-only arguments.
669
670 :param name:
671 the name of the command to use unless a group overrides it.
672 :param cls:
673 the ``click.Group`` (sub)class to instantiate. This is ``cloup.Group``
674 by default. Note that some of the arguments are only supported by
675 ``cloup.Group``.
676 :param sections:
677 a list of Section objects containing the subcommands of this ``Group``.
678 This argument is only supported by commands inheriting from
679 :class:`cloup.SectionMixin`.
680 :param align_sections:
681 whether to align the columns of all subcommands' help sections.
682 This is also available as a context setting having a lower priority
683 than this attribute. Given that this setting should be consistent
684 across all you commands, you should probably use the context
685 setting only.
686 :param context_settings:
687 an optional dictionary with defaults that are passed to the context object.
688 :param formatter_settings:
689 arguments for the formatter; you can use :meth:`HelpFormatter.settings`
690 to build this dictionary.
691 :param help:
692 the help string to use for this command.
693 :param short_help:
694 the short help to use for this command. This is shown on the command
695 listing of the parent command.
696 :param epilog:
697 like the help string but it's printed at the end of the help page after
698 everything else.
699 :param options_metavar:
700 metavar for options shown in the command's usage string.
701 :param add_help_option:
702 by default each command registers a ``--help`` option.
703 This can be disabled by this parameter.
704 :param hidden:
705 hide this command from help outputs.
706 :param deprecated:
707 issues a message indicating that the command is deprecated.
708 :param invoke_without_command:
709 this controls how the multi command itself is invoked. By default it's
710 only invoked if a subcommand is provided.
711 :param no_args_is_help:
712 this controls what happens if no arguments are provided. This option is
713 enabled by default if `invoke_without_command` is disabled or disabled
714 if it's enabled. If enabled this will add ``--help`` as argument if no
715 arguments are passed.
716 :param subcommand_metavar:
717 string used in the command's usage string to indicate the subcommand place.
718 :param chain:
719 if this is set to `True`, chaining of multiple subcommands is enabled.
720 This restricts the form of commands in that they cannot have optional
721 arguments but it allows multiple commands to be chained together.
722 :param params:
723 **(click >= 8.1.0)** a list of parameters (:class:`Argument` and
724 :class:`Option` instances). Params added with ``@option`` and ``@argument``
725 are appended to the end of the list if given.
726 :param kwargs:
727 any other argument accepted by the instantiated command class.
728 """
729 if cls is None:
730 return command(name=name, cls=Group, **kwargs)
731 elif issubclass(cls, click.Group):
732 return command(name=name, cls=cls, **kwargs)
733 else:
734 raise TypeError(
735 'this decorator requires `cls` to be a `click.Group` (or a subclass)')
736
737
738 # Side stuff for better error messages
739
740 class _ArgInfo(NamedTuple):
741 arg_name: str
742 requires: Type[Any]
743 supported_by: str = ""
744
745
746 _ARGS_INFO = {
747 info.arg_name: info for info in [
748 _ArgInfo('formatter_settings', Command, "both `Command` and `Group`"),
749 _ArgInfo('align_option_groups', OptionGroupMixin, "both `Command` and `Group`"),
750 _ArgInfo('show_constraints', ConstraintMixin, "both `Command` and `Group`"),
751 _ArgInfo('align_sections', SectionMixin, "`Group`")
752 ]
753 }
754
755
756 def _process_unexpected_kwarg_error(
757 error: TypeError, args_info: Dict[str, _ArgInfo], cls: Type[Command]
758 ) -> TypeError:
759 """Check if the developer tried to pass a Cloup-specific argument to a ``cls``
760 that doesn't support it and if that's the case, augments the error message
761 to provide useful more info about the error."""
762 import re
763
764 message = str(error)
765 match = re.search('|'.join(arg_name for arg_name in args_info), message)
766 if match is None:
767 return error
768 arg = match.group()
769 info = args_info[arg]
770 extra_info = reindent(f"""\n
771 Hint: you set `cls={cls}` but this class doesn't support the argument `{arg}`.
772 In Cloup, this argument is supported by `{info.supported_by}`
773 via `{info.requires.__name__}`.
774 """, 4)
775 new_message = message + '\n' + extra_info
776 return TypeError(new_message)