Skip to content
Myr

Exposed parser

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 72d26f6 · Browse files · 3 files+56 added−16 removed
This commit

State

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

Diff stats

3 files+56 added−16 removed

  • other:+56 added−16 removed

3 files+56 added−16 removed

modified:click/__init__.py+6 added
37 unmodified lines
3839# Formatting40from .formatting import HelpFormatter, wrap_text4142# Parsing43from .parser import OptionParser444546__all__ = [47 # Core classes48 'Context', 'Command', 'MultiCommand', 'Group', 'CommandCollection',49 'Parameter', 'Option', 'Argument',
17 unmodified lines
67 'ClickException', 'UsageError', 'FileError', 'Abort',6869 # Formatting70 'HelpFormatter', 'wrap_text',7172 # Parsing73 'OptionParser',74]
modified:click/parser.py+44 added-16 removed
64 unmodified lines
65 raise ValueError('unknown action %r' % self.action)666768class OptionParser(object):69 """The option parser is an internal class that is ultimately used to70 parse options and arguments. It's modelled after optparse and brings71 a similar but vastly simplified API. It should generally not be used72 directly as the high level click classes wrap it for you.7374 It's not nearly as extensible as optparse or argparse as it does not75 implement features that are implemented on a higher level (such as76 types or defaults).7778 :param ctx: optionally the :class:`~click.Context` where this parser79 should go with.80 """8170 def __init__(self, ctx):82 def __init__(self, ctx=None):83 #: The :class:`~click.Context` for this parser. This might be84 #: `None` for some advanced use cases.85 self.ctx = ctx86 #: This controls how the parser deals with interspersed arguments.87 #: If this is set to `False`, the parser will stop on the first88 #: non-option. Click uses this to implement nested subcommands89 #: safely.90 self.allow_interspersed_args = True91 self._short_opt = {}92 self._long_opt = {}93 self._arg_dest = []94 self._nargs = []95 self._opt_prefixes = set(['-', '--'])9679 def add_option(self, opts, **kwargs):80 option = Option(opts, **kwargs)97 def add_option(self, opts, dest, action=None, nargs=1, const=None):98 """Adds a new option named `dest` to the parser. The destination99 is not inferred unlike with optparse and needs to be explicitly100 provided. Action can be any of ``store``, ``store_const``,101 ``append``, ``appnd_const`` or ``count``.102 """103 option = Option(opts, dest, action=action, nargs=nargs, const=const)104 self._opt_prefixes.update(option.prefixes)105 for opt in option._short_opts:106 self._short_opt[opt] = option107 for opt in option._long_opts:108 self._long_opt[opt] = option109110 def add_argument(self, dest, nargs=1):111 """Adds a positional argument named `dest` to the parser."""112 self._arg_dest.append(dest)113 self._nargs.append(nargs)114115 def parse_args(self, args):116 """Parses positional arguments and returns ``(values, args)`` for117 the parsed options and arguments as well as the leftover arguments118 if there are any.119 """120 rargs = args121 opts = {}122 largs = []123
59 unmodified lines
183 if word.startswith(opt)]184185 # No exact match, so there had better be just one possibility.186 if not possibilities:159 self.error('no such option: %s' % opt)187 self._error('no such option: %s' % opt)188 elif len(possibilities) == 1:161 self.error('no such option: %s. Did you mean %s?' %162 (opt, possibilities[0]))189 self._error('no such option: %s. Did you mean %s?' %190 (opt, possibilities[0]))191 return possibilities[0]192 else:193 # More than one possible completion: ambiguous prefix.194 possibilities.sort()167 self.error('no such option: %s. (Possible options: %s)'168 % (opt, ', '.join(possibilities)))195 self._error('no such option: %s. (Possible options: %s)'196 % (opt, ', '.join(possibilities)))197198 def _process_long_opt(self, rargs, opts):199 arg = rargs.pop(0)200
12 unmodified lines
213 if option.takes_value:214 nargs = option.nargs215 if len(rargs) < nargs:216 if nargs == 1:189 self.error('%s option requires an argument' % opt)217 self._error('%s option requires an argument' % opt)218 else:191 self.error('%s option requires %d arguments' % (opt, nargs))219 self._error('%s option requires %d arguments' % (opt, nargs))220 elif nargs == 1:221 value = rargs.pop(0)222 else:223 value = tuple(rargs[:nargs])224 del rargs[:nargs]225226 elif had_explicit_value:199 self.error('%s option does not take a value' % opt)227 self._error('%s option does not take a value' % opt)228229 else:230 value = None231
9 unmodified lines
241 option = self._short_opt.get(opt)242 i += 1243244 if not option:217 self.error('no such option: %s' % opt)245 self._error('no such option: %s' % opt)246 if option.takes_value:247 # Any characters left in arg? Pretend they're the248 # next arg, and stop consuming characters of arg.249 if i < len(arg):
2 unmodified lines
252253 nargs = option.nargs254 if len(rargs) < nargs:255 if nargs == 1:228 self.error('%s option requires an argument' % opt)256 self._error('%s option requires an argument' % opt)257 else:230 self.error('%s option requires %d arguments' %231 (opt, nargs))258 self._error('%s option requires %d arguments' %259 (opt, nargs))260 elif nargs == 1:261 value = rargs.pop(0)262 else:263 value = tuple(rargs[:nargs])
6 unmodified lines
270271 if stop:272 break273246 def error(self, msg):274 def _error(self, msg):275 raise UsageError(msg, self.ctx)
modified:docs/api.rst+6 added
112 unmodified lines
113.. autoclass:: HelpFormatter114 :members:115116.. autofunction:: wrap_text117118Parsing119-------120121.. autoclass:: OptionParser122 :members: