Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/click/core.py: 35%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from __future__ import annotations
3import collections.abc as cabc
4import enum
5import errno
6import inspect
7import os
8import sys
9import typing as t
10from abc import ABC
11from abc import abstractmethod
12from collections import abc
13from collections import Counter
14from contextlib import AbstractContextManager
15from contextlib import contextmanager
16from contextlib import ExitStack
17from functools import update_wrapper
18from gettext import gettext as _
19from gettext import ngettext
20from itertools import repeat
21from types import TracebackType
23from . import types
24from ._utils import FLAG_NEEDS_VALUE
25from ._utils import UNSET
26from .exceptions import Abort
27from .exceptions import BadParameter
28from .exceptions import ClickException
29from .exceptions import Exit
30from .exceptions import MissingParameter
31from .exceptions import NoArgsIsHelpError
32from .exceptions import NoSuchCommand
33from .exceptions import UsageError
34from .formatting import HelpFormatter
35from .formatting import join_options
36from .globals import pop_context
37from .globals import push_context
38from .parser import _OptionParser
39from .parser import _split_opt
40from .termui import confirm
41from .termui import prompt
42from .termui import style
43from .utils import _detect_program_name
44from .utils import _expand_args
45from .utils import echo
46from .utils import make_default_short_help
47from .utils import make_str
48from .utils import PacifyFlushWrapper
50if t.TYPE_CHECKING:
51 from typing_extensions import Self
53 from .shell_completion import CompletionItem
55F = t.TypeVar("F", bound="t.Callable[..., t.Any]")
56V = t.TypeVar("V")
59def _complete_visible_commands(
60 ctx: Context, incomplete: str
61) -> cabc.Iterator[tuple[str, Command]]:
62 """List all the subcommands of a group that start with the
63 incomplete value and aren't hidden.
65 :param ctx: Invocation context for the group.
66 :param incomplete: Value being completed. May be empty.
67 """
68 multi = t.cast(Group, ctx.command)
70 for name in multi.list_commands(ctx):
71 if name.startswith(incomplete):
72 command = multi.get_command(ctx, name)
74 if command is not None and not command.hidden:
75 yield name, command
78def _check_nested_chain(
79 base_command: Group, cmd_name: str, cmd: Command, register: bool = False
80) -> None:
81 if not base_command.chain or not isinstance(cmd, Group):
82 return
84 if register:
85 message = (
86 f"It is not possible to add the group {cmd_name!r} to another"
87 f" group {base_command.name!r} that is in chain mode."
88 )
89 else:
90 message = (
91 f"Found the group {cmd_name!r} as subcommand to another group "
92 f" {base_command.name!r} that is in chain mode. This is not supported."
93 )
95 raise RuntimeError(message)
98def _format_deprecated_label(deprecated: bool | str) -> str:
99 """Return the parenthesized deprecation label shown in help text."""
100 label = _("deprecated").upper()
101 if isinstance(deprecated, str):
102 return f"({label}: {deprecated})"
103 return f"({label})"
106def _format_deprecated_suffix(deprecated: bool | str) -> str:
107 """Return the trailing reason for a ``DeprecationWarning`` message,
108 prefixed with a space, or an empty string when no reason was given.
109 """
110 if isinstance(deprecated, str):
111 return f" {deprecated}"
112 return ""
115def batch(iterable: cabc.Iterable[V], batch_size: int) -> list[tuple[V, ...]]:
116 return list(zip(*repeat(iter(iterable), batch_size), strict=False))
119@contextmanager
120def augment_usage_errors(
121 ctx: Context, param: Parameter | None = None
122) -> cabc.Generator[None]:
123 """Context manager that attaches extra information to exceptions."""
124 try:
125 yield
126 except BadParameter as e:
127 if e.ctx is None:
128 e.ctx = ctx
129 if param is not None and e.param is None:
130 e.param = param
131 raise
132 except UsageError as e:
133 if e.ctx is None:
134 e.ctx = ctx
135 raise
138def iter_params_for_processing(
139 invocation_order: cabc.Sequence[Parameter],
140 declaration_order: cabc.Sequence[Parameter],
141) -> list[Parameter]:
142 """Returns all declared parameters in the order they should be processed.
144 The declared parameters are re-shuffled depending on the order in which
145 they were invoked, as well as the eagerness of each parameters.
147 The invocation order takes precedence over the declaration order. I.e. the
148 order in which the user provided them to the CLI is respected.
150 This behavior and its effect on callback evaluation is detailed at:
151 https://click.palletsprojects.com/en/stable/advanced/#callback-evaluation-order
152 """
154 def sort_key(item: Parameter) -> tuple[bool, float]:
155 try:
156 idx: float = invocation_order.index(item)
157 except ValueError:
158 idx = float("inf")
160 return not item.is_eager, idx
162 return sorted(declaration_order, key=sort_key)
165class ParameterSource(enum.IntEnum):
166 """This is an :class:`~enum.IntEnum` that indicates the source of a
167 parameter's value.
169 Use :meth:`click.Context.get_parameter_source` to get the
170 source for a parameter by name.
172 Members are ordered from most explicit to least explicit source.
173 This allows comparison to check if a value was explicitly provided:
175 .. code-block:: python
177 source = ctx.get_parameter_source("port")
178 if source < click.ParameterSource.DEFAULT_MAP:
179 ... # value was explicitly set
181 .. versionchanged:: 8.3.3
182 Use :class:`~enum.IntEnum` and reorder members from most to
183 least explicit. Supports comparison operators.
185 .. versionchanged:: 8.0
186 Use :class:`~enum.Enum` and drop the ``validate`` method.
188 .. versionchanged:: 8.0
189 Added the ``PROMPT`` value.
190 """
192 PROMPT = enum.auto()
193 """Used a prompt to confirm a default or provide a value."""
194 COMMANDLINE = enum.auto()
195 """The value was provided by the command line args."""
196 ENVIRONMENT = enum.auto()
197 """The value was provided with an environment variable."""
198 DEFAULT_MAP = enum.auto()
199 """Used a default provided by :attr:`Context.default_map`."""
200 DEFAULT = enum.auto()
201 """Used the default specified by the parameter."""
204class Context:
205 """The context is a special internal object that holds state relevant
206 for the script execution at every single level. It's normally invisible
207 to commands unless they opt-in to getting access to it.
209 The context is useful as it can pass internal objects around and can
210 control special execution features such as reading data from
211 environment variables.
213 A context can be used as context manager in which case it will call
214 :meth:`close` on teardown.
216 :param command: the command class for this context.
217 :param parent: the parent context.
218 :param info_name: the info name for this invocation. Generally this
219 is the most descriptive name for the script or
220 command. For the toplevel script it is usually
221 the name of the script, for commands below that it's
222 the name of the script.
223 :param obj: an arbitrary object of user data.
224 :param auto_envvar_prefix: the prefix to use for automatic environment
225 variables. If this is `None` then reading
226 from environment variables is disabled. This
227 does not affect manually set environment
228 variables which are always read.
229 :param default_map: a dictionary (like object) with default values
230 for parameters.
231 :param terminal_width: the width of the terminal. The default is
232 inherit from parent context. If no context
233 defines the terminal width then auto
234 detection will be applied.
235 :param max_content_width: the maximum width for content rendered by
236 Click (this currently only affects help
237 pages). This defaults to 80 characters if
238 not overridden. In other words: even if the
239 terminal is larger than that, Click will not
240 format things wider than 80 characters by
241 default. In addition to that, formatters might
242 add some safety mapping on the right.
243 :param resilient_parsing: if this flag is enabled then Click will
244 parse without any interactivity or callback
245 invocation. Default values will also be
246 ignored. This is useful for implementing
247 things such as completion support.
248 :param allow_extra_args: if this is set to `True` then extra arguments
249 at the end will not raise an error and will be
250 kept on the context. The default is to inherit
251 from the command.
252 :param allow_interspersed_args: if this is set to `False` then options
253 and arguments cannot be mixed. The
254 default is to inherit from the command.
255 :param ignore_unknown_options: instructs click to ignore options it does
256 not know and keeps them for later
257 processing.
258 :param help_option_names: optionally a list of strings that define how
259 the default help parameter is named. The
260 default is ``['--help']``.
261 :param token_normalize_func: an optional function that is used to
262 normalize tokens (options, choices,
263 etc.). This for instance can be used to
264 implement case insensitive behavior.
265 :param color: controls if the terminal supports ANSI colors or not. The
266 default is autodetection. This is only needed if ANSI
267 codes are used in texts that Click prints which is by
268 default not the case. This for instance would affect
269 help output.
270 :param show_default: Show the default value for commands. If this
271 value is not set, it defaults to the value from the parent
272 context. ``Command.show_default`` overrides this default for the
273 specific command.
275 .. versionchanged:: 8.2
276 The ``protected_args`` attribute is deprecated and will be removed in
277 Click 9.0. ``args`` will contain remaining unparsed tokens.
279 .. versionchanged:: 8.1
280 The ``show_default`` parameter is overridden by
281 ``Command.show_default``, instead of the other way around.
283 .. versionchanged:: 8.0
284 The ``show_default`` parameter defaults to the value from the
285 parent context.
287 .. versionchanged:: 7.1
288 Added the ``show_default`` parameter.
290 .. versionchanged:: 4.0
291 Added the ``color``, ``ignore_unknown_options``, and
292 ``max_content_width`` parameters.
294 .. versionchanged:: 3.0
295 Added the ``allow_extra_args`` and ``allow_interspersed_args``
296 parameters.
298 .. versionchanged:: 2.0
299 Added the ``resilient_parsing``, ``help_option_names``, and
300 ``token_normalize_func`` parameters.
301 """
303 #: The formatter class to create with :meth:`make_formatter`.
304 #:
305 #: .. versionadded:: 8.0
306 formatter_class: type[HelpFormatter] = HelpFormatter
308 parent: Context | None
309 command: Command
310 info_name: str | None
311 params: dict[str, t.Any]
312 args: list[str]
313 _protected_args: list[str]
314 _opt_prefixes: set[str]
315 obj: t.Any
316 _meta: dict[str, t.Any]
317 default_map: cabc.MutableMapping[str, t.Any] | None
318 invoked_subcommand: str | None
319 terminal_width: int | None
320 max_content_width: int | None
321 allow_extra_args: bool
322 allow_interspersed_args: bool
323 ignore_unknown_options: bool
324 help_option_names: list[str]
325 token_normalize_func: t.Callable[[str], str] | None
326 resilient_parsing: bool
327 auto_envvar_prefix: str | None
328 color: bool | None
329 show_default: bool | None
330 _close_callbacks: list[t.Callable[[], t.Any]]
331 _depth: int
332 _parameter_source: dict[str, ParameterSource]
333 _param_default_explicit: dict[str, bool]
334 _exit_stack: ExitStack
336 def __init__(
337 self,
338 command: Command,
339 parent: Context | None = None,
340 info_name: str | None = None,
341 obj: t.Any | None = None,
342 auto_envvar_prefix: str | None = None,
343 default_map: cabc.MutableMapping[str, t.Any] | None = None,
344 terminal_width: int | None = None,
345 max_content_width: int | None = None,
346 resilient_parsing: bool = False,
347 allow_extra_args: bool | None = None,
348 allow_interspersed_args: bool | None = None,
349 ignore_unknown_options: bool | None = None,
350 help_option_names: list[str] | None = None,
351 token_normalize_func: t.Callable[[str], str] | None = None,
352 color: bool | None = None,
353 show_default: bool | None = None,
354 ) -> None:
355 #: the parent context or `None` if none exists.
356 self.parent = parent
357 #: the :class:`Command` for this context.
358 self.command = command
359 #: the descriptive information name
360 self.info_name = info_name
361 #: Map of parameter names to their parsed values. Parameters
362 #: with ``expose_value=False`` are not stored.
363 self.params = {}
364 #: the leftover arguments.
365 self.args = []
366 #: protected arguments. These are arguments that are prepended
367 #: to `args` when certain parsing scenarios are encountered but
368 #: must be never propagated to another arguments. This is used
369 #: to implement nested parsing.
370 self._protected_args = []
371 #: the collected prefixes of the command's options.
372 self._opt_prefixes = set(parent._opt_prefixes) if parent else set()
374 if obj is None and parent is not None:
375 obj = parent.obj
377 #: the user object stored.
378 self.obj = obj
379 self._meta = getattr(parent, "meta", {})
381 #: A dictionary (-like object) with defaults for parameters.
382 if (
383 default_map is None
384 and info_name is not None
385 and parent is not None
386 and parent.default_map is not None
387 ):
388 default_map = parent.default_map.get(info_name)
390 self.default_map = default_map
392 #: This flag indicates if a subcommand is going to be executed. A
393 #: group callback can use this information to figure out if it's
394 #: being executed directly or because the execution flow passes
395 #: onwards to a subcommand. By default it's None, but it can be
396 #: the name of the subcommand to execute.
397 #:
398 #: If chaining is enabled this will be set to ``'*'`` in case
399 #: any commands are executed. It is however not possible to
400 #: figure out which ones. If you require this knowledge you
401 #: should use a :func:`result_callback`.
402 self.invoked_subcommand = None
404 if terminal_width is None and parent is not None:
405 terminal_width = parent.terminal_width
407 #: The width of the terminal (None is autodetection).
408 self.terminal_width = terminal_width
410 if max_content_width is None and parent is not None:
411 max_content_width = parent.max_content_width
413 #: The maximum width of formatted content (None implies a sensible
414 #: default which is 80 for most things).
415 self.max_content_width = max_content_width
417 if allow_extra_args is None:
418 allow_extra_args = command.allow_extra_args
420 #: Indicates if the context allows extra args or if it should
421 #: fail on parsing.
422 #:
423 #: .. versionadded:: 3.0
424 self.allow_extra_args = allow_extra_args
426 if allow_interspersed_args is None:
427 allow_interspersed_args = command.allow_interspersed_args
429 #: Indicates if the context allows mixing of arguments and
430 #: options or not.
431 #:
432 #: .. versionadded:: 3.0
433 self.allow_interspersed_args = allow_interspersed_args
435 if ignore_unknown_options is None:
436 ignore_unknown_options = command.ignore_unknown_options
438 #: Instructs click to ignore options that a command does not
439 #: understand and will store it on the context for later
440 #: processing. This is primarily useful for situations where you
441 #: want to call into external programs. Generally this pattern is
442 #: strongly discouraged because it's not possibly to losslessly
443 #: forward all arguments.
444 #:
445 #: .. versionadded:: 4.0
446 self.ignore_unknown_options = ignore_unknown_options
448 if help_option_names is None:
449 if parent is not None:
450 help_option_names = parent.help_option_names
451 else:
452 help_option_names = ["--help"]
454 #: The names for the help options.
455 self.help_option_names = help_option_names
457 if token_normalize_func is None and parent is not None:
458 token_normalize_func = parent.token_normalize_func
460 #: An optional normalization function for tokens. This is
461 #: options, choices, commands etc.
462 self.token_normalize_func = token_normalize_func
464 #: Indicates if resilient parsing is enabled. In that case Click
465 #: will do its best to not cause any failures and default values
466 #: will be ignored. Useful for completion.
467 self.resilient_parsing = resilient_parsing
469 # If there is no envvar prefix yet, but the parent has one and
470 # the command on this level has a name, we can expand the envvar
471 # prefix automatically.
472 if auto_envvar_prefix is None:
473 if (
474 parent is not None
475 and parent.auto_envvar_prefix is not None
476 and self.info_name is not None
477 ):
478 auto_envvar_prefix = (
479 f"{parent.auto_envvar_prefix}_{self.info_name.upper()}"
480 )
481 else:
482 auto_envvar_prefix = auto_envvar_prefix.upper()
484 if auto_envvar_prefix is not None:
485 auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")
487 self.auto_envvar_prefix = auto_envvar_prefix
489 if color is None and parent is not None:
490 color = parent.color
492 #: Controls if styling output is wanted or not.
493 self.color = color
495 if show_default is None and parent is not None:
496 show_default = parent.show_default
498 #: Show option default values when formatting help text.
499 self.show_default = show_default
501 self._close_callbacks = []
502 self._depth = 0
503 self._parameter_source = {}
504 # Tracks whether the option that currently owns each parameter slot in
505 # :attr:`params` had its ``default`` set explicitly by the user. Used
506 # to tie-break feature-switch groups where multiple options share a
507 # parameter name and both fall back to their default value.
508 # Refs: https://github.com/pallets/click/issues/3403
509 self._param_default_explicit = {}
510 self._exit_stack = ExitStack()
512 @property
513 def protected_args(self) -> list[str]:
514 import warnings
516 warnings.warn(
517 "'protected_args' is deprecated and will be removed in Click 9.0."
518 " 'args' will contain remaining unparsed tokens.",
519 DeprecationWarning,
520 stacklevel=2,
521 )
522 return self._protected_args
524 def to_info_dict(self) -> dict[str, t.Any]:
525 """Gather information that could be useful for a tool generating
526 user-facing documentation. This traverses the entire CLI
527 structure.
529 .. code-block:: python
531 with Context(cli) as ctx:
532 info = ctx.to_info_dict()
534 .. versionadded:: 8.0
535 """
536 return {
537 "command": self.command.to_info_dict(self),
538 "info_name": self.info_name,
539 "allow_extra_args": self.allow_extra_args,
540 "allow_interspersed_args": self.allow_interspersed_args,
541 "ignore_unknown_options": self.ignore_unknown_options,
542 "auto_envvar_prefix": self.auto_envvar_prefix,
543 }
545 def __enter__(self) -> Self:
546 self._depth += 1
547 push_context(self)
548 return self
550 def __exit__(
551 self,
552 exc_type: type[BaseException] | None,
553 exc_value: BaseException | None,
554 tb: TracebackType | None,
555 ) -> bool | None:
556 self._depth -= 1
557 exit_result: bool | None = None
558 if self._depth == 0:
559 exit_result = self._close_with_exception_info(exc_type, exc_value, tb)
560 pop_context()
562 return exit_result
564 @contextmanager
565 def scope(self, cleanup: bool = True) -> cabc.Generator[Context]:
566 """This helper method can be used with the context object to promote
567 it to the current thread local (see :func:`get_current_context`).
568 The default behavior of this is to invoke the cleanup functions which
569 can be disabled by setting `cleanup` to `False`. The cleanup
570 functions are typically used for things such as closing file handles.
572 If the cleanup is intended the context object can also be directly
573 used as a context manager.
575 Example usage::
577 with ctx.scope():
578 assert get_current_context() is ctx
580 This is equivalent::
582 with ctx:
583 assert get_current_context() is ctx
585 .. versionadded:: 5.0
587 :param cleanup: controls if the cleanup functions should be run or
588 not. The default is to run these functions. In
589 some situations the context only wants to be
590 temporarily pushed in which case this can be disabled.
591 Nested pushes automatically defer the cleanup.
592 """
593 if not cleanup:
594 self._depth += 1
595 try:
596 with self as rv:
597 yield rv
598 finally:
599 if not cleanup:
600 self._depth -= 1
602 @property
603 def meta(self) -> dict[str, t.Any]:
604 """This is a dictionary which is shared with all the contexts
605 that are nested. It exists so that click utilities can store some
606 state here if they need to. It is however the responsibility of
607 that code to manage this dictionary well.
609 The keys are supposed to be unique dotted strings. For instance
610 module paths are a good choice for it. What is stored in there is
611 irrelevant for the operation of click. However what is important is
612 that code that places data here adheres to the general semantics of
613 the system.
615 Example usage::
617 LANG_KEY = f'{__name__}.lang'
619 def set_language(value):
620 ctx = get_current_context()
621 ctx.meta[LANG_KEY] = value
623 def get_language():
624 return get_current_context().meta.get(LANG_KEY, 'en_US')
626 .. versionadded:: 5.0
627 """
628 return self._meta
630 def make_formatter(self) -> HelpFormatter:
631 """Creates the :class:`~click.HelpFormatter` for the help and
632 usage output.
634 To quickly customize the formatter class used without overriding
635 this method, set the :attr:`formatter_class` attribute.
637 .. versionchanged:: 8.0
638 Added the :attr:`formatter_class` attribute.
639 """
640 return self.formatter_class(
641 width=self.terminal_width, max_width=self.max_content_width
642 )
644 def with_resource(self, context_manager: AbstractContextManager[V]) -> V:
645 """Register a resource as if it were used in a ``with``
646 statement. The resource will be cleaned up when the context is
647 popped.
649 Uses :meth:`contextlib.ExitStack.enter_context`. It calls the
650 resource's ``__enter__()`` method and returns the result. When
651 the context is popped, it closes the stack, which calls the
652 resource's ``__exit__()`` method.
654 To register a cleanup function for something that isn't a
655 context manager, use :meth:`call_on_close`. Or use something
656 from :mod:`contextlib` to turn it into a context manager first.
658 .. code-block:: python
660 @click.group()
661 @click.option("--name")
662 @click.pass_context
663 def cli(ctx):
664 ctx.obj = ctx.with_resource(connect_db(name))
666 :param context_manager: The context manager to enter.
667 :return: Whatever ``context_manager.__enter__()`` returns.
669 .. versionadded:: 8.0
670 """
671 return self._exit_stack.enter_context(context_manager)
673 def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:
674 """Register a function to be called when the context tears down.
676 This can be used to close resources opened during the script
677 execution. Resources that support Python's context manager
678 protocol which would be used in a ``with`` statement should be
679 registered with :meth:`with_resource` instead.
681 :param f: The function to execute on teardown.
682 """
683 return self._exit_stack.callback(f)
685 def close(self) -> None:
686 """Invoke all close callbacks registered with
687 :meth:`call_on_close`, and exit all context managers entered
688 with :meth:`with_resource`.
689 """
690 self._close_with_exception_info(None, None, None)
692 def _close_with_exception_info(
693 self,
694 exc_type: type[BaseException] | None,
695 exc_value: BaseException | None,
696 tb: TracebackType | None,
697 ) -> bool | None:
698 """Unwind the exit stack by calling its :meth:`__exit__` providing the exception
699 information to allow for exception handling by the various resources registered
700 using :meth;`with_resource`
702 :return: Whatever ``exit_stack.__exit__()`` returns.
703 """
704 exit_result = self._exit_stack.__exit__(exc_type, exc_value, tb)
705 # In case the context is reused, create a new exit stack.
706 self._exit_stack = ExitStack()
708 return exit_result
710 @property
711 def command_path(self) -> str:
712 """The computed command path. This is used for the ``usage``
713 information on the help page. It's automatically created by
714 combining the info names of the chain of contexts to the root.
715 """
716 rv = ""
717 if self.info_name is not None:
718 rv = self.info_name
719 if self.parent is not None:
720 parent_command_path = [self.parent.command_path]
722 if isinstance(self.parent.command, Command):
723 for param in self.parent.command.get_params(self):
724 parent_command_path.extend(param.get_usage_pieces(self))
726 rv = f"{' '.join(parent_command_path)} {rv}"
727 return rv.lstrip()
729 def find_root(self) -> Context:
730 """Finds the outermost context."""
731 node = self
732 while node.parent is not None:
733 node = node.parent
734 return node
736 def find_object(self, object_type: type[V]) -> V | None:
737 """Finds the closest object of a given type."""
738 node: Context | None = self
740 while node is not None:
741 if isinstance(node.obj, object_type):
742 return node.obj
744 node = node.parent
746 return None
748 def ensure_object(self, object_type: type[V]) -> V:
749 """Like :meth:`find_object` but sets the innermost object to a
750 new instance of `object_type` if it does not exist.
751 """
752 rv = self.find_object(object_type)
753 if rv is None:
754 self.obj = rv = object_type()
755 return rv
757 def _default_map_has(self, name: str | None) -> bool:
758 """Check if :attr:`default_map` contains a real value for ``name``.
760 Returns ``False`` when the key is absent, the map is ``None``,
761 ``name`` is ``None``, or the stored value is the internal
762 :data:`UNSET` sentinel.
763 """
764 return (
765 name is not None
766 and self.default_map is not None
767 and name in self.default_map
768 and self.default_map[name] is not UNSET
769 )
771 @t.overload
772 def lookup_default(
773 self, name: str, call: t.Literal[True] = True
774 ) -> t.Any | None: ...
776 @t.overload
777 def lookup_default(
778 self, name: str, call: t.Literal[False] = ...
779 ) -> t.Any | t.Callable[[], t.Any] | None: ...
781 def lookup_default(self, name: str, call: bool = True) -> t.Any | None:
782 """Get the default for a parameter from :attr:`default_map`.
784 :param name: Name of the parameter.
785 :param call: If the default is a callable, call it. Disable to
786 return the callable instead.
788 .. versionchanged:: 8.0
789 Added the ``call`` parameter.
790 """
791 if not self._default_map_has(name):
792 return None
794 # Assert to make the type checker happy.
795 assert self.default_map is not None
796 value = self.default_map[name]
798 if call and callable(value):
799 return value()
801 return value
803 def fail(self, message: str) -> t.NoReturn:
804 """Aborts the execution of the program with a specific error
805 message.
807 :param message: the error message to fail with.
808 """
809 raise UsageError(message, self)
811 def abort(self) -> t.NoReturn:
812 """Aborts the script."""
813 raise Abort()
815 def exit(self, code: int = 0) -> t.NoReturn:
816 """Exits the application with a given exit code.
818 .. versionchanged:: 8.2
819 Callbacks and context managers registered with :meth:`call_on_close`
820 and :meth:`with_resource` are closed before exiting.
821 """
822 self.close()
823 raise Exit(code)
825 def get_usage(self) -> str:
826 """Helper method to get formatted usage string for the current
827 context and command.
828 """
829 return self.command.get_usage(self)
831 def get_help(self) -> str:
832 """Helper method to get formatted help page for the current
833 context and command.
834 """
835 return self.command.get_help(self)
837 def _make_sub_context(self, command: Command) -> Context:
838 """Create a new context of the same type as this context, but
839 for a new command.
841 :meta private:
842 """
843 return type(self)(command, info_name=command.name, parent=self)
845 @t.overload
846 def invoke(
847 self, callback: t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any
848 ) -> V: ...
850 @t.overload
851 def invoke(self, callback: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: ...
853 def invoke(
854 self, callback: Command | t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any
855 ) -> t.Any | V:
856 """Invokes a command callback in exactly the way it expects. There
857 are two ways to invoke this method:
859 1. the first argument can be a callback and all other arguments and
860 keyword arguments are forwarded directly to the function.
861 2. the first argument is a click command object. In that case all
862 arguments are forwarded as well but proper click parameters
863 (options and click arguments) must be keyword arguments and Click
864 will fill in defaults.
866 .. versionchanged:: 8.0
867 All ``kwargs`` are tracked in :attr:`params` so they will be
868 passed if :meth:`forward` is called at multiple levels.
870 .. versionchanged:: 3.2
871 A new context is created, and missing arguments use default values.
872 """
873 if isinstance(callback, Command):
874 other_cmd = callback
876 if other_cmd.callback is None:
877 raise TypeError(
878 "The given command does not have a callback that can be invoked."
879 )
880 else:
881 callback = t.cast("t.Callable[..., V]", other_cmd.callback)
883 ctx = self._make_sub_context(other_cmd)
885 for param in other_cmd.params:
886 if param.name not in kwargs and param.expose_value:
887 default_value = param.get_default(ctx)
888 # We explicitly hide the :attr:`UNSET` value to the user, as we
889 # choose to make it an implementation detail. And because ``invoke``
890 # has been designed as part of Click public API, we return ``None``
891 # instead. Refs:
892 # https://github.com/pallets/click/issues/3066
893 # https://github.com/pallets/click/issues/3065
894 # https://github.com/pallets/click/pull/3068
895 if default_value is UNSET:
896 default_value = None
897 kwargs[param.name] = param.type_cast_value(ctx, default_value)
899 # Track all kwargs as params, so that forward() will pass
900 # them on in subsequent calls.
901 ctx.params.update(kwargs)
902 else:
903 ctx = self
905 with augment_usage_errors(self):
906 with ctx:
907 return callback(*args, **kwargs)
909 def forward(self, cmd: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any:
910 """Similar to :meth:`invoke` but fills in default keyword
911 arguments from the current context if the other command expects
912 it. This cannot invoke callbacks directly, only other commands.
914 .. versionchanged:: 8.0
915 All ``kwargs`` are tracked in :attr:`params` so they will be
916 passed if ``forward`` is called at multiple levels.
917 """
918 # Can only forward to other commands, not direct callbacks.
919 if not isinstance(cmd, Command):
920 raise TypeError("Callback is not a command.")
922 for param in self.params:
923 if param not in kwargs:
924 kwargs[param] = self.params[param]
926 return self.invoke(cmd, *args, **kwargs)
928 def set_parameter_source(self, name: str, source: ParameterSource) -> None:
929 """Set the source of a parameter. This indicates the location
930 from which the value of the parameter was obtained.
932 :param name: The name of the parameter.
933 :param source: A member of :class:`~click.core.ParameterSource`.
934 """
935 self._parameter_source[name] = source
937 def get_parameter_source(self, name: str) -> ParameterSource | None:
938 """Get the source of a parameter. This indicates the location
939 from which the value of the parameter was obtained.
941 This can be useful for determining when a user specified a value
942 on the command line that is the same as the default value. It
943 will be :attr:`~click.core.ParameterSource.DEFAULT` only if the
944 value was actually taken from the default.
946 :param name: The name of the parameter.
947 :rtype: ParameterSource
949 .. versionchanged:: 8.0
950 Returns ``None`` if the parameter was not provided from any
951 source.
952 """
953 return self._parameter_source.get(name)
956class Command:
957 """Commands are the basic building block of command line interfaces in
958 Click. A basic command handles command line parsing and might dispatch
959 more parsing to commands nested below it.
961 :param name: the name of the command to use unless a group overrides it.
962 :param context_settings: an optional dictionary with defaults that are
963 passed to the context object.
964 :param callback: the callback to invoke. This is optional.
965 :param params: the parameters to register with this command. This can
966 be either :class:`Option` or :class:`Argument` objects.
967 :param help: the help string to use for this command.
968 :param epilog: like the help string but it's printed at the end of the
969 help page after everything else.
970 :param short_help: the short help to use for this command. This is
971 shown on the command listing of the parent command.
972 :param add_help_option: by default each command registers a ``--help``
973 option. This can be disabled by this parameter.
974 :param no_args_is_help: this controls what happens if no arguments are
975 provided. This option is disabled by default.
976 If enabled this will add ``--help`` as argument
977 if no arguments are passed
978 :param hidden: hide this command from help outputs.
979 :param deprecated: If ``True`` or non-empty string, issues a message
980 indicating that the command is deprecated and highlights
981 its deprecation in --help. The message can be customized
982 by using a string as the value.
984 .. versionchanged:: 8.2
985 This is the base class for all commands, not ``BaseCommand``.
986 ``deprecated`` can be set to a string as well to customize the
987 deprecation message.
989 .. versionchanged:: 8.1
990 ``help``, ``epilog``, and ``short_help`` are stored unprocessed,
991 all formatting is done when outputting help text, not at init,
992 and is done even if not using the ``@command`` decorator.
994 .. versionchanged:: 8.0
995 Added a ``repr`` showing the command name.
997 .. versionchanged:: 7.1
998 Added the ``no_args_is_help`` parameter.
1000 .. versionchanged:: 2.0
1001 Added the ``context_settings`` parameter.
1002 """
1004 #: The context class to create with :meth:`make_context`.
1005 #:
1006 #: .. versionadded:: 8.0
1007 context_class: type[Context] = Context
1009 #: the default for the :attr:`Context.allow_extra_args` flag.
1010 allow_extra_args = False
1012 #: the default for the :attr:`Context.allow_interspersed_args` flag.
1013 allow_interspersed_args = True
1015 #: the default for the :attr:`Context.ignore_unknown_options` flag.
1016 ignore_unknown_options = False
1018 name: str | None
1019 context_settings: cabc.MutableMapping[str, t.Any]
1020 callback: t.Callable[..., t.Any] | None
1021 params: list[Parameter]
1022 help: str | None
1023 epilog: str | None
1024 options_metavar: str | None
1025 short_help: str | None
1026 add_help_option: bool
1027 _help_option: Option | None
1028 no_args_is_help: bool
1029 hidden: bool
1030 deprecated: bool | str
1032 def __init__(
1033 self,
1034 name: str | None,
1035 context_settings: cabc.MutableMapping[str, t.Any] | None = None,
1036 callback: t.Callable[..., t.Any] | None = None,
1037 params: list[Parameter] | None = None,
1038 help: str | None = None,
1039 epilog: str | None = None,
1040 short_help: str | None = None,
1041 options_metavar: str | None = "[OPTIONS]",
1042 add_help_option: bool = True,
1043 no_args_is_help: bool = False,
1044 hidden: bool = False,
1045 deprecated: bool | str = False,
1046 ) -> None:
1047 #: the name the command thinks it has. Upon registering a command
1048 #: on a :class:`Group` the group will default the command name
1049 #: with this information. You should instead use the
1050 #: :class:`Context`\'s :attr:`~Context.info_name` attribute.
1051 self.name = name
1053 if context_settings is None:
1054 context_settings = {}
1056 #: an optional dictionary with defaults passed to the context.
1057 self.context_settings = context_settings
1059 #: the callback to execute when the command fires. This might be
1060 #: `None` in which case nothing happens.
1061 self.callback = callback
1062 #: the list of parameters for this command in the order they
1063 #: should show up in the help page and execute. Eager parameters
1064 #: will automatically be handled before non eager ones.
1065 self.params = params or []
1066 self.help = help
1067 self.epilog = epilog
1068 self.options_metavar = options_metavar
1069 self.short_help = short_help
1070 self.add_help_option = add_help_option
1071 self._help_option = None
1072 self.no_args_is_help = no_args_is_help
1073 self.hidden = hidden
1074 self.deprecated = deprecated
1076 def to_info_dict(self, ctx: Context) -> dict[str, t.Any]:
1077 return {
1078 "name": self.name,
1079 "params": [param.to_info_dict() for param in self.get_params(ctx)],
1080 "help": self.help,
1081 "epilog": self.epilog,
1082 "short_help": self.short_help,
1083 "hidden": self.hidden,
1084 "deprecated": self.deprecated,
1085 }
1087 def __repr__(self) -> str:
1088 return f"<{self.__class__.__name__} {self.name}>"
1090 def get_usage(self, ctx: Context) -> str:
1091 """Formats the usage line into a string and returns it.
1093 Calls :meth:`format_usage` internally.
1094 """
1095 formatter = ctx.make_formatter()
1096 self.format_usage(ctx, formatter)
1097 return formatter.getvalue().rstrip("\n")
1099 def get_params(self, ctx: Context) -> list[Parameter]:
1100 params = self.params
1101 help_option = self.get_help_option(ctx)
1103 if help_option is not None:
1104 params = [*params, help_option]
1106 if __debug__:
1107 import warnings
1109 opts = [opt for param in params for opt in param.opts]
1110 opts_counter = Counter(opts)
1111 duplicate_opts = (opt for opt, count in opts_counter.items() if count > 1)
1113 for duplicate_opt in duplicate_opts:
1114 warnings.warn(
1115 (
1116 f"The parameter {duplicate_opt} is used more than once. "
1117 "Remove its duplicate as parameters should be unique."
1118 ),
1119 stacklevel=3,
1120 )
1122 return params
1124 def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None:
1125 """Writes the usage line into the formatter.
1127 This is a low-level method called by :meth:`get_usage`.
1128 """
1129 pieces = self.collect_usage_pieces(ctx)
1130 formatter.write_usage(ctx.command_path, " ".join(pieces))
1132 def collect_usage_pieces(self, ctx: Context) -> list[str]:
1133 """Returns all the pieces that go into the usage line and returns
1134 it as a list of strings.
1135 """
1136 rv = [self.options_metavar] if self.options_metavar else []
1138 for param in self.get_params(ctx):
1139 rv.extend(param.get_usage_pieces(ctx))
1141 return rv
1143 def get_help_option_names(self, ctx: Context) -> list[str]:
1144 """Returns the names for the help option."""
1145 all_names = set(ctx.help_option_names)
1146 for param in self.params:
1147 all_names.difference_update(param.opts)
1148 all_names.difference_update(param.secondary_opts)
1149 return list(all_names)
1151 def get_help_option(self, ctx: Context) -> Option | None:
1152 """Returns the help option object.
1154 Skipped if :attr:`add_help_option` is ``False``.
1156 .. versionchanged:: 8.1.8
1157 The help option is now cached to avoid creating it multiple times.
1158 """
1159 help_option_names = self.get_help_option_names(ctx)
1161 if not help_option_names or not self.add_help_option:
1162 return None
1164 # Cache the help option object in private _help_option attribute to
1165 # avoid creating it multiple times. Not doing this will break the
1166 # callback ordering by iter_params_for_processing(), which relies on
1167 # object comparison.
1168 if self._help_option is None:
1169 # Avoid circular import.
1170 from .decorators import help_option
1172 # Apply help_option decorator and pop resulting option
1173 help_option(*help_option_names)(self)
1174 self._help_option = self.params.pop() # type: ignore[assignment]
1176 return self._help_option
1178 def make_parser(self, ctx: Context) -> _OptionParser:
1179 """Creates the underlying option parser for this command."""
1180 parser = _OptionParser(ctx)
1181 for param in self.get_params(ctx):
1182 param.add_to_parser(parser, ctx)
1183 return parser
1185 def get_help(self, ctx: Context) -> str:
1186 """Formats the help into a string and returns it.
1188 Calls :meth:`format_help` internally.
1189 """
1190 formatter = ctx.make_formatter()
1191 self.format_help(ctx, formatter)
1192 return formatter.getvalue().rstrip("\n")
1194 def get_short_help_str(self, limit: int = 45) -> str:
1195 """Gets short help for the command or makes it by shortening the
1196 long help string.
1197 """
1198 if self.short_help:
1199 text = inspect.cleandoc(self.short_help)
1200 elif self.help:
1201 text = make_default_short_help(self.help, limit)
1202 else:
1203 text = ""
1205 if self.deprecated:
1206 text = f"{_(text)} {_format_deprecated_label(self.deprecated)}"
1208 return text.strip()
1210 def format_help(self, ctx: Context, formatter: HelpFormatter) -> None:
1211 """Writes the help into the formatter if it exists.
1213 This is a low-level method called by :meth:`get_help`.
1215 This calls the following methods:
1217 - :meth:`format_usage`
1218 - :meth:`format_help_text`
1219 - :meth:`format_arguments`
1220 - :meth:`format_options`
1221 - :meth:`format_epilog`
1222 """
1223 self.format_usage(ctx, formatter)
1224 self.format_help_text(ctx, formatter)
1225 self.format_arguments(ctx, formatter)
1226 self.format_options(ctx, formatter)
1227 self.format_epilog(ctx, formatter)
1229 def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None:
1230 """Writes the help text to the formatter if it exists."""
1231 if self.help is not None:
1232 # truncate the help text to the first form feed
1233 text = inspect.cleandoc(self.help).partition("\f")[0]
1234 else:
1235 text = ""
1237 if self.deprecated:
1238 label = _format_deprecated_label(self.deprecated)
1239 text = f"{_(text)} {label}" if text else label
1241 if text:
1242 formatter.write_paragraph()
1244 with formatter.indentation():
1245 formatter.write_text(text)
1247 def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:
1248 """Writes all the options into the formatter if they exist."""
1249 opts = []
1250 for param in self.get_params(ctx):
1251 rv = param.get_help_record(ctx)
1252 if rv is not None and not isinstance(param, Argument):
1253 opts.append(rv)
1255 if opts:
1256 with formatter.section(_("Options")):
1257 formatter.write_dl(opts)
1259 def format_arguments(self, ctx: Context, formatter: HelpFormatter) -> None:
1260 """Writes the arguments that have a help record into the formatter."""
1261 args = []
1262 for param in self.get_params(ctx):
1263 rv = param.get_help_record(ctx)
1264 if rv is not None and isinstance(param, Argument):
1265 args.append(rv)
1267 if args:
1268 with formatter.section(_("Positional arguments")):
1269 formatter.write_dl(args)
1271 def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None:
1272 """Writes the epilog into the formatter if it exists."""
1273 if self.epilog:
1274 epilog = inspect.cleandoc(self.epilog)
1275 formatter.write_paragraph()
1277 with formatter.indentation():
1278 formatter.write_text(epilog)
1280 def make_context(
1281 self,
1282 info_name: str | None,
1283 args: list[str],
1284 parent: Context | None = None,
1285 **extra: t.Any,
1286 ) -> Context:
1287 """This function when given an info name and arguments will kick
1288 off the parsing and create a new :class:`Context`. It does not
1289 invoke the actual command callback though.
1291 To quickly customize the context class used without overriding
1292 this method, set the :attr:`context_class` attribute.
1294 :param info_name: the info name for this invocation. Generally this
1295 is the most descriptive name for the script or
1296 command. For the toplevel script it's usually
1297 the name of the script, for commands below it's
1298 the name of the command.
1299 :param args: the arguments to parse as list of strings.
1300 :param parent: the parent context if available.
1301 :param extra: extra keyword arguments forwarded to the context
1302 constructor.
1304 .. versionchanged:: 8.0
1305 Added the :attr:`context_class` attribute.
1306 """
1307 for key, value in self.context_settings.items():
1308 if key not in extra:
1309 extra[key] = value
1311 ctx = self.context_class(self, info_name=info_name, parent=parent, **extra)
1313 with ctx.scope(cleanup=False):
1314 self.parse_args(ctx, args)
1315 return ctx
1317 def parse_args(self, ctx: Context, args: list[str]) -> list[str]:
1318 if not args and self.no_args_is_help and not ctx.resilient_parsing:
1319 raise NoArgsIsHelpError(ctx)
1321 parser = self.make_parser(ctx)
1322 opts, args, param_order = parser.parse_args(args=args)
1324 for param in iter_params_for_processing(param_order, self.get_params(ctx)):
1325 _, args = param.handle_parse_result(ctx, opts, args)
1327 # We now have all parameters' values into `ctx.params`, but the data may contain
1328 # the `UNSET` sentinel.
1329 # Convert `UNSET` to `None` to ensure that the user doesn't see `UNSET`.
1330 #
1331 # Waiting until after the initial parse to convert allows us to treat `UNSET`
1332 # more like a missing value when multiple params use the same name.
1333 # Refs:
1334 # https://github.com/pallets/click/issues/3071
1335 # https://github.com/pallets/click/pull/3079
1336 for name, value in ctx.params.items():
1337 if value is UNSET:
1338 ctx.params[name] = None
1340 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:
1341 ctx.fail(
1342 ngettext(
1343 "Got unexpected extra argument ({args})",
1344 "Got unexpected extra arguments ({args})",
1345 len(args),
1346 ).format(args=" ".join(map(str, args)))
1347 )
1349 ctx.args = args
1350 ctx._opt_prefixes.update(parser._opt_prefixes)
1351 return args
1353 def invoke(self, ctx: Context) -> t.Any:
1354 """Given a context, this invokes the attached callback (if it exists)
1355 in the right way.
1356 """
1357 if self.deprecated:
1358 message = _(
1359 "DeprecationWarning: The command {name!r} is deprecated.{extra_message}"
1360 ).format(
1361 name=self.name,
1362 extra_message=_format_deprecated_suffix(self.deprecated),
1363 )
1364 echo(style(message, fg="red"), err=True)
1366 if self.callback is not None:
1367 return ctx.invoke(self.callback, **ctx.params)
1369 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:
1370 """Return a list of completions for the incomplete value. Looks
1371 at the names of options and chained multi-commands.
1373 Any command could be part of a chained multi-command, so sibling
1374 commands are valid at any point during command completion.
1376 :param ctx: Invocation context for this command.
1377 :param incomplete: Value being completed. May be empty.
1379 .. versionadded:: 8.0
1380 """
1381 from click.shell_completion import CompletionItem
1383 results: list[CompletionItem] = []
1385 if incomplete and not incomplete[0].isalnum():
1386 for param in self.get_params(ctx):
1387 if (
1388 not isinstance(param, Option)
1389 or param.hidden
1390 or (
1391 not param.multiple
1392 and ctx.get_parameter_source(param.name)
1393 is ParameterSource.COMMANDLINE
1394 )
1395 ):
1396 continue
1398 results.extend(
1399 CompletionItem(name, help=param.help)
1400 for name in [*param.opts, *param.secondary_opts]
1401 if name.startswith(incomplete)
1402 )
1404 while ctx.parent is not None:
1405 ctx = ctx.parent
1407 if isinstance(ctx.command, Group) and ctx.command.chain:
1408 results.extend(
1409 CompletionItem(name, help=command.get_short_help_str())
1410 for name, command in _complete_visible_commands(ctx, incomplete)
1411 if name not in ctx._protected_args
1412 )
1414 return results
1416 @t.overload
1417 def main(
1418 self,
1419 args: cabc.Sequence[str] | None = None,
1420 prog_name: str | None = None,
1421 complete_var: str | None = None,
1422 standalone_mode: t.Literal[True] = True,
1423 **extra: t.Any,
1424 ) -> t.NoReturn: ...
1426 @t.overload
1427 def main(
1428 self,
1429 args: cabc.Sequence[str] | None = None,
1430 prog_name: str | None = None,
1431 complete_var: str | None = None,
1432 standalone_mode: bool = ...,
1433 **extra: t.Any,
1434 ) -> t.Any: ...
1436 def main(
1437 self,
1438 args: cabc.Sequence[str] | None = None,
1439 prog_name: str | None = None,
1440 complete_var: str | None = None,
1441 standalone_mode: bool = True,
1442 windows_expand_args: bool = True,
1443 **extra: t.Any,
1444 ) -> t.Any:
1445 """This is the way to invoke a script with all the bells and
1446 whistles as a command line application. This will always terminate
1447 the application after a call. If this is not wanted, ``SystemExit``
1448 needs to be caught.
1450 This method is also available by directly calling the instance of
1451 a :class:`Command`.
1453 :param args: the arguments that should be used for parsing. If not
1454 provided, ``sys.argv[1:]`` is used.
1455 :param prog_name: the program name that should be used. By default
1456 the program name is constructed by taking the file
1457 name from ``sys.argv[0]``.
1458 :param complete_var: the environment variable that controls the
1459 bash completion support. The default is
1460 ``"_<prog_name>_COMPLETE"`` with prog_name in
1461 uppercase.
1462 :param standalone_mode: the default behavior is to invoke the script
1463 in standalone mode. Click will then
1464 handle exceptions and convert them into
1465 error messages and the function will never
1466 return but shut down the interpreter. If
1467 this is set to `False` they will be
1468 propagated to the caller and the return
1469 value of this function is the return value
1470 of :meth:`invoke`.
1471 :param windows_expand_args: Expand glob patterns, user dir, and
1472 env vars in command line args on Windows.
1473 :param extra: extra keyword arguments are forwarded to the context
1474 constructor. See :class:`Context` for more information.
1476 .. versionchanged:: 8.0.1
1477 Added the ``windows_expand_args`` parameter to allow
1478 disabling command line arg expansion on Windows.
1480 .. versionchanged:: 8.0
1481 When taking arguments from ``sys.argv`` on Windows, glob
1482 patterns, user dir, and env vars are expanded.
1484 .. versionchanged:: 3.0
1485 Added the ``standalone_mode`` parameter.
1486 """
1487 if args is None:
1488 args = sys.argv[1:]
1490 if os.name == "nt" and windows_expand_args:
1491 args = _expand_args(args)
1492 else:
1493 args = list(args)
1495 if prog_name is None:
1496 prog_name = _detect_program_name()
1498 # Process shell completion requests and exit early.
1499 self._main_shell_completion(extra, prog_name, complete_var)
1501 try:
1502 try:
1503 with self.make_context(prog_name, args, **extra) as ctx:
1504 rv = self.invoke(ctx)
1505 if not standalone_mode:
1506 return rv
1507 # it's not safe to `ctx.exit(rv)` here!
1508 # note that `rv` may actually contain data like "1" which
1509 # has obvious effects
1510 # more subtle case: `rv=[None, None]` can come out of
1511 # chained commands which all returned `None` -- so it's not
1512 # even always obvious that `rv` indicates success/failure
1513 # by its truthiness/falsiness
1514 ctx.exit()
1515 except (EOFError, KeyboardInterrupt) as e:
1516 echo(file=sys.stderr)
1517 raise Abort() from e
1518 except ClickException as e:
1519 if not standalone_mode:
1520 raise
1521 e.show()
1522 sys.exit(e.exit_code)
1523 except OSError as e:
1524 if e.errno == errno.EPIPE:
1525 sys.stdout = t.cast(t.TextIO, PacifyFlushWrapper(sys.stdout))
1526 sys.stderr = t.cast(t.TextIO, PacifyFlushWrapper(sys.stderr))
1527 sys.exit(1)
1528 else:
1529 raise
1530 except Exit as e:
1531 if standalone_mode:
1532 sys.exit(e.exit_code)
1533 else:
1534 # in non-standalone mode, return the exit code
1535 # note that this is only reached if `self.invoke` above raises
1536 # an Exit explicitly -- thus bypassing the check there which
1537 # would return its result
1538 # the results of non-standalone execution may therefore be
1539 # somewhat ambiguous: if there are codepaths which lead to
1540 # `ctx.exit(1)` and to `return 1`, the caller won't be able to
1541 # tell the difference between the two
1542 return e.exit_code
1543 except Abort:
1544 if not standalone_mode:
1545 raise
1546 echo(_("Aborted!"), file=sys.stderr)
1547 sys.exit(1)
1549 def _main_shell_completion(
1550 self,
1551 ctx_args: cabc.MutableMapping[str, t.Any],
1552 prog_name: str,
1553 complete_var: str | None = None,
1554 ) -> None:
1555 """Check if the shell is asking for tab completion, process
1556 that, then exit early. Called from :meth:`main` before the
1557 program is invoked.
1559 :param prog_name: Name of the executable in the shell.
1560 :param complete_var: Name of the environment variable that holds
1561 the completion instruction. Defaults to
1562 ``_{PROG_NAME}_COMPLETE``.
1564 .. versionchanged:: 8.2.0
1565 Dots (``.``) in ``prog_name`` are replaced with underscores (``_``).
1566 """
1567 if complete_var is None:
1568 complete_name = prog_name.replace("-", "_").replace(".", "_")
1569 complete_var = f"_{complete_name}_COMPLETE".upper()
1571 instruction = os.environ.get(complete_var)
1573 if not instruction:
1574 return
1576 from .shell_completion import shell_complete
1578 rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)
1579 sys.exit(rv)
1581 def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
1582 """Alias for :meth:`main`."""
1583 return self.main(*args, **kwargs)
1586class _FakeSubclassCheck(type):
1587 def __subclasscheck__(cls, subclass: type) -> bool:
1588 return issubclass(subclass, cls.__bases__[0])
1590 def __instancecheck__(cls, instance: t.Any) -> bool:
1591 return isinstance(instance, cls.__bases__[0])
1594class _BaseCommand(Command, metaclass=_FakeSubclassCheck):
1595 """
1596 .. deprecated:: 8.2
1597 Will be removed in Click 9.0. Use ``Command`` instead.
1598 """
1601class Group(Command):
1602 """A group is a command that nests other commands (or more groups).
1604 :param name: The name of the group command.
1605 :param commands: Map names to :class:`Command` objects. Can be a list, which
1606 will use :attr:`Command.name` as the keys.
1607 :param invoke_without_command: Invoke the group's callback even if a
1608 subcommand is not given.
1609 :param no_args_is_help: If no arguments are given, show the group's help and
1610 exit. Defaults to the opposite of ``invoke_without_command``.
1611 :param subcommand_metavar: How to represent the subcommand argument in help.
1612 The default will represent whether ``chain`` is set or not.
1613 :param chain: Allow passing more than one subcommand argument. After parsing
1614 a command's arguments, if any arguments remain another command will be
1615 matched, and so on.
1616 :param result_callback: A function to call after the group's and
1617 subcommand's callbacks. The value returned by the subcommand is passed.
1618 If ``chain`` is enabled, the value will be a list of values returned by
1619 all the commands. If ``invoke_without_command`` is enabled, the value
1620 will be the value returned by the group's callback, or an empty list if
1621 ``chain`` is enabled.
1622 :param kwargs: Other arguments passed to :class:`Command`.
1624 .. versionchanged:: 8.0
1625 The ``commands`` argument can be a list of command objects.
1627 .. versionchanged:: 8.2
1628 Merged with and replaces the ``MultiCommand`` base class.
1629 """
1631 allow_extra_args = True
1632 allow_interspersed_args = False
1634 #: If set, this is used by the group's :meth:`command` decorator
1635 #: as the default :class:`Command` class. This is useful to make all
1636 #: subcommands use a custom command class.
1637 #:
1638 #: .. versionadded:: 8.0
1639 command_class: type[Command] | None = None
1641 #: If set, this is used by the group's :meth:`group` decorator
1642 #: as the default :class:`Group` class. This is useful to make all
1643 #: subgroups use a custom group class.
1644 #:
1645 #: If set to the special value :class:`type` (literally
1646 #: ``group_class = type``), this group's class will be used as the
1647 #: default class. This makes a custom group class continue to make
1648 #: custom groups.
1649 #:
1650 #: .. versionadded:: 8.0
1651 group_class: type[Group] | type[type] | None = None
1652 # Literal[type] isn't valid, so use Type[type]
1654 commands: cabc.MutableMapping[str, Command]
1655 invoke_without_command: bool
1656 subcommand_metavar: str
1657 chain: bool
1658 _result_callback: t.Callable[..., t.Any] | None
1660 def __init__(
1661 self,
1662 name: str | None = None,
1663 commands: cabc.MutableMapping[str, Command]
1664 | cabc.Sequence[Command]
1665 | None = None,
1666 invoke_without_command: bool = False,
1667 no_args_is_help: bool | None = None,
1668 subcommand_metavar: str | None = None,
1669 chain: bool = False,
1670 result_callback: t.Callable[..., t.Any] | None = None,
1671 **kwargs: t.Any,
1672 ) -> None:
1673 super().__init__(name, **kwargs)
1675 if commands is None:
1676 commands = {}
1677 elif isinstance(commands, abc.Sequence):
1678 commands = {c.name: c for c in commands if c.name is not None}
1680 #: The registered subcommands by their exported names.
1681 self.commands = commands
1683 if no_args_is_help is None:
1684 no_args_is_help = not invoke_without_command
1686 self.no_args_is_help = no_args_is_help
1687 self.invoke_without_command = invoke_without_command
1689 if subcommand_metavar is None:
1690 # When the group can run without a subcommand, the leading command
1691 # token is optional, so wrap it in brackets to reflect that.
1692 if chain:
1693 if invoke_without_command:
1694 subcommand_metavar = "[COMMAND1] [ARGS]... [COMMAND2 [ARGS]...]..."
1695 else:
1696 subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."
1697 elif invoke_without_command:
1698 subcommand_metavar = "[COMMAND] [ARGS]..."
1699 else:
1700 subcommand_metavar = "COMMAND [ARGS]..."
1702 self.subcommand_metavar = subcommand_metavar
1703 self.chain = chain
1704 # The result callback that is stored. This can be set or
1705 # overridden with the :func:`result_callback` decorator.
1706 self._result_callback = result_callback
1708 if self.chain:
1709 for param in self.params:
1710 if isinstance(param, Argument) and not param.required:
1711 raise RuntimeError(
1712 "A group in chain mode cannot have optional arguments."
1713 )
1715 def to_info_dict(self, ctx: Context) -> dict[str, t.Any]:
1716 info_dict = super().to_info_dict(ctx)
1717 commands = {}
1719 for name in self.list_commands(ctx):
1720 command = self.get_command(ctx, name)
1722 if command is None:
1723 continue
1725 sub_ctx = ctx._make_sub_context(command)
1727 with sub_ctx.scope(cleanup=False):
1728 commands[name] = command.to_info_dict(sub_ctx)
1730 info_dict.update(commands=commands, chain=self.chain)
1731 return info_dict
1733 def add_command(self, cmd: Command, name: str | None = None) -> None:
1734 """Registers another :class:`Command` with this group. If the name
1735 is not provided, the name of the command is used.
1736 """
1737 name = name or cmd.name
1738 if name is None:
1739 raise TypeError("Command has no name.")
1740 _check_nested_chain(self, name, cmd, register=True)
1741 self.commands[name] = cmd
1743 @t.overload
1744 def command(self, __func: t.Callable[..., t.Any]) -> Command: ...
1746 @t.overload
1747 def command(
1748 self, *args: t.Any, **kwargs: t.Any
1749 ) -> t.Callable[[t.Callable[..., t.Any]], Command]: ...
1751 def command(
1752 self, *args: t.Any, **kwargs: t.Any
1753 ) -> t.Callable[[t.Callable[..., t.Any]], Command] | Command:
1754 """A shortcut decorator for declaring and attaching a command to
1755 the group. This takes the same arguments as :func:`command` and
1756 immediately registers the created command with this group by
1757 calling :meth:`add_command`.
1759 To customize the command class used, set the
1760 :attr:`command_class` attribute.
1762 .. versionchanged:: 8.1
1763 This decorator can be applied without parentheses.
1765 .. versionchanged:: 8.0
1766 Added the :attr:`command_class` attribute.
1767 """
1768 from .decorators import command
1770 func: t.Callable[..., t.Any] | None = None
1772 if args and callable(args[0]):
1773 assert len(args) == 1 and not kwargs, (
1774 "Use 'command(**kwargs)(callable)' to provide arguments."
1775 )
1776 (func,) = args
1777 args = ()
1779 if self.command_class and kwargs.get("cls") is None:
1780 kwargs["cls"] = self.command_class
1782 def decorator(f: t.Callable[..., t.Any]) -> Command:
1783 cmd: Command = command(*args, **kwargs)(f)
1784 self.add_command(cmd)
1785 return cmd
1787 if func is not None:
1788 return decorator(func)
1790 return decorator
1792 @t.overload
1793 def group(self, __func: t.Callable[..., t.Any]) -> Group: ...
1795 @t.overload
1796 def group(
1797 self, *args: t.Any, **kwargs: t.Any
1798 ) -> t.Callable[[t.Callable[..., t.Any]], Group]: ...
1800 def group(
1801 self, *args: t.Any, **kwargs: t.Any
1802 ) -> t.Callable[[t.Callable[..., t.Any]], Group] | Group:
1803 """A shortcut decorator for declaring and attaching a group to
1804 the group. This takes the same arguments as :func:`group` and
1805 immediately registers the created group with this group by
1806 calling :meth:`add_command`.
1808 To customize the group class used, set the :attr:`group_class`
1809 attribute.
1811 .. versionchanged:: 8.1
1812 This decorator can be applied without parentheses.
1814 .. versionchanged:: 8.0
1815 Added the :attr:`group_class` attribute.
1816 """
1817 from .decorators import group
1819 func: t.Callable[..., t.Any] | None = None
1821 if args and callable(args[0]):
1822 assert len(args) == 1 and not kwargs, (
1823 "Use 'group(**kwargs)(callable)' to provide arguments."
1824 )
1825 (func,) = args
1826 args = ()
1828 if self.group_class is not None and kwargs.get("cls") is None:
1829 if self.group_class is type:
1830 kwargs["cls"] = type(self)
1831 else:
1832 kwargs["cls"] = self.group_class
1834 def decorator(f: t.Callable[..., t.Any]) -> Group:
1835 cmd: Group = group(*args, **kwargs)(f)
1836 self.add_command(cmd)
1837 return cmd
1839 if func is not None:
1840 return decorator(func)
1842 return decorator
1844 def result_callback(self, replace: bool = False) -> t.Callable[[F], F]:
1845 """Adds a result callback to the command. By default if a
1846 result callback is already registered this will chain them but
1847 this can be disabled with the `replace` parameter. The result
1848 callback is invoked with the return value of the subcommand
1849 (or the list of return values from all subcommands if chaining
1850 is enabled) as well as the parameters as they would be passed
1851 to the main callback.
1853 Example::
1855 @click.group()
1856 @click.option('-i', '--input', default=23)
1857 def cli(input):
1858 return 42
1860 @cli.result_callback()
1861 def process_result(result, input):
1862 return result + input
1864 :param replace: if set to `True` an already existing result
1865 callback will be removed.
1867 .. versionchanged:: 8.0
1868 Renamed from ``resultcallback``.
1870 .. versionadded:: 3.0
1871 """
1873 def decorator(f: F) -> F:
1874 old_callback = self._result_callback
1876 if old_callback is None or replace:
1877 self._result_callback = f
1878 return f
1880 def function(value: t.Any, /, *args: t.Any, **kwargs: t.Any) -> t.Any:
1881 inner = old_callback(value, *args, **kwargs)
1882 return f(inner, *args, **kwargs)
1884 self._result_callback = rv = update_wrapper(t.cast(F, function), f)
1885 return rv # type: ignore[return-value]
1887 return decorator
1889 def get_command(self, ctx: Context, cmd_name: str) -> Command | None:
1890 """Given a context and a command name, this returns a :class:`Command`
1891 object if it exists or returns ``None``.
1892 """
1893 return self.commands.get(cmd_name)
1895 def list_commands(self, ctx: Context) -> list[str]:
1896 """Returns a list of subcommand names in the order they should appear."""
1897 return sorted(self.commands)
1899 def collect_usage_pieces(self, ctx: Context) -> list[str]:
1900 rv = super().collect_usage_pieces(ctx)
1901 rv.append(self.subcommand_metavar)
1902 return rv
1904 def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:
1905 super().format_options(ctx, formatter)
1906 self.format_commands(ctx, formatter)
1908 def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None:
1909 """Extra format methods for multi methods that adds all the commands
1910 after the options.
1911 """
1912 commands = []
1913 for subcommand in self.list_commands(ctx):
1914 cmd = self.get_command(ctx, subcommand)
1915 # What is this, the tool lied about a command. Ignore it
1916 if cmd is None:
1917 continue
1918 if cmd.hidden:
1919 continue
1921 commands.append((subcommand, cmd))
1923 # allow for 3 times the default spacing
1924 if len(commands):
1925 limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands)
1927 rows = []
1928 for subcommand, cmd in commands:
1929 help = cmd.get_short_help_str(limit)
1930 rows.append((subcommand, help))
1932 if rows:
1933 with formatter.section(_("Commands")):
1934 formatter.write_dl(rows)
1936 def parse_args(self, ctx: Context, args: list[str]) -> list[str]:
1937 if not args and self.no_args_is_help and not ctx.resilient_parsing:
1938 raise NoArgsIsHelpError(ctx)
1940 rest = super().parse_args(ctx, args)
1942 if self.chain:
1943 ctx._protected_args = rest
1944 ctx.args = []
1945 elif rest:
1946 ctx._protected_args, ctx.args = rest[:1], rest[1:]
1948 return ctx.args
1950 def invoke(self, ctx: Context) -> t.Any:
1951 def _process_result(value: t.Any) -> t.Any:
1952 if self._result_callback is not None:
1953 value = ctx.invoke(self._result_callback, value, **ctx.params)
1954 return value
1956 if not ctx._protected_args:
1957 if self.invoke_without_command:
1958 # No subcommand was invoked, so the result callback is
1959 # invoked with the group return value for regular
1960 # groups, or an empty list for chained groups.
1961 with ctx:
1962 rv = super().invoke(ctx)
1963 return _process_result([] if self.chain else rv)
1964 ctx.fail(_("Missing command."))
1966 # Fetch args back out
1967 args = [*ctx._protected_args, *ctx.args]
1968 ctx.args = []
1969 ctx._protected_args = []
1971 # If we're not in chain mode, we only allow the invocation of a
1972 # single command but we also inform the current context about the
1973 # name of the command to invoke.
1974 if not self.chain:
1975 # Make sure the context is entered so we do not clean up
1976 # resources until the result processor has worked.
1977 with ctx:
1978 cmd_name, cmd, args = self.resolve_command(ctx, args)
1979 assert cmd is not None
1980 ctx.invoked_subcommand = cmd_name
1981 super().invoke(ctx)
1982 sub_ctx = cmd.make_context(cmd_name, args, parent=ctx)
1983 with sub_ctx:
1984 return _process_result(sub_ctx.command.invoke(sub_ctx))
1986 # In chain mode we create the contexts step by step, but after the
1987 # base command has been invoked. Because at that point we do not
1988 # know the subcommands yet, the invoked subcommand attribute is
1989 # set to ``*`` to inform the command that subcommands are executed
1990 # but nothing else.
1991 with ctx:
1992 ctx.invoked_subcommand = "*" if args else None
1993 super().invoke(ctx)
1995 # Otherwise we make every single context and invoke them in a
1996 # chain. In that case the return value to the result processor
1997 # is the list of all invoked subcommand's results.
1998 contexts = []
1999 while args:
2000 cmd_name, cmd, args = self.resolve_command(ctx, args)
2001 assert cmd is not None
2002 sub_ctx = cmd.make_context(
2003 cmd_name,
2004 args,
2005 parent=ctx,
2006 allow_extra_args=True,
2007 allow_interspersed_args=False,
2008 )
2009 contexts.append(sub_ctx)
2010 args, sub_ctx.args = sub_ctx.args, []
2012 rv = []
2013 for sub_ctx in contexts:
2014 with sub_ctx:
2015 rv.append(sub_ctx.command.invoke(sub_ctx))
2016 return _process_result(rv)
2018 def resolve_command(
2019 self, ctx: Context, args: list[str]
2020 ) -> tuple[str | None, Command | None, list[str]]:
2021 cmd_name = make_str(args[0])
2023 # Get the command
2024 cmd = self.get_command(ctx, cmd_name)
2026 # If we can't find the command but there is a normalization
2027 # function available, we try with that one.
2028 if cmd is None and ctx.token_normalize_func is not None:
2029 cmd_name = ctx.token_normalize_func(cmd_name)
2030 cmd = self.get_command(ctx, cmd_name)
2032 # If we don't find the command we want to show an error message
2033 # to the user that it was not provided. However, there is
2034 # something else we should do: if the first argument looks like
2035 # an option we want to kick off parsing again for arguments to
2036 # resolve things like --help which now should go to the main
2037 # place.
2038 if cmd is None and not ctx.resilient_parsing:
2039 if _split_opt(cmd_name)[0]:
2040 self.parse_args(ctx, args)
2041 raise NoSuchCommand(cmd_name, possibilities=self.commands, ctx=ctx)
2042 return cmd_name if cmd else None, cmd, args[1:]
2044 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:
2045 """Return a list of completions for the incomplete value. Looks
2046 at the names of options, subcommands, and chained
2047 multi-commands.
2049 :param ctx: Invocation context for this command.
2050 :param incomplete: Value being completed. May be empty.
2052 .. versionadded:: 8.0
2053 """
2054 from click.shell_completion import CompletionItem
2056 results = [
2057 CompletionItem(name, help=command.get_short_help_str())
2058 for name, command in _complete_visible_commands(ctx, incomplete)
2059 ]
2060 results.extend(super().shell_complete(ctx, incomplete))
2061 return results
2064class _MultiCommand(Group, metaclass=_FakeSubclassCheck):
2065 """
2066 .. deprecated:: 8.2
2067 Will be removed in Click 9.0. Use ``Group`` instead.
2068 """
2071class CommandCollection(Group):
2072 """A :class:`Group` that looks up subcommands on other groups. If a command
2073 is not found on this group, each registered source is checked in order.
2074 Parameters on a source are not added to this group, and a source's callback
2075 is not invoked when invoking its commands. In other words, this "flattens"
2076 commands in many groups into this one group.
2078 :param name: The name of the group command.
2079 :param sources: A list of :class:`Group` objects to look up commands from.
2080 :param kwargs: Other arguments passed to :class:`Group`.
2082 .. versionchanged:: 8.2
2083 This is a subclass of ``Group``. Commands are looked up first on this
2084 group, then each of its sources.
2085 """
2087 sources: list[Group]
2089 def __init__(
2090 self,
2091 name: str | None = None,
2092 sources: list[Group] | None = None,
2093 **kwargs: t.Any,
2094 ) -> None:
2095 super().__init__(name, **kwargs)
2096 #: The list of registered groups.
2097 self.sources = sources or []
2099 def add_source(self, group: Group) -> None:
2100 """Add a group as a source of commands."""
2101 self.sources.append(group)
2103 def get_command(self, ctx: Context, cmd_name: str) -> Command | None:
2104 rv = super().get_command(ctx, cmd_name)
2106 if rv is not None:
2107 return rv
2109 for source in self.sources:
2110 rv = source.get_command(ctx, cmd_name)
2112 if rv is not None:
2113 if self.chain:
2114 _check_nested_chain(self, cmd_name, rv)
2116 return rv
2118 return None
2120 def list_commands(self, ctx: Context) -> list[str]:
2121 rv: set[str] = set(super().list_commands(ctx))
2123 for source in self.sources:
2124 rv.update(source.list_commands(ctx))
2126 return sorted(rv)
2129def _check_iter(value: cabc.Iterable[V]) -> cabc.Iterator[V]:
2130 """Check if the value is iterable but not a string. Raises a type
2131 error, or return an iterator over the value.
2132 """
2133 if isinstance(value, str):
2134 raise TypeError
2136 return iter(value)
2139class Parameter(ABC):
2140 r"""A parameter to a command comes in two versions: they are either
2141 :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently
2142 not supported by design as some of the internals for parsing are
2143 intentionally not finalized.
2145 Some settings are supported by both options and arguments.
2147 :param param_decls: the parameter declarations for this option or
2148 argument. This is a list of flags or argument
2149 names.
2150 :param type: the type that should be used. Either a :class:`ParamType`
2151 or a Python type. The latter is converted into the former
2152 automatically if supported.
2153 :param required: controls if this is optional or not.
2154 :param default: the default value if omitted. This can also be a callable,
2155 in which case it's invoked when the default is needed
2156 without any arguments.
2157 :param callback: A function to further process or validate the value
2158 after type conversion. It is called as ``f(ctx, param, value)``
2159 and must return the value. It is called for all sources,
2160 including prompts.
2161 :param nargs: the number of arguments to match. If not ``1`` the return
2162 value is a tuple instead of single value. The default for
2163 nargs is ``1`` (except if the type is a tuple, then it's
2164 the arity of the tuple). If ``nargs=-1``, all remaining
2165 parameters are collected.
2166 :param metavar: how the value is represented in the help page.
2167 :param expose_value: if this is `True` then the value is passed onwards
2168 to the command callback and stored on the context,
2169 otherwise it's skipped.
2170 :param is_eager: eager values are processed before non eager ones. This
2171 should not be set for arguments or it will inverse the
2172 order of processing.
2173 :param envvar: environment variable(s) that are used to provide a default value for
2174 this parameter. This can be a string or a sequence of strings. If a sequence is
2175 given, only the first non-empty environment variable is used for the parameter.
2176 :param shell_complete: A function that returns custom shell
2177 completions. Used instead of the param's type completion if
2178 given. Takes ``ctx, param, incomplete`` and must return a list
2179 of :class:`~click.shell_completion.CompletionItem` or a list of
2180 strings.
2181 :param deprecated: If ``True`` or non-empty string, issues a message
2182 indicating that the argument is deprecated and highlights
2183 its deprecation in --help. The message can be customized
2184 by using a string as the value. A deprecated parameter
2185 cannot be required, a ValueError will be raised otherwise.
2187 .. versionchanged:: 8.2.0
2188 Introduction of ``deprecated``.
2190 .. versionchanged:: 8.2
2191 Adding duplicate parameter names to a :class:`~click.core.Command` will
2192 result in a ``UserWarning`` being shown.
2194 .. versionchanged:: 8.2
2195 Adding duplicate parameter names to a :class:`~click.core.Command` will
2196 result in a ``UserWarning`` being shown.
2198 .. versionchanged:: 8.0
2199 ``process_value`` validates required parameters and bounded
2200 ``nargs``, and invokes the parameter callback before returning
2201 the value. This allows the callback to validate prompts.
2202 ``full_process_value`` is removed.
2204 .. versionchanged:: 8.0
2205 ``autocompletion`` is renamed to ``shell_complete`` and has new
2206 semantics described above. The old name is deprecated and will
2207 be removed in 8.1, until then it will be wrapped to match the
2208 new requirements.
2210 .. versionchanged:: 8.0
2211 For ``multiple=True, nargs>1``, the default must be a list of
2212 tuples.
2214 .. versionchanged:: 8.0
2215 Setting a default is no longer required for ``nargs>1``, it will
2216 default to ``None``. ``multiple=True`` or ``nargs=-1`` will
2217 default to ``()``.
2219 .. versionchanged:: 7.1
2220 Empty environment variables are ignored rather than taking the
2221 empty string value. This makes it possible for scripts to clear
2222 variables if they can't unset them.
2224 .. versionchanged:: 2.0
2225 Changed signature for parameter callback to also be passed the
2226 parameter. The old callback format will still work, but it will
2227 raise a warning to give you a chance to migrate the code easier.
2228 """
2230 param_type_name = "parameter"
2232 name: str
2233 opts: list[str]
2234 secondary_opts: list[str]
2235 # `Parameter.type` is annotated in `__init__` to avoid confusing mypy
2236 required: bool
2237 callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None
2238 nargs: int
2239 multiple: bool
2240 expose_value: bool
2241 default: t.Any | t.Callable[[], t.Any] | None
2242 _default_explicit: bool
2243 is_eager: bool
2244 metavar: str | None
2245 envvar: str | cabc.Sequence[str] | None
2246 _custom_shell_complete: (
2247 t.Callable[[Context, Parameter, str], list[CompletionItem] | list[str]] | None
2248 )
2249 deprecated: bool | str
2251 def __init__(
2252 self,
2253 param_decls: cabc.Sequence[str] | None = None,
2254 type: types.ParamType[t.Any] | t.Any | None = None,
2255 required: bool = False,
2256 # XXX The default historically embed two concepts:
2257 # - the declaration of a Parameter object carrying the default (handy to
2258 # arbitrage the default value of coupled Parameters sharing the same
2259 # self.name, like flag options),
2260 # - and the actual value of the default.
2261 # It is confusing and is the source of many issues discussed in:
2262 # https://github.com/pallets/click/pull/3030
2263 # In the future, we might think of splitting it in two, not unlike
2264 # Option.is_flag and Option.flag_value: we could have something like
2265 # Parameter.is_default and Parameter.default_value.
2266 default: t.Any | t.Callable[[], t.Any] | None = UNSET,
2267 callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None = None,
2268 nargs: int | None = None,
2269 multiple: bool = False,
2270 metavar: str | None = None,
2271 expose_value: bool = True,
2272 is_eager: bool = False,
2273 envvar: str | cabc.Sequence[str] | None = None,
2274 shell_complete: t.Callable[
2275 [Context, Parameter, str], list[CompletionItem] | list[str]
2276 ]
2277 | None = None,
2278 deprecated: bool | str = False,
2279 ) -> None:
2280 self.name, self.opts, self.secondary_opts = self._parse_decls(
2281 param_decls or (), expose_value
2282 )
2283 self.type: types.ParamType[t.Any] = types.convert_type(type, default)
2285 # Default nargs to what the type tells us if we have that
2286 # information available.
2287 if nargs is None:
2288 if self.type.is_composite:
2289 nargs = self.type.arity
2290 else:
2291 nargs = 1
2293 self.required = required
2294 self.callback = callback
2295 self.nargs = nargs
2296 self.multiple = multiple
2297 self.expose_value = expose_value
2298 self.default = default
2299 # Whether the user passed ``default`` explicitly to the constructor.
2300 # Captured before any auto-derived default (like ``False`` for boolean
2301 # flags in :class:`Option`) replaces the :data:`UNSET` sentinel, so it
2302 # remains ``False`` when the default was inferred rather than chosen.
2303 # Refs: https://github.com/pallets/click/issues/3403
2304 self._default_explicit = default is not UNSET
2305 self.is_eager = is_eager
2306 self.metavar = metavar
2307 self.envvar = envvar
2308 self._custom_shell_complete = shell_complete
2309 self.deprecated = deprecated
2311 if __debug__:
2312 if self.type.is_composite and nargs != self.type.arity:
2313 raise ValueError(
2314 f"'nargs' must be {self.type.arity} (or None) for"
2315 f" type {self.type!r}, but it was {nargs}."
2316 )
2318 if required and deprecated:
2319 raise ValueError(
2320 f"The {self.param_type_name} '{self.human_readable_name}' "
2321 "is deprecated and still required. A deprecated "
2322 f"{self.param_type_name} cannot be required."
2323 )
2325 def to_info_dict(self) -> dict[str, t.Any]:
2326 """Gather information that could be useful for a tool generating
2327 user-facing documentation.
2329 Use :meth:`click.Context.to_info_dict` to traverse the entire
2330 CLI structure.
2332 .. versionchanged:: 8.3.0
2333 Returns ``None`` for the :attr:`default` if it was not set.
2335 .. versionadded:: 8.0
2336 """
2337 return {
2338 "name": self.name,
2339 "param_type_name": self.param_type_name,
2340 "opts": self.opts,
2341 "secondary_opts": self.secondary_opts,
2342 "type": self.type.to_info_dict(),
2343 "required": self.required,
2344 "nargs": self.nargs,
2345 "multiple": self.multiple,
2346 # We explicitly hide the :attr:`UNSET` value to the user, as we choose to
2347 # make it an implementation detail. And because ``to_info_dict`` has been
2348 # designed for documentation purposes, we return ``None`` instead.
2349 "default": self.default if self.default is not UNSET else None,
2350 "envvar": self.envvar,
2351 }
2353 def __repr__(self) -> str:
2354 return f"<{self.__class__.__name__} {self.name}>"
2356 @abstractmethod
2357 def _parse_decls(
2358 self, decls: cabc.Sequence[str], expose_value: bool
2359 ) -> tuple[str, list[str], list[str]]: ...
2361 @property
2362 def human_readable_name(self) -> str:
2363 """Returns the human readable name of this parameter. This is the
2364 same as the name for options, but the metavar for arguments.
2365 """
2366 return self.name
2368 def make_metavar(self, ctx: Context) -> str:
2369 if self.metavar is not None:
2370 return self.metavar
2372 metavar = self.type.get_metavar(param=self, ctx=ctx)
2374 if metavar is None:
2375 metavar = self.type.name.upper()
2377 if self.nargs != 1:
2378 metavar += "..."
2380 return metavar
2382 @t.overload
2383 def get_default(
2384 self, ctx: Context, call: t.Literal[True] = True
2385 ) -> t.Any | None: ...
2387 @t.overload
2388 def get_default(
2389 self, ctx: Context, call: bool = ...
2390 ) -> t.Any | t.Callable[[], t.Any] | None: ...
2392 def get_default(
2393 self, ctx: Context, call: bool = True
2394 ) -> t.Any | t.Callable[[], t.Any] | None:
2395 """Get the default for the parameter. Tries
2396 :meth:`Context.lookup_default` first, then the local default.
2398 :param ctx: Current context.
2399 :param call: If the default is a callable, call it. Disable to
2400 return the callable instead.
2402 .. versionchanged:: 8.0.2
2403 Type casting is no longer performed when getting a default.
2405 .. versionchanged:: 8.0.1
2406 Type casting can fail in resilient parsing mode. Invalid
2407 defaults will not prevent showing help text.
2409 .. versionchanged:: 8.0
2410 Looks at ``ctx.default_map`` first.
2412 .. versionchanged:: 8.0
2413 Added the ``call`` parameter.
2414 """
2415 value = ctx.lookup_default(self.name, call=False)
2417 if value is None and not ctx._default_map_has(self.name):
2418 value = self.default
2420 if call and callable(value):
2421 value = value()
2423 return value
2425 @abstractmethod
2426 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: ...
2428 def consume_value(
2429 self, ctx: Context, opts: cabc.Mapping[str, t.Any]
2430 ) -> tuple[t.Any, ParameterSource]:
2431 """Returns the parameter value produced by the parser.
2433 If the parser did not produce a value from user input, the value is either
2434 sourced from the environment variable, the default map, or the parameter's
2435 default value. In that order of precedence.
2437 If no value is found, an internal sentinel value is returned.
2439 :meta private:
2440 """
2441 # Collect from the parse the value passed by the user to the CLI.
2442 value = opts.get(self.name, UNSET)
2443 # If the value is set, it means it was sourced from the command line by the
2444 # parser, otherwise it left unset by default.
2445 source = (
2446 ParameterSource.COMMANDLINE
2447 if value is not UNSET
2448 else ParameterSource.DEFAULT
2449 )
2451 if value is UNSET:
2452 envvar_value = self.value_from_envvar(ctx)
2453 if envvar_value is not None:
2454 value = envvar_value
2455 source = ParameterSource.ENVIRONMENT
2457 if value is UNSET:
2458 default_map_value = ctx.lookup_default(self.name)
2459 if default_map_value is not None or ctx._default_map_has(self.name):
2460 value = default_map_value
2461 source = ParameterSource.DEFAULT_MAP
2463 # A string from default_map must be split for multi-value
2464 # parameters, matching value_from_envvar behavior.
2465 if isinstance(value, str) and self.nargs != 1:
2466 value = self.type.split_envvar_value(value)
2468 if value is UNSET:
2469 default_value = self.get_default(ctx)
2470 if default_value is not UNSET:
2471 value = default_value
2472 source = ParameterSource.DEFAULT
2474 return value, source
2476 def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:
2477 """Convert and validate a value against the parameter's
2478 :attr:`type`, :attr:`multiple`, and :attr:`nargs`.
2479 """
2480 if value is None:
2481 if self.multiple or self.nargs == -1:
2482 return ()
2483 else:
2484 return value
2486 def check_iter(value: t.Any) -> cabc.Iterator[t.Any]:
2487 try:
2488 return _check_iter(value)
2489 except TypeError:
2490 # This should only happen when passing in args manually,
2491 # the parser should construct an iterable when parsing
2492 # the command line.
2493 raise BadParameter(
2494 _("Value must be an iterable."), ctx=ctx, param=self
2495 ) from None
2497 # Define the conversion function based on nargs and type.
2499 if self.nargs == 1 or self.type.is_composite:
2501 def convert(value: t.Any) -> t.Any:
2502 return self.type(value, param=self, ctx=ctx)
2504 elif self.nargs == -1:
2506 def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...]
2507 return tuple(self.type(x, self, ctx) for x in check_iter(value))
2509 else: # nargs > 1
2511 def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...]
2512 value = tuple(check_iter(value))
2514 if len(value) != self.nargs:
2515 raise BadParameter(
2516 ngettext(
2517 "Takes {nargs} values but 1 was given.",
2518 "Takes {nargs} values but {len} were given.",
2519 len(value),
2520 ).format(nargs=self.nargs, len=len(value)),
2521 ctx=ctx,
2522 param=self,
2523 )
2525 return tuple(self.type(x, self, ctx) for x in value)
2527 if self.multiple:
2528 return tuple(convert(x) for x in check_iter(value))
2530 return convert(value)
2532 def value_is_missing(self, value: t.Any) -> bool:
2533 """A value is considered missing if:
2535 - it is :attr:`UNSET`,
2536 - or if it is an empty sequence while the parameter is suppose to have
2537 non-single value (i.e. :attr:`nargs` is not ``1`` or :attr:`multiple` is
2538 set).
2540 :meta private:
2541 """
2542 if value is UNSET:
2543 return True
2545 if (self.nargs != 1 or self.multiple) and value == ():
2546 return True
2548 return False
2550 def process_value(self, ctx: Context, value: t.Any) -> t.Any:
2551 """Process the value of this parameter:
2553 1. Type cast the value using :meth:`type_cast_value`.
2554 2. Check if the value is missing (see: :meth:`value_is_missing`), and raise
2555 :exc:`MissingParameter` if it is required.
2556 3. If a :attr:`callback` is set, call it to have the value replaced by the
2557 result of the callback. If the value was not set, the callback receive
2558 ``None``. This keep the legacy behavior as it was before the introduction of
2559 the :attr:`UNSET` sentinel.
2561 :meta private:
2562 """
2563 # shelter `type_cast_value` from ever seeing an `UNSET` value by handling the
2564 # cases in which `UNSET` gets special treatment explicitly at this layer
2565 #
2566 # Refs:
2567 # https://github.com/pallets/click/issues/3069
2568 if value is UNSET:
2569 if self.multiple or self.nargs == -1:
2570 value = ()
2571 else:
2572 value = self.type_cast_value(ctx, value)
2574 if self.required and self.value_is_missing(value):
2575 raise MissingParameter(ctx=ctx, param=self)
2577 if self.callback is not None:
2578 # Legacy case: UNSET is not exposed directly to the callback, but converted
2579 # to None.
2580 if value is UNSET:
2581 value = None
2583 # Search for parameters with UNSET values in the context.
2584 unset_keys = {k: None for k, v in ctx.params.items() if v is UNSET}
2585 # No UNSET values, call the callback as usual.
2586 if not unset_keys:
2587 value = self.callback(ctx, self, value)
2589 # Legacy case: provide a temporarily manipulated context to the callback
2590 # to hide UNSET values as None.
2591 #
2592 # Refs:
2593 # https://github.com/pallets/click/issues/3136
2594 # https://github.com/pallets/click/pull/3137
2595 else:
2596 # Add another layer to the context stack to clearly hint that the
2597 # context is temporarily modified.
2598 with ctx:
2599 # Update the context parameters to replace UNSET with None.
2600 ctx.params.update(unset_keys)
2601 # Feed these fake context parameters to the callback.
2602 value = self.callback(ctx, self, value)
2603 # Restore the UNSET values in the context parameters.
2604 ctx.params.update(
2605 {
2606 k: UNSET
2607 for k in unset_keys
2608 # Only restore keys that are present and still None, in case
2609 # the callback modified other parameters.
2610 if k in ctx.params and ctx.params[k] is None
2611 }
2612 )
2614 return value
2616 def resolve_envvar_value(self, ctx: Context) -> str | None:
2617 """Returns the value found in the environment variable(s) attached to this
2618 parameter.
2620 Environment variables values are `always returned as strings
2621 <https://docs.python.org/3/library/os.html#os.environ>`_.
2623 This method returns ``None`` if:
2625 - the :attr:`envvar` property is not set on the :class:`Parameter`,
2626 - the environment variable is not found in the environment,
2627 - the variable is found in the environment but its value is empty (i.e. the
2628 environment variable is present but has an empty string).
2630 If :attr:`envvar` is setup with multiple environment variables,
2631 then only the first non-empty value is returned.
2633 .. caution::
2635 The raw value extracted from the environment is not normalized and is
2636 returned as-is. Any normalization or reconciliation is performed later by
2637 the :class:`Parameter`'s :attr:`type`.
2639 :meta private:
2640 """
2641 if not self.envvar:
2642 return None
2644 if isinstance(self.envvar, str):
2645 rv = os.environ.get(self.envvar)
2647 if rv:
2648 return rv
2649 else:
2650 for envvar in self.envvar:
2651 rv = os.environ.get(envvar)
2653 # Return the first non-empty value of the list of environment variables.
2654 if rv:
2655 return rv
2656 # Else, absence of value is interpreted as an environment variable that
2657 # is not set, so proceed to the next one.
2659 return None
2661 def value_from_envvar(self, ctx: Context) -> str | cabc.Sequence[str] | None:
2662 """Process the raw environment variable string for this parameter.
2664 Returns the string as-is or splits it into a sequence of strings if the
2665 parameter is expecting multiple values (i.e. its :attr:`nargs` property is set
2666 to a value other than ``1``).
2668 :meta private:
2669 """
2670 rv = self.resolve_envvar_value(ctx)
2672 if rv is not None and self.nargs != 1:
2673 return self.type.split_envvar_value(rv)
2675 return rv
2677 def handle_parse_result(
2678 self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str]
2679 ) -> tuple[t.Any, list[str]]:
2680 """Process the value produced by the parser from user input.
2682 Always process the value through the Parameter's :attr:`type`, wherever it
2683 comes from.
2685 If the parameter is deprecated, this method warn the user about it. But only if
2686 the value has been explicitly set by the user (and as such, is not coming from
2687 a default).
2689 :meta private:
2690 """
2691 # Capture the slot's existing state before we mutate
2692 # ``_parameter_source`` so the write decision below can compare our
2693 # incoming source against the source of the option that already wrote
2694 # the slot (if any).
2695 existing_value = ctx.params.get(self.name, UNSET)
2696 existing_source = ctx.get_parameter_source(self.name)
2697 existing_default_explicit = ctx._param_default_explicit.get(self.name, False)
2699 with augment_usage_errors(ctx, param=self):
2700 value, source = self.consume_value(ctx, opts)
2702 # Record the source before processing so eager callbacks and type
2703 # conversion can inspect it. Restored after arbitration if this
2704 # option loses a feature-switch group.
2705 ctx.set_parameter_source(self.name, source)
2707 # Display a deprecation warning if necessary.
2708 if (
2709 self.deprecated
2710 and value is not UNSET
2711 and source < ParameterSource.DEFAULT_MAP
2712 ):
2713 message = _(
2714 "DeprecationWarning: The {param_type} {name!r} is deprecated."
2715 "{extra_message}"
2716 ).format(
2717 param_type=self.param_type_name,
2718 name=self.human_readable_name,
2719 extra_message=_format_deprecated_suffix(self.deprecated),
2720 )
2721 echo(style(message, fg="red"), err=True)
2723 # Process the value through the parameter's type.
2724 try:
2725 value = self.process_value(ctx, value)
2726 except Exception:
2727 if not ctx.resilient_parsing:
2728 raise
2729 # In resilient parsing mode, we do not want to fail the command if the
2730 # value is incompatible with the parameter type, so we reset the value
2731 # to UNSET, which will be interpreted as a missing value.
2732 value = UNSET
2734 # Arbitrate the slot when several parameters target the same variable
2735 # name (feature-switch groups). See: https://github.com/pallets/click/issues/3403
2736 slot_empty = existing_value is UNSET
2737 more_explicit = existing_source is not None and source < existing_source
2738 same_source = existing_source is not None and source == existing_source
2739 auto_would_downgrade_explicit = (
2740 same_source
2741 and source == ParameterSource.DEFAULT
2742 and existing_default_explicit
2743 and not self._default_explicit
2744 )
2745 is_winner = (
2746 slot_empty
2747 or more_explicit
2748 or (same_source and not auto_would_downgrade_explicit)
2749 )
2751 if is_winner:
2752 if self.expose_value:
2753 ctx.params[self.name] = value
2754 ctx._param_default_explicit[self.name] = self._default_explicit
2755 elif existing_source is not None:
2756 # Lost arbitration; restore the winning option's source.
2757 ctx.set_parameter_source(self.name, existing_source)
2758 # else: ctx.params[self.name] was populated by code that bypassed
2759 # handle_parse_result (from another option's callback for example). Keep
2760 # the provisional source recorded before process_value so downstream
2761 # lookups don't return ``None``.
2763 return value, args
2765 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:
2766 return None
2768 def get_usage_pieces(self, ctx: Context) -> list[str]:
2769 return []
2771 def get_error_hint(self, ctx: Context | None) -> str:
2772 """Get a stringified version of the param for use in error messages to
2773 indicate which param caused the error.
2775 .. versionchanged:: 8.4.0
2776 ``ctx`` can be ``None``.
2777 """
2778 hint_list = self.opts or [self.human_readable_name]
2779 return " / ".join(f"'{x}'" for x in hint_list)
2781 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:
2782 """Return a list of completions for the incomplete value. If a
2783 ``shell_complete`` function was given during init, it is used.
2784 Otherwise, the :attr:`type`
2785 :meth:`~click.types.ParamType[t.Any].shell_complete` function is used.
2787 :param ctx: Invocation context for this command.
2788 :param incomplete: Value being completed. May be empty.
2790 .. versionadded:: 8.0
2791 """
2792 if self._custom_shell_complete is not None:
2793 results = self._custom_shell_complete(ctx, self, incomplete)
2795 if results and isinstance(results[0], str):
2796 from click.shell_completion import CompletionItem
2798 results = [CompletionItem(c) for c in results]
2800 return t.cast("list[CompletionItem]", results)
2802 return self.type.shell_complete(ctx, self, incomplete)
2805class Option(Parameter):
2806 """Options are usually optional values on the command line and
2807 have some extra features that arguments don't have.
2809 All other parameters are passed onwards to the parameter constructor.
2811 :param show_default: Show the default value for this option in its
2812 help text. Values are not shown by default, unless
2813 :attr:`Context.show_default` is ``True``. If this value is a
2814 string, it shows that string in parentheses instead of the
2815 actual value. This is particularly useful for dynamic options.
2816 For single option boolean flags, the default remains hidden if
2817 its value is ``False``.
2818 :param show_envvar: Controls if an environment variable should be
2819 shown on the help page and error messages.
2820 Normally, environment variables are not shown.
2821 :param prompt: If set to ``True`` or a non empty string then the
2822 user will be prompted for input. If set to ``True`` the prompt
2823 will be the option name capitalized. A deprecated option cannot be
2824 prompted.
2825 :param confirmation_prompt: Prompt a second time to confirm the
2826 value if it was prompted for. Can be set to a string instead of
2827 ``True`` to customize the message.
2828 :param prompt_required: If set to ``False``, the user will be
2829 prompted for input only when the option was specified as a flag
2830 without a value.
2831 :param hide_input: If this is ``True`` then the input on the prompt
2832 will be hidden from the user. This is useful for password input.
2833 :param is_flag: forces this option to act as a flag. The default is
2834 auto detection.
2835 :param flag_value: which value should be used for this flag if it's
2836 enabled. This is set to a boolean automatically if
2837 the option string contains a slash to mark two options.
2838 :param multiple: if this is set to `True` then the argument is accepted
2839 multiple times and recorded. This is similar to ``nargs``
2840 in how it works but supports arbitrary number of
2841 arguments.
2842 :param count: this flag makes an option increment an integer.
2843 :param allow_from_autoenv: if this is enabled then the value of this
2844 parameter will be pulled from an environment
2845 variable in case a prefix is defined on the
2846 context.
2847 :param help: the help string.
2848 :param hidden: hide this option from help outputs.
2849 :param attrs: Other command arguments described in :class:`Parameter`.
2851 .. versionchanged:: 8.4.0
2852 Non-basic ``flag_value`` types (not ``str``, ``int``, ``float``, or
2853 ``bool``) are passed through unchanged instead of being stringified.
2854 Previously, ``type=click.UNPROCESSED`` was required to preserve them.
2856 .. versionchanged:: 8.2
2857 ``envvar`` used with ``flag_value`` will always use the ``flag_value``,
2858 previously it would use the value of the environment variable.
2860 .. versionchanged:: 8.1
2861 Help text indentation is cleaned here instead of only in the
2862 ``@option`` decorator.
2864 .. versionchanged:: 8.1
2865 The ``show_default`` parameter overrides
2866 ``Context.show_default``.
2868 .. versionchanged:: 8.1
2869 The default of a single option boolean flag is not shown if the
2870 default value is ``False``.
2872 .. versionchanged:: 8.0.1
2873 ``type`` is detected from ``flag_value`` if given, for basic Python
2874 types (``str``, ``int``, ``float``, ``bool``).
2875 """
2877 param_type_name = "option"
2879 prompt: str | None
2880 confirmation_prompt: bool | str
2881 prompt_required: bool
2882 hide_input: bool
2883 hidden: bool
2885 _flag_needs_value: bool
2886 is_flag: bool
2887 is_bool_flag: bool
2888 flag_value: t.Any
2890 count: bool
2891 allow_from_autoenv: bool
2892 help: str | None
2893 show_default: bool | str | None
2894 show_choices: bool
2895 show_envvar: bool
2897 def __init__(
2898 self,
2899 param_decls: cabc.Sequence[str] | None = None,
2900 show_default: bool | str | None = None,
2901 prompt: bool | str = False,
2902 confirmation_prompt: bool | str = False,
2903 prompt_required: bool = True,
2904 hide_input: bool = False,
2905 is_flag: bool | None = None,
2906 flag_value: t.Any = UNSET,
2907 multiple: bool = False,
2908 count: bool = False,
2909 allow_from_autoenv: bool = True,
2910 type: types.ParamType[t.Any] | t.Any | None = None,
2911 help: str | None = None,
2912 hidden: bool = False,
2913 show_choices: bool = True,
2914 show_envvar: bool = False,
2915 deprecated: bool | str = False,
2916 **attrs: t.Any,
2917 ) -> None:
2918 if help:
2919 help = inspect.cleandoc(help)
2921 super().__init__(
2922 param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs
2923 )
2925 if prompt is True:
2926 if not self.name:
2927 raise TypeError("'name' is required with 'prompt=True'.")
2929 prompt_text = self.name.replace("_", " ").capitalize()
2930 elif prompt is False:
2931 prompt_text = None
2932 else:
2933 prompt_text = prompt
2935 if deprecated:
2936 label = _format_deprecated_label(deprecated)
2937 help = f"{help} {label}" if help else label
2939 self.prompt = prompt_text
2940 self.confirmation_prompt = confirmation_prompt
2941 self.prompt_required = prompt_required
2942 self.hide_input = hide_input
2943 self.hidden = hidden
2945 # The _flag_needs_value property tells the parser that this option is a flag
2946 # that cannot be used standalone and needs a value. With this information, the
2947 # parser can determine whether to consider the next user-provided argument in
2948 # the CLI as a value for this flag or as a new option.
2949 # If prompt is enabled but not required, then it opens the possibility for the
2950 # option to gets its value from the user.
2951 self._flag_needs_value = self.prompt is not None and not self.prompt_required
2953 # Auto-detect if this is a flag or not.
2954 if is_flag is None:
2955 # Implicitly a flag because flag_value was set.
2956 if flag_value is not UNSET:
2957 is_flag = True
2958 # Not a flag, but when used as a flag it shows a prompt.
2959 elif self._flag_needs_value:
2960 is_flag = False
2961 # Implicitly a flag because secondary options names were given.
2962 elif self.secondary_opts:
2963 is_flag = True
2965 # The option is explicitly not a flag, but to determine whether or not it needs
2966 # value, we need to check if `flag_value` or `default` was set. Either one is
2967 # sufficient.
2968 # Ref: https://github.com/pallets/click/issues/3084
2969 elif is_flag is False and not self._flag_needs_value:
2970 self._flag_needs_value = flag_value is not UNSET or self.default is UNSET
2972 if is_flag:
2973 # Set missing default for flags if not explicitly required or prompted.
2974 if self.default is UNSET and not self.required and not self.prompt:
2975 if multiple:
2976 self.default = ()
2978 # Auto-detect the type of the flag based on the flag_value.
2979 if type is None:
2980 # A flag without a flag_value is a boolean flag.
2981 if flag_value is UNSET:
2982 self.type: types.ParamType[t.Any] = types.BoolParamType()
2983 # If the flag value is a boolean, use BoolParamType.
2984 elif isinstance(flag_value, bool):
2985 self.type = types.BoolParamType()
2986 # Otherwise, guess the type from the flag value.
2987 else:
2988 guessed = types.convert_type(None, flag_value)
2989 if (
2990 isinstance(guessed, types.StringParamType)
2991 and not isinstance(flag_value, str)
2992 and flag_value is not None
2993 ):
2994 # The flag_value type couldn't be auto-detected
2995 # (not str, int, float, or bool). Since flag_value
2996 # is a programmer-provided Python object, not CLI
2997 # input, pass it through unchanged instead of
2998 # stringifying it.
2999 self.type = types.UNPROCESSED
3000 else:
3001 self.type = guessed
3003 self.is_flag = bool(is_flag)
3004 self.is_bool_flag = self.is_flag and isinstance(self.type, types.BoolParamType)
3005 self.flag_value = flag_value
3007 # Set boolean flag default to False if unset and not required.
3008 if self.is_bool_flag:
3009 if self.default is UNSET and not self.required:
3010 self.default = False
3012 # The alignment of default to the flag_value is resolved lazily in
3013 # get_default() to prevent callable flag_values (like classes) from
3014 # being instantiated. Refs:
3015 # https://github.com/pallets/click/issues/3121
3016 # https://github.com/pallets/click/issues/3024#issuecomment-3146199461
3017 # https://github.com/pallets/click/pull/3030/commits/06847da
3019 # Set the default flag_value if it is not set.
3020 if self.flag_value is UNSET:
3021 if self.is_flag:
3022 self.flag_value = True
3023 else:
3024 self.flag_value = None
3026 # Counting.
3027 self.count = count
3028 if count:
3029 if type is None:
3030 self.type = types.IntRange(min=0)
3031 if self.default is UNSET:
3032 self.default = 0
3034 self.allow_from_autoenv = allow_from_autoenv
3035 self.help = help
3036 self.show_default = show_default
3037 self.show_choices = show_choices
3038 self.show_envvar = show_envvar
3040 if __debug__:
3041 if deprecated and prompt:
3042 raise ValueError("`deprecated` options cannot use `prompt`.")
3044 if self.nargs == -1:
3045 raise TypeError("nargs=-1 is not supported for options.")
3047 if not self.is_bool_flag and self.secondary_opts:
3048 raise TypeError("Secondary flag is not valid for non-boolean flag.")
3050 if self.is_bool_flag and self.hide_input and self.prompt is not None:
3051 raise TypeError(
3052 "'prompt' with 'hide_input' is not valid for boolean flag."
3053 )
3055 if self.count:
3056 if self.multiple:
3057 raise TypeError("'count' is not valid with 'multiple'.")
3059 if self.is_flag:
3060 raise TypeError("'count' is not valid with 'is_flag'.")
3062 def to_info_dict(self) -> dict[str, t.Any]:
3063 """
3064 .. versionchanged:: 8.3.0
3065 Returns ``None`` for the :attr:`flag_value` if it was not set.
3066 """
3067 info_dict = super().to_info_dict()
3068 info_dict.update(
3069 help=self.help,
3070 prompt=self.prompt,
3071 is_flag=self.is_flag,
3072 # We explicitly hide the :attr:`UNSET` value to the user, as we choose to
3073 # make it an implementation detail. And because ``to_info_dict`` has been
3074 # designed for documentation purposes, we return ``None`` instead.
3075 flag_value=self.flag_value if self.flag_value is not UNSET else None,
3076 count=self.count,
3077 hidden=self.hidden,
3078 )
3079 return info_dict
3081 def get_default(
3082 self, ctx: Context, call: bool = True
3083 ) -> t.Any | t.Callable[[], t.Any] | None:
3084 """Return the default value for this option.
3086 For non-boolean flag options, ``default=True`` is treated as a sentinel
3087 meaning "activate this flag by default" and is resolved to
3088 :attr:`flag_value`. For example, with ``--upper/--lower`` feature
3089 switches where ``flag_value="upper"`` and ``default=True``, the default
3090 resolves to ``"upper"``.
3092 .. caution::
3093 This substitution only applies to non-boolean flags
3094 (:attr:`is_bool_flag` is ``False``). For boolean flags, ``True`` is
3095 a legitimate Python value and ``default=True`` is returned as-is.
3097 .. versionchanged:: 8.3.3
3098 ``default=True`` is no longer substituted with ``flag_value`` for
3099 boolean flags, fixing negative boolean flags like
3100 ``flag_value=False, default=True``.
3101 """
3102 value = super().get_default(ctx, call=False)
3104 # Resolve default=True to flag_value lazily (here instead of
3105 # __init__) to prevent callable flag_values (like classes) from
3106 # being instantiated by the callable check below.
3107 if value is True and self.is_flag and not self.is_bool_flag:
3108 value = self.flag_value
3109 elif call and callable(value):
3110 value = value()
3112 return value
3114 def get_error_hint(self, ctx: Context | None) -> str:
3115 result = super().get_error_hint(ctx)
3116 if self.show_envvar and self.envvar is not None:
3117 result += f" (env var: '{self.envvar}')"
3118 return result
3120 def _parse_decls(
3121 self, decls: cabc.Sequence[str], expose_value: bool
3122 ) -> tuple[str, list[str], list[str]]:
3123 opts = []
3124 secondary_opts = []
3125 name = None
3126 possible_names = []
3128 for decl in decls:
3129 if decl.isidentifier():
3130 if name is not None:
3131 raise TypeError(_("Name '{name}' defined twice").format(name=name))
3132 name = decl
3133 else:
3134 split_char = ";" if decl[:1] == "/" else "/"
3135 if split_char in decl:
3136 first, second = decl.split(split_char, 1)
3137 first = first.rstrip()
3138 if first:
3139 possible_names.append(_split_opt(first))
3140 opts.append(first)
3141 second = second.lstrip()
3142 if second:
3143 secondary_opts.append(second.lstrip())
3144 if first == second:
3145 raise ValueError(
3146 _(
3147 "Boolean option {decl!r} cannot use the"
3148 " same flag for true/false."
3149 ).format(decl=decl)
3150 )
3151 else:
3152 possible_names.append(_split_opt(decl))
3153 opts.append(decl)
3155 if name is None and possible_names:
3156 possible_names.sort(key=lambda x: -len(x[0])) # group long options first
3157 name = possible_names[0][1].replace("-", "_").lower()
3158 if not name.isidentifier():
3159 name = None
3161 if name is None:
3162 if not expose_value:
3163 return "", opts, secondary_opts
3164 raise TypeError(
3165 _(
3166 "Could not determine name for option with declarations {decls!r}"
3167 ).format(decls=decls)
3168 )
3170 if not opts and not secondary_opts:
3171 raise TypeError(
3172 _(
3173 "No options defined but a name was passed ({name})."
3174 " Did you mean to declare an argument instead? Did"
3175 " you mean to pass '--{name}'?"
3176 ).format(name=name)
3177 )
3179 return name, opts, secondary_opts
3181 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:
3182 if self.multiple:
3183 action = "append"
3184 elif self.count:
3185 action = "count"
3186 else:
3187 action = "store"
3189 if self.is_flag:
3190 action = f"{action}_const"
3192 if self.is_bool_flag and self.secondary_opts:
3193 parser.add_option(
3194 obj=self, opts=self.opts, dest=self.name, action=action, const=True
3195 )
3196 parser.add_option(
3197 obj=self,
3198 opts=self.secondary_opts,
3199 dest=self.name,
3200 action=action,
3201 const=False,
3202 )
3203 else:
3204 parser.add_option(
3205 obj=self,
3206 opts=self.opts,
3207 dest=self.name,
3208 action=action,
3209 const=self.flag_value,
3210 )
3211 else:
3212 parser.add_option(
3213 obj=self,
3214 opts=self.opts,
3215 dest=self.name,
3216 action=action,
3217 nargs=self.nargs,
3218 )
3220 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:
3221 if self.hidden:
3222 return None
3224 any_prefix_is_slash = False
3226 def _write_opts(opts: cabc.Sequence[str]) -> str:
3227 nonlocal any_prefix_is_slash
3229 rv, any_slashes = join_options(opts)
3231 if any_slashes:
3232 any_prefix_is_slash = True
3234 if not self.is_flag and not self.count:
3235 rv += f" {self.make_metavar(ctx=ctx)}"
3237 return rv
3239 rv = [_write_opts(self.opts)]
3241 if self.secondary_opts:
3242 rv.append(_write_opts(self.secondary_opts))
3244 help = self.help or ""
3246 extra = self.get_help_extra(ctx)
3247 extra_items = []
3248 if "envvars" in extra:
3249 extra_items.append(
3250 _("env var: {var}").format(var=", ".join(extra["envvars"]))
3251 )
3252 if "default" in extra:
3253 extra_items.append(_("default: {default}").format(default=extra["default"]))
3254 if "range" in extra:
3255 extra_items.append(extra["range"])
3256 if "required" in extra:
3257 extra_items.append(_(extra["required"]))
3259 if extra_items:
3260 extra_str = "; ".join(extra_items)
3261 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"
3263 return ("; " if any_prefix_is_slash else " / ").join(rv), help
3265 def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra:
3266 extra: types.OptionHelpExtra = {}
3268 if self.show_envvar:
3269 envvar = self.envvar
3271 if envvar is None:
3272 if (
3273 self.allow_from_autoenv
3274 and ctx.auto_envvar_prefix is not None
3275 and self.name
3276 ):
3277 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
3279 if envvar is not None:
3280 if isinstance(envvar, str):
3281 extra["envvars"] = (envvar,)
3282 else:
3283 extra["envvars"] = tuple(str(d) for d in envvar)
3285 # Temporarily enable resilient parsing to avoid type casting
3286 # failing for the default. Might be possible to extend this to
3287 # help formatting in general.
3288 resilient = ctx.resilient_parsing
3289 ctx.resilient_parsing = True
3291 try:
3292 default_value = self.get_default(ctx, call=False)
3293 finally:
3294 ctx.resilient_parsing = resilient
3296 show_default = False
3297 show_default_is_str = False
3299 if self.show_default is not None:
3300 if isinstance(self.show_default, str):
3301 show_default_is_str = show_default = True
3302 else:
3303 show_default = self.show_default
3304 elif ctx.show_default is not None:
3305 show_default = ctx.show_default
3307 if show_default_is_str or (
3308 show_default and (default_value not in (None, UNSET))
3309 ):
3310 if show_default_is_str:
3311 default_string = f"({self.show_default})"
3312 elif isinstance(default_value, (list, tuple)):
3313 default_string = ", ".join(str(d) for d in default_value)
3314 elif isinstance(default_value, enum.Enum):
3315 default_string = default_value.name
3316 elif inspect.isfunction(default_value):
3317 default_string = _("(dynamic)")
3318 elif self.is_bool_flag and self.secondary_opts:
3319 # For boolean flags that have distinct True/False opts,
3320 # use the opt without prefix instead of the value.
3321 default_string = _split_opt(
3322 (self.opts if default_value else self.secondary_opts)[0]
3323 )[1]
3324 elif self.is_bool_flag and not self.secondary_opts and not default_value:
3325 default_string = ""
3326 elif isinstance(default_value, str) and default_value == "":
3327 default_string = '""'
3328 else:
3329 default_string = str(default_value)
3331 if default_string:
3332 extra["default"] = default_string
3334 if (
3335 isinstance(self.type, types._NumberRangeBase)
3336 # skip count with default range type
3337 and not (self.count and self.type.min == 0 and self.type.max is None)
3338 ):
3339 range_str = self.type._describe_range()
3341 if range_str:
3342 extra["range"] = range_str
3344 if self.required:
3345 extra["required"] = "required"
3347 return extra
3349 def prompt_for_value(self, ctx: Context) -> t.Any:
3350 """This is an alternative flow that can be activated in the full
3351 value processing if a value does not exist. It will prompt the
3352 user until a valid value exists and then returns the processed
3353 value as result.
3354 """
3355 assert self.prompt is not None
3357 # Calculate the default before prompting anything to lock in the value before
3358 # attempting any user interaction.
3359 default = self.get_default(ctx)
3361 # A boolean flag can use a simplified [y/n] confirmation prompt.
3362 if self.is_bool_flag:
3363 # If we have no boolean default, we force the user to explicitly provide
3364 # one.
3365 if default in (UNSET, None):
3366 default = None
3367 # Nothing prevent you to declare an option that is simultaneously:
3368 # 1) auto-detected as a boolean flag,
3369 # 2) allowed to prompt, and
3370 # 3) still declare a non-boolean default.
3371 # This forced casting into a boolean is necessary to align any non-boolean
3372 # default to the prompt, which is going to be a [y/n]-style confirmation
3373 # because the option is still a boolean flag. That way, instead of [y/n],
3374 # we get [Y/n] or [y/N] depending on the truthy value of the default.
3375 # Refs: https://github.com/pallets/click/pull/3030#discussion_r2289180249
3376 else:
3377 default = bool(default)
3378 return confirm(self.prompt, default)
3380 # If show_default is given, provide this to `prompt` as well,
3381 # otherwise we use `prompt`'s default behavior
3382 prompt_kwargs: t.Any = {}
3383 if self.show_default is not None:
3384 prompt_kwargs["show_default"] = self.show_default
3386 return prompt(
3387 self.prompt,
3388 # Use ``None`` to inform the prompt() function to reiterate until a valid
3389 # value is provided by the user if we have no default.
3390 default=None if default is UNSET else default,
3391 type=self.type,
3392 hide_input=self.hide_input,
3393 show_choices=self.show_choices,
3394 confirmation_prompt=self.confirmation_prompt,
3395 value_proc=lambda x: self.process_value(ctx, x),
3396 **prompt_kwargs,
3397 )
3399 def resolve_envvar_value(self, ctx: Context) -> str | None:
3400 """:class:`Option` resolves its environment variable the same way as
3401 :func:`Parameter.resolve_envvar_value`, but it also supports
3402 :attr:`Context.auto_envvar_prefix`. If we could not find an environment from
3403 the :attr:`envvar` property, we fallback on :attr:`Context.auto_envvar_prefix`
3404 to build dynamiccaly the environment variable name using the
3405 :python:`{ctx.auto_envvar_prefix}_{self.name.upper()}` template.
3407 :meta private:
3408 """
3409 rv = super().resolve_envvar_value(ctx)
3411 if rv is not None:
3412 return rv
3414 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None and self.name:
3415 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
3416 rv = os.environ.get(envvar)
3418 if rv:
3419 return rv
3421 return None
3423 def value_from_envvar(self, ctx: Context) -> t.Any:
3424 """For :class:`Option`, this method processes the raw environment variable
3425 string the same way as :func:`Parameter.value_from_envvar` does.
3427 But in the case of non-boolean flags, the value is analyzed to determine if the
3428 flag is activated or not, and returns a boolean of its activation, or the
3429 :attr:`flag_value` if the latter is set.
3431 This method also takes care of repeated options (i.e. options with
3432 :attr:`multiple` set to ``True``).
3434 :meta private:
3435 """
3436 rv = self.resolve_envvar_value(ctx)
3438 # Absent environment variable or an empty string is interpreted as unset.
3439 if rv is None:
3440 return None
3442 # Non-boolean flags are more liberal in what they accept. But a flag being a
3443 # flag, its envvar value still needs to be analyzed to determine if the flag is
3444 # activated or not.
3445 if self.is_flag and not self.is_bool_flag:
3446 # If the flag_value is set and match the envvar value, return it
3447 # directly.
3448 if self.flag_value is not UNSET and rv == self.flag_value:
3449 return self.flag_value
3450 # Analyze the envvar value as a boolean to know if the flag is
3451 # activated or not.
3452 return types.BoolParamType.str_to_bool(rv)
3454 # Split the envvar value if it is allowed to be repeated.
3455 value_depth = (self.nargs != 1) + bool(self.multiple)
3456 if value_depth > 0:
3457 multi_rv = self.type.split_envvar_value(rv)
3458 if self.multiple and self.nargs != 1:
3459 multi_rv = batch(multi_rv, self.nargs) # type: ignore[assignment]
3461 return multi_rv
3463 return rv
3465 def consume_value(
3466 self, ctx: Context, opts: cabc.Mapping[str, Parameter]
3467 ) -> tuple[t.Any, ParameterSource]:
3468 """For :class:`Option`, the value can be collected from an interactive prompt
3469 if the option is a flag that needs a value (and the :attr:`prompt` property is
3470 set).
3472 Additionally, this method handles flag option that are activated without a
3473 value, in which case the :attr:`flag_value` is returned.
3475 :meta private:
3476 """
3477 value, source = super().consume_value(ctx, opts)
3479 # The parser will emit a sentinel value if the option is allowed to as a flag
3480 # without a value.
3481 if value is FLAG_NEEDS_VALUE:
3482 # If the option allows for a prompt, we start an interaction with the user.
3483 if self.prompt is not None and not ctx.resilient_parsing:
3484 value = self.prompt_for_value(ctx)
3485 source = ParameterSource.PROMPT
3486 # Else the flag takes its flag_value as value.
3487 else:
3488 value = self.flag_value
3489 source = ParameterSource.COMMANDLINE
3491 # A flag which is activated always returns the flag value, unless the value
3492 # comes from the explicitly sets default.
3493 elif (
3494 self.is_flag
3495 and value is True
3496 and not self.is_bool_flag
3497 and source < ParameterSource.DEFAULT_MAP
3498 ):
3499 value = self.flag_value
3501 # Re-interpret a multiple option which has been sent as-is by the parser.
3502 # Here we replace each occurrence of value-less flags (marked by the
3503 # FLAG_NEEDS_VALUE sentinel) with the flag_value.
3504 elif (
3505 self.multiple
3506 and value is not UNSET
3507 and isinstance(value, cabc.Iterable)
3508 and source < ParameterSource.DEFAULT_MAP
3509 and any(v is FLAG_NEEDS_VALUE for v in value)
3510 ):
3511 value = [self.flag_value if v is FLAG_NEEDS_VALUE else v for v in value]
3512 source = ParameterSource.COMMANDLINE
3514 # The value wasn't set, or used the param's default, prompt for one to the user
3515 # if prompting is enabled.
3516 elif (
3517 (value is UNSET or source >= ParameterSource.DEFAULT_MAP)
3518 and self.prompt is not None
3519 and (self.required or self.prompt_required)
3520 and not ctx.resilient_parsing
3521 ):
3522 value = self.prompt_for_value(ctx)
3523 source = ParameterSource.PROMPT
3525 return value, source
3527 def process_value(self, ctx: Context, value: t.Any) -> t.Any:
3528 # process_value has to be overridden on Options in order to capture
3529 # `value == UNSET` cases before `type_cast_value()` gets called.
3530 #
3531 # Refs:
3532 # https://github.com/pallets/click/issues/3069
3533 if self.is_flag and not self.required and self.is_bool_flag and value is UNSET:
3534 value = False
3536 if self.callback is not None:
3537 value = self.callback(ctx, self, value)
3539 return value
3541 # in the normal case, rely on Parameter.process_value
3542 return super().process_value(ctx, value)
3545class Argument(Parameter):
3546 """Arguments are positional parameters to a command. They generally
3547 provide fewer features than options but can have infinite ``nargs``
3548 and are required by default.
3550 All parameters are passed onwards to the constructor of :class:`Parameter`.
3552 :param help: the help string.
3554 .. versionchanged:: 8.5
3555 Added the ``help`` parameter.
3556 """
3558 param_type_name = "argument"
3560 def __init__(
3561 self,
3562 param_decls: cabc.Sequence[str],
3563 required: bool | None = None,
3564 help: str | None = None,
3565 **attrs: t.Any,
3566 ) -> None:
3567 # Auto-detect the requirement status of the argument if not explicitly set.
3568 if required is None:
3569 # The argument gets automatically required if it has no explicit default
3570 # value set and is setup to match at least one value.
3571 if attrs.get("default", UNSET) is UNSET:
3572 required = attrs.get("nargs", 1) > 0
3573 # If the argument has a default value, it is not required.
3574 else:
3575 required = False
3577 if "multiple" in attrs:
3578 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.")
3580 deprecated = attrs.get("deprecated", False)
3582 if help:
3583 help = inspect.cleandoc(help)
3585 if deprecated:
3586 label = _format_deprecated_label(deprecated)
3587 help = f"{help} {label}" if help else label
3589 self.help = help
3591 super().__init__(param_decls, required=required, **attrs)
3593 def to_info_dict(self) -> dict[str, t.Any]:
3594 info_dict = super().to_info_dict()
3595 info_dict.update(help=self.help)
3596 return info_dict
3598 @property
3599 def human_readable_name(self) -> str:
3600 if self.metavar is not None:
3601 return self.metavar
3602 return self.name.upper()
3604 def make_metavar(self, ctx: Context) -> str:
3605 if self.metavar is not None:
3606 return self.metavar
3607 var = self.type.get_metavar(param=self, ctx=ctx)
3608 if not var:
3609 var = self.name.upper()
3610 if self.deprecated:
3611 var += "!"
3612 if not self.required:
3613 var = f"[{var}]"
3614 if self.nargs != 1:
3615 var += "..."
3616 return var
3618 def _parse_decls(
3619 self, decls: cabc.Sequence[str], expose_value: bool
3620 ) -> tuple[str, list[str], list[str]]:
3621 if not decls:
3622 if not expose_value:
3623 return "", [], []
3624 raise TypeError("Argument is marked as exposed, but does not have a name.")
3625 if len(decls) == 1:
3626 name = arg = decls[0]
3627 name = name.replace("-", "_").lower()
3628 else:
3629 raise TypeError(
3630 _(
3631 "Arguments take exactly one parameter declaration, got"
3632 " {length}: {decls}."
3633 ).format(length=len(decls), decls=decls)
3634 )
3635 return name, [arg], []
3637 def get_usage_pieces(self, ctx: Context) -> list[str]:
3638 return [self.make_metavar(ctx)]
3640 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:
3641 if self.help is None:
3642 return None
3644 return self.make_metavar(ctx), self.help
3646 def get_error_hint(self, ctx: Context | None) -> str:
3647 if ctx is not None:
3648 return f"'{self.make_metavar(ctx)}'"
3649 return f"'{self.human_readable_name}'"
3651 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:
3652 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)
3655def __getattr__(name: str) -> object:
3656 import warnings
3658 if name == "BaseCommand":
3659 warnings.warn(
3660 "'BaseCommand' is deprecated and will be removed in Click 9.0. Use"
3661 " 'Command' instead.",
3662 DeprecationWarning,
3663 stacklevel=2,
3664 )
3665 return _BaseCommand
3667 if name == "MultiCommand":
3668 warnings.warn(
3669 "'MultiCommand' is deprecated and will be removed in Click 9.0. Use"
3670 " 'Group' instead.",
3671 DeprecationWarning,
3672 stacklevel=2,
3673 )
3674 return _MultiCommand
3676 raise AttributeError(name)