Skip to content
Myr

core.py

This file

Path

src/click/core.py

3,827 lines · 145.3 KiB · Python

Last changed by

Fix race condition on `KeyboardInterrupt` in `Command.main()` (#3818)Rowlando13before adoption00f257b

History of this file

Take it

1from __future__ import annotations23import collections.abc as cabc4import enum5import errno6import inspect7import os8import sys9import typing as t10from abc import ABC11from abc import abstractmethod12from collections import abc13from collections import Counter14from contextlib import AbstractContextManager15from contextlib import contextmanager16from contextlib import ExitStack17from functools import update_wrapper18from gettext import gettext as _19from gettext import ngettext20from itertools import repeat21from types import TracebackType2223from . import types24from ._utils import FLAG_NEEDS_VALUE25from ._utils import UNSET26from .exceptions import Abort27from .exceptions import BadParameter28from .exceptions import ClickException29from .exceptions import Exit30from .exceptions import MissingParameter31from .exceptions import NoArgsIsHelpError32from .exceptions import NoSuchCommand33from .exceptions import UsageError34from .formatting import HelpFormatter35from .formatting import join_options36from .globals import pop_context37from .globals import push_context38from .parser import _OptionParser39from .parser import _split_opt40from .termui import confirm41from .termui import prompt42from .termui import style43from .utils import _detect_program_name44from .utils import _expand_args45from .utils import _make_default_short_help46from .utils import _PacifyFlushWrapper47from .utils import echo48from .utils import make_str4950if t.TYPE_CHECKING:51    from typing_extensions import Self5253    from .shell_completion import CompletionItem5455F = t.TypeVar("F", bound="t.Callable[..., t.Any]")56V = t.TypeVar("V")5758# Reserved storage name of the automatic help option. No user parameter is59# expected to claim it.60_HELP_OPTION_STORAGE_NAME = "_click_default_help"616263def _complete_visible_commands(64    ctx: Context, incomplete: str65) -> cabc.Iterator[tuple[str, Command]]:66    """List all the subcommands of a group that start with the67    incomplete value and aren't hidden.6869    :param ctx: Invocation context for the group.70    :param incomplete: Value being completed. May be empty.71    """72    multi = t.cast(Group, ctx.command)7374    for name in multi.list_commands(ctx):75        if name.startswith(incomplete):76            command = multi.get_command(ctx, name)7778            if command is not None and not command.hidden:79                yield name, command808182def _check_nested_chain(83    base_command: Group, cmd_name: str, cmd: Command, register: bool = False84) -> None:85    if not base_command.chain or not isinstance(cmd, Group):86        return8788    if register:89        message = (90            f"It is not possible to add the group {cmd_name!r} to another"91            f" group {base_command.name!r} that is in chain mode."92        )93    else:94        message = (95            f"Found the group {cmd_name!r} as subcommand to another group "96            f" {base_command.name!r} that is in chain mode. This is not supported."97        )9899    raise RuntimeError(message)100101102def _echo_aborted() -> None:103    """Write the final abort message to standard error."""104    echo(_("Aborted!"), file=sys.stderr)105106107def _format_deprecated_label(deprecated: bool | str) -> str:108    """Return the parenthesized deprecation label shown in help text."""109    label = _("deprecated").upper()110    if isinstance(deprecated, str):111        return f"({label}: {deprecated})"112    return f"({label})"113114115def _format_deprecated_suffix(deprecated: bool | str) -> str:116    """Return the trailing reason for a ``DeprecationWarning`` message,117    prefixed with a space, or an empty string when no reason was given.118    """119    if isinstance(deprecated, str):120        return f" {deprecated}"121    return ""122123124def batch(iterable: cabc.Iterable[V], batch_size: int) -> list[tuple[V, ...]]:125    return list(zip(*repeat(iter(iterable), batch_size), strict=False))126127128@contextmanager129def augment_usage_errors(130    ctx: Context, param: Parameter | None = None131) -> cabc.Generator[None]:132    """Context manager that attaches extra information to exceptions."""133    try:134        yield135    except BadParameter as e:136        if e.ctx is None:137            e.ctx = ctx138        if param is not None and e.param is None:139            e.param = param140        raise141    except UsageError as e:142        if e.ctx is None:143            e.ctx = ctx144        raise145146147def iter_params_for_processing(148    invocation_order: cabc.Sequence[Parameter],149    declaration_order: cabc.Sequence[Parameter],150) -> list[Parameter]:151    """Returns all declared parameters in the order they should be processed.152153    The declared parameters are re-shuffled depending on the order in which154    they were invoked, as well as the eagerness of each parameters.155156    The invocation order takes precedence over the declaration order. I.e. the157    order in which the user provided them to the CLI is respected.158159    This behavior and its effect on callback evaluation is detailed at:160    https://click.palletsprojects.com/en/stable/advanced/#callback-evaluation-order161    """162163    def sort_key(item: Parameter) -> tuple[bool, float]:164        try:165            idx: float = invocation_order.index(item)166        except ValueError:167            idx = float("inf")168169        return not item.is_eager, idx170171    return sorted(declaration_order, key=sort_key)172173174class ParameterSource(enum.IntEnum):175    """This is an :class:`~enum.IntEnum` that indicates the source of a176    parameter's value.177178    Use :meth:`click.Context.get_parameter_source` to get the179    source for a parameter by name.180181    Members are ordered from most explicit to least explicit source.182    This allows comparison to check if a value was explicitly provided:183184    .. code-block:: python185186        source = ctx.get_parameter_source("port")187        if source < click.ParameterSource.DEFAULT_MAP:188            ...  # value was explicitly set189190    .. versionchanged:: 8.3.3191        Use :class:`~enum.IntEnum` and reorder members from most to192        least explicit. Supports comparison operators.193194    .. versionchanged:: 8.0195        Use :class:`~enum.Enum` and drop the ``validate`` method.196197    .. versionchanged:: 8.0198        Added the ``PROMPT`` value.199    """200201    PROMPT = enum.auto()202    """Used a prompt to confirm a default or provide a value."""203    COMMANDLINE = enum.auto()204    """The value was provided by the command line args."""205    ENVIRONMENT = enum.auto()206    """The value was provided with an environment variable."""207    DEFAULT_MAP = enum.auto()208    """Used a default provided by :attr:`Context.default_map`."""209    DEFAULT = enum.auto()210    """Used the default specified by the parameter."""211212213class Context:214    """The context is a special internal object that holds state relevant215    for the script execution at every single level.  It's normally invisible216    to commands unless they opt-in to getting access to it.217218    The context is useful as it can pass internal objects around and can219    control special execution features such as reading data from220    environment variables.221222    A context can be used as context manager in which case it will call223    :meth:`close` on teardown.224225    :param command: the command class for this context.226    :param parent: the parent context.227    :param info_name: the info name for this invocation.  Generally this228                      is the most descriptive name for the script or229                      command.  For the toplevel script it is usually230                      the name of the script, for commands below that it's231                      the name of the script.232    :param obj: an arbitrary object of user data.233    :param auto_envvar_prefix: the prefix to use for automatic environment234                               variables.  If this is `None` then reading235                               from environment variables is disabled.  This236                               does not affect manually set environment237                               variables which are always read.238    :param default_map: a dictionary (like object) with default values239                        for parameters.240    :param terminal_width: the width of the terminal.  The default is241                           inherit from parent context.  If no context242                           defines the terminal width then auto243                           detection will be applied.244    :param max_content_width: the maximum width for content rendered by245                              Click (this currently only affects help246                              pages).  This defaults to 80 characters if247                              not overridden.  In other words: even if the248                              terminal is larger than that, Click will not249                              format things wider than 80 characters by250                              default.  In addition to that, formatters might251                              add some safety mapping on the right.252    :param resilient_parsing: if this flag is enabled then Click will253                              parse without any interactivity or callback254                              invocation.  Default values will also be255                              ignored.  This is useful for implementing256                              things such as completion support.257    :param allow_extra_args: if this is set to `True` then extra arguments258                             at the end will not raise an error and will be259                             kept on the context.  The default is to inherit260                             from the command.261    :param allow_interspersed_args: if this is set to `False` then options262                                    and arguments cannot be mixed.  The263                                    default is to inherit from the command.264    :param ignore_unknown_options: instructs click to ignore options it does265                                   not know and keeps them for later266                                   processing.267    :param help_option_names: optionally a list of strings that define how268                              the default help parameter is named.  The269                              default is ``['--help']``.270    :param token_normalize_func: an optional function that is used to271                                 normalize tokens (options, choices,272                                 etc.).  This for instance can be used to273                                 implement case insensitive behavior.274    :param color: controls if the terminal supports ANSI colors or not.  The275                  default is autodetection.  This is only needed if ANSI276                  codes are used in texts that Click prints which is by277                  default not the case.  This for instance would affect278                  help output.279    :param show_default: Show the default value for commands. If this280        value is not set, it defaults to the value from the parent281        context. ``Command.show_default`` overrides this default for the282        specific command.283284    .. versionchanged:: 8.2285        The ``protected_args`` attribute is deprecated and will be removed in286        Click 9.0. ``args`` will contain remaining unparsed tokens.287288    .. versionchanged:: 8.1289        The ``show_default`` parameter is overridden by290        ``Command.show_default``, instead of the other way around.291292    .. versionchanged:: 8.0293        The ``show_default`` parameter defaults to the value from the294        parent context.295296    .. versionchanged:: 7.1297       Added the ``show_default`` parameter.298299    .. versionchanged:: 4.0300        Added the ``color``, ``ignore_unknown_options``, and301        ``max_content_width`` parameters.302303    .. versionchanged:: 3.0304        Added the ``allow_extra_args`` and ``allow_interspersed_args``305        parameters.306307    .. versionchanged:: 2.0308        Added the ``resilient_parsing``, ``help_option_names``, and309        ``token_normalize_func`` parameters.310    """311312    #: The formatter class to create with :meth:`make_formatter`.313    #:314    #: .. versionadded:: 8.0315    formatter_class: type[HelpFormatter] = HelpFormatter316317    parent: Context | None318    command: Command319    info_name: str | None320    params: dict[str, t.Any]321    args: list[str]322    _protected_args: list[str]323    _opt_prefixes: set[str]324    obj: t.Any325    _meta: dict[str, t.Any]326    default_map: cabc.MutableMapping[str, t.Any] | None327    invoked_subcommand: str | None328    terminal_width: int | None329    max_content_width: int | None330    allow_extra_args: bool331    allow_interspersed_args: bool332    ignore_unknown_options: bool333    help_option_names: list[str]334    token_normalize_func: t.Callable[[str], str] | None335    resilient_parsing: bool336    auto_envvar_prefix: str | None337    color: bool | None338    show_default: bool | None339    _close_callbacks: list[t.Callable[[], t.Any]]340    _depth: int341    _parameter_source: dict[str, ParameterSource]342    _param_default_explicit: dict[str, bool]343    _exit_stack: ExitStack344345    def __init__(346        self,347        command: Command,348        parent: Context | None = None,349        info_name: str | None = None,350        obj: t.Any | None = None,351        auto_envvar_prefix: str | None = None,352        default_map: cabc.MutableMapping[str, t.Any] | None = None,353        terminal_width: int | None = None,354        max_content_width: int | None = None,355        resilient_parsing: bool = False,356        allow_extra_args: bool | None = None,357        allow_interspersed_args: bool | None = None,358        ignore_unknown_options: bool | None = None,359        help_option_names: list[str] | None = None,360        token_normalize_func: t.Callable[[str], str] | None = None,361        color: bool | None = None,362        show_default: bool | None = None,363    ) -> None:364        #: the parent context or `None` if none exists.365        self.parent = parent366        #: the :class:`Command` for this context.367        self.command = command368        #: the descriptive information name369        self.info_name = info_name370        #: Map of parameter names to their parsed values. Parameters371        #: with ``expose_value=False`` are not stored.372        self.params = {}373        #: the leftover arguments.374        self.args = []375        #: protected arguments.  These are arguments that are prepended376        #: to `args` when certain parsing scenarios are encountered but377        #: must be never propagated to another arguments.  This is used378        #: to implement nested parsing.379        self._protected_args = []380        #: the collected prefixes of the command's options.381        self._opt_prefixes = set(parent._opt_prefixes) if parent else set()382383        if obj is None and parent is not None:384            obj = parent.obj385386        #: the user object stored.387        self.obj = obj388        self._meta = getattr(parent, "meta", {})389390        #: A dictionary (-like object) with defaults for parameters.391        if (392            default_map is None393            and info_name is not None394            and parent is not None395            and parent.default_map is not None396        ):397            default_map = parent.default_map.get(info_name)398399        self.default_map = default_map400401        #: This flag indicates if a subcommand is going to be executed. A402        #: group callback can use this information to figure out if it's403        #: being executed directly or because the execution flow passes404        #: onwards to a subcommand. By default it's None, but it can be405        #: the name of the subcommand to execute.406        #:407        #: If chaining is enabled this will be set to ``'*'`` in case408        #: any commands are executed.  It is however not possible to409        #: figure out which ones.  If you require this knowledge you410        #: should use a :func:`result_callback`.411        self.invoked_subcommand = None412413        if terminal_width is None and parent is not None:414            terminal_width = parent.terminal_width415416        #: The width of the terminal (None is autodetection).417        self.terminal_width = terminal_width418419        if max_content_width is None and parent is not None:420            max_content_width = parent.max_content_width421422        #: The maximum width of formatted content (None implies a sensible423        #: default which is 80 for most things).424        self.max_content_width = max_content_width425426        if allow_extra_args is None:427            allow_extra_args = command.allow_extra_args428429        #: Indicates if the context allows extra args or if it should430        #: fail on parsing.431        #:432        #: .. versionadded:: 3.0433        self.allow_extra_args = allow_extra_args434435        if allow_interspersed_args is None:436            allow_interspersed_args = command.allow_interspersed_args437438        #: Indicates if the context allows mixing of arguments and439        #: options or not.440        #:441        #: .. versionadded:: 3.0442        self.allow_interspersed_args = allow_interspersed_args443444        if ignore_unknown_options is None:445            ignore_unknown_options = command.ignore_unknown_options446447        #: Instructs click to ignore options that a command does not448        #: understand and will store it on the context for later449        #: processing.  This is primarily useful for situations where you450        #: want to call into external programs.  Generally this pattern is451        #: strongly discouraged because it's not possibly to losslessly452        #: forward all arguments.453        #:454        #: .. versionadded:: 4.0455        self.ignore_unknown_options = ignore_unknown_options456457        if help_option_names is None:458            if parent is not None:459                help_option_names = parent.help_option_names460            else:461                help_option_names = ["--help"]462463        #: The names for the help options.464        self.help_option_names = help_option_names465466        if token_normalize_func is None and parent is not None:467            token_normalize_func = parent.token_normalize_func468469        #: An optional normalization function for tokens.  This is470        #: options, choices, commands etc.471        self.token_normalize_func = token_normalize_func472473        #: Indicates if resilient parsing is enabled.  In that case Click474        #: will do its best to not cause any failures and default values475        #: will be ignored. Useful for completion.476        self.resilient_parsing = resilient_parsing477478        # If there is no envvar prefix yet, but the parent has one and479        # the command on this level has a name, we can expand the envvar480        # prefix automatically.481        if auto_envvar_prefix is None:482            if (483                parent is not None484                and parent.auto_envvar_prefix is not None485                and self.info_name is not None486            ):487                auto_envvar_prefix = (488                    f"{parent.auto_envvar_prefix}_{self.info_name.upper()}"489                )490        else:491            auto_envvar_prefix = auto_envvar_prefix.upper()492493        if auto_envvar_prefix is not None:494            auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")495496        self.auto_envvar_prefix = auto_envvar_prefix497498        if color is None and parent is not None:499            color = parent.color500501        #: Controls if styling output is wanted or not.502        self.color = color503504        if show_default is None and parent is not None:505            show_default = parent.show_default506507        #: Show option default values when formatting help text.508        self.show_default = show_default509510        self._close_callbacks = []511        self._depth = 0512        self._parameter_source = {}513        # Tracks whether the option that currently owns each parameter slot in514        # :attr:`params` had its ``default`` set explicitly by the user. Used515        # to tie-break feature-switch groups where multiple options share a516        # parameter name and both fall back to their default value.517        # Refs: https://github.com/pallets/click/issues/3403518        self._param_default_explicit = {}519        self._exit_stack = ExitStack()520521    @property522    def protected_args(self) -> list[str]:523        import warnings524525        warnings.warn(526            "'protected_args' is deprecated and will be removed in Click 9.0."527            " 'args' will contain remaining unparsed tokens.",528            DeprecationWarning,529            stacklevel=2,530        )531        return self._protected_args532533    def to_info_dict(self) -> dict[str, t.Any]:534        """Gather information that could be useful for a tool generating535        user-facing documentation. This traverses the entire CLI536        structure.537538        .. code-block:: python539540            with Context(cli) as ctx:541                info = ctx.to_info_dict()542543        .. versionadded:: 8.0544        """545        return {546            "command": self.command.to_info_dict(self),547            "info_name": self.info_name,548            "allow_extra_args": self.allow_extra_args,549            "allow_interspersed_args": self.allow_interspersed_args,550            "ignore_unknown_options": self.ignore_unknown_options,551            "auto_envvar_prefix": self.auto_envvar_prefix,552        }553554    def __enter__(self) -> Self:555        self._depth += 1556        push_context(self)557        return self558559    def __exit__(560        self,561        exc_type: type[BaseException] | None,562        exc_value: BaseException | None,563        tb: TracebackType | None,564    ) -> bool | None:565        self._depth -= 1566        exit_result: bool | None = None567        if self._depth == 0:568            exit_result = self._close_with_exception_info(exc_type, exc_value, tb)569        pop_context()570571        return exit_result572573    @contextmanager574    def scope(self, cleanup: bool = True) -> cabc.Generator[Context]:575        """This helper method can be used with the context object to promote576        it to the current thread local (see :func:`get_current_context`).577        The default behavior of this is to invoke the cleanup functions which578        can be disabled by setting `cleanup` to `False`.  The cleanup579        functions are typically used for things such as closing file handles.580581        If the cleanup is intended the context object can also be directly582        used as a context manager.583584        Example usage::585586            with ctx.scope():587                assert get_current_context() is ctx588589        This is equivalent::590591            with ctx:592                assert get_current_context() is ctx593594        .. versionadded:: 5.0595596        :param cleanup: controls if the cleanup functions should be run or597                        not.  The default is to run these functions.  In598                        some situations the context only wants to be599                        temporarily pushed in which case this can be disabled.600                        Nested pushes automatically defer the cleanup.601        """602        if not cleanup:603            self._depth += 1604        try:605            with self as rv:606                yield rv607        finally:608            if not cleanup:609                self._depth -= 1610611    @property612    def meta(self) -> dict[str, t.Any]:613        """This is a dictionary which is shared with all the contexts614        that are nested.  It exists so that click utilities can store some615        state here if they need to.  It is however the responsibility of616        that code to manage this dictionary well.617618        The keys are supposed to be unique dotted strings.  For instance619        module paths are a good choice for it.  What is stored in there is620        irrelevant for the operation of click.  However what is important is621        that code that places data here adheres to the general semantics of622        the system.623624        Example usage::625626            LANG_KEY = f'{__name__}.lang'627628            def set_language(value):629                ctx = get_current_context()630                ctx.meta[LANG_KEY] = value631632            def get_language():633                return get_current_context().meta.get(LANG_KEY, 'en_US')634635        .. versionadded:: 5.0636        """637        return self._meta638639    def make_formatter(self) -> HelpFormatter:640        """Creates the :class:`~click.HelpFormatter` for the help and641        usage output.642643        To quickly customize the formatter class used without overriding644        this method, set the :attr:`formatter_class` attribute.645646        .. versionchanged:: 8.0647            Added the :attr:`formatter_class` attribute.648        """649        return self.formatter_class(650            width=self.terminal_width, max_width=self.max_content_width651        )652653    def with_resource(self, context_manager: AbstractContextManager[V]) -> V:654        """Register a resource as if it were used in a ``with``655        statement. The resource will be cleaned up when the context is656        popped.657658        Uses :meth:`contextlib.ExitStack.enter_context`. It calls the659        resource's ``__enter__()`` method and returns the result. When660        the context is popped, it closes the stack, which calls the661        resource's ``__exit__()`` method.662663        To register a cleanup function for something that isn't a664        context manager, use :meth:`call_on_close`. Or use something665        from :mod:`contextlib` to turn it into a context manager first.666667        .. code-block:: python668669            @click.group()670            @click.option("--name")671            @click.pass_context672            def cli(ctx):673                ctx.obj = ctx.with_resource(connect_db(name))674675        :param context_manager: The context manager to enter.676        :return: Whatever ``context_manager.__enter__()`` returns.677678        .. versionadded:: 8.0679        """680        return self._exit_stack.enter_context(context_manager)681682    def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:683        """Register a function to be called when the context tears down.684685        This can be used to close resources opened during the script686        execution. Resources that support Python's context manager687        protocol which would be used in a ``with`` statement should be688        registered with :meth:`with_resource` instead.689690        :param f: The function to execute on teardown.691        """692        return self._exit_stack.callback(f)693694    def close(self) -> None:695        """Invoke all close callbacks registered with696        :meth:`call_on_close`, and exit all context managers entered697        with :meth:`with_resource`.698        """699        self._close_with_exception_info(None, None, None)700701    def _close_with_exception_info(702        self,703        exc_type: type[BaseException] | None,704        exc_value: BaseException | None,705        tb: TracebackType | None,706    ) -> bool | None:707        """Unwind the exit stack by calling its :meth:`__exit__` providing the exception708        information to allow for exception handling by the various resources registered709        using :meth;`with_resource`710711        :return: Whatever ``exit_stack.__exit__()`` returns.712        """713        exit_result = self._exit_stack.__exit__(exc_type, exc_value, tb)714        # In case the context is reused, create a new exit stack.715        self._exit_stack = ExitStack()716717        return exit_result718719    @property720    def command_path(self) -> str:721        """The computed command path.  This is used for the ``usage``722        information on the help page.  It's automatically created by723        combining the info names of the chain of contexts to the root.724        """725        rv = ""726        if self.info_name is not None:727            rv = self.info_name728        if self.parent is not None:729            parent_command_path = [self.parent.command_path]730731            if isinstance(self.parent.command, Command):732                for param in self.parent.command.get_params(self):733                    parent_command_path.extend(param.get_usage_pieces(self))734735            rv = f"{' '.join(parent_command_path)} {rv}"736        return rv.lstrip()737738    def find_root(self) -> Context:739        """Finds the outermost context."""740        node = self741        while node.parent is not None:742            node = node.parent743        return node744745    def find_object(self, object_type: type[V]) -> V | None:746        """Finds the closest object of a given type."""747        node: Context | None = self748749        while node is not None:750            if isinstance(node.obj, object_type):751                return node.obj752753            node = node.parent754755        return None756757    def ensure_object(self, object_type: type[V]) -> V:758        """Like :meth:`find_object` but sets the innermost object to a759        new instance of `object_type` if it does not exist.760        """761        rv = self.find_object(object_type)762        if rv is None:763            self.obj = rv = object_type()764        return rv765766    def _default_map_has(self, name: str | None) -> bool:767        """Check if :attr:`default_map` contains a real value for ``name``.768769        Returns ``False`` when the key is absent, the map is ``None``,770        ``name`` is ``None``, or the stored value is the internal771        :data:`UNSET` sentinel.772        """773        return (774            name is not None775            and self.default_map is not None776            and name in self.default_map777            and self.default_map[name] is not UNSET778        )779780    @t.overload781    def lookup_default(782        self, name: str, call: t.Literal[True] = True783    ) -> t.Any | None: ...784785    @t.overload786    def lookup_default(787        self, name: str, call: t.Literal[False] = ...788    ) -> t.Any | t.Callable[[], t.Any] | None: ...789790    def lookup_default(self, name: str, call: bool = True) -> t.Any | None:791        """Get the default for a parameter from :attr:`default_map`.792793        :param name: Name of the parameter.794        :param call: If the default is a callable, call it. Disable to795            return the callable instead.796797        .. versionchanged:: 8.0798            Added the ``call`` parameter.799        """800        if not self._default_map_has(name):801            return None802803        # Assert to make the type checker happy.804        assert self.default_map is not None805        value = self.default_map[name]806807        if call and callable(value):808            return value()809810        return value811812    def fail(self, message: str) -> t.NoReturn:813        """Aborts the execution of the program with a specific error814        message.815816        :param message: the error message to fail with.817        """818        raise UsageError(message, self)819820    def abort(self) -> t.NoReturn:821        """Aborts the script."""822        raise Abort()823824    def exit(self, code: int = 0) -> t.NoReturn:825        """Exits the application with a given exit code.826827        .. versionchanged:: 8.2828            Callbacks and context managers registered with :meth:`call_on_close`829            and :meth:`with_resource` are closed before exiting.830        """831        self.close()832        raise Exit(code)833834    def get_usage(self) -> str:835        """Helper method to get formatted usage string for the current836        context and command.837        """838        return self.command.get_usage(self)839840    def get_help(self) -> str:841        """Helper method to get formatted help page for the current842        context and command.843        """844        return self.command.get_help(self)845846    def _make_sub_context(self, command: Command) -> Context:847        """Create a new context of the same type as this context, but848        for a new command.849850        :meta private:851        """852        return type(self)(command, info_name=command.name, parent=self)853854    @t.overload855    def invoke(856        self, callback: t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any857    ) -> V: ...858859    @t.overload860    def invoke(self, callback: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: ...861862    def invoke(863        self, callback: Command | t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any864    ) -> t.Any | V:865        """Invokes a command callback in exactly the way it expects.  There866        are two ways to invoke this method:867868        1.  the first argument can be a callback and all other arguments and869            keyword arguments are forwarded directly to the function.870        2.  the first argument is a click command object.  In that case all871            arguments are forwarded as well but proper click parameters872            (options and click arguments) must be keyword arguments and Click873            will fill in defaults.874875        .. versionchanged:: 8.0876            All ``kwargs`` are tracked in :attr:`params` so they will be877            passed if :meth:`forward` is called at multiple levels.878879        .. versionchanged:: 3.2880            A new context is created, and missing arguments use default values.881        """882        if isinstance(callback, Command):883            other_cmd = callback884885            if other_cmd.callback is None:886                raise TypeError(887                    "The given command does not have a callback that can be invoked."888                )889            else:890                callback = t.cast("t.Callable[..., V]", other_cmd.callback)891892            ctx = self._make_sub_context(other_cmd)893894            for param in other_cmd.params:895                if param.name not in kwargs and param.expose_value:896                    default_value = param.get_default(ctx)897                    # We explicitly hide the :attr:`UNSET` value to the user, as we898                    # choose to make it an implementation detail. And because ``invoke``899                    # has been designed as part of Click public API, we return ``None``900                    # instead. Refs:901                    # https://github.com/pallets/click/issues/3066902                    # https://github.com/pallets/click/issues/3065903                    # https://github.com/pallets/click/pull/3068904                    if default_value is UNSET:905                        default_value = None906                    kwargs[param.name] = param.type_cast_value(ctx, default_value)907908            # Track all kwargs as params, so that forward() will pass909            # them on in subsequent calls.910            ctx.params.update(kwargs)911        else:912            ctx = self913914        with augment_usage_errors(self), ctx:915            return callback(*args, **kwargs)916917    def forward(self, cmd: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any:918        """Similar to :meth:`invoke` but fills in default keyword919        arguments from the current context if the other command expects920        it.  This cannot invoke callbacks directly, only other commands.921922        .. versionchanged:: 8.0923            All ``kwargs`` are tracked in :attr:`params` so they will be924            passed if ``forward`` is called at multiple levels.925        """926        # Can only forward to other commands, not direct callbacks.927        if not isinstance(cmd, Command):928            raise TypeError("Callback is not a command.")929930        for param in self.params:931            if param not in kwargs:932                kwargs[param] = self.params[param]933934        return self.invoke(cmd, *args, **kwargs)935936    def set_parameter_source(self, name: str, source: ParameterSource) -> None:937        """Set the source of a parameter. This indicates the location938        from which the value of the parameter was obtained.939940        :param name: The name of the parameter.941        :param source: A member of :class:`~click.core.ParameterSource`.942        """943        self._parameter_source[name] = source944945    def get_parameter_source(self, name: str) -> ParameterSource | None:946        """Get the source of a parameter. This indicates the location947        from which the value of the parameter was obtained.948949        This can be useful for determining when a user specified a value950        on the command line that is the same as the default value. It951        will be :attr:`~click.core.ParameterSource.DEFAULT` only if the952        value was actually taken from the default.953954        :param name: The name of the parameter.955        :rtype: ParameterSource956957        .. versionchanged:: 8.0958            Returns ``None`` if the parameter was not provided from any959            source.960        """961        return self._parameter_source.get(name)962963964class Command:965    """Commands are the basic building block of command line interfaces in966    Click.  A basic command handles command line parsing and might dispatch967    more parsing to commands nested below it.968969    :param name: the name of the command to use unless a group overrides it.970    :param context_settings: an optional dictionary with defaults that are971                             passed to the context object.972    :param callback: the callback to invoke.  This is optional.973    :param params: the parameters to register with this command.  This can974                   be either :class:`Option` or :class:`Argument` objects.975    :param help: the help string to use for this command.976    :param epilog: like the help string but it's printed at the end of the977                   help page after everything else.978    :param short_help: the short help to use for this command.  This is979                       shown on the command listing of the parent command.980    :param add_help_option: by default each command registers a ``--help``981                            option.  This can be disabled by this parameter.982    :param no_args_is_help: this controls what happens if no arguments are983                            provided.  This option is disabled by default.984                            If enabled this will add ``--help`` as argument985                            if no arguments are passed986    :param hidden: hide this command from help outputs.987    :param deprecated: If ``True`` or non-empty string, issues a message988                        indicating that the command is deprecated and highlights989                        its deprecation in --help. The message can be customized990                        by using a string as the value.991992    .. versionchanged:: 8.2993        This is the base class for all commands, not ``BaseCommand``.994        ``deprecated`` can be set to a string as well to customize the995        deprecation message.996997    .. versionchanged:: 8.1998        ``help``, ``epilog``, and ``short_help`` are stored unprocessed,999        all formatting is done when outputting help text, not at init,1000        and is done even if not using the ``@command`` decorator.10011002    .. versionchanged:: 8.01003        Added a ``repr`` showing the command name.10041005    .. versionchanged:: 7.11006        Added the ``no_args_is_help`` parameter.10071008    .. versionchanged:: 2.01009        Added the ``context_settings`` parameter.1010    """10111012    #: The context class to create with :meth:`make_context`.1013    #:1014    #: .. versionadded:: 8.01015    context_class: type[Context] = Context10161017    #: the default for the :attr:`Context.allow_extra_args` flag.1018    allow_extra_args = False10191020    #: the default for the :attr:`Context.allow_interspersed_args` flag.1021    allow_interspersed_args = True10221023    #: the default for the :attr:`Context.ignore_unknown_options` flag.1024    ignore_unknown_options = False10251026    name: str | None1027    context_settings: cabc.MutableMapping[str, t.Any]1028    callback: t.Callable[..., t.Any] | None1029    params: list[Parameter]1030    help: str | None1031    epilog: str | None1032    options_metavar: str | None1033    short_help: str | None1034    add_help_option: bool1035    _help_option: Option | None1036    no_args_is_help: bool1037    hidden: bool1038    deprecated: bool | str10391040    def __init__(1041        self,1042        name: str | None,1043        context_settings: cabc.MutableMapping[str, t.Any] | None = None,1044        callback: t.Callable[..., t.Any] | None = None,1045        params: list[Parameter] | None = None,1046        help: str | None = None,1047        epilog: str | None = None,1048        short_help: str | None = None,1049        options_metavar: str | None = "[OPTIONS]",1050        add_help_option: bool = True,1051        no_args_is_help: bool = False,1052        hidden: bool = False,1053        deprecated: bool | str = False,1054    ) -> None:1055        #: the name the command thinks it has.  Upon registering a command1056        #: on a :class:`Group` the group will default the command name1057        #: with this information.  You should instead use the1058        #: :class:`Context`\'s :attr:`~Context.info_name` attribute.1059        self.name = name10601061        if context_settings is None:1062            context_settings = {}10631064        #: an optional dictionary with defaults passed to the context.1065        self.context_settings = context_settings10661067        #: the callback to execute when the command fires.  This might be1068        #: `None` in which case nothing happens.1069        self.callback = callback1070        #: the list of parameters for this command in the order they1071        #: should show up in the help page and execute.  Eager parameters1072        #: will automatically be handled before non eager ones.1073        self.params = params or []1074        self.help = help1075        self.epilog = epilog1076        self.options_metavar = options_metavar1077        self.short_help = short_help1078        self.add_help_option = add_help_option1079        self._help_option = None1080        self.no_args_is_help = no_args_is_help1081        self.hidden = hidden1082        self.deprecated = deprecated10831084    def to_info_dict(self, ctx: Context) -> dict[str, t.Any]:1085        return {1086            "name": self.name,1087            "params": [param.to_info_dict() for param in self.get_params(ctx)],1088            "help": self.help,1089            "epilog": self.epilog,1090            "short_help": self.short_help,1091            "hidden": self.hidden,1092            "deprecated": self.deprecated,1093        }10941095    def __repr__(self) -> str:1096        return f"<{self.__class__.__name__} {self.name}>"10971098    def get_usage(self, ctx: Context) -> str:1099        """Formats the usage line into a string and returns it.11001101        Calls :meth:`format_usage` internally.1102        """1103        formatter = ctx.make_formatter()1104        self.format_usage(ctx, formatter)1105        return formatter.getvalue().rstrip("\n")11061107    def get_params(self, ctx: Context) -> list[Parameter]:1108        params = self.params1109        help_option = self.get_help_option(ctx)11101111        if help_option is not None:1112            params = [*params, help_option]11131114        if __debug__:1115            import warnings11161117            opts = [opt for param in params for opt in param.opts]1118            opts_counter = Counter(opts)1119            duplicate_opts = (opt for opt, count in opts_counter.items() if count > 1)11201121            for duplicate_opt in duplicate_opts:1122                warnings.warn(1123                    (1124                        f"The parameter {duplicate_opt} is used more than once. "1125                        "Remove its duplicate as parameters should be unique."1126                    ),1127                    stacklevel=3,1128                )11291130            # Options may deliberately share a storage name to compete for1131            # the same value (feature switches), but an argument sharing a1132            # name silently overwrites the other parameter's value.1133            names_counter = Counter(param.name for param in params)1134            duplicate_names = (1135                name for name, count in names_counter.items() if count > 11136            )11371138            for duplicate_name in duplicate_names:1139                sharers = [param for param in params if param.name == duplicate_name]11401141                if help_option in sharers:1142                    warnings.warn(1143                        (1144                            f"The name {duplicate_name!r} is reserved for the "1145                            "automatic help option. Give the parameter a "1146                            "different name."1147                        ),1148                        stacklevel=3,1149                    )1150                elif any(isinstance(param, Argument) for param in sharers):1151                    warnings.warn(1152                        (1153                            f"The name {duplicate_name!r} is used by an argument "1154                            "and another parameter. They will overwrite each "1155                            "other's value during parsing. Give each parameter "1156                            "a unique name."1157                        ),1158                        stacklevel=3,1159                    )11601161        return params11621163    def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None:1164        """Writes the usage line into the formatter.11651166        This is a low-level method called by :meth:`get_usage`.1167        """1168        pieces = self.collect_usage_pieces(ctx)1169        formatter.write_usage(ctx.command_path, " ".join(pieces))11701171    def collect_usage_pieces(self, ctx: Context) -> list[str]:1172        """Returns all the pieces that go into the usage line and returns1173        it as a list of strings.1174        """1175        rv = [self.options_metavar] if self.options_metavar else []11761177        for param in self.get_params(ctx):1178            rv.extend(param.get_usage_pieces(ctx))11791180        return rv11811182    def get_help_option_names(self, ctx: Context) -> list[str]:1183        """Returns the names for the help option.11841185        Drops duplicates and names already reserved by another parameter. Order of1186        :attr:`Context.help_option_names` is preserved, so the result is stable.11871188        .. versionchanged:: 8.5.01189            Names keep their declaration order.1190        """1191        all_names = dict.fromkeys(ctx.help_option_names)1192        for param in self.params:1193            for name in (*param.opts, *param.secondary_opts):1194                all_names.pop(name, None)1195        return list(all_names)11961197    def get_help_option(self, ctx: Context) -> Option | None:1198        """Returns the help option object.11991200        Skipped if :attr:`add_help_option` is ``False``.12011202        .. versionchanged:: 8.5.01203            The help option stores its value under the reserved name1204            ``_click_default_help``, so a parameter named ``help`` no1205            longer breaks parsing.12061207        .. versionchanged:: 8.1.81208            The help option is now cached to avoid creating it multiple times.1209        """1210        help_option_names = self.get_help_option_names(ctx)12111212        if not help_option_names or not self.add_help_option:1213            return None12141215        # Cache the help option object in private _help_option attribute to1216        # avoid creating it multiple times. Not doing this will break the1217        # callback ordering by iter_params_for_processing(), which relies on1218        # object comparison.1219        if self._help_option is None:1220            # Avoid circular import.1221            from .decorators import help_option12221223            # The help option never exposes its value, so it uses a reserved1224            # storage name, keeping it clear of user parameters (like an1225            # argument named "help") that would otherwise clobber its value.1226            help_option(*help_option_names, _HELP_OPTION_STORAGE_NAME)(self)1227            self._help_option = self.params.pop()  # type: ignore[assignment]12281229        return self._help_option12301231    def make_parser(self, ctx: Context) -> _OptionParser:1232        """Creates the underlying option parser for this command."""1233        parser = _OptionParser(ctx)1234        for param in self.get_params(ctx):1235            param.add_to_parser(parser, ctx)1236        return parser12371238    def get_help(self, ctx: Context) -> str:1239        """Formats the help into a string and returns it.12401241        Calls :meth:`format_help` internally.1242        """1243        formatter = ctx.make_formatter()1244        self.format_help(ctx, formatter)1245        return formatter.getvalue().rstrip("\n")12461247    def get_short_help_str(self, limit: int = 45) -> str:1248        """Gets short help for the command or makes it by shortening the1249        long help string.1250        """1251        if self.short_help:1252            text = inspect.cleandoc(self.short_help)1253        elif self.help:1254            text = _make_default_short_help(self.help, limit)1255        else:1256            text = ""12571258        if self.deprecated:1259            text = f"{_(text)} {_format_deprecated_label(self.deprecated)}"12601261        return text.strip()12621263    def format_help(self, ctx: Context, formatter: HelpFormatter) -> None:1264        """Writes the help into the formatter if it exists.12651266        This is a low-level method called by :meth:`get_help`.12671268        This calls the following methods:12691270        -   :meth:`format_usage`1271        -   :meth:`format_help_text`1272        -   :meth:`format_arguments`1273        -   :meth:`format_options`1274        -   :meth:`format_epilog`1275        """1276        self.format_usage(ctx, formatter)1277        self.format_help_text(ctx, formatter)1278        self.format_arguments(ctx, formatter)1279        self.format_options(ctx, formatter)1280        self.format_epilog(ctx, formatter)12811282    def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None:1283        """Writes the help text to the formatter if it exists."""1284        if self.help is not None:1285            # truncate the help text to the first form feed1286            text = inspect.cleandoc(self.help).partition("\f")[0]1287        else:1288            text = ""12891290        if self.deprecated:1291            label = _format_deprecated_label(self.deprecated)1292            text = f"{_(text)} {label}" if text else label12931294        if text:1295            formatter.write_paragraph()12961297            with formatter.indentation():1298                formatter.write_text(text)12991300    def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:1301        """Writes all the options into the formatter if they exist."""1302        opts = []1303        for param in self.get_params(ctx):1304            rv = param.get_help_record(ctx)1305            if rv is not None and not isinstance(param, Argument):1306                opts.append(rv)13071308        if opts:1309            with formatter.section(_("Options")):1310                formatter.write_dl(opts)13111312    def format_arguments(self, ctx: Context, formatter: HelpFormatter) -> None:1313        """Writes the arguments that have a help record into the formatter."""1314        args = []1315        for param in self.get_params(ctx):1316            rv = param.get_help_record(ctx)1317            if rv is not None and isinstance(param, Argument):1318                args.append(rv)13191320        if args:1321            with formatter.section(_("Positional arguments")):1322                formatter.write_dl(args)13231324    def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None:1325        """Writes the epilog into the formatter if it exists."""1326        if self.epilog:1327            epilog = inspect.cleandoc(self.epilog)1328            formatter.write_paragraph()13291330            with formatter.indentation():1331                formatter.write_text(epilog)13321333    def make_context(1334        self,1335        info_name: str | None,1336        args: list[str],1337        parent: Context | None = None,1338        **extra: t.Any,1339    ) -> Context:1340        """This function when given an info name and arguments will kick1341        off the parsing and create a new :class:`Context`.  It does not1342        invoke the actual command callback though.13431344        To quickly customize the context class used without overriding1345        this method, set the :attr:`context_class` attribute.13461347        :param info_name: the info name for this invocation.  Generally this1348                          is the most descriptive name for the script or1349                          command.  For the toplevel script it's usually1350                          the name of the script, for commands below it's1351                          the name of the command.1352        :param args: the arguments to parse as list of strings.1353        :param parent: the parent context if available.1354        :param extra: extra keyword arguments forwarded to the context1355                      constructor.13561357        .. versionchanged:: 8.01358            Added the :attr:`context_class` attribute.1359        """1360        for key, value in self.context_settings.items():1361            if key not in extra:1362                extra[key] = value13631364        ctx = self.context_class(self, info_name=info_name, parent=parent, **extra)13651366        with ctx.scope(cleanup=False):1367            self.parse_args(ctx, args)1368        return ctx13691370    def parse_args(self, ctx: Context, args: list[str]) -> list[str]:1371        if not args and self.no_args_is_help and not ctx.resilient_parsing:1372            raise NoArgsIsHelpError(ctx)13731374        parser = self.make_parser(ctx)1375        opts, args, param_order = parser.parse_args(args=args)13761377        for param in iter_params_for_processing(param_order, self.get_params(ctx)):1378            _, args = param.handle_parse_result(ctx, opts, args)13791380        # We now have all parameters' values into `ctx.params`, but the data may contain1381        # the `UNSET` sentinel.1382        # Convert `UNSET` to `None` to ensure that the user doesn't see `UNSET`.1383        #1384        # Waiting until after the initial parse to convert allows us to treat `UNSET`1385        # more like a missing value when multiple params use the same name.1386        # Refs:1387        # https://github.com/pallets/click/issues/30711388        # https://github.com/pallets/click/pull/30791389        for name, value in ctx.params.items():1390            if value is UNSET:1391                ctx.params[name] = None13921393        if args and not ctx.allow_extra_args and not ctx.resilient_parsing:1394            ctx.fail(1395                ngettext(1396                    "Got unexpected extra argument ({args})",1397                    "Got unexpected extra arguments ({args})",1398                    len(args),1399                ).format(args=" ".join(map(str, args)))1400            )14011402        ctx.args = args1403        ctx._opt_prefixes.update(parser._opt_prefixes)1404        return args14051406    def invoke(self, ctx: Context) -> t.Any:1407        """Given a context, this invokes the attached callback (if it exists)1408        in the right way.1409        """1410        if self.deprecated:1411            message = _(1412                "DeprecationWarning: The command {name!r} is deprecated.{extra_message}"1413            ).format(1414                name=self.name,1415                extra_message=_format_deprecated_suffix(self.deprecated),1416            )1417            echo(style(message, fg="red"), err=True)14181419        if self.callback is not None:1420            return ctx.invoke(self.callback, **ctx.params)14211422    def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:1423        """Return a list of completions for the incomplete value. Looks1424        at the names of options and chained multi-commands.14251426        Any command could be part of a chained multi-command, so sibling1427        commands are valid at any point during command completion.14281429        :param ctx: Invocation context for this command.1430        :param incomplete: Value being completed. May be empty.14311432        .. versionadded:: 8.01433        """1434        from click.shell_completion import CompletionItem14351436        results: list[CompletionItem] = []14371438        if incomplete and not incomplete[0].isalnum():1439            for param in self.get_params(ctx):1440                if (1441                    not isinstance(param, Option)1442                    or param.hidden1443                    or (1444                        not param.multiple1445                        and ctx.get_parameter_source(param.name)1446                        is ParameterSource.COMMANDLINE1447                    )1448                ):1449                    continue14501451                results.extend(1452                    CompletionItem(name, help=param.help)1453                    for name in [*param.opts, *param.secondary_opts]1454                    if name.startswith(incomplete)1455                )14561457        while ctx.parent is not None:1458            ctx = ctx.parent14591460            if isinstance(ctx.command, Group) and ctx.command.chain:1461                results.extend(1462                    CompletionItem(name, help=command.get_short_help_str())1463                    for name, command in _complete_visible_commands(ctx, incomplete)1464                    if name not in ctx._protected_args1465                )14661467        return results14681469    @t.overload1470    def main(1471        self,1472        args: cabc.Sequence[str] | None = None,1473        prog_name: str | None = None,1474        complete_var: str | None = None,1475        standalone_mode: t.Literal[True] = True,1476        **extra: t.Any,1477    ) -> t.NoReturn: ...14781479    @t.overload1480    def main(1481        self,1482        args: cabc.Sequence[str] | None = None,1483        prog_name: str | None = None,1484        complete_var: str | None = None,1485        standalone_mode: bool = ...,1486        **extra: t.Any,1487    ) -> t.Any: ...14881489    def main(1490        self,1491        args: cabc.Sequence[str] | None = None,1492        prog_name: str | None = None,1493        complete_var: str | None = None,1494        standalone_mode: bool = True,1495        windows_expand_args: bool = True,1496        **extra: t.Any,1497    ) -> t.Any:1498        """This is the way to invoke a script with all the bells and1499        whistles as a command line application.  This will always terminate1500        the application after a call.  If this is not wanted, ``SystemExit``1501        needs to be caught.15021503        This method is also available by directly calling the instance of1504        a :class:`Command`.15051506        :param args: the arguments that should be used for parsing.  If not1507                     provided, ``sys.argv[1:]`` is used.1508        :param prog_name: the program name that should be used.  By default1509                          the program name is constructed by taking the file1510                          name from ``sys.argv[0]``.1511        :param complete_var: the environment variable that controls the1512                             bash completion support.  The default is1513                             ``"_<prog_name>_COMPLETE"`` with prog_name in1514                             uppercase.1515        :param standalone_mode: the default behavior is to invoke the script1516                                in standalone mode.  Click will then1517                                handle exceptions and convert them into1518                                error messages and the function will never1519                                return but shut down the interpreter.  If1520                                this is set to `False` they will be1521                                propagated to the caller and the return1522                                value of this function is the return value1523                                of :meth:`invoke`.1524        :param windows_expand_args: Expand glob patterns, user dir, and1525            env vars in command line args on Windows.1526        :param extra: extra keyword arguments are forwarded to the context1527                      constructor.  See :class:`Context` for more information.15281529        .. versionchanged:: 8.0.11530            Added the ``windows_expand_args`` parameter to allow1531            disabling command line arg expansion on Windows.15321533        .. versionchanged:: 8.01534            When taking arguments from ``sys.argv`` on Windows, glob1535            patterns, user dir, and env vars are expanded.15361537        .. versionchanged:: 3.01538           Added the ``standalone_mode`` parameter.1539        """1540        if args is None:1541            args = sys.argv[1:]15421543            if os.name == "nt" and windows_expand_args:1544                args = _expand_args(args)1545        else:1546            args = list(args)15471548        if prog_name is None:1549            prog_name = _detect_program_name()15501551        # Process shell completion requests and exit early.1552        self._main_shell_completion(extra, prog_name, complete_var)15531554        # Every handler below takes the same two steps: propagate when1555        # standalone mode is disabled, otherwise collect the message and the1556        # exit code, and leave both to the teardown after the ``try``. The1557        # teardown writes the message and exits, and the outermost handler1558        # holds one policy for every interrupt arriving that late: the1559        # message may be lost, the intended exit code still wins.1560        report: cabc.Callable[[], None] | None = None1561        exit_code = 115621563        try:1564            try:1565                with self.make_context(prog_name, args, **extra) as ctx:1566                    rv = self.invoke(ctx)1567                    if not standalone_mode:1568                        return rv1569                    # it's not safe to `ctx.exit(rv)` here!1570                    # note that `rv` may actually contain data like "1" which1571                    # has obvious effects1572                    # more subtle case: `rv=[None, None]` can come out of1573                    # chained commands which all returned `None` -- so it's not1574                    # even always obvious that `rv` indicates success/failure1575                    # by its truthiness/falsiness1576                    ctx.exit()1577            except Exit as e:1578                if not standalone_mode:1579                    # in non-standalone mode, return the exit code1580                    # note that this is only reached if `self.invoke` above raises1581                    # an Exit explicitly -- thus bypassing the check there which1582                    # would return its result1583                    # the results of non-standalone execution may therefore be1584                    # somewhat ambiguous: if there are codepaths which lead to1585                    # `ctx.exit(1)` and to `return 1`, the caller won't be able to1586                    # tell the difference between the two1587                    return e.exit_code15881589                exit_code = e.exit_code1590            except Abort:1591                if not standalone_mode:1592                    raise15931594                report = _echo_aborted1595            except (EOFError, KeyboardInterrupt) as e:1596                # The blank line closes the terminal's ``^C`` echo.1597                echo(file=sys.stderr)15981599                if not standalone_mode:1600                    raise Abort() from e16011602                report = _echo_aborted1603            except ClickException as e:1604                if not standalone_mode:1605                    raise16061607                report, exit_code = e.show, e.exit_code1608            except OSError as e:1609                if e.errno != errno.EPIPE:1610                    raise16111612                sys.stdout = t.cast(t.TextIO, _PacifyFlushWrapper(sys.stdout))1613                sys.stderr = t.cast(t.TextIO, _PacifyFlushWrapper(sys.stderr))16141615            if report is not None:1616                report()16171618            sys.exit(exit_code)1619        except (EOFError, KeyboardInterrupt):1620            if not standalone_mode:1621                raise16221623            sys.exit(exit_code)16241625    def _main_shell_completion(1626        self,1627        ctx_args: cabc.MutableMapping[str, t.Any],1628        prog_name: str,1629        complete_var: str | None = None,1630    ) -> None:1631        """Check if the shell is asking for tab completion, process1632        that, then exit early. Called from :meth:`main` before the1633        program is invoked.16341635        :param prog_name: Name of the executable in the shell.1636        :param complete_var: Name of the environment variable that holds1637            the completion instruction. Defaults to1638            ``_{PROG_NAME}_COMPLETE``.16391640        .. versionchanged:: 8.2.01641            Dots (``.``) in ``prog_name`` are replaced with underscores (``_``).1642        """1643        if complete_var is None:1644            complete_name = prog_name.replace("-", "_").replace(".", "_")1645            complete_var = f"_{complete_name}_COMPLETE".upper()16461647        instruction = os.environ.get(complete_var)16481649        if not instruction:1650            return16511652        from .shell_completion import shell_complete16531654        rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)1655        sys.exit(rv)16561657    def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any:1658        """Alias for :meth:`main`."""1659        return self.main(*args, **kwargs)166016611662class _FakeSubclassCheck(type):1663    def __subclasscheck__(cls, subclass: type) -> bool:1664        return issubclass(subclass, cls.__bases__[0])16651666    def __instancecheck__(cls, instance: t.Any) -> bool:1667        return isinstance(instance, cls.__bases__[0])166816691670class _BaseCommand(Command, metaclass=_FakeSubclassCheck):1671    """1672    .. deprecated:: 8.21673        Will be removed in Click 9.0. Use ``Command`` instead.1674    """167516761677class Group(Command):1678    """A group is a command that nests other commands (or more groups).16791680    :param name: The name of the group command.1681    :param commands: Map names to :class:`Command` objects. Can be a list, which1682        will use :attr:`Command.name` as the keys.1683    :param invoke_without_command: Invoke the group's callback even if a1684        subcommand is not given.1685    :param no_args_is_help: If no arguments are given, show the group's help and1686        exit. Defaults to the opposite of ``invoke_without_command``.1687    :param subcommand_metavar: How to represent the subcommand argument in help.1688        The default will represent whether ``chain`` is set or not.1689    :param chain: Allow passing more than one subcommand argument. After parsing1690        a command's arguments, if any arguments remain another command will be1691        matched, and so on.1692    :param result_callback: A function to call after the group's and1693        subcommand's callbacks. The value returned by the subcommand is passed.1694        If ``chain`` is enabled, the value will be a list of values returned by1695        all the commands. If ``invoke_without_command`` is enabled, the value1696        will be the value returned by the group's callback, or an empty list if1697        ``chain`` is enabled.1698    :param kwargs: Other arguments passed to :class:`Command`.16991700    .. versionchanged:: 8.01701        The ``commands`` argument can be a list of command objects.17021703    .. versionchanged:: 8.21704        Merged with and replaces the ``MultiCommand`` base class.1705    """17061707    allow_extra_args = True1708    allow_interspersed_args = False17091710    #: If set, this is used by the group's :meth:`command` decorator1711    #: as the default :class:`Command` class. This is useful to make all1712    #: subcommands use a custom command class.1713    #:1714    #: .. versionadded:: 8.01715    command_class: type[Command] | None = None17161717    #: If set, this is used by the group's :meth:`group` decorator1718    #: as the default :class:`Group` class. This is useful to make all1719    #: subgroups use a custom group class.1720    #:1721    #: If set to the special value :class:`type` (literally1722    #: ``group_class = type``), this group's class will be used as the1723    #: default class. This makes a custom group class continue to make1724    #: custom groups.1725    #:1726    #: .. versionadded:: 8.01727    group_class: type[Group | type] | None = None1728    # Literal[type] isn't valid, so use Type[type]17291730    commands: cabc.MutableMapping[str, Command]1731    invoke_without_command: bool1732    subcommand_metavar: str1733    chain: bool1734    _result_callback: t.Callable[..., t.Any] | None17351736    def __init__(1737        self,1738        name: str | None = None,1739        commands: cabc.MutableMapping[str, Command]1740        | cabc.Sequence[Command]1741        | None = None,1742        invoke_without_command: bool = False,1743        no_args_is_help: bool | None = None,1744        subcommand_metavar: str | None = None,1745        chain: bool = False,1746        result_callback: t.Callable[..., t.Any] | None = None,1747        **kwargs: t.Any,1748    ) -> None:1749        super().__init__(name, **kwargs)17501751        if commands is None:1752            commands = {}1753        elif isinstance(commands, abc.Sequence):1754            commands = {c.name: c for c in commands if c.name is not None}17551756        #: The registered subcommands by their exported names.1757        self.commands = commands17581759        if no_args_is_help is None:1760            no_args_is_help = not invoke_without_command17611762        self.no_args_is_help = no_args_is_help1763        self.invoke_without_command = invoke_without_command17641765        if subcommand_metavar is None:1766            # When the group can run without a subcommand, the leading command1767            # token is optional, so wrap it in brackets to reflect that.1768            if chain:1769                if invoke_without_command:1770                    subcommand_metavar = "[COMMAND1] [ARGS]... [COMMAND2 [ARGS]...]..."1771                else:1772                    subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."1773            elif invoke_without_command:1774                subcommand_metavar = "[COMMAND] [ARGS]..."1775            else:1776                subcommand_metavar = "COMMAND [ARGS]..."17771778        self.subcommand_metavar = subcommand_metavar1779        self.chain = chain1780        # The result callback that is stored. This can be set or1781        # overridden with the :func:`result_callback` decorator.1782        self._result_callback = result_callback17831784        if self.chain:1785            for param in self.params:1786                if isinstance(param, Argument) and not param.required:1787                    raise RuntimeError(1788                        "A group in chain mode cannot have optional arguments."1789                    )17901791    def to_info_dict(self, ctx: Context) -> dict[str, t.Any]:1792        info_dict = super().to_info_dict(ctx)1793        commands = {}17941795        for name in self.list_commands(ctx):1796            command = self.get_command(ctx, name)17971798            if command is None:1799                continue18001801            sub_ctx = ctx._make_sub_context(command)18021803            with sub_ctx.scope(cleanup=False):1804                commands[name] = command.to_info_dict(sub_ctx)18051806        info_dict.update(commands=commands, chain=self.chain)1807        return info_dict18081809    def add_command(self, cmd: Command, name: str | None = None) -> None:1810        """Registers another :class:`Command` with this group.  If the name1811        is not provided, the name of the command is used.1812        """1813        name = name or cmd.name1814        if name is None:1815            raise TypeError("Command has no name.")1816        _check_nested_chain(self, name, cmd, register=True)1817        self.commands[name] = cmd18181819    @t.overload1820    def command(self, __func: t.Callable[..., t.Any]) -> Command: ...18211822    @t.overload1823    def command(1824        self, *args: t.Any, **kwargs: t.Any1825    ) -> t.Callable[[t.Callable[..., t.Any]], Command]: ...18261827    def command(1828        self, *args: t.Any, **kwargs: t.Any1829    ) -> t.Callable[[t.Callable[..., t.Any]], Command] | Command:1830        """A shortcut decorator for declaring and attaching a command to1831        the group. This takes the same arguments as :func:`command` and1832        immediately registers the created command with this group by1833        calling :meth:`add_command`.18341835        To customize the command class used, set the1836        :attr:`command_class` attribute.18371838        .. versionchanged:: 8.11839            This decorator can be applied without parentheses.18401841        .. versionchanged:: 8.01842            Added the :attr:`command_class` attribute.1843        """1844        from .decorators import command18451846        func: t.Callable[..., t.Any] | None = None18471848        if args and callable(args[0]):1849            assert len(args) == 1 and not kwargs, (1850                "Use 'command(**kwargs)(callable)' to provide arguments."1851            )1852            (func,) = args1853            args = ()18541855        if self.command_class and kwargs.get("cls") is None:1856            kwargs["cls"] = self.command_class18571858        def decorator(f: t.Callable[..., t.Any]) -> Command:1859            cmd: Command = command(*args, **kwargs)(f)1860            self.add_command(cmd)1861            return cmd18621863        if func is not None:1864            return decorator(func)18651866        return decorator18671868    @t.overload1869    def group(self, __func: t.Callable[..., t.Any]) -> Group: ...18701871    @t.overload1872    def group(1873        self, *args: t.Any, **kwargs: t.Any1874    ) -> t.Callable[[t.Callable[..., t.Any]], Group]: ...18751876    def group(1877        self, *args: t.Any, **kwargs: t.Any1878    ) -> t.Callable[[t.Callable[..., t.Any]], Group] | Group:1879        """A shortcut decorator for declaring and attaching a group to1880        the group. This takes the same arguments as :func:`group` and1881        immediately registers the created group with this group by1882        calling :meth:`add_command`.18831884        To customize the group class used, set the :attr:`group_class`1885        attribute.18861887        .. versionchanged:: 8.11888            This decorator can be applied without parentheses.18891890        .. versionchanged:: 8.01891            Added the :attr:`group_class` attribute.1892        """1893        from .decorators import group18941895        func: t.Callable[..., t.Any] | None = None18961897        if args and callable(args[0]):1898            assert len(args) == 1 and not kwargs, (1899                "Use 'group(**kwargs)(callable)' to provide arguments."1900            )1901            (func,) = args1902            args = ()19031904        if self.group_class is not None and kwargs.get("cls") is None:1905            if self.group_class is type:1906                kwargs["cls"] = type(self)1907            else:1908                kwargs["cls"] = self.group_class19091910        def decorator(f: t.Callable[..., t.Any]) -> Group:1911            cmd: Group = group(*args, **kwargs)(f)1912            self.add_command(cmd)1913            return cmd19141915        if func is not None:1916            return decorator(func)19171918        return decorator19191920    def result_callback(self, replace: bool = False) -> t.Callable[[F], F]:1921        """Adds a result callback to the command.  By default if a1922        result callback is already registered this will chain them but1923        this can be disabled with the `replace` parameter.  The result1924        callback is invoked with the return value of the subcommand1925        (or the list of return values from all subcommands if chaining1926        is enabled) as well as the parameters as they would be passed1927        to the main callback.19281929        Example::19301931            @click.group()1932            @click.option('-i', '--input', default=23)1933            def cli(input):1934                return 4219351936            @cli.result_callback()1937            def process_result(result, input):1938                return result + input19391940        :param replace: if set to `True` an already existing result1941                        callback will be removed.19421943        .. versionchanged:: 8.01944            Renamed from ``resultcallback``.19451946        .. versionadded:: 3.01947        """19481949        def decorator(f: F) -> F:1950            old_callback = self._result_callback19511952            if old_callback is None or replace:1953                self._result_callback = f1954                return f19551956            def function(value: t.Any, /, *args: t.Any, **kwargs: t.Any) -> t.Any:1957                inner = old_callback(value, *args, **kwargs)1958                return f(inner, *args, **kwargs)19591960            self._result_callback = rv = update_wrapper(t.cast(F, function), f)1961            return rv  # type: ignore[return-value]19621963        return decorator19641965    def get_command(self, ctx: Context, cmd_name: str) -> Command | None:1966        """Given a context and a command name, this returns a :class:`Command`1967        object if it exists or returns ``None``.1968        """1969        return self.commands.get(cmd_name)19701971    def list_commands(self, ctx: Context) -> list[str]:1972        """Returns a list of subcommand names in the order they should appear."""1973        return sorted(self.commands)19741975    def collect_usage_pieces(self, ctx: Context) -> list[str]:1976        rv = super().collect_usage_pieces(ctx)1977        rv.append(self.subcommand_metavar)1978        return rv19791980    def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:1981        super().format_options(ctx, formatter)1982        self.format_commands(ctx, formatter)19831984    def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None:1985        """Extra format methods for multi methods that adds all the commands1986        after the options.1987        """1988        commands = []1989        for subcommand in self.list_commands(ctx):1990            cmd = self.get_command(ctx, subcommand)1991            # What is this, the tool lied about a command.  Ignore it1992            if cmd is None:1993                continue1994            if cmd.hidden:1995                continue19961997            commands.append((subcommand, cmd))19981999        # allow for 3 times the default spacing2000        if len(commands):

The first 2,000 of 3,827 lines.