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
Provenance
- Commit
1726e47- Tree
453ec1e- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
72d26f6
3 files changed+56 added−16 removed
modified:click/__init__.py+6 added
37 unmodified lines38 39 # Formatting40 from .formatting import HelpFormatter, wrap_text41 42+# Parsing43+from .parser import OptionParser44 45+46 __all__ = [47 # Core classes48 'Context', 'Command', 'MultiCommand', 'Group', 'CommandCollection',49 'Parameter', 'Option', 'Argument',17 unmodified lines67 'ClickException', 'UsageError', 'FileError', 'Abort',68 69 # Formatting70 'HelpFormatter', 'wrap_text',71+72+ # Parsing73+ 'OptionParser',74 ]modified:click/parser.py+44 added-16 removed
64 unmodified lines65 raise ValueError('unknown action %r' % self.action)66 67 68 class 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.73 74+ 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).77+78+ :param ctx: optionally the :class:`~click.Context` where this parser79+ should go with.80+ """81+70- 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(['-', '--'])96 79- 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] = option109 110 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)114 115 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 lines183 if word.startswith(opt)]184 185 # 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)))197 198 def _process_long_opt(self, rargs, opts):199 arg = rargs.pop(0)200 12 unmodified lines213 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]225 226 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)228 229 else:230 value = None231 9 unmodified lines241 option = self._short_opt.get(opt)242 i += 1243 244 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 lines252 253 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 lines270 271 if stop:272 break273 246- def error(self, msg):274+ def _error(self, msg):275 raise UsageError(msg, self.ctx)modified:docs/api.rst+6 added
112 unmodified lines113 .. autoclass:: HelpFormatter114 :members:115 116 .. autofunction:: wrap_text117+118+Parsing119+-------120+121+.. autoclass:: OptionParser122+ :members: