Skip to content
Myr

Implemented first pass of unprocessed option handling.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 67b1349 · Browse files · 2 files+93 added−56 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+93 added−56 removed

  • other:+93 added−56 removed

2 files+93 added−56 removed

modified:click/core.py+19 added-2 removed
138 unmodified lines
139 from the command.140 :param allow_interspersed_args: if this is set to `False` then options141 and arguments cannot be mixed. The142 default is to inherit from the command.143 :param ignore_unknown_options: instructs click to ignore options it does144 not know and keeps them for later145 processing.146 :param help_option_names: optionally a list of strings that define how147 the default help parameter is named. The148 default is ``['--help']``.149 :param token_normalize_func: an optional function that is used to
10 unmodified lines
160 def __init__(self, command, parent=None, info_name=None, obj=None,161 auto_envvar_prefix=None, default_map=None,162 terminal_width=None, resilient_parsing=False,163 allow_extra_args=None, allow_interspersed_args=None,161 help_option_names=None, token_normalize_func=None,162 color=None):164 ignore_unknown_options=None, help_option_names=None,165 token_normalize_func=None, color=None):166 #: the parent context or `None` if none exists.167 self.parent = parent168 #: the :class:`Command` for this context.169 self.command = command
47 unmodified lines
217 #:218 #: .. versionadded:: 3.0219 self.allow_interspersed_args = allow_interspersed_args220221 if ignore_unknown_options is None:222 ignore_unknown_options = command.ignore_unknown_options223 #: Instructs click to ignore options that a command does not224 #: understand and will store it on the context for later225 #: processing. This is primarily useful for situations where you226 #: want to call into external programs. Generally this pattern is227 #: strongly discouraged because it's not possibly to losslessly228 #: forward all arguments.229 #:230 #: .. versionadded:: 4.0231 self.ignore_unknown_options = ignore_unknown_options232233 if help_option_names is None:234 if parent is not None:235 help_option_names = parent.help_option_names236 else:
260 unmodified lines
497 passed to the context object.498 """499 allow_extra_args = False500 allow_interspersed_args = True501 ignore_unknown_options = False502503 def __init__(self, name, context_settings=None):504 #: the name the command thinks it has. Upon registering a command505 #: on a :class:`Group` the group will default the command name
229 unmodified lines
735 def make_parser(self, ctx):736 """Creates the underlying option parser for this command."""737 parser = OptionParser(ctx)738 parser.allow_interspersed_args = ctx.allow_interspersed_args739 parser.ignore_unknown_options = ctx.ignore_unknown_options740 for param in self.get_params(ctx):741 param.add_to_parser(parser, ctx)742 return parser743
864 unmodified lines
modified:click/parser.py+74 added-54 removed
14 unmodified lines
15 generated and optparse in the stdlib uses gettext for no good reason16 and might cause us issues.17"""18import re19from .exceptions import UsageError19from .exceptions import UsageError, NoSuchOption, BadOptionUsage20from .utils import unpack_args212223def _error_args(nargs, opt):24 if nargs == 1:25 raise BadOptionUsage(opt, '%s option requires an argument' % opt)26 raise BadOptionUsage(opt, '%s option requires %d arguments' % (opt, nargs))272829def split_opt(opt):30 first = opt[:1]31 if first.isalnum():32 return '', opt
118 unmodified lines
151 #: If this is set to `False`, the parser will stop on the first152 #: non-option. Click uses this to implement nested subcommands153 #: safely.154 self.allow_interspersed_args = True155 #: This tells the parser how to deal with unknown options. By156 #: default it will error out (which is sensible), but there is a157 #: second mode where it will ignore it and continue processing158 #: after shifting all the unknown options into the resulting args.159 self.ignore_unknown_options = False160 if ctx is not None:161 self.allow_interspersed_args = ctx.allow_interspersed_args162 self.ignore_unknown_options = ctx.ignore_unknown_options163 self._short_opt = {}164 self._long_opt = {}165 self._opt_prefixes = set(['-', '--'])166 self._args = []
40 unmodified lines
207 try:208 self._process_args_for_options(state)209 self._process_args_for_args(state)210 except UsageError:197 if not self.ctx.resilient_parsing:211 if self.ctx is None or not self.ctx.resilient_parsing:212 raise213 return state.opts, state.largs, state.order214215 def _process_args_for_args(self, state):
41 unmodified lines
257 # If allow_interspersed_args is false, largs will always be258 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but259 # not a very interesting subset!260247 def _match_long_opt(self, opt):248 # Is there an exact match?249 if opt in self._long_opt:250 return opt261 def _match_long_opt(self, opt, explicit_value, state):262 if opt not in self._long_opt:263 possibilities = [word for word in self._long_opt264 if word.startswith(opt)]265 raise NoSuchOption(opt, possibilities=possibilities)266252 # Isolate all words with s as a prefix.253 possibilities = [word for word in self._long_opt254 if word.startswith(opt)]255256 # No exact match, so there had better be just one possibility.257 if not possibilities:258 self._error('no such option: %s' % opt)259 elif len(possibilities) == 1:260 self._error('no such option: %s. Did you mean %s?' %261 (opt, possibilities[0]))262 return possibilities[0]263 else:264 # More than one possible completion: ambiguous prefix.265 possibilities.sort()266 self._error('no such option: %s. (Possible options: %s)'267 % (opt, ', '.join(possibilities)))268269 def _process_long_opt(self, arg, state):270 # Value explicitly attached to arg? Pretend it's the next argument.271 if '=' in arg:272 opt, next_arg = arg.split('=', 1)273 state.rargs.insert(0, next_arg)274 had_explicit_value = True275 else:276 opt = arg277 had_explicit_value = False278279 opt = normalize_opt(opt, self.ctx)280281 opt = self._match_long_opt(opt)267 option = self._long_opt[opt]268 if option.takes_value:269 # At this point it's safe to modify rargs by injecting the270 # explicit value, because no exception is raised in this271 # branch. This means that the inserted value will be fully272 # consumed.273 if explicit_value is not None:274 state.rargs.insert(0, explicit_value)275276 nargs = option.nargs277 if len(state.rargs) < nargs:286 if nargs == 1:287 self._error('%s option requires an argument' % opt)288 else:289 self._error('%s option requires %d arguments' % (opt, nargs))278 _error_args(nargs, opt)279 elif nargs == 1:280 value = state.rargs.pop(0)281 else:282 value = tuple(state.rargs[:nargs])283 del state.rargs[:nargs]284296 elif had_explicit_value:297 self._error('%s option does not take a value' % opt)285 elif explicit_value is not None:286 raise BadOptionUsage(opt, '%s option does not take a value' % opt)287288 else:289 value = None290291 option.process(value, state)292304 def _process_opts(self, arg, state):305 if '=' in arg or normalize_opt(arg, self.ctx) in self._long_opt:306 return self._process_long_opt(arg, state)307293 def _match_short_opt(self, arg, state):294 stop = False295 i = 1296 prefix = arg[0]297 unknown_options = []298299 for ch in arg[1:]:300 opt = normalize_opt(prefix + ch, self.ctx)301 option = self._short_opt.get(opt)302 i += 1303304 if not option:317 self._error('no such option: %s' % (arg if arg.startswith('--') else opt))305 if self.ignore_unknown_options:306 unknown_options.append(ch)307 continue308 raise NoSuchOption(opt)309 if option.takes_value:310 # Any characters left in arg? Pretend they're the311 # next arg, and stop consuming characters of arg.312 if i < len(arg):
1 unmodified line
314 stop = True315316 nargs = option.nargs317 if len(state.rargs) < nargs:327 if nargs == 1:328 self._error('%s option requires an argument' % opt)329 else:330 self._error('%s option requires %d arguments' %331 (opt, nargs))318 _error_args(nargs, opt)319 elif nargs == 1:320 value = state.rargs.pop(0)321 else:322 value = tuple(state.rargs[:nargs])
6 unmodified lines
329330 if stop:331 break332346 def _error(self, msg):347 raise UsageError(msg, self.ctx)333 # If we got any unknown options we re-combinate the string of the334 # remaining options and re-attach the prefix, then report that335 # to the state as new larg. This way there is basic combinatorics336 # that can be achieved while still ignoring unknown arguments.337 if self.ignore_unknown_options and unknown_options:338 state.largs.append(prefix + ''.join(unknown_options))339340 def _process_opts(self, arg, state):341 explicit_value = None342 # Long option handling happens in two parts. The first part is343 # supporting explicitly attached values. In any case, we will try344 # to long match the option first.345 if '=' in arg:346 long_opt, explicit_value = arg.split('=', 1)347 else:348 long_opt = arg349 norm_long_opt = normalize_opt(long_opt, self.ctx)350351 # At this point we will match the (assumed) long option through352 # the long option matching code. Note that this allows options353 # like "-foo" to be matched as long options.354 try:355 self._match_long_opt(norm_long_opt, explicit_value, state)356 except NoSuchOption:357 # At this point the long option matching failed, and we need358 # to try with short options. However there is a special rule359 # which says, that if we have a two character options prefix360 # (applies to "--foo" for instance), we do not dispatch to the361 # short option code and will instead raise the no option362 # error.363 if arg[:2] not in self._opt_prefixes:364 return self._match_short_opt(arg, state)365 if not self.ignore_unknown_options:366 raise367 state.largs.append(arg)