Skip to content
Myr

parser.py

This file

Path

click/parser.py

430 lines · 15.4 KiB · Python

Last changed by

update project metadataDavid Lordbefore adoption3592995

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3This module started out as largely a copy paste from the stdlib's4optparse module with the features removed that we do not need from5optparse because we implement them in Click on a higher level (for6instance type handling, help formatting and a lot more).78The plan is to remove more and more from here over time.910The reason this is a different module and not optparse from the stdlib11is that there are differences in 2.x and 3.x about the error messages12generated and optparse in the stdlib uses gettext for no good reason13and might cause us issues.1415Click uses parts of optparse written by Gregory P. Ward and maintained16by the Python Software Foundation. This is limited to code in parser.py.1718Copyright 2001-2006 Gregory P. Ward. All rights reserved.19Copyright 2002-2006 Python Software Foundation. All rights reserved.20"""2122import re23from collections import deque24from .exceptions import UsageError, NoSuchOption, BadOptionUsage, \25     BadArgumentUsage262728def _unpack_args(args, nargs_spec):29    """Given an iterable of arguments and an iterable of nargs specifications,30    it returns a tuple with all the unpacked arguments at the first index31    and all remaining arguments as the second.3233    The nargs specification is the number of arguments that should be consumed34    or `-1` to indicate that this position should eat up all the remainders.3536    Missing items are filled with `None`.37    """38    args = deque(args)39    nargs_spec = deque(nargs_spec)40    rv = []41    spos = None4243    def _fetch(c):44        try:45            if spos is None:46                return c.popleft()47            else:48                return c.pop()49        except IndexError:50            return None5152    while nargs_spec:53        nargs = _fetch(nargs_spec)54        if nargs == 1:55            rv.append(_fetch(args))56        elif nargs > 1:57            x = [_fetch(args) for _ in range(nargs)]58            # If we're reversed, we're pulling in the arguments in reverse,59            # so we need to turn them around.60            if spos is not None:61                x.reverse()62            rv.append(tuple(x))63        elif nargs < 0:64            if spos is not None:65                raise TypeError('Cannot have two nargs < 0')66            spos = len(rv)67            rv.append(None)6869    # spos is the position of the wildcard (star).  If it's not `None`,70    # we fill it with the remainder.71    if spos is not None:72        rv[spos] = tuple(args)73        args = []74        rv[spos + 1:] = reversed(rv[spos + 1:])7576    return tuple(rv), list(args)777879def _error_opt_args(nargs, opt):80    if nargs == 1:81        raise BadOptionUsage(opt, '%s option requires an argument' % opt)82    raise BadOptionUsage(opt, '%s option requires %d arguments' % (opt, nargs))838485def split_opt(opt):86    first = opt[:1]87    if first.isalnum():88        return '', opt89    if opt[1:2] == first:90        return opt[:2], opt[2:]91    return first, opt[1:]929394def normalize_opt(opt, ctx):95    if ctx is None or ctx.token_normalize_func is None:96        return opt97    prefix, opt = split_opt(opt)98    return prefix + ctx.token_normalize_func(opt)99100101def split_arg_string(string):102    """Given an argument string this attempts to split it into small parts."""103    rv = []104    for match in re.finditer(r"('([^'\\]*(?:\\.[^'\\]*)*)'"105                             r'|"([^"\\]*(?:\\.[^"\\]*)*)"'106                             r'|\S+)\s*', string, re.S):107        arg = match.group().strip()108        if arg[:1] == arg[-1:] and arg[:1] in '"\'':109            arg = arg[1:-1].encode('ascii', 'backslashreplace') \110                .decode('unicode-escape')111        try:112            arg = type(string)(arg)113        except UnicodeError:114            pass115        rv.append(arg)116    return rv117118119class Option(object):120121    def __init__(self, opts, dest, action=None, nargs=1, const=None, obj=None):122        self._short_opts = []123        self._long_opts = []124        self.prefixes = set()125126        for opt in opts:127            prefix, value = split_opt(opt)128            if not prefix:129                raise ValueError('Invalid start character for option (%s)'130                                 % opt)131            self.prefixes.add(prefix[0])132            if len(prefix) == 1 and len(value) == 1:133                self._short_opts.append(opt)134            else:135                self._long_opts.append(opt)136                self.prefixes.add(prefix)137138        if action is None:139            action = 'store'140141        self.dest = dest142        self.action = action143        self.nargs = nargs144        self.const = const145        self.obj = obj146147    @property148    def takes_value(self):149        return self.action in ('store', 'append')150151    def process(self, value, state):152        if self.action == 'store':153            state.opts[self.dest] = value154        elif self.action == 'store_const':155            state.opts[self.dest] = self.const156        elif self.action == 'append':157            state.opts.setdefault(self.dest, []).append(value)158        elif self.action == 'append_const':159            state.opts.setdefault(self.dest, []).append(self.const)160        elif self.action == 'count':161            state.opts[self.dest] = state.opts.get(self.dest, 0) + 1162        else:163            raise ValueError('unknown action %r' % self.action)164        state.order.append(self.obj)165166167class Argument(object):168169    def __init__(self, dest, nargs=1, obj=None):170        self.dest = dest171        self.nargs = nargs172        self.obj = obj173174    def process(self, value, state):175        if self.nargs > 1:176            holes = sum(1 for x in value if x is None)177            if holes == len(value):178                value = None179            elif holes != 0:180                raise BadArgumentUsage('argument %s takes %d values'181                                       % (self.dest, self.nargs))182        state.opts[self.dest] = value183        state.order.append(self.obj)184185186class ParsingState(object):187188    def __init__(self, rargs):189        self.opts = {}190        self.largs = []191        self.rargs = rargs192        self.order = []193194195class OptionParser(object):196    """The option parser is an internal class that is ultimately used to197    parse options and arguments.  It's modelled after optparse and brings198    a similar but vastly simplified API.  It should generally not be used199    directly as the high level Click classes wrap it for you.200201    It's not nearly as extensible as optparse or argparse as it does not202    implement features that are implemented on a higher level (such as203    types or defaults).204205    :param ctx: optionally the :class:`~click.Context` where this parser206                should go with.207    """208209    def __init__(self, ctx=None):210        #: The :class:`~click.Context` for this parser.  This might be211        #: `None` for some advanced use cases.212        self.ctx = ctx213        #: This controls how the parser deals with interspersed arguments.214        #: If this is set to `False`, the parser will stop on the first215        #: non-option.  Click uses this to implement nested subcommands216        #: safely.217        self.allow_interspersed_args = True218        #: This tells the parser how to deal with unknown options.  By219        #: default it will error out (which is sensible), but there is a220        #: second mode where it will ignore it and continue processing221        #: after shifting all the unknown options into the resulting args.222        self.ignore_unknown_options = False223        if ctx is not None:224            self.allow_interspersed_args = ctx.allow_interspersed_args225            self.ignore_unknown_options = ctx.ignore_unknown_options226        self._short_opt = {}227        self._long_opt = {}228        self._opt_prefixes = set(['-', '--'])229        self._args = []230231    def add_option(self, opts, dest, action=None, nargs=1, const=None,232                   obj=None):233        """Adds a new option named `dest` to the parser.  The destination234        is not inferred (unlike with optparse) and needs to be explicitly235        provided.  Action can be any of ``store``, ``store_const``,236        ``append``, ``appnd_const`` or ``count``.237238        The `obj` can be used to identify the option in the order list239        that is returned from the parser.240        """241        if obj is None:242            obj = dest243        opts = [normalize_opt(opt, self.ctx) for opt in opts]244        option = Option(opts, dest, action=action, nargs=nargs,245                        const=const, obj=obj)246        self._opt_prefixes.update(option.prefixes)247        for opt in option._short_opts:248            self._short_opt[opt] = option249        for opt in option._long_opts:250            self._long_opt[opt] = option251252    def add_argument(self, dest, nargs=1, obj=None):253        """Adds a positional argument named `dest` to the parser.254255        The `obj` can be used to identify the option in the order list256        that is returned from the parser.257        """258        if obj is None:259            obj = dest260        self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))261262    def parse_args(self, args):263        """Parses positional arguments and returns ``(values, args, order)``264        for the parsed options and arguments as well as the leftover265        arguments if there are any.  The order is a list of objects as they266        appear on the command line.  If arguments appear multiple times they267        will be memorized multiple times as well.268        """269        state = ParsingState(args)270        try:271            self._process_args_for_options(state)272            self._process_args_for_args(state)273        except UsageError:274            if self.ctx is None or not self.ctx.resilient_parsing:275                raise276        return state.opts, state.largs, state.order277278    def _process_args_for_args(self, state):279        pargs, args = _unpack_args(state.largs + state.rargs,280                                   [x.nargs for x in self._args])281282        for idx, arg in enumerate(self._args):283            arg.process(pargs[idx], state)284285        state.largs = args286        state.rargs = []287288    def _process_args_for_options(self, state):289        while state.rargs:290            arg = state.rargs.pop(0)291            arglen = len(arg)292            # Double dashes always handled explicitly regardless of what293            # prefixes are valid.294            if arg == '--':295                return296            elif arg[:1] in self._opt_prefixes and arglen > 1:297                self._process_opts(arg, state)298            elif self.allow_interspersed_args:299                state.largs.append(arg)300            else:301                state.rargs.insert(0, arg)302                return303304        # Say this is the original argument list:305        # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]306        #                            ^307        # (we are about to process arg(i)).308        #309        # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of310        # [arg0, ..., arg(i-1)] (any options and their arguments will have311        # been removed from largs).312        #313        # The while loop will usually consume 1 or more arguments per pass.314        # If it consumes 1 (eg. arg is an option that takes no arguments),315        # then after _process_arg() is done the situation is:316        #317        #   largs = subset of [arg0, ..., arg(i)]318        #   rargs = [arg(i+1), ..., arg(N-1)]319        #320        # If allow_interspersed_args is false, largs will always be321        # *empty* -- still a subset of [arg0, ..., arg(i-1)], but322        # not a very interesting subset!323324    def _match_long_opt(self, opt, explicit_value, state):325        if opt not in self._long_opt:326            possibilities = [word for word in self._long_opt327                             if word.startswith(opt)]328            raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)329330        option = self._long_opt[opt]331        if option.takes_value:332            # At this point it's safe to modify rargs by injecting the333            # explicit value, because no exception is raised in this334            # branch.  This means that the inserted value will be fully335            # consumed.336            if explicit_value is not None:337                state.rargs.insert(0, explicit_value)338339            nargs = option.nargs340            if len(state.rargs) < nargs:341                _error_opt_args(nargs, opt)342            elif nargs == 1:343                value = state.rargs.pop(0)344            else:345                value = tuple(state.rargs[:nargs])346                del state.rargs[:nargs]347348        elif explicit_value is not None:349            raise BadOptionUsage(opt, '%s option does not take a value' % opt)350351        else:352            value = None353354        option.process(value, state)355356    def _match_short_opt(self, arg, state):357        stop = False358        i = 1359        prefix = arg[0]360        unknown_options = []361362        for ch in arg[1:]:363            opt = normalize_opt(prefix + ch, self.ctx)364            option = self._short_opt.get(opt)365            i += 1366367            if not option:368                if self.ignore_unknown_options:369                    unknown_options.append(ch)370                    continue371                raise NoSuchOption(opt, ctx=self.ctx)372            if option.takes_value:373                # Any characters left in arg?  Pretend they're the374                # next arg, and stop consuming characters of arg.375                if i < len(arg):376                    state.rargs.insert(0, arg[i:])377                    stop = True378379                nargs = option.nargs380                if len(state.rargs) < nargs:381                    _error_opt_args(nargs, opt)382                elif nargs == 1:383                    value = state.rargs.pop(0)384                else:385                    value = tuple(state.rargs[:nargs])386                    del state.rargs[:nargs]387388            else:389                value = None390391            option.process(value, state)392393            if stop:394                break395396        # If we got any unknown options we re-combinate the string of the397        # remaining options and re-attach the prefix, then report that398        # to the state as new larg.  This way there is basic combinatorics399        # that can be achieved while still ignoring unknown arguments.400        if self.ignore_unknown_options and unknown_options:401            state.largs.append(prefix + ''.join(unknown_options))402403    def _process_opts(self, arg, state):404        explicit_value = None405        # Long option handling happens in two parts.  The first part is406        # supporting explicitly attached values.  In any case, we will try407        # to long match the option first.408        if '=' in arg:409            long_opt, explicit_value = arg.split('=', 1)410        else:411            long_opt = arg412        norm_long_opt = normalize_opt(long_opt, self.ctx)413414        # At this point we will match the (assumed) long option through415        # the long option matching code.  Note that this allows options416        # like "-foo" to be matched as long options.417        try:418            self._match_long_opt(norm_long_opt, explicit_value, state)419        except NoSuchOption:420            # At this point the long option matching failed, and we need421            # to try with short options.  However there is a special rule422            # which says, that if we have a two character options prefix423            # (applies to "--foo" for instance), we do not dispatch to the424            # short option code and will instead raise the no option425            # error.426            if arg[:2] not in self._opt_prefixes:427                return self._match_short_opt(arg, state)428            if not self.ignore_unknown_options:429                raise430            state.largs.append(arg)