Skip to content
Myr

parser.py

This file

Path

src/click/parser.py

533 lines · 18.6 KiB · Python

Last changed by

Differentiate absence of value and value of absence for `default` and `flag_value`Kevin Deldyckebefore adoptionb64ea07

History of this file

Take it

1"""2This module started out as largely a copy paste from the stdlib's3optparse module with the features removed that we do not need from4optparse because we implement them in Click on a higher level (for5instance type handling, help formatting and a lot more).67The plan is to remove more and more from here over time.89The reason this is a different module and not optparse from the stdlib10is that there are differences in 2.x and 3.x about the error messages11generated and optparse in the stdlib uses gettext for no good reason12and might cause us issues.1314Click uses parts of optparse written by Gregory P. Ward and maintained15by the Python Software Foundation. This is limited to code in parser.py.1617Copyright 2001-2006 Gregory P. Ward. All rights reserved.18Copyright 2002-2006 Python Software Foundation. All rights reserved.19"""2021# This code uses parts of optparse written by Gregory P. Ward and22# maintained by the Python Software Foundation.23# Copyright 2001-2006 Gregory P. Ward24# Copyright 2002-2006 Python Software Foundation25from __future__ import annotations2627import collections.abc as cabc28import typing as t29from collections import deque30from gettext import gettext as _31from gettext import ngettext3233from ._utils import UNSET34from .exceptions import BadArgumentUsage35from .exceptions import BadOptionUsage36from .exceptions import NoSuchOption37from .exceptions import UsageError3839if t.TYPE_CHECKING:40    from ._utils import T_UNSET41    from .core import Argument as CoreArgument42    from .core import Context43    from .core import Option as CoreOption44    from .core import Parameter as CoreParameter4546V = t.TypeVar("V")4748# Sentinel value that indicates an option was passed as a flag without a49# value but is not a flag option. Option.consume_value uses this to50# prompt or use the flag_value.51_flag_needs_value = object()525354def _unpack_args(55    args: cabc.Sequence[str], nargs_spec: cabc.Sequence[int]56) -> tuple[cabc.Sequence[str | cabc.Sequence[str | None] | None], list[str]]:57    """Given an iterable of arguments and an iterable of nargs specifications,58    it returns a tuple with all the unpacked arguments at the first index59    and all remaining arguments as the second.6061    The nargs specification is the number of arguments that should be consumed62    or `-1` to indicate that this position should eat up all the remainders.6364    Missing items are filled with ``UNSET``.65    """66    args = deque(args)67    nargs_spec = deque(nargs_spec)68    rv: list[str | tuple[str | T_UNSET, ...] | T_UNSET] = []69    spos: int | None = None7071    def _fetch(c: deque[V]) -> V | T_UNSET:72        try:73            if spos is None:74                return c.popleft()75            else:76                return c.pop()77        except IndexError:78            return UNSET7980    while nargs_spec:81        nargs = _fetch(nargs_spec)8283        if nargs is None:84            continue8586        if nargs == 1:87            rv.append(_fetch(args))  # type: ignore[arg-type]88        elif nargs > 1:89            x = [_fetch(args) for _ in range(nargs)]9091            # If we're reversed, we're pulling in the arguments in reverse,92            # so we need to turn them around.93            if spos is not None:94                x.reverse()9596            rv.append(tuple(x))97        elif nargs < 0:98            if spos is not None:99                raise TypeError("Cannot have two nargs < 0")100101            spos = len(rv)102            rv.append(UNSET)103104    # spos is the position of the wildcard (star).  If it's not `None`,105    # we fill it with the remainder.106    if spos is not None:107        rv[spos] = tuple(args)108        args = []109        rv[spos + 1 :] = reversed(rv[spos + 1 :])110111    return tuple(rv), list(args)112113114def _split_opt(opt: str) -> tuple[str, str]:115    first = opt[:1]116    if first.isalnum():117        return "", opt118    if opt[1:2] == first:119        return opt[:2], opt[2:]120    return first, opt[1:]121122123def _normalize_opt(opt: str, ctx: Context | None) -> str:124    if ctx is None or ctx.token_normalize_func is None:125        return opt126    prefix, opt = _split_opt(opt)127    return f"{prefix}{ctx.token_normalize_func(opt)}"128129130class _Option:131    def __init__(132        self,133        obj: CoreOption,134        opts: cabc.Sequence[str],135        dest: str | None,136        action: str | None = None,137        nargs: int = 1,138        const: t.Any | None = None,139    ):140        self._short_opts = []141        self._long_opts = []142        self.prefixes: set[str] = set()143144        for opt in opts:145            prefix, value = _split_opt(opt)146            if not prefix:147                raise ValueError(f"Invalid start character for option ({opt})")148            self.prefixes.add(prefix[0])149            if len(prefix) == 1 and len(value) == 1:150                self._short_opts.append(opt)151            else:152                self._long_opts.append(opt)153                self.prefixes.add(prefix)154155        if action is None:156            action = "store"157158        self.dest = dest159        self.action = action160        self.nargs = nargs161        self.const = const162        self.obj = obj163164    @property165    def takes_value(self) -> bool:166        return self.action in ("store", "append")167168    def process(self, value: t.Any, state: _ParsingState) -> None:169        if self.action == "store":170            state.opts[self.dest] = value  # type: ignore171        elif self.action == "store_const":172            state.opts[self.dest] = self.const  # type: ignore173        elif self.action == "append":174            state.opts.setdefault(self.dest, []).append(value)  # type: ignore175        elif self.action == "append_const":176            state.opts.setdefault(self.dest, []).append(self.const)  # type: ignore177        elif self.action == "count":178            state.opts[self.dest] = state.opts.get(self.dest, 0) + 1  # type: ignore179        else:180            raise ValueError(f"unknown action '{self.action}'")181        state.order.append(self.obj)182183184class _Argument:185    def __init__(self, obj: CoreArgument, dest: str | None, nargs: int = 1):186        self.dest = dest187        self.nargs = nargs188        self.obj = obj189190    def process(191        self,192        value: str | cabc.Sequence[str | None] | None | T_UNSET,193        state: _ParsingState,194    ) -> None:195        if self.nargs > 1:196            assert isinstance(value, cabc.Sequence)197            holes = sum(1 for x in value if x is UNSET)198            if holes == len(value):199                value = UNSET200            elif holes != 0:201                raise BadArgumentUsage(202                    _("Argument {name!r} takes {nargs} values.").format(203                        name=self.dest, nargs=self.nargs204                    )205                )206207        # We failed to collect any argument value so we consider the argument as unset.208        if value == ():209            value = UNSET210211        state.opts[self.dest] = value  # type: ignore212        state.order.append(self.obj)213214215class _ParsingState:216    def __init__(self, rargs: list[str]) -> None:217        self.opts: dict[str, t.Any] = {}218        self.largs: list[str] = []219        self.rargs = rargs220        self.order: list[CoreParameter] = []221222223class _OptionParser:224    """The option parser is an internal class that is ultimately used to225    parse options and arguments.  It's modelled after optparse and brings226    a similar but vastly simplified API.  It should generally not be used227    directly as the high level Click classes wrap it for you.228229    It's not nearly as extensible as optparse or argparse as it does not230    implement features that are implemented on a higher level (such as231    types or defaults).232233    :param ctx: optionally the :class:`~click.Context` where this parser234                should go with.235236    .. deprecated:: 8.2237        Will be removed in Click 9.0.238    """239240    def __init__(self, ctx: Context | None = None) -> None:241        #: The :class:`~click.Context` for this parser.  This might be242        #: `None` for some advanced use cases.243        self.ctx = ctx244        #: This controls how the parser deals with interspersed arguments.245        #: If this is set to `False`, the parser will stop on the first246        #: non-option.  Click uses this to implement nested subcommands247        #: safely.248        self.allow_interspersed_args: bool = True249        #: This tells the parser how to deal with unknown options.  By250        #: default it will error out (which is sensible), but there is a251        #: second mode where it will ignore it and continue processing252        #: after shifting all the unknown options into the resulting args.253        self.ignore_unknown_options: bool = False254255        if ctx is not None:256            self.allow_interspersed_args = ctx.allow_interspersed_args257            self.ignore_unknown_options = ctx.ignore_unknown_options258259        self._short_opt: dict[str, _Option] = {}260        self._long_opt: dict[str, _Option] = {}261        self._opt_prefixes = {"-", "--"}262        self._args: list[_Argument] = []263264    def add_option(265        self,266        obj: CoreOption,267        opts: cabc.Sequence[str],268        dest: str | None,269        action: str | None = None,270        nargs: int = 1,271        const: t.Any | None = None,272    ) -> None:273        """Adds a new option named `dest` to the parser.  The destination274        is not inferred (unlike with optparse) and needs to be explicitly275        provided.  Action can be any of ``store``, ``store_const``,276        ``append``, ``append_const`` or ``count``.277278        The `obj` can be used to identify the option in the order list279        that is returned from the parser.280        """281        opts = [_normalize_opt(opt, self.ctx) for opt in opts]282        option = _Option(obj, opts, dest, action=action, nargs=nargs, const=const)283        self._opt_prefixes.update(option.prefixes)284        for opt in option._short_opts:285            self._short_opt[opt] = option286        for opt in option._long_opts:287            self._long_opt[opt] = option288289    def add_argument(self, obj: CoreArgument, dest: str | None, nargs: int = 1) -> None:290        """Adds a positional argument named `dest` to the parser.291292        The `obj` can be used to identify the option in the order list293        that is returned from the parser.294        """295        self._args.append(_Argument(obj, dest=dest, nargs=nargs))296297    def parse_args(298        self, args: list[str]299    ) -> tuple[dict[str, t.Any], list[str], list[CoreParameter]]:300        """Parses positional arguments and returns ``(values, args, order)``301        for the parsed options and arguments as well as the leftover302        arguments if there are any.  The order is a list of objects as they303        appear on the command line.  If arguments appear multiple times they304        will be memorized multiple times as well.305        """306        state = _ParsingState(args)307        try:308            self._process_args_for_options(state)309            self._process_args_for_args(state)310        except UsageError:311            if self.ctx is None or not self.ctx.resilient_parsing:312                raise313        return state.opts, state.largs, state.order314315    def _process_args_for_args(self, state: _ParsingState) -> None:316        pargs, args = _unpack_args(317            state.largs + state.rargs, [x.nargs for x in self._args]318        )319320        for idx, arg in enumerate(self._args):321            arg.process(pargs[idx], state)322323        state.largs = args324        state.rargs = []325326    def _process_args_for_options(self, state: _ParsingState) -> None:327        while state.rargs:328            arg = state.rargs.pop(0)329            arglen = len(arg)330            # Double dashes always handled explicitly regardless of what331            # prefixes are valid.332            if arg == "--":333                return334            elif arg[:1] in self._opt_prefixes and arglen > 1:335                self._process_opts(arg, state)336            elif self.allow_interspersed_args:337                state.largs.append(arg)338            else:339                state.rargs.insert(0, arg)340                return341342        # Say this is the original argument list:343        # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]344        #                            ^345        # (we are about to process arg(i)).346        #347        # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of348        # [arg0, ..., arg(i-1)] (any options and their arguments will have349        # been removed from largs).350        #351        # The while loop will usually consume 1 or more arguments per pass.352        # If it consumes 1 (eg. arg is an option that takes no arguments),353        # then after _process_arg() is done the situation is:354        #355        #   largs = subset of [arg0, ..., arg(i)]356        #   rargs = [arg(i+1), ..., arg(N-1)]357        #358        # If allow_interspersed_args is false, largs will always be359        # *empty* -- still a subset of [arg0, ..., arg(i-1)], but360        # not a very interesting subset!361362    def _match_long_opt(363        self, opt: str, explicit_value: str | None, state: _ParsingState364    ) -> None:365        if opt not in self._long_opt:366            from difflib import get_close_matches367368            possibilities = get_close_matches(opt, self._long_opt)369            raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)370371        option = self._long_opt[opt]372        if option.takes_value:373            # At this point it's safe to modify rargs by injecting the374            # explicit value, because no exception is raised in this375            # branch.  This means that the inserted value will be fully376            # consumed.377            if explicit_value is not None:378                state.rargs.insert(0, explicit_value)379380            value = self._get_value_from_state(opt, option, state)381382        elif explicit_value is not None:383            raise BadOptionUsage(384                opt, _("Option {name!r} does not take a value.").format(name=opt)385            )386387        else:388            value = UNSET389390        option.process(value, state)391392    def _match_short_opt(self, arg: str, state: _ParsingState) -> None:393        stop = False394        i = 1395        prefix = arg[0]396        unknown_options = []397398        for ch in arg[1:]:399            opt = _normalize_opt(f"{prefix}{ch}", self.ctx)400            option = self._short_opt.get(opt)401            i += 1402403            if not option:404                if self.ignore_unknown_options:405                    unknown_options.append(ch)406                    continue407                raise NoSuchOption(opt, ctx=self.ctx)408            if option.takes_value:409                # Any characters left in arg?  Pretend they're the410                # next arg, and stop consuming characters of arg.411                if i < len(arg):412                    state.rargs.insert(0, arg[i:])413                    stop = True414415                value = self._get_value_from_state(opt, option, state)416417            else:418                value = UNSET419420            option.process(value, state)421422            if stop:423                break424425        # If we got any unknown options we recombine the string of the426        # remaining options and re-attach the prefix, then report that427        # to the state as new larg.  This way there is basic combinatorics428        # that can be achieved while still ignoring unknown arguments.429        if self.ignore_unknown_options and unknown_options:430            state.largs.append(f"{prefix}{''.join(unknown_options)}")431432    def _get_value_from_state(433        self, option_name: str, option: _Option, state: _ParsingState434    ) -> t.Any:435        nargs = option.nargs436437        if len(state.rargs) < nargs:438            if option.obj._flag_needs_value:439                # Option allows omitting the value.440                value = _flag_needs_value441            else:442                raise BadOptionUsage(443                    option_name,444                    ngettext(445                        "Option {name!r} requires an argument.",446                        "Option {name!r} requires {nargs} arguments.",447                        nargs,448                    ).format(name=option_name, nargs=nargs),449                )450        elif nargs == 1:451            next_rarg = state.rargs[0]452453            if (454                option.obj._flag_needs_value455                and isinstance(next_rarg, str)456                and next_rarg[:1] in self._opt_prefixes457                and len(next_rarg) > 1458            ):459                # The next arg looks like the start of an option, don't460                # use it as the value if omitting the value is allowed.461                value = _flag_needs_value462            else:463                value = state.rargs.pop(0)464        else:465            value = tuple(state.rargs[:nargs])466            del state.rargs[:nargs]467468        return value469470    def _process_opts(self, arg: str, state: _ParsingState) -> None:471        explicit_value = None472        # Long option handling happens in two parts.  The first part is473        # supporting explicitly attached values.  In any case, we will try474        # to long match the option first.475        if "=" in arg:476            long_opt, explicit_value = arg.split("=", 1)477        else:478            long_opt = arg479        norm_long_opt = _normalize_opt(long_opt, self.ctx)480481        # At this point we will match the (assumed) long option through482        # the long option matching code.  Note that this allows options483        # like "-foo" to be matched as long options.484        try:485            self._match_long_opt(norm_long_opt, explicit_value, state)486        except NoSuchOption:487            # At this point the long option matching failed, and we need488            # to try with short options.  However there is a special rule489            # which says, that if we have a two character options prefix490            # (applies to "--foo" for instance), we do not dispatch to the491            # short option code and will instead raise the no option492            # error.493            if arg[:2] not in self._opt_prefixes:494                self._match_short_opt(arg, state)495                return496497            if not self.ignore_unknown_options:498                raise499500            state.largs.append(arg)501502503def __getattr__(name: str) -> object:504    import warnings505506    if name in {507        "OptionParser",508        "Argument",509        "Option",510        "split_opt",511        "normalize_opt",512        "ParsingState",513    }:514        warnings.warn(515            f"'parser.{name}' is deprecated and will be removed in Click 9.0."516            " The old parser is available in 'optparse'.",517            DeprecationWarning,518            stacklevel=2,519        )520        return globals()[f"_{name}"]521522    if name == "split_arg_string":523        from .shell_completion import split_arg_string524525        warnings.warn(526            "Importing 'parser.split_arg_string' is deprecated, it will only be"527            " available in 'shell_completion' in Click 9.0.",528            DeprecationWarning,529            stacklevel=2,530        )531        return split_arg_string532533    raise AttributeError(name)