Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
core.py3043 linesDownload Raw Back to click
1import enum2import errno3import inspect4import os5import sys6import typing as t7from collections import abc8from contextlib import contextmanager9from contextlib import ExitStack10from functools import update_wrapper11from gettext import gettext as _12from gettext import ngettext13from itertools import repeat14from types import TracebackType15 16from . import types17from .exceptions import Abort18from .exceptions import BadParameter19from .exceptions import ClickException20from .exceptions import Exit21from .exceptions import MissingParameter22from .exceptions import UsageError23from .formatting import HelpFormatter24from .formatting import join_options25from .globals import pop_context26from .globals import push_context27from .parser import _flag_needs_value28from .parser import OptionParser29from .parser import split_opt30from .termui import confirm31from .termui import prompt32from .termui import style33from .utils import _detect_program_name34from .utils import _expand_args35from .utils import echo36from .utils import make_default_short_help37from .utils import make_str38from .utils import PacifyFlushWrapper39 40if t.TYPE_CHECKING:41    import typing_extensions as te42    from .shell_completion import CompletionItem43 44F = t.TypeVar("F", bound=t.Callable[..., t.Any])45V = t.TypeVar("V")46 47 48def _complete_visible_commands(49    ctx: "Context", incomplete: str50) -> t.Iterator[t.Tuple[str, "Command"]]:51    """List all the subcommands of a group that start with the52    incomplete value and aren't hidden.53 54    :param ctx: Invocation context for the group.55    :param incomplete: Value being completed. May be empty.56    """57    multi = t.cast(MultiCommand, ctx.command)58 59    for name in multi.list_commands(ctx):60        if name.startswith(incomplete):61            command = multi.get_command(ctx, name)62 63            if command is not None and not command.hidden:64                yield name, command65 66 67def _check_multicommand(68    base_command: "MultiCommand", cmd_name: str, cmd: "Command", register: bool = False69) -> None:70    if not base_command.chain or not isinstance(cmd, MultiCommand):71        return72    if register:73        hint = (74            "It is not possible to add multi commands as children to"75            " another multi command that is in chain mode."76        )77    else:78        hint = (79            "Found a multi command as subcommand to a multi command"80            " that is in chain mode. This is not supported."81        )82    raise RuntimeError(83        f"{hint}. Command {base_command.name!r} is set to chain and"84        f" {cmd_name!r} was added as a subcommand but it in itself is a"85        f" multi command. ({cmd_name!r} is a {type(cmd).__name__}"86        f" within a chained {type(base_command).__name__} named"87        f" {base_command.name!r})."88    )89 90 91def batch(iterable: t.Iterable[V], batch_size: int) -> t.List[t.Tuple[V, ...]]:92    return list(zip(*repeat(iter(iterable), batch_size)))93 94 95@contextmanager96def augment_usage_errors(97    ctx: "Context", param: t.Optional["Parameter"] = None98) -> t.Iterator[None]:99    """Context manager that attaches extra information to exceptions."""100    try:101        yield102    except BadParameter as e:103        if e.ctx is None:104            e.ctx = ctx105        if param is not None and e.param is None:106            e.param = param107        raise108    except UsageError as e:109        if e.ctx is None:110            e.ctx = ctx111        raise112 113 114def iter_params_for_processing(115    invocation_order: t.Sequence["Parameter"],116    declaration_order: t.Sequence["Parameter"],117) -> t.List["Parameter"]:118    """Given a sequence of parameters in the order as should be considered119    for processing and an iterable of parameters that exist, this returns120    a list in the correct order as they should be processed.121    """122 123    def sort_key(item: "Parameter") -> t.Tuple[bool, float]:124        try:125            idx: float = invocation_order.index(item)126        except ValueError:127            idx = float("inf")128 129        return not item.is_eager, idx130 131    return sorted(declaration_order, key=sort_key)132 133 134class ParameterSource(enum.Enum):135    """This is an :class:`~enum.Enum` that indicates the source of a136    parameter's value.137 138    Use :meth:`click.Context.get_parameter_source` to get the139    source for a parameter by name.140 141    .. versionchanged:: 8.0142        Use :class:`~enum.Enum` and drop the ``validate`` method.143 144    .. versionchanged:: 8.0145        Added the ``PROMPT`` value.146    """147 148    COMMANDLINE = enum.auto()149    """The value was provided by the command line args."""150    ENVIRONMENT = enum.auto()151    """The value was provided with an environment variable."""152    DEFAULT = enum.auto()153    """Used the default specified by the parameter."""154    DEFAULT_MAP = enum.auto()155    """Used a default provided by :attr:`Context.default_map`."""156    PROMPT = enum.auto()157    """Used a prompt to confirm a default or provide a value."""158 159 160class Context:161    """The context is a special internal object that holds state relevant162    for the script execution at every single level.  It's normally invisible163    to commands unless they opt-in to getting access to it.164 165    The context is useful as it can pass internal objects around and can166    control special execution features such as reading data from167    environment variables.168 169    A context can be used as context manager in which case it will call170    :meth:`close` on teardown.171 172    :param command: the command class for this context.173    :param parent: the parent context.174    :param info_name: the info name for this invocation.  Generally this175                      is the most descriptive name for the script or176                      command.  For the toplevel script it is usually177                      the name of the script, for commands below it it's178                      the name of the script.179    :param obj: an arbitrary object of user data.180    :param auto_envvar_prefix: the prefix to use for automatic environment181                               variables.  If this is `None` then reading182                               from environment variables is disabled.  This183                               does not affect manually set environment184                               variables which are always read.185    :param default_map: a dictionary (like object) with default values186                        for parameters.187    :param terminal_width: the width of the terminal.  The default is188                           inherit from parent context.  If no context189                           defines the terminal width then auto190                           detection will be applied.191    :param max_content_width: the maximum width for content rendered by192                              Click (this currently only affects help193                              pages).  This defaults to 80 characters if194                              not overridden.  In other words: even if the195                              terminal is larger than that, Click will not196                              format things wider than 80 characters by197                              default.  In addition to that, formatters might198                              add some safety mapping on the right.199    :param resilient_parsing: if this flag is enabled then Click will200                              parse without any interactivity or callback201                              invocation.  Default values will also be202                              ignored.  This is useful for implementing203                              things such as completion support.204    :param allow_extra_args: if this is set to `True` then extra arguments205                             at the end will not raise an error and will be206                             kept on the context.  The default is to inherit207                             from the command.208    :param allow_interspersed_args: if this is set to `False` then options209                                    and arguments cannot be mixed.  The210                                    default is to inherit from the command.211    :param ignore_unknown_options: instructs click to ignore options it does212                                   not know and keeps them for later213                                   processing.214    :param help_option_names: optionally a list of strings that define how215                              the default help parameter is named.  The216                              default is ``['--help']``.217    :param token_normalize_func: an optional function that is used to218                                 normalize tokens (options, choices,219                                 etc.).  This for instance can be used to220                                 implement case insensitive behavior.221    :param color: controls if the terminal supports ANSI colors or not.  The222                  default is autodetection.  This is only needed if ANSI223                  codes are used in texts that Click prints which is by224                  default not the case.  This for instance would affect225                  help output.226    :param show_default: Show the default value for commands. If this227        value is not set, it defaults to the value from the parent228        context. ``Command.show_default`` overrides this default for the229        specific command.230 231    .. versionchanged:: 8.1232        The ``show_default`` parameter is overridden by233        ``Command.show_default``, instead of the other way around.234 235    .. versionchanged:: 8.0236        The ``show_default`` parameter defaults to the value from the237        parent context.238 239    .. versionchanged:: 7.1240       Added the ``show_default`` parameter.241 242    .. versionchanged:: 4.0243        Added the ``color``, ``ignore_unknown_options``, and244        ``max_content_width`` parameters.245 246    .. versionchanged:: 3.0247        Added the ``allow_extra_args`` and ``allow_interspersed_args``248        parameters.249 250    .. versionchanged:: 2.0251        Added the ``resilient_parsing``, ``help_option_names``, and252        ``token_normalize_func`` parameters.253    """254 255    #: The formatter class to create with :meth:`make_formatter`.256    #:257    #: .. versionadded:: 8.0258    formatter_class: t.Type["HelpFormatter"] = HelpFormatter259 260    def __init__(261        self,262        command: "Command",263        parent: t.Optional["Context"] = None,264        info_name: t.Optional[str] = None,265        obj: t.Optional[t.Any] = None,266        auto_envvar_prefix: t.Optional[str] = None,267        default_map: t.Optional[t.MutableMapping[str, t.Any]] = None,268        terminal_width: t.Optional[int] = None,269        max_content_width: t.Optional[int] = None,270        resilient_parsing: bool = False,271        allow_extra_args: t.Optional[bool] = None,272        allow_interspersed_args: t.Optional[bool] = None,273        ignore_unknown_options: t.Optional[bool] = None,274        help_option_names: t.Optional[t.List[str]] = None,275        token_normalize_func: t.Optional[t.Callable[[str], str]] = None,276        color: t.Optional[bool] = None,277        show_default: t.Optional[bool] = None,278    ) -> None:279        #: the parent context or `None` if none exists.280        self.parent = parent281        #: the :class:`Command` for this context.282        self.command = command283        #: the descriptive information name284        self.info_name = info_name285        #: Map of parameter names to their parsed values. Parameters286        #: with ``expose_value=False`` are not stored.287        self.params: t.Dict[str, t.Any] = {}288        #: the leftover arguments.289        self.args: t.List[str] = []290        #: protected arguments.  These are arguments that are prepended291        #: to `args` when certain parsing scenarios are encountered but292        #: must be never propagated to another arguments.  This is used293        #: to implement nested parsing.294        self.protected_args: t.List[str] = []295        #: the collected prefixes of the command's options.296        self._opt_prefixes: t.Set[str] = set(parent._opt_prefixes) if parent else set()297 298        if obj is None and parent is not None:299            obj = parent.obj300 301        #: the user object stored.302        self.obj: t.Any = obj303        self._meta: t.Dict[str, t.Any] = getattr(parent, "meta", {})304 305        #: A dictionary (-like object) with defaults for parameters.306        if (307            default_map is None308            and info_name is not None309            and parent is not None310            and parent.default_map is not None311        ):312            default_map = parent.default_map.get(info_name)313 314        self.default_map: t.Optional[t.MutableMapping[str, t.Any]] = default_map315 316        #: This flag indicates if a subcommand is going to be executed. A317        #: group callback can use this information to figure out if it's318        #: being executed directly or because the execution flow passes319        #: onwards to a subcommand. By default it's None, but it can be320        #: the name of the subcommand to execute.321        #:322        #: If chaining is enabled this will be set to ``'*'`` in case323        #: any commands are executed.  It is however not possible to324        #: figure out which ones.  If you require this knowledge you325        #: should use a :func:`result_callback`.326        self.invoked_subcommand: t.Optional[str] = None327 328        if terminal_width is None and parent is not None:329            terminal_width = parent.terminal_width330 331        #: The width of the terminal (None is autodetection).332        self.terminal_width: t.Optional[int] = terminal_width333 334        if max_content_width is None and parent is not None:335            max_content_width = parent.max_content_width336 337        #: The maximum width of formatted content (None implies a sensible338        #: default which is 80 for most things).339        self.max_content_width: t.Optional[int] = max_content_width340 341        if allow_extra_args is None:342            allow_extra_args = command.allow_extra_args343 344        #: Indicates if the context allows extra args or if it should345        #: fail on parsing.346        #:347        #: .. versionadded:: 3.0348        self.allow_extra_args = allow_extra_args349 350        if allow_interspersed_args is None:351            allow_interspersed_args = command.allow_interspersed_args352 353        #: Indicates if the context allows mixing of arguments and354        #: options or not.355        #:356        #: .. versionadded:: 3.0357        self.allow_interspersed_args: bool = allow_interspersed_args358 359        if ignore_unknown_options is None:360            ignore_unknown_options = command.ignore_unknown_options361 362        #: Instructs click to ignore options that a command does not363        #: understand and will store it on the context for later364        #: processing.  This is primarily useful for situations where you365        #: want to call into external programs.  Generally this pattern is366        #: strongly discouraged because it's not possibly to losslessly367        #: forward all arguments.368        #:369        #: .. versionadded:: 4.0370        self.ignore_unknown_options: bool = ignore_unknown_options371 372        if help_option_names is None:373            if parent is not None:374                help_option_names = parent.help_option_names375            else:376                help_option_names = ["--help"]377 378        #: The names for the help options.379        self.help_option_names: t.List[str] = help_option_names380 381        if token_normalize_func is None and parent is not None:382            token_normalize_func = parent.token_normalize_func383 384        #: An optional normalization function for tokens.  This is385        #: options, choices, commands etc.386        self.token_normalize_func: t.Optional[387            t.Callable[[str], str]388        ] = token_normalize_func389 390        #: Indicates if resilient parsing is enabled.  In that case Click391        #: will do its best to not cause any failures and default values392        #: will be ignored. Useful for completion.393        self.resilient_parsing: bool = resilient_parsing394 395        # If there is no envvar prefix yet, but the parent has one and396        # the command on this level has a name, we can expand the envvar397        # prefix automatically.398        if auto_envvar_prefix is None:399            if (400                parent is not None401                and parent.auto_envvar_prefix is not None402                and self.info_name is not None403            ):404                auto_envvar_prefix = (405                    f"{parent.auto_envvar_prefix}_{self.info_name.upper()}"406                )407        else:408            auto_envvar_prefix = auto_envvar_prefix.upper()409 410        if auto_envvar_prefix is not None:411            auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")412 413        self.auto_envvar_prefix: t.Optional[str] = auto_envvar_prefix414 415        if color is None and parent is not None:416            color = parent.color417 418        #: Controls if styling output is wanted or not.419        self.color: t.Optional[bool] = color420 421        if show_default is None and parent is not None:422            show_default = parent.show_default423 424        #: Show option default values when formatting help text.425        self.show_default: t.Optional[bool] = show_default426 427        self._close_callbacks: t.List[t.Callable[[], t.Any]] = []428        self._depth = 0429        self._parameter_source: t.Dict[str, ParameterSource] = {}430        self._exit_stack = ExitStack()431 432    def to_info_dict(self) -> t.Dict[str, t.Any]:433        """Gather information that could be useful for a tool generating434        user-facing documentation. This traverses the entire CLI435        structure.436 437        .. code-block:: python438 439            with Context(cli) as ctx:440                info = ctx.to_info_dict()441 442        .. versionadded:: 8.0443        """444        return {445            "command": self.command.to_info_dict(self),446            "info_name": self.info_name,447            "allow_extra_args": self.allow_extra_args,448            "allow_interspersed_args": self.allow_interspersed_args,449            "ignore_unknown_options": self.ignore_unknown_options,450            "auto_envvar_prefix": self.auto_envvar_prefix,451        }452 453    def __enter__(self) -> "Context":454        self._depth += 1455        push_context(self)456        return self457 458    def __exit__(459        self,460        exc_type: t.Optional[t.Type[BaseException]],461        exc_value: t.Optional[BaseException],462        tb: t.Optional[TracebackType],463    ) -> None:464        self._depth -= 1465        if self._depth == 0:466            self.close()467        pop_context()468 469    @contextmanager470    def scope(self, cleanup: bool = True) -> t.Iterator["Context"]:471        """This helper method can be used with the context object to promote472        it to the current thread local (see :func:`get_current_context`).473        The default behavior of this is to invoke the cleanup functions which474        can be disabled by setting `cleanup` to `False`.  The cleanup475        functions are typically used for things such as closing file handles.476 477        If the cleanup is intended the context object can also be directly478        used as a context manager.479 480        Example usage::481 482            with ctx.scope():483                assert get_current_context() is ctx484 485        This is equivalent::486 487            with ctx:488                assert get_current_context() is ctx489 490        .. versionadded:: 5.0491 492        :param cleanup: controls if the cleanup functions should be run or493                        not.  The default is to run these functions.  In494                        some situations the context only wants to be495                        temporarily pushed in which case this can be disabled.496                        Nested pushes automatically defer the cleanup.497        """498        if not cleanup:499            self._depth += 1500        try:501            with self as rv:502                yield rv503        finally:504            if not cleanup:505                self._depth -= 1506 507    @property508    def meta(self) -> t.Dict[str, t.Any]:509        """This is a dictionary which is shared with all the contexts510        that are nested.  It exists so that click utilities can store some511        state here if they need to.  It is however the responsibility of512        that code to manage this dictionary well.513 514        The keys are supposed to be unique dotted strings.  For instance515        module paths are a good choice for it.  What is stored in there is516        irrelevant for the operation of click.  However what is important is517        that code that places data here adheres to the general semantics of518        the system.519 520        Example usage::521 522            LANG_KEY = f'{__name__}.lang'523 524            def set_language(value):525                ctx = get_current_context()526                ctx.meta[LANG_KEY] = value527 528            def get_language():529                return get_current_context().meta.get(LANG_KEY, 'en_US')530 531        .. versionadded:: 5.0532        """533        return self._meta534 535    def make_formatter(self) -> HelpFormatter:536        """Creates the :class:`~click.HelpFormatter` for the help and537        usage output.538 539        To quickly customize the formatter class used without overriding540        this method, set the :attr:`formatter_class` attribute.541 542        .. versionchanged:: 8.0543            Added the :attr:`formatter_class` attribute.544        """545        return self.formatter_class(546            width=self.terminal_width, max_width=self.max_content_width547        )548 549    def with_resource(self, context_manager: t.ContextManager[V]) -> V:550        """Register a resource as if it were used in a ``with``551        statement. The resource will be cleaned up when the context is552        popped.553 554        Uses :meth:`contextlib.ExitStack.enter_context`. It calls the555        resource's ``__enter__()`` method and returns the result. When556        the context is popped, it closes the stack, which calls the557        resource's ``__exit__()`` method.558 559        To register a cleanup function for something that isn't a560        context manager, use :meth:`call_on_close`. Or use something561        from :mod:`contextlib` to turn it into a context manager first.562 563        .. code-block:: python564 565            @click.group()566            @click.option("--name")567            @click.pass_context568            def cli(ctx):569                ctx.obj = ctx.with_resource(connect_db(name))570 571        :param context_manager: The context manager to enter.572        :return: Whatever ``context_manager.__enter__()`` returns.573 574        .. versionadded:: 8.0575        """576        return self._exit_stack.enter_context(context_manager)577 578    def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:579        """Register a function to be called when the context tears down.580 581        This can be used to close resources opened during the script582        execution. Resources that support Python's context manager583        protocol which would be used in a ``with`` statement should be584        registered with :meth:`with_resource` instead.585 586        :param f: The function to execute on teardown.587        """588        return self._exit_stack.callback(f)589 590    def close(self) -> None:591        """Invoke all close callbacks registered with592        :meth:`call_on_close`, and exit all context managers entered593        with :meth:`with_resource`.594        """595        self._exit_stack.close()596        # In case the context is reused, create a new exit stack.597        self._exit_stack = ExitStack()598 599    @property600    def command_path(self) -> str:601        """The computed command path.  This is used for the ``usage``602        information on the help page.  It's automatically created by603        combining the info names of the chain of contexts to the root.604        """605        rv = ""606        if self.info_name is not None:607            rv = self.info_name608        if self.parent is not None:609            parent_command_path = [self.parent.command_path]610 611            if isinstance(self.parent.command, Command):612                for param in self.parent.command.get_params(self):613                    parent_command_path.extend(param.get_usage_pieces(self))614 615            rv = f"{' '.join(parent_command_path)} {rv}"616        return rv.lstrip()617 618    def find_root(self) -> "Context":619        """Finds the outermost context."""620        node = self621        while node.parent is not None:622            node = node.parent623        return node624 625    def find_object(self, object_type: t.Type[V]) -> t.Optional[V]:626        """Finds the closest object of a given type."""627        node: t.Optional["Context"] = self628 629        while node is not None:630            if isinstance(node.obj, object_type):631                return node.obj632 633            node = node.parent634 635        return None636 637    def ensure_object(self, object_type: t.Type[V]) -> V:638        """Like :meth:`find_object` but sets the innermost object to a639        new instance of `object_type` if it does not exist.640        """641        rv = self.find_object(object_type)642        if rv is None:643            self.obj = rv = object_type()644        return rv645 646    @t.overload647    def lookup_default(648        self, name: str, call: "te.Literal[True]" = True649    ) -> t.Optional[t.Any]:650        ...651 652    @t.overload653    def lookup_default(654        self, name: str, call: "te.Literal[False]" = ...655    ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:656        ...657 658    def lookup_default(self, name: str, call: bool = True) -> t.Optional[t.Any]:659        """Get the default for a parameter from :attr:`default_map`.660 661        :param name: Name of the parameter.662        :param call: If the default is a callable, call it. Disable to663            return the callable instead.664 665        .. versionchanged:: 8.0666            Added the ``call`` parameter.667        """668        if self.default_map is not None:669            value = self.default_map.get(name)670 671            if call and callable(value):672                return value()673 674            return value675 676        return None677 678    def fail(self, message: str) -> "te.NoReturn":679        """Aborts the execution of the program with a specific error680        message.681 682        :param message: the error message to fail with.683        """684        raise UsageError(message, self)685 686    def abort(self) -> "te.NoReturn":687        """Aborts the script."""688        raise Abort()689 690    def exit(self, code: int = 0) -> "te.NoReturn":691        """Exits the application with a given exit code."""692        raise Exit(code)693 694    def get_usage(self) -> str:695        """Helper method to get formatted usage string for the current696        context and command.697        """698        return self.command.get_usage(self)699 700    def get_help(self) -> str:701        """Helper method to get formatted help page for the current702        context and command.703        """704        return self.command.get_help(self)705 706    def _make_sub_context(self, command: "Command") -> "Context":707        """Create a new context of the same type as this context, but708        for a new command.709 710        :meta private:711        """712        return type(self)(command, info_name=command.name, parent=self)713 714    @t.overload715    def invoke(716        __self,  # noqa: B902717        __callback: "t.Callable[..., V]",718        *args: t.Any,719        **kwargs: t.Any,720    ) -> V:721        ...722 723    @t.overload724    def invoke(725        __self,  # noqa: B902726        __callback: "Command",727        *args: t.Any,728        **kwargs: t.Any,729    ) -> t.Any:730        ...731 732    def invoke(733        __self,  # noqa: B902734        __callback: t.Union["Command", "t.Callable[..., V]"],735        *args: t.Any,736        **kwargs: t.Any,737    ) -> t.Union[t.Any, V]:738        """Invokes a command callback in exactly the way it expects.  There739        are two ways to invoke this method:740 741        1.  the first argument can be a callback and all other arguments and742            keyword arguments are forwarded directly to the function.743        2.  the first argument is a click command object.  In that case all744            arguments are forwarded as well but proper click parameters745            (options and click arguments) must be keyword arguments and Click746            will fill in defaults.747 748        Note that before Click 3.2 keyword arguments were not properly filled749        in against the intention of this code and no context was created.  For750        more information about this change and why it was done in a bugfix751        release see :ref:`upgrade-to-3.2`.752 753        .. versionchanged:: 8.0754            All ``kwargs`` are tracked in :attr:`params` so they will be755            passed if :meth:`forward` is called at multiple levels.756        """757        if isinstance(__callback, Command):758            other_cmd = __callback759 760            if other_cmd.callback is None:761                raise TypeError(762                    "The given command does not have a callback that can be invoked."763                )764            else:765                __callback = t.cast("t.Callable[..., V]", other_cmd.callback)766 767            ctx = __self._make_sub_context(other_cmd)768 769            for param in other_cmd.params:770                if param.name not in kwargs and param.expose_value:771                    kwargs[param.name] = param.type_cast_value(  # type: ignore772                        ctx, param.get_default(ctx)773                    )774 775            # Track all kwargs as params, so that forward() will pass776            # them on in subsequent calls.777            ctx.params.update(kwargs)778        else:779            ctx = __self780 781        with augment_usage_errors(__self):782            with ctx:783                return __callback(*args, **kwargs)784 785    def forward(786        __self, __cmd: "Command", *args: t.Any, **kwargs: t.Any  # noqa: B902787    ) -> t.Any:788        """Similar to :meth:`invoke` but fills in default keyword789        arguments from the current context if the other command expects790        it.  This cannot invoke callbacks directly, only other commands.791 792        .. versionchanged:: 8.0793            All ``kwargs`` are tracked in :attr:`params` so they will be794            passed if ``forward`` is called at multiple levels.795        """796        # Can only forward to other commands, not direct callbacks.797        if not isinstance(__cmd, Command):798            raise TypeError("Callback is not a command.")799 800        for param in __self.params:801            if param not in kwargs:802                kwargs[param] = __self.params[param]803 804        return __self.invoke(__cmd, *args, **kwargs)805 806    def set_parameter_source(self, name: str, source: ParameterSource) -> None:807        """Set the source of a parameter. This indicates the location808        from which the value of the parameter was obtained.809 810        :param name: The name of the parameter.811        :param source: A member of :class:`~click.core.ParameterSource`.812        """813        self._parameter_source[name] = source814 815    def get_parameter_source(self, name: str) -> t.Optional[ParameterSource]:816        """Get the source of a parameter. This indicates the location817        from which the value of the parameter was obtained.818 819        This can be useful for determining when a user specified a value820        on the command line that is the same as the default value. It821        will be :attr:`~click.core.ParameterSource.DEFAULT` only if the822        value was actually taken from the default.823 824        :param name: The name of the parameter.825        :rtype: ParameterSource826 827        .. versionchanged:: 8.0828            Returns ``None`` if the parameter was not provided from any829            source.830        """831        return self._parameter_source.get(name)832 833 834class BaseCommand:835    """The base command implements the minimal API contract of commands.836    Most code will never use this as it does not implement a lot of useful837    functionality but it can act as the direct subclass of alternative838    parsing methods that do not depend on the Click parser.839 840    For instance, this can be used to bridge Click and other systems like841    argparse or docopt.842 843    Because base commands do not implement a lot of the API that other844    parts of Click take for granted, they are not supported for all845    operations.  For instance, they cannot be used with the decorators846    usually and they have no built-in callback system.847 848    .. versionchanged:: 2.0849       Added the `context_settings` parameter.850 851    :param name: the name of the command to use unless a group overrides it.852    :param context_settings: an optional dictionary with defaults that are853                             passed to the context object.854    """855 856    #: The context class to create with :meth:`make_context`.857    #:858    #: .. versionadded:: 8.0859    context_class: t.Type[Context] = Context860    #: the default for the :attr:`Context.allow_extra_args` flag.861    allow_extra_args = False862    #: the default for the :attr:`Context.allow_interspersed_args` flag.863    allow_interspersed_args = True864    #: the default for the :attr:`Context.ignore_unknown_options` flag.865    ignore_unknown_options = False866 867    def __init__(868        self,869        name: t.Optional[str],870        context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None,871    ) -> None:872        #: the name the command thinks it has.  Upon registering a command873        #: on a :class:`Group` the group will default the command name874        #: with this information.  You should instead use the875        #: :class:`Context`\'s :attr:`~Context.info_name` attribute.876        self.name = name877 878        if context_settings is None:879            context_settings = {}880 881        #: an optional dictionary with defaults passed to the context.882        self.context_settings: t.MutableMapping[str, t.Any] = context_settings883 884    def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]:885        """Gather information that could be useful for a tool generating886        user-facing documentation. This traverses the entire structure887        below this command.888 889        Use :meth:`click.Context.to_info_dict` to traverse the entire890        CLI structure.891 892        :param ctx: A :class:`Context` representing this command.893 894        .. versionadded:: 8.0895        """896        return {"name": self.name}897 898    def __repr__(self) -> str:899        return f"<{self.__class__.__name__} {self.name}>"900 901    def get_usage(self, ctx: Context) -> str:902        raise NotImplementedError("Base commands cannot get usage")903 904    def get_help(self, ctx: Context) -> str:905        raise NotImplementedError("Base commands cannot get help")906 907    def make_context(908        self,909        info_name: t.Optional[str],910        args: t.List[str],911        parent: t.Optional[Context] = None,912        **extra: t.Any,913    ) -> Context:914        """This function when given an info name and arguments will kick915        off the parsing and create a new :class:`Context`.  It does not916        invoke the actual command callback though.917 918        To quickly customize the context class used without overriding919        this method, set the :attr:`context_class` attribute.920 921        :param info_name: the info name for this invocation.  Generally this922                          is the most descriptive name for the script or923                          command.  For the toplevel script it's usually924                          the name of the script, for commands below it's925                          the name of the command.926        :param args: the arguments to parse as list of strings.927        :param parent: the parent context if available.928        :param extra: extra keyword arguments forwarded to the context929                      constructor.930 931        .. versionchanged:: 8.0932            Added the :attr:`context_class` attribute.933        """934        for key, value in self.context_settings.items():935            if key not in extra:936                extra[key] = value937 938        ctx = self.context_class(939            self, info_name=info_name, parent=parent, **extra  # type: ignore940        )941 942        with ctx.scope(cleanup=False):943            self.parse_args(ctx, args)944        return ctx945 946    def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]:947        """Given a context and a list of arguments this creates the parser948        and parses the arguments, then modifies the context as necessary.949        This is automatically invoked by :meth:`make_context`.950        """951        raise NotImplementedError("Base commands do not know how to parse arguments.")952 953    def invoke(self, ctx: Context) -> t.Any:954        """Given a context, this invokes the command.  The default955        implementation is raising a not implemented error.956        """957        raise NotImplementedError("Base commands are not invocable by default")958 959    def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:960        """Return a list of completions for the incomplete value. Looks961        at the names of chained multi-commands.962 963        Any command could be part of a chained multi-command, so sibling964        commands are valid at any point during command completion. Other965        command classes will return more completions.966 967        :param ctx: Invocation context for this command.968        :param incomplete: Value being completed. May be empty.969 970        .. versionadded:: 8.0971        """972        from click.shell_completion import CompletionItem973 974        results: t.List["CompletionItem"] = []975 976        while ctx.parent is not None:977            ctx = ctx.parent978 979            if isinstance(ctx.command, MultiCommand) and ctx.command.chain:980                results.extend(981                    CompletionItem(name, help=command.get_short_help_str())982                    for name, command in _complete_visible_commands(ctx, incomplete)983                    if name not in ctx.protected_args984                )985 986        return results987 988    @t.overload989    def main(990        self,991        args: t.Optional[t.Sequence[str]] = None,992        prog_name: t.Optional[str] = None,993        complete_var: t.Optional[str] = None,994        standalone_mode: "te.Literal[True]" = True,995        **extra: t.Any,996    ) -> "te.NoReturn":997        ...998 999    @t.overload1000    def main(1001        self,1002        args: t.Optional[t.Sequence[str]] = None,1003        prog_name: t.Optional[str] = None,1004        complete_var: t.Optional[str] = None,1005        standalone_mode: bool = ...,1006        **extra: t.Any,1007    ) -> t.Any:1008        ...1009 1010    def main(1011        self,1012        args: t.Optional[t.Sequence[str]] = None,1013        prog_name: t.Optional[str] = None,1014        complete_var: t.Optional[str] = None,1015        standalone_mode: bool = True,1016        windows_expand_args: bool = True,1017        **extra: t.Any,1018    ) -> t.Any:1019        """This is the way to invoke a script with all the bells and1020        whistles as a command line application.  This will always terminate1021        the application after a call.  If this is not wanted, ``SystemExit``1022        needs to be caught.1023 1024        This method is also available by directly calling the instance of1025        a :class:`Command`.1026 1027        :param args: the arguments that should be used for parsing.  If not1028                     provided, ``sys.argv[1:]`` is used.1029        :param prog_name: the program name that should be used.  By default1030                          the program name is constructed by taking the file1031                          name from ``sys.argv[0]``.1032        :param complete_var: the environment variable that controls the1033                             bash completion support.  The default is1034                             ``"_<prog_name>_COMPLETE"`` with prog_name in1035                             uppercase.1036        :param standalone_mode: the default behavior is to invoke the script1037                                in standalone mode.  Click will then1038                                handle exceptions and convert them into1039                                error messages and the function will never1040                                return but shut down the interpreter.  If1041                                this is set to `False` they will be1042                                propagated to the caller and the return1043                                value of this function is the return value1044                                of :meth:`invoke`.1045        :param windows_expand_args: Expand glob patterns, user dir, and1046            env vars in command line args on Windows.1047        :param extra: extra keyword arguments are forwarded to the context1048                      constructor.  See :class:`Context` for more information.1049 1050        .. versionchanged:: 8.0.11051            Added the ``windows_expand_args`` parameter to allow1052            disabling command line arg expansion on Windows.1053 1054        .. versionchanged:: 8.01055            When taking arguments from ``sys.argv`` on Windows, glob1056            patterns, user dir, and env vars are expanded.1057 1058        .. versionchanged:: 3.01059           Added the ``standalone_mode`` parameter.1060        """1061        if args is None:1062            args = sys.argv[1:]1063 1064            if os.name == "nt" and windows_expand_args:1065                args = _expand_args(args)1066        else:1067            args = list(args)1068 1069        if prog_name is None:1070            prog_name = _detect_program_name()1071 1072        # Process shell completion requests and exit early.1073        self._main_shell_completion(extra, prog_name, complete_var)1074 1075        try:1076            try:1077                with self.make_context(prog_name, args, **extra) as ctx:1078                    rv = self.invoke(ctx)1079                    if not standalone_mode:1080                        return rv1081                    # it's not safe to `ctx.exit(rv)` here!1082                    # note that `rv` may actually contain data like "1" which1083                    # has obvious effects1084                    # more subtle case: `rv=[None, None]` can come out of1085                    # chained commands which all returned `None` -- so it's not1086                    # even always obvious that `rv` indicates success/failure1087                    # by its truthiness/falsiness1088                    ctx.exit()1089            except (EOFError, KeyboardInterrupt) as e:1090                echo(file=sys.stderr)1091                raise Abort() from e1092            except ClickException as e:1093                if not standalone_mode:1094                    raise1095                e.show()1096                sys.exit(e.exit_code)1097            except OSError as e:1098                if e.errno == errno.EPIPE:1099                    sys.stdout = t.cast(t.TextIO, PacifyFlushWrapper(sys.stdout))1100                    sys.stderr = t.cast(t.TextIO, PacifyFlushWrapper(sys.stderr))1101                    sys.exit(1)1102                else:1103                    raise1104        except Exit as e:1105            if standalone_mode:1106                sys.exit(e.exit_code)1107            else:1108                # in non-standalone mode, return the exit code1109                # note that this is only reached if `self.invoke` above raises1110                # an Exit explicitly -- thus bypassing the check there which1111                # would return its result1112                # the results of non-standalone execution may therefore be1113                # somewhat ambiguous: if there are codepaths which lead to1114                # `ctx.exit(1)` and to `return 1`, the caller won't be able to1115                # tell the difference between the two1116                return e.exit_code1117        except Abort:1118            if not standalone_mode:1119                raise1120            echo(_("Aborted!"), file=sys.stderr)1121            sys.exit(1)1122 1123    def _main_shell_completion(1124        self,1125        ctx_args: t.MutableMapping[str, t.Any],1126        prog_name: str,1127        complete_var: t.Optional[str] = None,1128    ) -> None:1129        """Check if the shell is asking for tab completion, process1130        that, then exit early. Called from :meth:`main` before the1131        program is invoked.1132 1133        :param prog_name: Name of the executable in the shell.1134        :param complete_var: Name of the environment variable that holds1135            the completion instruction. Defaults to1136            ``_{PROG_NAME}_COMPLETE``.1137 1138        .. versionchanged:: 8.2.01139            Dots (``.``) in ``prog_name`` are replaced with underscores (``_``).1140        """1141        if complete_var is None:1142            complete_name = prog_name.replace("-", "_").replace(".", "_")1143            complete_var = f"_{complete_name}_COMPLETE".upper()1144 1145        instruction = os.environ.get(complete_var)1146 1147        if not instruction:1148            return1149 1150        from .shell_completion import shell_complete1151 1152        rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)1153        sys.exit(rv)1154 1155    def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any:1156        """Alias for :meth:`main`."""1157        return self.main(*args, **kwargs)1158 1159 1160class Command(BaseCommand):1161    """Commands are the basic building block of command line interfaces in1162    Click.  A basic command handles command line parsing and might dispatch1163    more parsing to commands nested below it.1164 1165    :param name: the name of the command to use unless a group overrides it.1166    :param context_settings: an optional dictionary with defaults that are1167                             passed to the context object.1168    :param callback: the callback to invoke.  This is optional.1169    :param params: the parameters to register with this command.  This can1170                   be either :class:`Option` or :class:`Argument` objects.1171    :param help: the help string to use for this command.1172    :param epilog: like the help string but it's printed at the end of the1173                   help page after everything else.1174    :param short_help: the short help to use for this command.  This is1175                       shown on the command listing of the parent command.1176    :param add_help_option: by default each command registers a ``--help``1177                            option.  This can be disabled by this parameter.1178    :param no_args_is_help: this controls what happens if no arguments are1179                            provided.  This option is disabled by default.1180                            If enabled this will add ``--help`` as argument1181                            if no arguments are passed1182    :param hidden: hide this command from help outputs.1183 1184    :param deprecated: issues a message indicating that1185                             the command is deprecated.1186 1187    .. versionchanged:: 8.11188        ``help``, ``epilog``, and ``short_help`` are stored unprocessed,1189        all formatting is done when outputting help text, not at init,1190        and is done even if not using the ``@command`` decorator.1191 1192    .. versionchanged:: 8.01193        Added a ``repr`` showing the command name.1194 1195    .. versionchanged:: 7.11196        Added the ``no_args_is_help`` parameter.1197 1198    .. versionchanged:: 2.01199        Added the ``context_settings`` parameter.1200    """

Showing the first 1,200 of 3043 lines. Download the file for the rest.

codekingpro/portable-devtools · Team Ai