Skip to content
Myr

core.py

This file

Path

src/click/core.py

2,600 lines · 94.6 KiB · Python

Last changed by

Merge pull request #1551 from yo-main/7.xDavid Lordbefore adoption4aabded

History of this file

Take it

1import enum2import errno3import os4import sys5from contextlib import contextmanager6from contextlib import ExitStack7from functools import update_wrapper8from itertools import repeat910from ._unicodefun import _verify_python_env11from .exceptions import Abort12from .exceptions import BadParameter13from .exceptions import ClickException14from .exceptions import Exit15from .exceptions import MissingParameter16from .exceptions import UsageError17from .formatting import HelpFormatter18from .formatting import join_options19from .globals import pop_context20from .globals import push_context21from .parser import _flag_needs_value22from .parser import OptionParser23from .parser import split_opt24from .termui import confirm25from .termui import prompt26from .termui import style27from .types import _NumberRangeBase28from .types import BOOL29from .types import convert_type30from .types import IntRange31from .utils import _detect_program_name32from .utils import echo33from .utils import make_default_short_help34from .utils import make_str35from .utils import PacifyFlushWrapper3637_missing = object()3839SUBCOMMAND_METAVAR = "COMMAND [ARGS]..."40SUBCOMMANDS_METAVAR = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."4142DEPRECATED_HELP_NOTICE = " (DEPRECATED)"43DEPRECATED_INVOKE_NOTICE = "DeprecationWarning: The command {name} is deprecated."444546def _maybe_show_deprecated_notice(cmd):47    if cmd.deprecated:48        echo(style(DEPRECATED_INVOKE_NOTICE.format(name=cmd.name), fg="red"), err=True)495051def _fast_exit(code):52    """Low-level exit that skips Python's cleanup but speeds up exit by53    about 10ms for things like shell completion.5455    :param code: Exit code.56    """57    sys.stdout.flush()58    sys.stderr.flush()59    os._exit(code)606162def _complete_visible_commands(ctx, incomplete):63    """List all the subcommands of a group that start with the64    incomplete value and aren't hidden.6566    :param ctx: Invocation context for the group.67    :param incomplete: Value being completed. May be empty.68    """69    for name in ctx.command.list_commands(ctx):70        if name.startswith(incomplete):71            command = ctx.command.get_command(ctx, name)7273            if not command.hidden:74                yield name, command757677def _check_multicommand(base_command, cmd_name, cmd, register=False):78    if not base_command.chain or not isinstance(cmd, MultiCommand):79        return80    if register:81        hint = (82            "It is not possible to add multi commands as children to"83            " another multi command that is in chain mode."84        )85    else:86        hint = (87            "Found a multi command as subcommand to a multi command"88            " that is in chain mode. This is not supported."89        )90    raise RuntimeError(91        f"{hint}. Command {base_command.name!r} is set to chain and"92        f" {cmd_name!r} was added as a subcommand but it in itself is a"93        f" multi command. ({cmd_name!r} is a {type(cmd).__name__}"94        f" within a chained {type(base_command).__name__} named"95        f" {base_command.name!r})."96    )979899def batch(iterable, batch_size):100    return list(zip(*repeat(iter(iterable), batch_size)))101102103@contextmanager104def augment_usage_errors(ctx, param=None):105    """Context manager that attaches extra information to exceptions."""106    try:107        yield108    except BadParameter as e:109        if e.ctx is None:110            e.ctx = ctx111        if param is not None and e.param is None:112            e.param = param113        raise114    except UsageError as e:115        if e.ctx is None:116            e.ctx = ctx117        raise118119120def iter_params_for_processing(invocation_order, declaration_order):121    """Given a sequence of parameters in the order as should be considered122    for processing and an iterable of parameters that exist, this returns123    a list in the correct order as they should be processed.124    """125126    def sort_key(item):127        try:128            idx = invocation_order.index(item)129        except ValueError:130            idx = float("inf")131        return (not item.is_eager, idx)132133    return sorted(declaration_order, key=sort_key)134135136class ParameterSource(enum.Enum):137    """This is an :class:`~enum.Enum` that indicates the source of a138    parameter's value.139140    Use :meth:`click.Context.get_parameter_source` to get the141    source for a parameter by name.142143    .. versionchanged:: 8.0144        Use :class:`~enum.Enum` and drop the ``validate`` method.145146    .. versionchanged:: 8.0147        Added the ``PROMPT`` value.148    """149150    COMMANDLINE = enum.auto()151    """The value was provided by the command line args."""152    ENVIRONMENT = enum.auto()153    """The value was provided with an environment variable."""154    DEFAULT = enum.auto()155    """Used the default specified by the parameter."""156    DEFAULT_MAP = enum.auto()157    """Used a default provided by :attr:`Context.default_map`."""158    PROMPT = enum.auto()159    """Used a prompt to confirm a default or provide a value."""160161162class Context:163    """The context is a special internal object that holds state relevant164    for the script execution at every single level.  It's normally invisible165    to commands unless they opt-in to getting access to it.166167    The context is useful as it can pass internal objects around and can168    control special execution features such as reading data from169    environment variables.170171    A context can be used as context manager in which case it will call172    :meth:`close` on teardown.173174    :param command: the command class for this context.175    :param parent: the parent context.176    :param info_name: the info name for this invocation.  Generally this177                      is the most descriptive name for the script or178                      command.  For the toplevel script it is usually179                      the name of the script, for commands below it it's180                      the name of the script.181    :param obj: an arbitrary object of user data.182    :param auto_envvar_prefix: the prefix to use for automatic environment183                               variables.  If this is `None` then reading184                               from environment variables is disabled.  This185                               does not affect manually set environment186                               variables which are always read.187    :param default_map: a dictionary (like object) with default values188                        for parameters.189    :param terminal_width: the width of the terminal.  The default is190                           inherit from parent context.  If no context191                           defines the terminal width then auto192                           detection will be applied.193    :param max_content_width: the maximum width for content rendered by194                              Click (this currently only affects help195                              pages).  This defaults to 80 characters if196                              not overridden.  In other words: even if the197                              terminal is larger than that, Click will not198                              format things wider than 80 characters by199                              default.  In addition to that, formatters might200                              add some safety mapping on the right.201    :param resilient_parsing: if this flag is enabled then Click will202                              parse without any interactivity or callback203                              invocation.  Default values will also be204                              ignored.  This is useful for implementing205                              things such as completion support.206    :param allow_extra_args: if this is set to `True` then extra arguments207                             at the end will not raise an error and will be208                             kept on the context.  The default is to inherit209                             from the command.210    :param allow_interspersed_args: if this is set to `False` then options211                                    and arguments cannot be mixed.  The212                                    default is to inherit from the command.213    :param ignore_unknown_options: instructs click to ignore options it does214                                   not know and keeps them for later215                                   processing.216    :param help_option_names: optionally a list of strings that define how217                              the default help parameter is named.  The218                              default is ``['--help']``.219    :param token_normalize_func: an optional function that is used to220                                 normalize tokens (options, choices,221                                 etc.).  This for instance can be used to222                                 implement case insensitive behavior.223    :param color: controls if the terminal supports ANSI colors or not.  The224                  default is autodetection.  This is only needed if ANSI225                  codes are used in texts that Click prints which is by226                  default not the case.  This for instance would affect227                  help output.228    :param show_default: Show defaults for all options. If not set,229        defaults to the value from a parent context. Overrides an230        option's ``show_default`` argument.231232    .. versionchanged:: 8.0233        The ``show_default`` parameter defaults to the value from the234        parent context.235236    .. versionchanged:: 7.1237       Added the ``show_default`` parameter.238239    .. versionchanged:: 4.0240        Added the ``color``, ``ignore_unknown_options``, and241        ``max_content_width`` parameters.242243    .. versionchanged:: 3.0244        Added the ``allow_extra_args`` and ``allow_interspersed_args``245        parameters.246247    .. versionchanged:: 2.0248        Added the ``resilient_parsing``, ``help_option_names``, and249        ``token_normalize_func`` parameters.250    """251252    #: The formatter class to create with :meth:`make_formatter`.253    #:254    #: .. versionadded:: 8.0255    formatter_class = HelpFormatter256257    def __init__(258        self,259        command,260        parent=None,261        info_name=None,262        obj=None,263        auto_envvar_prefix=None,264        default_map=None,265        terminal_width=None,266        max_content_width=None,267        resilient_parsing=False,268        allow_extra_args=None,269        allow_interspersed_args=None,270        ignore_unknown_options=None,271        help_option_names=None,272        token_normalize_func=None,273        color=None,274        show_default=None,275    ):276        #: the parent context or `None` if none exists.277        self.parent = parent278        #: the :class:`Command` for this context.279        self.command = command280        #: the descriptive information name281        self.info_name = info_name282        #: Map of parameter names to their parsed values. Parameters283        #: with ``expose_value=False`` are not stored.284        self.params = {}285        #: the leftover arguments.286        self.args = []287        #: protected arguments.  These are arguments that are prepended288        #: to `args` when certain parsing scenarios are encountered but289        #: must be never propagated to another arguments.  This is used290        #: to implement nested parsing.291        self.protected_args = []292        if obj is None and parent is not None:293            obj = parent.obj294        #: the user object stored.295        self.obj = obj296        self._meta = getattr(parent, "meta", {})297298        #: A dictionary (-like object) with defaults for parameters.299        if (300            default_map is None301            and parent is not None302            and parent.default_map is not None303        ):304            default_map = parent.default_map.get(info_name)305        self.default_map = default_map306307        #: This flag indicates if a subcommand is going to be executed. A308        #: group callback can use this information to figure out if it's309        #: being executed directly or because the execution flow passes310        #: onwards to a subcommand. By default it's None, but it can be311        #: the name of the subcommand to execute.312        #:313        #: If chaining is enabled this will be set to ``'*'`` in case314        #: any commands are executed.  It is however not possible to315        #: figure out which ones.  If you require this knowledge you316        #: should use a :func:`resultcallback`.317        self.invoked_subcommand = None318319        if terminal_width is None and parent is not None:320            terminal_width = parent.terminal_width321        #: The width of the terminal (None is autodetection).322        self.terminal_width = terminal_width323324        if max_content_width is None and parent is not None:325            max_content_width = parent.max_content_width326        #: The maximum width of formatted content (None implies a sensible327        #: default which is 80 for most things).328        self.max_content_width = max_content_width329330        if allow_extra_args is None:331            allow_extra_args = command.allow_extra_args332        #: Indicates if the context allows extra args or if it should333        #: fail on parsing.334        #:335        #: .. versionadded:: 3.0336        self.allow_extra_args = allow_extra_args337338        if allow_interspersed_args is None:339            allow_interspersed_args = command.allow_interspersed_args340        #: Indicates if the context allows mixing of arguments and341        #: options or not.342        #:343        #: .. versionadded:: 3.0344        self.allow_interspersed_args = allow_interspersed_args345346        if ignore_unknown_options is None:347            ignore_unknown_options = command.ignore_unknown_options348        #: Instructs click to ignore options that a command does not349        #: understand and will store it on the context for later350        #: processing.  This is primarily useful for situations where you351        #: want to call into external programs.  Generally this pattern is352        #: strongly discouraged because it's not possibly to losslessly353        #: forward all arguments.354        #:355        #: .. versionadded:: 4.0356        self.ignore_unknown_options = ignore_unknown_options357358        if help_option_names is None:359            if parent is not None:360                help_option_names = parent.help_option_names361            else:362                help_option_names = ["--help"]363364        #: The names for the help options.365        self.help_option_names = help_option_names366367        if token_normalize_func is None and parent is not None:368            token_normalize_func = parent.token_normalize_func369370        #: An optional normalization function for tokens.  This is371        #: options, choices, commands etc.372        self.token_normalize_func = token_normalize_func373374        #: Indicates if resilient parsing is enabled.  In that case Click375        #: will do its best to not cause any failures and default values376        #: will be ignored. Useful for completion.377        self.resilient_parsing = resilient_parsing378379        # If there is no envvar prefix yet, but the parent has one and380        # the command on this level has a name, we can expand the envvar381        # prefix automatically.382        if auto_envvar_prefix is None:383            if (384                parent is not None385                and parent.auto_envvar_prefix is not None386                and self.info_name is not None387            ):388                auto_envvar_prefix = (389                    f"{parent.auto_envvar_prefix}_{self.info_name.upper()}"390                )391        else:392            auto_envvar_prefix = auto_envvar_prefix.upper()393        if auto_envvar_prefix is not None:394            auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")395        self.auto_envvar_prefix = auto_envvar_prefix396397        if color is None and parent is not None:398            color = parent.color399400        #: Controls if styling output is wanted or not.401        self.color = color402403        if show_default is None and parent is not None:404            show_default = parent.show_default405406        #: Show option default values when formatting help text.407        self.show_default = show_default408409        self._close_callbacks = []410        self._depth = 0411        self._parameter_source = {}412        self._exit_stack = ExitStack()413414    def to_info_dict(self):415        """Gather information that could be useful for a tool generating416        user-facing documentation. This traverses the entire CLI417        structure.418419        .. code-block:: python420421            with Context(cli) as ctx:422                info = ctx.to_info_dict()423424        .. versionadded:: 8.0425        """426        return {427            "command": self.command.to_info_dict(self),428            "info_name": self.info_name,429            "allow_extra_args": self.allow_extra_args,430            "allow_interspersed_args": self.allow_interspersed_args,431            "ignore_unknown_options": self.ignore_unknown_options,432            "auto_envvar_prefix": self.auto_envvar_prefix,433        }434435    def __enter__(self):436        self._depth += 1437        push_context(self)438        return self439440    def __exit__(self, exc_type, exc_value, tb):441        self._depth -= 1442        if self._depth == 0:443            self.close()444        pop_context()445446    @contextmanager447    def scope(self, cleanup=True):448        """This helper method can be used with the context object to promote449        it to the current thread local (see :func:`get_current_context`).450        The default behavior of this is to invoke the cleanup functions which451        can be disabled by setting `cleanup` to `False`.  The cleanup452        functions are typically used for things such as closing file handles.453454        If the cleanup is intended the context object can also be directly455        used as a context manager.456457        Example usage::458459            with ctx.scope():460                assert get_current_context() is ctx461462        This is equivalent::463464            with ctx:465                assert get_current_context() is ctx466467        .. versionadded:: 5.0468469        :param cleanup: controls if the cleanup functions should be run or470                        not.  The default is to run these functions.  In471                        some situations the context only wants to be472                        temporarily pushed in which case this can be disabled.473                        Nested pushes automatically defer the cleanup.474        """475        if not cleanup:476            self._depth += 1477        try:478            with self as rv:479                yield rv480        finally:481            if not cleanup:482                self._depth -= 1483484    @property485    def meta(self):486        """This is a dictionary which is shared with all the contexts487        that are nested.  It exists so that click utilities can store some488        state here if they need to.  It is however the responsibility of489        that code to manage this dictionary well.490491        The keys are supposed to be unique dotted strings.  For instance492        module paths are a good choice for it.  What is stored in there is493        irrelevant for the operation of click.  However what is important is494        that code that places data here adheres to the general semantics of495        the system.496497        Example usage::498499            LANG_KEY = f'{__name__}.lang'500501            def set_language(value):502                ctx = get_current_context()503                ctx.meta[LANG_KEY] = value504505            def get_language():506                return get_current_context().meta.get(LANG_KEY, 'en_US')507508        .. versionadded:: 5.0509        """510        return self._meta511512    def make_formatter(self):513        """Creates the :class:`~click.HelpFormatter` for the help and514        usage output.515516        To quickly customize the formatter class used without overriding517        this method, set the :attr:`formatter_class` attribute.518519        .. versionchanged:: 8.0520            Added the :attr:`formatter_class` attribute.521        """522        return self.formatter_class(523            width=self.terminal_width, max_width=self.max_content_width524        )525526    def with_resource(self, context_manager):527        """Register a resource as if it were used in a ``with``528        statement. The resource will be cleaned up when the context is529        popped.530531        Uses :meth:`contextlib.ExitStack.enter_context`. It calls the532        resource's ``__enter__()`` method and returns the result. When533        the context is popped, it closes the stack, which calls the534        resource's ``__exit__()`` method.535536        To register a cleanup function for something that isn't a537        context manager, use :meth:`call_on_close`. Or use something538        from :mod:`contextlib` to turn it into a context manager first.539540        .. code-block:: python541542            @click.group()543            @click.option("--name")544            @click.pass_context545            def cli(ctx):546                ctx.obj = ctx.with_resource(connect_db(name))547548        :param context_manager: The context manager to enter.549        :return: Whatever ``context_manager.__enter__()`` returns.550551        .. versionadded:: 8.0552        """553        return self._exit_stack.enter_context(context_manager)554555    def call_on_close(self, f):556        """Register a function to be called when the context tears down.557558        This can be used to close resources opened during the script559        execution. Resources that support Python's context manager560        protocol which would be used in a ``with`` statement should be561        registered with :meth:`with_resource` instead.562563        :param f: The function to execute on teardown.564        """565        return self._exit_stack.callback(f)566567    def close(self):568        """Invoke all close callbacks registered with569        :meth:`call_on_close`, and exit all context managers entered570        with :meth:`with_resource`.571        """572        self._exit_stack.close()573        # In case the context is reused, create a new exit stack.574        self._exit_stack = ExitStack()575576    @property577    def command_path(self):578        """The computed command path.  This is used for the ``usage``579        information on the help page.  It's automatically created by580        combining the info names of the chain of contexts to the root.581        """582        rv = ""583        if self.info_name is not None:584            rv = self.info_name585        if self.parent is not None:586            parent_command_path = [self.parent.command_path]587            for param in self.parent.command.get_params(self):588                parent_command_path.extend(param.get_usage_pieces(self))589            rv = f"{' '.join(parent_command_path)} {rv}"590        return rv.lstrip()591592    def find_root(self):593        """Finds the outermost context."""594        node = self595        while node.parent is not None:596            node = node.parent597        return node598599    def find_object(self, object_type):600        """Finds the closest object of a given type."""601        node = self602        while node is not None:603            if isinstance(node.obj, object_type):604                return node.obj605            node = node.parent606607    def ensure_object(self, object_type):608        """Like :meth:`find_object` but sets the innermost object to a609        new instance of `object_type` if it does not exist.610        """611        rv = self.find_object(object_type)612        if rv is None:613            self.obj = rv = object_type()614        return rv615616    def lookup_default(self, name, call=True):617        """Get the default for a parameter from :attr:`default_map`.618619        :param name: Name of the parameter.620        :param call: If the default is a callable, call it. Disable to621            return the callable instead.622623        .. versionchanged:: 8.0624            Added the ``call`` parameter.625        """626        if self.default_map is not None:627            value = self.default_map.get(name)628629            if call and callable(value):630                return value()631632            return value633634    def fail(self, message):635        """Aborts the execution of the program with a specific error636        message.637638        :param message: the error message to fail with.639        """640        raise UsageError(message, self)641642    def abort(self):643        """Aborts the script."""644        raise Abort()645646    def exit(self, code=0):647        """Exits the application with a given exit code."""648        raise Exit(code)649650    def get_usage(self):651        """Helper method to get formatted usage string for the current652        context and command.653        """654        return self.command.get_usage(self)655656    def get_help(self):657        """Helper method to get formatted help page for the current658        context and command.659        """660        return self.command.get_help(self)661662    def _make_sub_context(self, command):663        """Create a new context of the same type as this context, but664        for a new command.665666        :meta private:667        """668        return type(self)(command, info_name=command.name, parent=self)669670    def invoke(*args, **kwargs):  # noqa: B902671        """Invokes a command callback in exactly the way it expects.  There672        are two ways to invoke this method:673674        1.  the first argument can be a callback and all other arguments and675            keyword arguments are forwarded directly to the function.676        2.  the first argument is a click command object.  In that case all677            arguments are forwarded as well but proper click parameters678            (options and click arguments) must be keyword arguments and Click679            will fill in defaults.680681        Note that before Click 3.2 keyword arguments were not properly filled682        in against the intention of this code and no context was created.  For683        more information about this change and why it was done in a bugfix684        release see :ref:`upgrade-to-3.2`.685        """686        self, callback = args[:2]687        ctx = self688689        # It's also possible to invoke another command which might or690        # might not have a callback.  In that case we also fill691        # in defaults and make a new context for this command.692        if isinstance(callback, Command):693            other_cmd = callback694            callback = other_cmd.callback695696            if callback is None:697                raise TypeError(698                    "The given command does not have a callback that can be invoked."699                )700701            ctx = self._make_sub_context(other_cmd)702703            for param in other_cmd.params:704                if param.name not in kwargs and param.expose_value:705                    kwargs[param.name] = param.get_default(ctx)706707        args = args[2:]708        with augment_usage_errors(self):709            with ctx:710                return callback(*args, **kwargs)711712    def forward(*args, **kwargs):  # noqa: B902713        """Similar to :meth:`invoke` but fills in default keyword714        arguments from the current context if the other command expects715        it.  This cannot invoke callbacks directly, only other commands.716        """717        self, cmd = args[:2]718719        # Can only forward to other commands, not direct callbacks.720        if not isinstance(cmd, Command):721            raise TypeError("Callback is not a command.")722723        for param in self.params:724            if param not in kwargs:725                kwargs[param] = self.params[param]726727        return self.invoke(cmd, **kwargs)728729    def set_parameter_source(self, name, source):730        """Set the source of a parameter. This indicates the location731        from which the value of the parameter was obtained.732733        :param name: The name of the parameter.734        :param source: A member of :class:`~click.core.ParameterSource`.735        """736        self._parameter_source[name] = source737738    def get_parameter_source(self, name):739        """Get the source of a parameter. This indicates the location740        from which the value of the parameter was obtained.741742        This can be useful for determining when a user specified a value743        on the command line that is the same as the default value. It744        will be :attr:`~click.core.ParameterSource.DEFAULT` only if the745        value was actually taken from the default.746747        :param name: The name of the parameter.748        :rtype: ParameterSource749750        .. versionchanged:: 8.0751            Returns ``None`` if the parameter was not provided from any752            source.753        """754        return self._parameter_source.get(name)755756757class BaseCommand:758    """The base command implements the minimal API contract of commands.759    Most code will never use this as it does not implement a lot of useful760    functionality but it can act as the direct subclass of alternative761    parsing methods that do not depend on the Click parser.762763    For instance, this can be used to bridge Click and other systems like764    argparse or docopt.765766    Because base commands do not implement a lot of the API that other767    parts of Click take for granted, they are not supported for all768    operations.  For instance, they cannot be used with the decorators769    usually and they have no built-in callback system.770771    .. versionchanged:: 2.0772       Added the `context_settings` parameter.773774    :param name: the name of the command to use unless a group overrides it.775    :param context_settings: an optional dictionary with defaults that are776                             passed to the context object.777    """778779    #: The context class to create with :meth:`make_context`.780    #:781    #: .. versionadded:: 8.0782    context_class = Context783    #: the default for the :attr:`Context.allow_extra_args` flag.784    allow_extra_args = False785    #: the default for the :attr:`Context.allow_interspersed_args` flag.786    allow_interspersed_args = True787    #: the default for the :attr:`Context.ignore_unknown_options` flag.788    ignore_unknown_options = False789790    def __init__(self, name, context_settings=None):791        #: the name the command thinks it has.  Upon registering a command792        #: on a :class:`Group` the group will default the command name793        #: with this information.  You should instead use the794        #: :class:`Context`\'s :attr:`~Context.info_name` attribute.795        self.name = name796        if context_settings is None:797            context_settings = {}798        #: an optional dictionary with defaults passed to the context.799        self.context_settings = context_settings800801    def to_info_dict(self, ctx):802        """Gather information that could be useful for a tool generating803        user-facing documentation. This traverses the entire structure804        below this command.805806        Use :meth:`click.Context.to_info_dict` to traverse the entire807        CLI structure.808809        :param ctx: A :class:`Context` representing this command.810811        .. versionadded:: 8.0812        """813        return {"name": self.name}814815    def __repr__(self):816        return f"<{self.__class__.__name__} {self.name}>"817818    def get_usage(self, ctx):819        raise NotImplementedError("Base commands cannot get usage")820821    def get_help(self, ctx):822        raise NotImplementedError("Base commands cannot get help")823824    def make_context(self, info_name, args, parent=None, **extra):825        """This function when given an info name and arguments will kick826        off the parsing and create a new :class:`Context`.  It does not827        invoke the actual command callback though.828829        To quickly customize the context class used without overriding830        this method, set the :attr:`context_class` attribute.831832        :param info_name: the info name for this invokation.  Generally this833                          is the most descriptive name for the script or834                          command.  For the toplevel script it's usually835                          the name of the script, for commands below it it's836                          the name of the script.837        :param args: the arguments to parse as list of strings.838        :param parent: the parent context if available.839        :param extra: extra keyword arguments forwarded to the context840                      constructor.841842        .. versionchanged:: 8.0843            Added the :attr:`context_class` attribute.844        """845        for key, value in self.context_settings.items():846            if key not in extra:847                extra[key] = value848849        ctx = self.context_class(self, info_name=info_name, parent=parent, **extra)850851        with ctx.scope(cleanup=False):852            self.parse_args(ctx, args)853        return ctx854855    def parse_args(self, ctx, args):856        """Given a context and a list of arguments this creates the parser857        and parses the arguments, then modifies the context as necessary.858        This is automatically invoked by :meth:`make_context`.859        """860        raise NotImplementedError("Base commands do not know how to parse arguments.")861862    def invoke(self, ctx):863        """Given a context, this invokes the command.  The default864        implementation is raising a not implemented error.865        """866        raise NotImplementedError("Base commands are not invokable by default")867868    def shell_complete(self, ctx, incomplete):869        """Return a list of completions for the incomplete value. Looks870        at the names of chained multi-commands.871872        Any command could be part of a chained multi-command, so sibling873        commands are valid at any point during command completion. Other874        command classes will return more completions.875876        :param ctx: Invocation context for this command.877        :param incomplete: Value being completed. May be empty.878879        .. versionadded:: 8.0880        """881        from click.shell_completion import CompletionItem882883        results = []884885        while ctx.parent is not None:886            ctx = ctx.parent887888            if isinstance(ctx.command, MultiCommand) and ctx.command.chain:889                results.extend(890                    CompletionItem(name, help=command.get_short_help_str())891                    for name, command in _complete_visible_commands(ctx, incomplete)892                    if name not in ctx.protected_args893                )894895        return results896897    def main(898        self,899        args=None,900        prog_name=None,901        complete_var=None,902        standalone_mode=True,903        **extra,904    ):905        """This is the way to invoke a script with all the bells and906        whistles as a command line application.  This will always terminate907        the application after a call.  If this is not wanted, ``SystemExit``908        needs to be caught.909910        This method is also available by directly calling the instance of911        a :class:`Command`.912913        .. versionadded:: 3.0914           Added the `standalone_mode` flag to control the standalone mode.915916        :param args: the arguments that should be used for parsing.  If not917                     provided, ``sys.argv[1:]`` is used.918        :param prog_name: the program name that should be used.  By default919                          the program name is constructed by taking the file920                          name from ``sys.argv[0]``.921        :param complete_var: the environment variable that controls the922                             bash completion support.  The default is923                             ``"_<prog_name>_COMPLETE"`` with prog_name in924                             uppercase.925        :param standalone_mode: the default behavior is to invoke the script926                                in standalone mode.  Click will then927                                handle exceptions and convert them into928                                error messages and the function will never929                                return but shut down the interpreter.  If930                                this is set to `False` they will be931                                propagated to the caller and the return932                                value of this function is the return value933                                of :meth:`invoke`.934        :param extra: extra keyword arguments are forwarded to the context935                      constructor.  See :class:`Context` for more information.936        """937        # Verify that the environment is configured correctly, or reject938        # further execution to avoid a broken script.939        _verify_python_env()940941        if args is None:942            args = sys.argv[1:]943        else:944            args = list(args)945946        if prog_name is None:947            prog_name = _detect_program_name()948949        # Process shell completion requests and exit early.950        self._main_shell_completion(extra, prog_name, complete_var)951952        try:953            try:954                with self.make_context(prog_name, args, **extra) as ctx:955                    rv = self.invoke(ctx)956                    if not standalone_mode:957                        return rv958                    # it's not safe to `ctx.exit(rv)` here!959                    # note that `rv` may actually contain data like "1" which960                    # has obvious effects961                    # more subtle case: `rv=[None, None]` can come out of962                    # chained commands which all returned `None` -- so it's not963                    # even always obvious that `rv` indicates success/failure964                    # by its truthiness/falsiness965                    ctx.exit()966            except (EOFError, KeyboardInterrupt):967                echo(file=sys.stderr)968                raise Abort()969            except ClickException as e:970                if not standalone_mode:971                    raise972                e.show()973                sys.exit(e.exit_code)974            except OSError as e:975                if e.errno == errno.EPIPE:976                    sys.stdout = PacifyFlushWrapper(sys.stdout)977                    sys.stderr = PacifyFlushWrapper(sys.stderr)978                    sys.exit(1)979                else:980                    raise981        except Exit as e:982            if standalone_mode:983                sys.exit(e.exit_code)984            else:985                # in non-standalone mode, return the exit code986                # note that this is only reached if `self.invoke` above raises987                # an Exit explicitly -- thus bypassing the check there which988                # would return its result989                # the results of non-standalone execution may therefore be990                # somewhat ambiguous: if there are codepaths which lead to991                # `ctx.exit(1)` and to `return 1`, the caller won't be able to992                # tell the difference between the two993                return e.exit_code994        except Abort:995            if not standalone_mode:996                raise997            echo("Aborted!", file=sys.stderr)998            sys.exit(1)9991000    def _main_shell_completion(self, ctx_args, prog_name, complete_var=None):1001        """Check if the shell is asking for tab completion, process1002        that, then exit early. Called from :meth:`main` before the1003        program is invoked.10041005        :param prog_name: Name of the executable in the shell.1006        :param complete_var: Name of the environment variable that holds1007            the completion instruction. Defaults to1008            ``_{PROG_NAME}_COMPLETE``.1009        """1010        if complete_var is None:1011            complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper()10121013        instruction = os.environ.get(complete_var)10141015        if not instruction:1016            return10171018        from .shell_completion import shell_complete10191020        rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)1021        _fast_exit(rv)10221023    def __call__(self, *args, **kwargs):1024        """Alias for :meth:`main`."""1025        return self.main(*args, **kwargs)102610271028class Command(BaseCommand):1029    """Commands are the basic building block of command line interfaces in1030    Click.  A basic command handles command line parsing and might dispatch1031    more parsing to commands nested below it.10321033    .. versionchanged:: 2.01034       Added the `context_settings` parameter.1035    .. versionchanged:: 8.01036       Added repr showing the command name1037    .. versionchanged:: 7.11038       Added the `no_args_is_help` parameter.10391040    :param name: the name of the command to use unless a group overrides it.1041    :param context_settings: an optional dictionary with defaults that are1042                             passed to the context object.1043    :param callback: the callback to invoke.  This is optional.1044    :param params: the parameters to register with this command.  This can1045                   be either :class:`Option` or :class:`Argument` objects.1046    :param help: the help string to use for this command.1047    :param epilog: like the help string but it's printed at the end of the1048                   help page after everything else.1049    :param short_help: the short help to use for this command.  This is1050                       shown on the command listing of the parent command.1051    :param add_help_option: by default each command registers a ``--help``1052                            option.  This can be disabled by this parameter.1053    :param no_args_is_help: this controls what happens if no arguments are1054                            provided.  This option is disabled by default.1055                            If enabled this will add ``--help`` as argument1056                            if no arguments are passed1057    :param hidden: hide this command from help outputs.10581059    :param deprecated: issues a message indicating that1060                             the command is deprecated.1061    """10621063    def __init__(1064        self,1065        name,1066        context_settings=None,1067        callback=None,1068        params=None,1069        help=None,1070        epilog=None,1071        short_help=None,1072        options_metavar="[OPTIONS]",1073        add_help_option=True,1074        no_args_is_help=False,1075        hidden=False,1076        deprecated=False,1077    ):1078        super().__init__(name, context_settings)1079        #: the callback to execute when the command fires.  This might be1080        #: `None` in which case nothing happens.1081        self.callback = callback1082        #: the list of parameters for this command in the order they1083        #: should show up in the help page and execute.  Eager parameters1084        #: will automatically be handled before non eager ones.1085        self.params = params or []1086        # if a form feed (page break) is found in the help text, truncate help1087        # text to the content preceding the first form feed1088        if help and "\f" in help:1089            help = help.split("\f", 1)[0]1090        self.help = help1091        self.epilog = epilog1092        self.options_metavar = options_metavar1093        self.short_help = short_help1094        self.add_help_option = add_help_option1095        self.no_args_is_help = no_args_is_help1096        self.hidden = hidden1097        self.deprecated = deprecated10981099    def to_info_dict(self, ctx):1100        info_dict = super().to_info_dict(ctx)1101        info_dict.update(1102            params=[param.to_info_dict() for param in self.get_params(ctx)],1103            help=self.help,1104            epilog=self.epilog,1105            short_help=self.short_help,1106            hidden=self.hidden,1107            deprecated=self.deprecated,1108        )1109        return info_dict11101111    def __repr__(self):1112        return f"<{self.__class__.__name__} {self.name}>"11131114    def get_usage(self, ctx):1115        """Formats the usage line into a string and returns it.11161117        Calls :meth:`format_usage` internally.1118        """1119        formatter = ctx.make_formatter()1120        self.format_usage(ctx, formatter)1121        return formatter.getvalue().rstrip("\n")11221123    def get_params(self, ctx):1124        rv = self.params1125        help_option = self.get_help_option(ctx)1126        if help_option is not None:1127            rv = rv + [help_option]1128        return rv11291130    def format_usage(self, ctx, formatter):1131        """Writes the usage line into the formatter.11321133        This is a low-level method called by :meth:`get_usage`.1134        """1135        pieces = self.collect_usage_pieces(ctx)1136        formatter.write_usage(ctx.command_path, " ".join(pieces))11371138    def collect_usage_pieces(self, ctx):1139        """Returns all the pieces that go into the usage line and returns1140        it as a list of strings.1141        """1142        rv = [self.options_metavar] if self.options_metavar else []1143        for param in self.get_params(ctx):1144            rv.extend(param.get_usage_pieces(ctx))1145        return rv11461147    def get_help_option_names(self, ctx):1148        """Returns the names for the help option."""1149        all_names = set(ctx.help_option_names)1150        for param in self.params:1151            all_names.difference_update(param.opts)1152            all_names.difference_update(param.secondary_opts)1153        return all_names11541155    def get_help_option(self, ctx):1156        """Returns the help option object."""1157        help_options = self.get_help_option_names(ctx)1158        if not help_options or not self.add_help_option:1159            return11601161        def show_help(ctx, param, value):1162            if value and not ctx.resilient_parsing:1163                echo(ctx.get_help(), color=ctx.color)1164                ctx.exit()11651166        return Option(1167            help_options,1168            is_flag=True,1169            is_eager=True,1170            expose_value=False,1171            callback=show_help,1172            help="Show this message and exit.",1173        )11741175    def make_parser(self, ctx):1176        """Creates the underlying option parser for this command."""1177        parser = OptionParser(ctx)1178        for param in self.get_params(ctx):1179            param.add_to_parser(parser, ctx)1180        return parser11811182    def get_help(self, ctx):1183        """Formats the help into a string and returns it.11841185        Calls :meth:`format_help` internally.1186        """1187        formatter = ctx.make_formatter()1188        self.format_help(ctx, formatter)1189        return formatter.getvalue().rstrip("\n")11901191    def get_short_help_str(self, limit=45):1192        """Gets short help for the command or makes it by shortening the1193        long help string.1194        """1195        return (1196            self.short_help1197            or self.help1198            and make_default_short_help(self.help, limit)1199            or ""1200        )12011202    def format_help(self, ctx, formatter):1203        """Writes the help into the formatter if it exists.12041205        This is a low-level method called by :meth:`get_help`.12061207        This calls the following methods:12081209        -   :meth:`format_usage`1210        -   :meth:`format_help_text`1211        -   :meth:`format_options`1212        -   :meth:`format_epilog`1213        """1214        self.format_usage(ctx, formatter)1215        self.format_help_text(ctx, formatter)1216        self.format_options(ctx, formatter)1217        self.format_epilog(ctx, formatter)12181219    def format_help_text(self, ctx, formatter):1220        """Writes the help text to the formatter if it exists."""1221        if self.help:1222            formatter.write_paragraph()1223            with formatter.indentation():1224                help_text = self.help1225                if self.deprecated:1226                    help_text += DEPRECATED_HELP_NOTICE1227                formatter.write_text(help_text)1228        elif self.deprecated:1229            formatter.write_paragraph()1230            with formatter.indentation():1231                formatter.write_text(DEPRECATED_HELP_NOTICE)12321233    def format_options(self, ctx, formatter):1234        """Writes all the options into the formatter if they exist."""1235        opts = []1236        for param in self.get_params(ctx):1237            rv = param.get_help_record(ctx)1238            if rv is not None:1239                opts.append(rv)12401241        if opts:1242            with formatter.section("Options"):1243                formatter.write_dl(opts)12441245    def format_epilog(self, ctx, formatter):1246        """Writes the epilog into the formatter if it exists."""1247        if self.epilog:1248            formatter.write_paragraph()1249            with formatter.indentation():1250                formatter.write_text(self.epilog)12511252    def parse_args(self, ctx, args):1253        if not args and self.no_args_is_help and not ctx.resilient_parsing:1254            echo(ctx.get_help(), color=ctx.color)1255            ctx.exit()12561257        parser = self.make_parser(ctx)1258        opts, args, param_order = parser.parse_args(args=args)12591260        for param in iter_params_for_processing(param_order, self.get_params(ctx)):1261            value, args = param.handle_parse_result(ctx, opts, args)12621263        if args and not ctx.allow_extra_args and not ctx.resilient_parsing:1264            ctx.fail(1265                "Got unexpected extra"1266                f" argument{'s' if len(args) != 1 else ''}"1267                f" ({' '.join(map(make_str, args))})"1268            )12691270        ctx.args = args1271        return args12721273    def invoke(self, ctx):1274        """Given a context, this invokes the attached callback (if it exists)1275        in the right way.1276        """1277        _maybe_show_deprecated_notice(self)1278        if self.callback is not None:1279            return ctx.invoke(self.callback, **ctx.params)12801281    def shell_complete(self, ctx, incomplete):1282        """Return a list of completions for the incomplete value. Looks1283        at the names of options and chained multi-commands.12841285        :param ctx: Invocation context for this command.1286        :param incomplete: Value being completed. May be empty.12871288        .. versionadded:: 8.01289        """1290        from click.shell_completion import CompletionItem12911292        results = []12931294        if incomplete and not incomplete[0].isalnum():1295            for param in self.get_params(ctx):1296                if (1297                    not isinstance(param, Option)1298                    or param.hidden1299                    or (1300                        not param.multiple1301                        and ctx.get_parameter_source(param.name)1302                        is ParameterSource.COMMANDLINE1303                    )1304                ):1305                    continue13061307                results.extend(1308                    CompletionItem(name, help=param.help)1309                    for name in param.opts + param.secondary_opts1310                    if name.startswith(incomplete)1311                )13121313        results.extend(super().shell_complete(ctx, incomplete))1314        return results131513161317class MultiCommand(Command):1318    """A multi command is the basic implementation of a command that1319    dispatches to subcommands.  The most common version is the1320    :class:`Group`.13211322    :param invoke_without_command: this controls how the multi command itself1323                                   is invoked.  By default it's only invoked1324                                   if a subcommand is provided.1325    :param no_args_is_help: this controls what happens if no arguments are1326                            provided.  This option is enabled by default if1327                            `invoke_without_command` is disabled or disabled1328                            if it's enabled.  If enabled this will add1329                            ``--help`` as argument if no arguments are1330                            passed.1331    :param subcommand_metavar: the string that is used in the documentation1332                               to indicate the subcommand place.1333    :param chain: if this is set to `True` chaining of multiple subcommands1334                  is enabled.  This restricts the form of commands in that1335                  they cannot have optional arguments but it allows1336                  multiple commands to be chained together.1337    :param result_callback: the result callback to attach to this multi1338                            command.1339    """13401341    allow_extra_args = True1342    allow_interspersed_args = False13431344    def __init__(1345        self,1346        name=None,1347        invoke_without_command=False,1348        no_args_is_help=None,1349        subcommand_metavar=None,1350        chain=False,1351        result_callback=None,1352        **attrs,1353    ):1354        super().__init__(name, **attrs)1355        if no_args_is_help is None:1356            no_args_is_help = not invoke_without_command1357        self.no_args_is_help = no_args_is_help1358        self.invoke_without_command = invoke_without_command1359        if subcommand_metavar is None:1360            if chain:1361                subcommand_metavar = SUBCOMMANDS_METAVAR1362            else:1363                subcommand_metavar = SUBCOMMAND_METAVAR1364        self.subcommand_metavar = subcommand_metavar1365        self.chain = chain1366        #: The result callback that is stored.  This can be set or1367        #: overridden with the :func:`resultcallback` decorator.1368        self.result_callback = result_callback13691370        if self.chain:1371            for param in self.params:1372                if isinstance(param, Argument) and not param.required:1373                    raise RuntimeError(1374                        "Multi commands in chain mode cannot have"1375                        " optional arguments."1376                    )13771378    def to_info_dict(self, ctx):1379        info_dict = super().to_info_dict(ctx)1380        commands = {}13811382        for name in self.list_commands(ctx):1383            command = self.get_command(ctx, name)1384            sub_ctx = ctx._make_sub_context(command)13851386            with sub_ctx.scope(cleanup=False):1387                commands[name] = command.to_info_dict(sub_ctx)13881389        info_dict.update(commands=commands, chain=self.chain)1390        return info_dict13911392    def collect_usage_pieces(self, ctx):1393        rv = super().collect_usage_pieces(ctx)1394        rv.append(self.subcommand_metavar)1395        return rv13961397    def format_options(self, ctx, formatter):1398        super().format_options(ctx, formatter)1399        self.format_commands(ctx, formatter)14001401    def resultcallback(self, replace=False):1402        """Adds a result callback to the command.  By default if a1403        result callback is already registered this will chain them but1404        this can be disabled with the `replace` parameter.  The result1405        callback is invoked with the return value of the subcommand1406        (or the list of return values from all subcommands if chaining1407        is enabled) as well as the parameters as they would be passed1408        to the main callback.14091410        Example::14111412            @click.group()1413            @click.option('-i', '--input', default=23)1414            def cli(input):1415                return 4214161417            @cli.resultcallback()1418            def process_result(result, input):1419                return result + input14201421        :param replace: if set to `True` an already existing result1422                        callback will be removed.14231424        .. versionadded:: 3.01425        """14261427        def decorator(f):1428            old_callback = self.result_callback1429            if old_callback is None or replace:1430                self.result_callback = f1431                return f14321433            def function(__value, *args, **kwargs):1434                return f(old_callback(__value, *args, **kwargs), *args, **kwargs)14351436            self.result_callback = rv = update_wrapper(function, f)1437            return rv14381439        return decorator14401441    def format_commands(self, ctx, formatter):1442        """Extra format methods for multi methods that adds all the commands1443        after the options.1444        """1445        commands = []1446        for subcommand in self.list_commands(ctx):1447            cmd = self.get_command(ctx, subcommand)1448            # What is this, the tool lied about a command.  Ignore it1449            if cmd is None:1450                continue1451            if cmd.hidden:1452                continue14531454            commands.append((subcommand, cmd))14551456        # allow for 3 times the default spacing1457        if len(commands):1458            limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands)14591460            rows = []1461            for subcommand, cmd in commands:1462                help = cmd.get_short_help_str(limit)1463                rows.append((subcommand, help))14641465            if rows:1466                with formatter.section("Commands"):1467                    formatter.write_dl(rows)14681469    def parse_args(self, ctx, args):1470        if not args and self.no_args_is_help and not ctx.resilient_parsing:1471            echo(ctx.get_help(), color=ctx.color)1472            ctx.exit()14731474        rest = super().parse_args(ctx, args)14751476        if self.chain:1477            ctx.protected_args = rest1478            ctx.args = []1479        elif rest:1480            ctx.protected_args, ctx.args = rest[:1], rest[1:]14811482        return ctx.args14831484    def invoke(self, ctx):1485        def _process_result(value):1486            if self.result_callback is not None:1487                value = ctx.invoke(self.result_callback, value, **ctx.params)1488            return value14891490        if not ctx.protected_args:1491            if self.invoke_without_command:1492                # No subcommand was invoked, so the result callback is1493                # invoked with None for regular groups, or an empty list1494                # for chained groups.1495                with ctx:1496                    super().invoke(ctx)1497                    return _process_result([] if self.chain else None)1498            ctx.fail("Missing command.")14991500        # Fetch args back out1501        args = ctx.protected_args + ctx.args1502        ctx.args = []1503        ctx.protected_args = []15041505        # If we're not in chain mode, we only allow the invocation of a1506        # single command but we also inform the current context about the1507        # name of the command to invoke.1508        if not self.chain:1509            # Make sure the context is entered so we do not clean up1510            # resources until the result processor has worked.1511            with ctx:1512                cmd_name, cmd, args = self.resolve_command(ctx, args)1513                ctx.invoked_subcommand = cmd_name1514                super().invoke(ctx)1515                sub_ctx = cmd.make_context(cmd_name, args, parent=ctx)1516                with sub_ctx:1517                    return _process_result(sub_ctx.command.invoke(sub_ctx))15181519        # In chain mode we create the contexts step by step, but after the1520        # base command has been invoked.  Because at that point we do not1521        # know the subcommands yet, the invoked subcommand attribute is1522        # set to ``*`` to inform the command that subcommands are executed1523        # but nothing else.1524        with ctx:1525            ctx.invoked_subcommand = "*" if args else None1526            super().invoke(ctx)15271528            # Otherwise we make every single context and invoke them in a1529            # chain.  In that case the return value to the result processor1530            # is the list of all invoked subcommand's results.1531            contexts = []1532            while args:1533                cmd_name, cmd, args = self.resolve_command(ctx, args)1534                sub_ctx = cmd.make_context(1535                    cmd_name,1536                    args,1537                    parent=ctx,1538                    allow_extra_args=True,1539                    allow_interspersed_args=False,1540                )1541                contexts.append(sub_ctx)1542                args, sub_ctx.args = sub_ctx.args, []15431544            rv = []1545            for sub_ctx in contexts:1546                with sub_ctx:1547                    rv.append(sub_ctx.command.invoke(sub_ctx))1548            return _process_result(rv)15491550    def resolve_command(self, ctx, args):1551        cmd_name = make_str(args[0])1552        original_cmd_name = cmd_name15531554        # Get the command1555        cmd = self.get_command(ctx, cmd_name)15561557        # If we can't find the command but there is a normalization1558        # function available, we try with that one.1559        if cmd is None and ctx.token_normalize_func is not None:1560            cmd_name = ctx.token_normalize_func(cmd_name)1561            cmd = self.get_command(ctx, cmd_name)15621563        # If we don't find the command we want to show an error message1564        # to the user that it was not provided.  However, there is1565        # something else we should do: if the first argument looks like1566        # an option we want to kick off parsing again for arguments to1567        # resolve things like --help which now should go to the main1568        # place.1569        if cmd is None and not ctx.resilient_parsing:1570            if split_opt(cmd_name)[0]:1571                self.parse_args(ctx, ctx.args)1572            ctx.fail(f"No such command '{original_cmd_name}'.")1573        return cmd.name if cmd else None, cmd, args[1:]15741575    def get_command(self, ctx, cmd_name):1576        """Given a context and a command name, this returns a1577        :class:`Command` object if it exists or returns `None`.1578        """1579        raise NotImplementedError()15801581    def list_commands(self, ctx):1582        """Returns a list of subcommand names in the order they should1583        appear.1584        """1585        return []15861587    def shell_complete(self, ctx, incomplete):1588        """Return a list of completions for the incomplete value. Looks1589        at the names of options, subcommands, and chained1590        multi-commands.15911592        :param ctx: Invocation context for this command.1593        :param incomplete: Value being completed. May be empty.15941595        .. versionadded:: 8.01596        """1597        from click.shell_completion import CompletionItem15981599        results = [1600            CompletionItem(name, help=command.get_short_help_str())1601            for name, command in _complete_visible_commands(ctx, incomplete)1602        ]1603        results.extend(super().shell_complete(ctx, incomplete))1604        return results160516061607class Group(MultiCommand):1608    """A group allows a command to have subcommands attached. This is1609    the most common way to implement nesting in Click.16101611    :param name: The name of the group command.1612    :param commands: A dict mapping names to :class:`Command` objects.1613        Can also be a list of :class:`Command`, which will use1614        :attr:`Command.name` to create the dict.1615    :param attrs: Other command arguments described in1616        :class:`MultiCommand`, :class:`Command`, and1617        :class:`BaseCommand`.16181619    .. versionchanged:: 8.01620        The ``commmands`` argument can be a list of command objects.1621    """16221623    #: If set, this is used by the group's :meth:`command` decorator1624    #: as the default :class:`Command` class. This is useful to make all1625    #: subcommands use a custom command class.1626    #:1627    #: .. versionadded:: 8.01628    command_class = None16291630    #: If set, this is used by the group's :meth:`group` decorator1631    #: as the default :class:`Group` class. This is useful to make all1632    #: subgroups use a custom group class.1633    #:1634    #: If set to the special value :class:`type` (literally1635    #: ``group_class = type``), this group's class will be used as the1636    #: default class. This makes a custom group class continue to make1637    #: custom groups.1638    #:1639    #: .. versionadded:: 8.01640    group_class = None16411642    def __init__(self, name=None, commands=None, **attrs):1643        super().__init__(name, **attrs)16441645        if commands is None:1646            commands = {}1647        elif isinstance(commands, (list, tuple)):1648            commands = {c.name: c for c in commands}16491650        #: The registered subcommands by their exported names.1651        self.commands = commands16521653    def add_command(self, cmd, name=None):1654        """Registers another :class:`Command` with this group.  If the name1655        is not provided, the name of the command is used.1656        """1657        name = name or cmd.name1658        if name is None:1659            raise TypeError("Command has no name.")1660        _check_multicommand(self, name, cmd, register=True)1661        self.commands[name] = cmd16621663    def command(self, *args, **kwargs):1664        """A shortcut decorator for declaring and attaching a command to1665        the group. This takes the same arguments as :func:`command` and1666        immediately registers the created command with this group by1667        calling :meth:`add_command`.16681669        To customize the command class used, set the1670        :attr:`command_class` attribute.16711672        .. versionchanged:: 8.01673            Added the :attr:`command_class` attribute.1674        """1675        from .decorators import command16761677        if self.command_class is not None and "cls" not in kwargs:1678            kwargs["cls"] = self.command_class16791680        def decorator(f):1681            cmd = command(*args, **kwargs)(f)1682            self.add_command(cmd)1683            return cmd16841685        return decorator16861687    def group(self, *args, **kwargs):1688        """A shortcut decorator for declaring and attaching a group to1689        the group. This takes the same arguments as :func:`group` and1690        immediately registers the created group with this group by1691        calling :meth:`add_command`.16921693        To customize the group class used, set the :attr:`group_class`1694        attribute.16951696        .. versionchanged:: 8.01697            Added the :attr:`group_class` attribute.1698        """1699        from .decorators import group17001701        if self.group_class is not None and "cls" not in kwargs:1702            if self.group_class is type:1703                kwargs["cls"] = type(self)1704            else:1705                kwargs["cls"] = self.group_class17061707        def decorator(f):1708            cmd = group(*args, **kwargs)(f)1709            self.add_command(cmd)1710            return cmd17111712        return decorator17131714    def get_command(self, ctx, cmd_name):1715        return self.commands.get(cmd_name)17161717    def list_commands(self, ctx):1718        return sorted(self.commands)171917201721class CommandCollection(MultiCommand):1722    """A command collection is a multi command that merges multiple multi1723    commands together into one.  This is a straightforward implementation1724    that accepts a list of different multi commands as sources and1725    provides all the commands for each of them.1726    """17271728    def __init__(self, name=None, sources=None, **attrs):1729        super().__init__(name, **attrs)1730        #: The list of registered multi commands.1731        self.sources = sources or []17321733    def add_source(self, multi_cmd):1734        """Adds a new multi command to the chain dispatcher."""1735        self.sources.append(multi_cmd)17361737    def get_command(self, ctx, cmd_name):1738        for source in self.sources:1739            rv = source.get_command(ctx, cmd_name)1740            if rv is not None:1741                if self.chain:1742                    _check_multicommand(self, cmd_name, rv)1743                return rv17441745    def list_commands(self, ctx):1746        rv = set()1747        for source in self.sources:1748            rv.update(source.list_commands(ctx))1749        return sorted(rv)175017511752class Parameter:1753    r"""A parameter to a command comes in two versions: they are either1754    :class:`Option`\s or :class:`Argument`\s.  Other subclasses are currently1755    not supported by design as some of the internals for parsing are1756    intentionally not finalized.17571758    Some settings are supported by both options and arguments.17591760    :param param_decls: the parameter declarations for this option or1761                        argument.  This is a list of flags or argument1762                        names.1763    :param type: the type that should be used.  Either a :class:`ParamType`1764                 or a Python type.  The later is converted into the former1765                 automatically if supported.1766    :param required: controls if this is optional or not.1767    :param default: the default value if omitted.  This can also be a callable,1768                    in which case it's invoked when the default is needed1769                    without any arguments.1770    :param callback: a callback that should be executed after the parameter1771                     was matched.  This is called as ``fn(ctx, param,1772                     value)`` and needs to return the value.1773    :param nargs: the number of arguments to match.  If not ``1`` the return1774                  value is a tuple instead of single value.  The default for1775                  nargs is ``1`` (except if the type is a tuple, then it's1776                  the arity of the tuple). If ``nargs=-1``, all remaining1777                  parameters are collected.1778    :param metavar: how the value is represented in the help page.1779    :param expose_value: if this is `True` then the value is passed onwards1780                         to the command callback and stored on the context,1781                         otherwise it's skipped.1782    :param is_eager: eager values are processed before non eager ones.  This1783                     should not be set for arguments or it will inverse the1784                     order of processing.1785    :param envvar: a string or list of strings that are environment variables1786                   that should be checked.1787    :param shell_complete: A function that returns custom shell1788        completions. Used instead of the param's type completion if1789        given. Takes ``ctx, param, incomplete`` and must return a list1790        of :class:`~click.shell_completion.CompletionItem` or a list of1791        strings.17921793    .. versionchanged:: 8.01794        ``autocompletion`` is renamed to ``shell_complete`` and has new1795        semantics described above. The old name is deprecated and will1796        be removed in 8.1, until then it will be wrapped to match the1797        new requirements.17981799    .. versionchanged:: 8.01800        For ``multiple=True, nargs>1``, the default must be a list of1801        tuples.18021803    .. versionchanged:: 8.01804        Setting a default is no longer required for ``nargs>1``, it will1805        default to ``None``. ``multiple=True`` or ``nargs=-1`` will1806        default to ``()``.18071808    .. versionchanged:: 7.11809        Empty environment variables are ignored rather than taking the1810        empty string value. This makes it possible for scripts to clear1811        variables if they can't unset them.18121813    .. versionchanged:: 2.01814        Changed signature for parameter callback to also be passed the1815        parameter. The old callback format will still work, but it will1816        raise a warning to give you a chance to migrate the code easier.1817    """18181819    param_type_name = "parameter"18201821    def __init__(1822        self,1823        param_decls=None,1824        type=None,1825        required=False,1826        default=None,1827        callback=None,1828        nargs=None,1829        metavar=None,1830        expose_value=True,1831        is_eager=False,1832        envvar=None,1833        shell_complete=None,1834        autocompletion=None,1835    ):1836        self.name, self.opts, self.secondary_opts = self._parse_decls(1837            param_decls or (), expose_value1838        )18391840        self.type = convert_type(type, default)18411842        # Default nargs to what the type tells us if we have that1843        # information available.1844        if nargs is None:1845            if self.type.is_composite:1846                nargs = self.type.arity1847            else:1848                nargs = 118491850        self.required = required1851        self.callback = callback1852        self.nargs = nargs1853        self.multiple = False1854        self.expose_value = expose_value1855        self.default = default1856        self.is_eager = is_eager1857        self.metavar = metavar1858        self.envvar = envvar18591860        if autocompletion is not None:1861            import warnings18621863            warnings.warn(1864                "'autocompletion' is renamed to 'shell_complete'. The old name is"1865                " deprecated and will be removed in Click 8.1. See the docs about"1866                " 'Parameter' for information about new behavior.",1867                DeprecationWarning,1868                stacklevel=2,1869            )18701871            def shell_complete(ctx, param, incomplete):1872                from click.shell_completion import CompletionItem18731874                out = []18751876                for c in autocompletion(ctx, [], incomplete):1877                    if isinstance(c, tuple):1878                        c = CompletionItem(c[0], help=c[1])1879                    elif isinstance(c, str):1880                        c = CompletionItem(c)18811882                    if c.value.startswith(incomplete):1883                        out.append(c)18841885                return out18861887        self._custom_shell_complete = shell_complete18881889    def to_info_dict(self):1890        """Gather information that could be useful for a tool generating1891        user-facing documentation.18921893        Use :meth:`click.Context.to_info_dict` to traverse the entire1894        CLI structure.18951896        .. versionadded:: 8.01897        """1898        return {1899            "name": self.name,1900            "param_type_name": self.param_type_name,1901            "opts": self.opts,1902            "secondary_opts": self.secondary_opts,1903            "type": self.type.to_info_dict(),1904            "required": self.required,1905            "nargs": self.nargs,1906            "multiple": self.multiple,1907            "default": self.default,1908            "envvar": self.envvar,1909        }19101911    def __repr__(self):1912        return f"<{self.__class__.__name__} {self.name}>"19131914    @property1915    def human_readable_name(self):1916        """Returns the human readable name of this parameter.  This is the1917        same as the name for options, but the metavar for arguments.1918        """1919        return self.name19201921    def make_metavar(self):1922        if self.metavar is not None:1923            return self.metavar1924        metavar = self.type.get_metavar(self)1925        if metavar is None:1926            metavar = self.type.name.upper()1927        if self.nargs != 1:1928            metavar += "..."1929        return metavar19301931    def get_default(self, ctx, call=True):1932        """Get the default for the parameter. Tries1933        :meth:`Context.lookup_value` first, then the local default.19341935        :param ctx: Current context.1936        :param call: If the default is a callable, call it. Disable to1937            return the callable instead.19381939        .. versionchanged:: 8.01940            Looks at ``ctx.default_map`` first.19411942        .. versionchanged:: 8.01943            Added the ``call`` parameter.1944        """1945        value = ctx.lookup_default(self.name, call=False)19461947        if value is None:1948            value = self.default19491950        if callable(value):1951            if not call:1952                # Don't type cast the callable.1953                return value19541955            value = value()19561957        return self.type_cast_value(ctx, value)19581959    def add_to_parser(self, parser, ctx):1960        pass19611962    def consume_value(self, ctx, opts):1963        value = opts.get(self.name)1964        source = ParameterSource.COMMANDLINE19651966        if value is None:1967            value = self.value_from_envvar(ctx)1968            source = ParameterSource.ENVIRONMENT19691970        if value is None:1971            value = ctx.lookup_default(self.name)1972            source = ParameterSource.DEFAULT_MAP19731974        if value is None:1975            value = self.get_default(ctx)1976            source = ParameterSource.DEFAULT19771978        return value, source19791980    def type_cast_value(self, ctx, value):1981        """Given a value this runs it properly through the type system.1982        This automatically handles things like `nargs` and `multiple` as1983        well as composite types.1984        """1985        if value is None:1986            return () if self.multiple or self.nargs == -1 else None19871988        if self.type.is_composite:1989            if self.nargs <= 1:1990                raise TypeError(1991                    "Attempted to invoke composite type but nargs has"1992                    f" been set to {self.nargs}. This is not supported;"1993                    " nargs needs to be set to a fixed value > 1."1994                )19951996            if self.multiple:1997                return tuple(self.type(x, self, ctx) for x in value)19981999            return self.type(value, self, ctx)2000

The first 2,000 of 2,600 lines.