parser.py
This file
Path
src/click/parser.py
431 lines · 15.4 KiB · Python
Last changed by
Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
History of this fileTake 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"""20# This code uses parts of optparse written by Gregory P. Ward and21# maintained by the Python Software Foundation.22# Copyright 2001-2006 Gregory P. Ward23# Copyright 2002-2006 Python Software Foundation24import re25from collections import deque2627from .exceptions import BadArgumentUsage28from .exceptions import BadOptionUsage29from .exceptions import NoSuchOption30from .exceptions import UsageError313233def _unpack_args(args, nargs_spec):34 """Given an iterable of arguments and an iterable of nargs specifications,35 it returns a tuple with all the unpacked arguments at the first index36 and all remaining arguments as the second.3738 The nargs specification is the number of arguments that should be consumed39 or `-1` to indicate that this position should eat up all the remainders.4041 Missing items are filled with `None`.42 """43 args = deque(args)44 nargs_spec = deque(nargs_spec)45 rv = []46 spos = None4748 def _fetch(c):49 try:50 if spos is None:51 return c.popleft()52 else:53 return c.pop()54 except IndexError:55 return None5657 while nargs_spec:58 nargs = _fetch(nargs_spec)59 if nargs == 1:60 rv.append(_fetch(args))61 elif nargs > 1:62 x = [_fetch(args) for _ in range(nargs)]63 # If we're reversed, we're pulling in the arguments in reverse,64 # so we need to turn them around.65 if spos is not None:66 x.reverse()67 rv.append(tuple(x))68 elif nargs < 0:69 if spos is not None:70 raise TypeError("Cannot have two nargs < 0")71 spos = len(rv)72 rv.append(None)7374 # spos is the position of the wildcard (star). If it's not `None`,75 # we fill it with the remainder.76 if spos is not None:77 rv[spos] = tuple(args)78 args = []79 rv[spos + 1 :] = reversed(rv[spos + 1 :])8081 return tuple(rv), list(args)828384def _error_opt_args(nargs, opt):85 if nargs == 1:86 raise BadOptionUsage(opt, f"{opt} option requires an argument")87 raise BadOptionUsage(opt, f"{opt} option requires {nargs} arguments")888990def split_opt(opt):91 first = opt[:1]92 if first.isalnum():93 return "", opt94 if opt[1:2] == first:95 return opt[:2], opt[2:]96 return first, opt[1:]979899def normalize_opt(opt, ctx):100 if ctx is None or ctx.token_normalize_func is None:101 return opt102 prefix, opt = split_opt(opt)103 return f"{prefix}{ctx.token_normalize_func(opt)}"104105106def split_arg_string(string):107 """Given an argument string this attempts to split it into small parts."""108 rv = []109 for match in re.finditer(110 r"('([^'\\]*(?:\\.[^'\\]*)*)'|\"([^\"\\]*(?:\\.[^\"\\]*)*)\"|\S+)\s*",111 string,112 re.S,113 ):114 arg = match.group().strip()115 if arg[:1] == arg[-1:] and arg[:1] in "\"'":116 arg = arg[1:-1].encode("ascii", "backslashreplace").decode("unicode-escape")117 try:118 arg = type(string)(arg)119 except UnicodeError:120 pass121 rv.append(arg)122 return rv123124125class Option:126 def __init__(self, opts, dest, action=None, nargs=1, const=None, obj=None):127 self._short_opts = []128 self._long_opts = []129 self.prefixes = set()130131 for opt in opts:132 prefix, value = split_opt(opt)133 if not prefix:134 raise ValueError(f"Invalid start character for option ({opt})")135 self.prefixes.add(prefix[0])136 if len(prefix) == 1 and len(value) == 1:137 self._short_opts.append(opt)138 else:139 self._long_opts.append(opt)140 self.prefixes.add(prefix)141142 if action is None:143 action = "store"144145 self.dest = dest146 self.action = action147 self.nargs = nargs148 self.const = const149 self.obj = obj150151 @property152 def takes_value(self):153 return self.action in ("store", "append")154155 def process(self, value, state):156 if self.action == "store":157 state.opts[self.dest] = value158 elif self.action == "store_const":159 state.opts[self.dest] = self.const160 elif self.action == "append":161 state.opts.setdefault(self.dest, []).append(value)162 elif self.action == "append_const":163 state.opts.setdefault(self.dest, []).append(self.const)164 elif self.action == "count":165 state.opts[self.dest] = state.opts.get(self.dest, 0) + 1166 else:167 raise ValueError(f"unknown action '{self.action}'")168 state.order.append(self.obj)169170171class Argument:172 def __init__(self, dest, nargs=1, obj=None):173 self.dest = dest174 self.nargs = nargs175 self.obj = obj176177 def process(self, value, state):178 if self.nargs > 1:179 holes = sum(1 for x in value if x is None)180 if holes == len(value):181 value = None182 elif holes != 0:183 raise BadArgumentUsage(184 f"argument {self.dest} takes {self.nargs} values"185 )186 state.opts[self.dest] = value187 state.order.append(self.obj)188189190class ParsingState:191 def __init__(self, rargs):192 self.opts = {}193 self.largs = []194 self.rargs = rargs195 self.order = []196197198class OptionParser:199 """The option parser is an internal class that is ultimately used to200 parse options and arguments. It's modelled after optparse and brings201 a similar but vastly simplified API. It should generally not be used202 directly as the high level Click classes wrap it for you.203204 It's not nearly as extensible as optparse or argparse as it does not205 implement features that are implemented on a higher level (such as206 types or defaults).207208 :param ctx: optionally the :class:`~click.Context` where this parser209 should go with.210 """211212 def __init__(self, ctx=None):213 #: The :class:`~click.Context` for this parser. This might be214 #: `None` for some advanced use cases.215 self.ctx = ctx216 #: This controls how the parser deals with interspersed arguments.217 #: If this is set to `False`, the parser will stop on the first218 #: non-option. Click uses this to implement nested subcommands219 #: safely.220 self.allow_interspersed_args = True221 #: This tells the parser how to deal with unknown options. By222 #: default it will error out (which is sensible), but there is a223 #: second mode where it will ignore it and continue processing224 #: after shifting all the unknown options into the resulting args.225 self.ignore_unknown_options = False226 if ctx is not None:227 self.allow_interspersed_args = ctx.allow_interspersed_args228 self.ignore_unknown_options = ctx.ignore_unknown_options229 self._short_opt = {}230 self._long_opt = {}231 self._opt_prefixes = {"-", "--"}232 self._args = []233234 def add_option(self, opts, dest, action=None, nargs=1, const=None, obj=None):235 """Adds a new option named `dest` to the parser. The destination236 is not inferred (unlike with optparse) and needs to be explicitly237 provided. Action can be any of ``store``, ``store_const``,238 ``append``, ``appnd_const`` or ``count``.239240 The `obj` can be used to identify the option in the order list241 that is returned from the parser.242 """243 if obj is None:244 obj = dest245 opts = [normalize_opt(opt, self.ctx) for opt in opts]246 option = Option(opts, dest, action=action, nargs=nargs, const=const, obj=obj)247 self._opt_prefixes.update(option.prefixes)248 for opt in option._short_opts:249 self._short_opt[opt] = option250 for opt in option._long_opts:251 self._long_opt[opt] = option252253 def add_argument(self, dest, nargs=1, obj=None):254 """Adds a positional argument named `dest` to the parser.255256 The `obj` can be used to identify the option in the order list257 that is returned from the parser.258 """259 if obj is None:260 obj = dest261 self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))262263 def parse_args(self, args):264 """Parses positional arguments and returns ``(values, args, order)``265 for the parsed options and arguments as well as the leftover266 arguments if there are any. The order is a list of objects as they267 appear on the command line. If arguments appear multiple times they268 will be memorized multiple times as well.269 """270 state = ParsingState(args)271 try:272 self._process_args_for_options(state)273 self._process_args_for_args(state)274 except UsageError:275 if self.ctx is None or not self.ctx.resilient_parsing:276 raise277 return state.opts, state.largs, state.order278279 def _process_args_for_args(self, state):280 pargs, args = _unpack_args(281 state.largs + state.rargs, [x.nargs for x in self._args]282 )283284 for idx, arg in enumerate(self._args):285 arg.process(pargs[idx], state)286287 state.largs = args288 state.rargs = []289290 def _process_args_for_options(self, state):291 while state.rargs:292 arg = state.rargs.pop(0)293 arglen = len(arg)294 # Double dashes always handled explicitly regardless of what295 # prefixes are valid.296 if arg == "--":297 return298 elif arg[:1] in self._opt_prefixes and arglen > 1:299 self._process_opts(arg, state)300 elif self.allow_interspersed_args:301 state.largs.append(arg)302 else:303 state.rargs.insert(0, arg)304 return305306 # Say this is the original argument list:307 # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]308 # ^309 # (we are about to process arg(i)).310 #311 # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of312 # [arg0, ..., arg(i-1)] (any options and their arguments will have313 # been removed from largs).314 #315 # The while loop will usually consume 1 or more arguments per pass.316 # If it consumes 1 (eg. arg is an option that takes no arguments),317 # then after _process_arg() is done the situation is:318 #319 # largs = subset of [arg0, ..., arg(i)]320 # rargs = [arg(i+1), ..., arg(N-1)]321 #322 # If allow_interspersed_args is false, largs will always be323 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but324 # not a very interesting subset!325326 def _match_long_opt(self, opt, explicit_value, state):327 if opt not in self._long_opt:328 possibilities = [word for word in self._long_opt if word.startswith(opt)]329 raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)330331 option = self._long_opt[opt]332 if option.takes_value:333 # At this point it's safe to modify rargs by injecting the334 # explicit value, because no exception is raised in this335 # branch. This means that the inserted value will be fully336 # consumed.337 if explicit_value is not None:338 state.rargs.insert(0, explicit_value)339340 nargs = option.nargs341 if len(state.rargs) < nargs:342 _error_opt_args(nargs, opt)343 elif nargs == 1:344 value = state.rargs.pop(0)345 else:346 value = tuple(state.rargs[:nargs])347 del state.rargs[:nargs]348349 elif explicit_value is not None:350 raise BadOptionUsage(opt, f"{opt} option does not take a value")351352 else:353 value = None354355 option.process(value, state)356357 def _match_short_opt(self, arg, state):358 stop = False359 i = 1360 prefix = arg[0]361 unknown_options = []362363 for ch in arg[1:]:364 opt = normalize_opt(f"{prefix}{ch}", self.ctx)365 option = self._short_opt.get(opt)366 i += 1367368 if not option:369 if self.ignore_unknown_options:370 unknown_options.append(ch)371 continue372 raise NoSuchOption(opt, ctx=self.ctx)373 if option.takes_value:374 # Any characters left in arg? Pretend they're the375 # next arg, and stop consuming characters of arg.376 if i < len(arg):377 state.rargs.insert(0, arg[i:])378 stop = True379380 nargs = option.nargs381 if len(state.rargs) < nargs:382 _error_opt_args(nargs, opt)383 elif nargs == 1:384 value = state.rargs.pop(0)385 else:386 value = tuple(state.rargs[:nargs])387 del state.rargs[:nargs]388389 else:390 value = None391392 option.process(value, state)393394 if stop:395 break396397 # If we got any unknown options we re-combinate the string of the398 # remaining options and re-attach the prefix, then report that399 # to the state as new larg. This way there is basic combinatorics400 # that can be achieved while still ignoring unknown arguments.401 if self.ignore_unknown_options and unknown_options:402 state.largs.append(f"{prefix}{''.join(unknown_options)}")403404 def _process_opts(self, arg, state):405 explicit_value = None406 # Long option handling happens in two parts. The first part is407 # supporting explicitly attached values. In any case, we will try408 # to long match the option first.409 if "=" in arg:410 long_opt, explicit_value = arg.split("=", 1)411 else:412 long_opt = arg413 norm_long_opt = normalize_opt(long_opt, self.ctx)414415 # At this point we will match the (assumed) long option through416 # the long option matching code. Note that this allows options417 # like "-foo" to be matched as long options.418 try:419 self._match_long_opt(norm_long_opt, explicit_value, state)420 except NoSuchOption:421 # At this point the long option matching failed, and we need422 # to try with short options. However there is a special rule423 # which says, that if we have a two character options prefix424 # (applies to "--foo" for instance), we do not dispatch to the425 # short option code and will instead raise the no option426 # error.427 if arg[:2] not in self._opt_prefixes:428 return self._match_short_opt(arg, state)429 if not self.ignore_unknown_options:430 raise431 state.largs.append(arg)