Skip to content
Myr

Added a base command for dispatching to other parsers.

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 baa7d30 · Browse files · 4 files+233 added−125 removed
This commit

State

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

Diff stats

4 files+233 added−125 removed

  • tests:+65 added−0 removed
  • other:+168 added−125 removed

4 files+233 added−125 removed

modified:click/__init__.py+4 added-4 removed
13 unmodified lines
14 :license: BSD, see LICENSE for more details.15"""1617# Core classes18from .core import Context, Command, MultiCommand, Group, CommandCollection, \19 Parameter, Option, Argument18from .core import Context, BaseCommand, Command, MultiCommand, Group, \19 CommandCollection, Parameter, Option, Argument2021# Decorators22from .decorators import pass_context, pass_obj, make_pass_decorator, \23 command, group, argument, option, confirmation_option, \
20 unmodified lines
444546__all__ = [47 # Core classes48 'Context', 'Command', 'MultiCommand', 'Group', 'CommandCollection',49 'Parameter', 'Option', 'Argument',48 'Context', 'BaseCommand', 'Command', 'MultiCommand', 'Group',49 'CommandCollection', 'Parameter', 'Option', 'Argument',5051 # Decorators52 'pass_context', 'pass_obj', 'make_pass_decorator', 'command', 'group',53 'argument', 'option', 'confirmation_option', 'password_option',
21 unmodified lines
modified:click/core.py+161 added-121 removed
249 unmodified lines
250251 return self.invoke(cmd, **kwargs)252253254class Command(object):255 """Commands are the basic building block of command line interfaces in256 click. A basic command handles command line parsing and might dispatch257 more parsing to commands nested below it.254class BaseCommand(object):255 """The base command implements the minimal API contract of commands.256 Most code will never use this as it does not implement a lot of useful257 functionality but it can act as the direct subclass of alternative258 parsing methods that do not depend on the click parser.259260 For instance this can be used to bridge Click and other systems like261 argparse or docopt.262263 Because base commands do not implement a lot of the API that other264 parts of click take for granted they are not supported for all265 operations. For instance they cannot be used with the decorators266 usually and they have no built-in callback system.267268 :param name: the name of the command to use unless a group overrides it.260 :param callback: the callback to invoke. This is optional.261 :param params: the parameters to register with this command. This can262 be either :class:`Option` or :class:`Argument` objects.263 :param help: the help string to use for this command.264 :param epilog: like the help string but it's printed at the end of the265 help page after everything else.266 :param short_help: the short help to use for this command. This is267 shown on the command listing of the parent command.268 :param add_help_option: by default each command registers a ``--help``269 option. This can be disabled by this parameter.269 """271 allow_extra_args = False270273 def __init__(self, name, callback=None, params=None, help=None,274 epilog=None, short_help=None,275 options_metavar='[OPTIONS]', add_help_option=True):271 def __init__(self, name):272 #: the name the command thinks it has. Upon registering a command273 #: on a :class:`Group` the group will default the command name274 #: with this information. You should instead use the275 #: :class:`Context`\'s :attr:`~Context.info_name` attribute.276 self.name = name281 #: the callback to execute when the command fires. This might be282 #: `None` in which case nothing happens.283 self.callback = callback284 #: the list of parameters for this command in the order they285 #: should show up in the help page and execute. Eager parameters286 #: will automatically be handled before non eager ones.287 self.params = params or []288 self.help = help289 self.epilog = epilog290 self.options_metavar = options_metavar291 if short_help is None and help:292 short_help = make_default_short_help(help)293 self.short_help = short_help294 if add_help_option:295 self.add_help_option()277297 def add_help_option(self):298 """Adds a help option to the command."""299 help_option()(self)300301 def make_parser(self, ctx):302 """Creates the underlying option parser for this command."""303 parser = OptionParser(ctx)304 for param in self.params:305 param.add_to_parser(parser, ctx)306 return parser307278 def get_usage(self, ctx):309 """Formats the usage line into a string and returns it. This310 creates a formatter and will call into the following formatting311 methods:279 raise NotImplementedError('Base commands cannot get usage')280313 - :meth:`format_usage`314 """315 formatter = ctx.make_formatter()316 self.format_usage(ctx, formatter)317 return formatter.getvalue().rstrip('\n')318281 def get_help(self, ctx):320 """Formats the help into a string and returns it. This creates a321 formatter and will call into the following formatting methods:282 raise NotImplementedError('Base commands cannot get help')283323 - :meth:`format_usage`324 - :meth:`format_help`325 - :meth:`format_options`326 - :meth:`format_epilog`327 """328 formatter = ctx.make_formatter()329 self.format_usage(ctx, formatter)330 self.format_help(ctx, formatter)331 self.format_options(ctx, formatter)332 self.format_epilog(ctx, formatter)333 return formatter.getvalue().rstrip('\n')334335 def format_usage(self, ctx, formatter):336 """Writes the usage line into the formatter."""337 pieces = self.collect_usage_pieces(ctx)338 formatter.write_usage(ctx.command_path, ' '.join(pieces))339340 def format_help(self, ctx, formatter):341 """Writes the help into the formatter if it exists."""342 if self.help:343 formatter.write_paragraph()344 with formatter.indentation():345 formatter.write_text(self.help)346347 def format_options(self, ctx, formatter):348 """Writes all the options into the formatter if they exist."""349 opts = []350 for param in self.params:351 rv = param.get_help_record(ctx)352 if rv is not None:353 opts.append(rv)354355 if opts:356 with formatter.section('Options'):357 formatter.write_dl(opts)358359 def format_epilog(self, ctx, formatter):360 """Writes the epilog into the formatter if it exists."""361 if self.epilog:362 formatter.write_paragraph()363 with formatter.indentation():364 formatter.write_text(self.epilog)365366 def collect_usage_pieces(self, ctx):367 """Returns all the pieces that go into the usage line."""368 rv = [self.options_metavar]369 for param in self.params:370 rv.extend(param.get_usage_pieces(ctx))371 return rv372284 def make_context(self, info_name, args, parent=None, **extra):285 """This function when given an info name and arguments will kick286 off the parsing and create a new :class:`Context`. It does not287 invoke the actual command callback though.
21 unmodified lines
309 """Given a context and a list of arguments this creates the parser310 and parses the arguments, then modifies the context as necessary.311 This is automatically invoked by :meth:`make_context`.312 """402 parser = self.make_parser(ctx)403 opts, args, param_order = parser.parse_args(args=args)313 raise NotImplementedError('Base commands do not know how to parse '314 'arguments.')315405 for param in iter_params_for_processing(param_order, self.params):406 value, args = param.handle_parse_result(ctx, opts, args)407408 if args and not self.allow_extra_args:409 ctx.fail('Got unexpected extra argument%s (%s)'410 % (len(args) != 1 and 's' or '',411 ' '.join(map(make_str, args))))412413 ctx.args = args414316 def invoke(self, ctx):416 """Given a context, this invokes the attached callback (if it exists)417 in the right way.317 """Given a context, this invokes the command. The default318 implementation is raising a not implemented error.319 """419 if self.callback is not None:420 ctx.invoke(self.callback, **ctx.params)320 raise NotImplementedError('Base commands are not invokable by default')321322 def main(self, args=None, prog_name=None, **extra):323 """This is the way to invoke a script with all the bells and324 whistles as a command line application. This will always terminate
54 unmodified lines
379 """Alias for :meth:`main`."""380 return self.main(*args, **kwargs)381382383class Command(BaseCommand):384 """Commands are the basic building block of command line interfaces in385 click. A basic command handles command line parsing and might dispatch386 more parsing to commands nested below it.387388 :param name: the name of the command to use unless a group overrides it.389 :param callback: the callback to invoke. This is optional.390 :param params: the parameters to register with this command. This can391 be either :class:`Option` or :class:`Argument` objects.392 :param help: the help string to use for this command.393 :param epilog: like the help string but it's printed at the end of the394 help page after everything else.395 :param short_help: the short help to use for this command. This is396 shown on the command listing of the parent command.397 :param add_help_option: by default each command registers a ``--help``398 option. This can be disabled by this parameter.399 """400 allow_extra_args = False401402 def __init__(self, name, callback=None, params=None, help=None,403 epilog=None, short_help=None,404 options_metavar='[OPTIONS]', add_help_option=True):405 BaseCommand.__init__(self, name)406 #: the callback to execute when the command fires. This might be407 #: `None` in which case nothing happens.408 self.callback = callback409 #: the list of parameters for this command in the order they410 #: should show up in the help page and execute. Eager parameters411 #: will automatically be handled before non eager ones.412 self.params = params or []413 self.help = help414 self.epilog = epilog415 self.options_metavar = options_metavar416 if short_help is None and help:417 short_help = make_default_short_help(help)418 self.short_help = short_help419 if add_help_option:420 self.add_help_option()421422 def add_help_option(self):423 """Adds a help option to the command."""424 help_option()(self)425426 def get_usage(self, ctx):427 formatter = ctx.make_formatter()428 self.format_usage(ctx, formatter)429 return formatter.getvalue().rstrip('\n')430431 def format_usage(self, ctx, formatter):432 """Writes the usage line into the formatter."""433 pieces = self.collect_usage_pieces(ctx)434 formatter.write_usage(ctx.command_path, ' '.join(pieces))435436 def collect_usage_pieces(self, ctx):437 """Returns all the pieces that go into the usage line and returns438 it as a list of strings.439 """440 rv = [self.options_metavar]441 for param in self.params:442 rv.extend(param.get_usage_pieces(ctx))443 return rv444445 def make_parser(self, ctx):446 """Creates the underlying option parser for this command."""447 parser = OptionParser(ctx)448 for param in self.params:449 param.add_to_parser(parser, ctx)450 return parser451452 def get_help(self, ctx):453 """Formats the help into a string and returns it. This creates a454 formatter and will call into the following formatting methods:455 """456 formatter = ctx.make_formatter()457 self.format_help(ctx, formatter)458 return formatter.getvalue().rstrip('\n')459460 def format_help(self, ctx, formatter):461 """Writes the help into the formatter if it exists.462463 This calls into the following methods:464465 - :meth:`format_usage`466 - :meth:`format_help_text`467 - :meth:`format_options`468 - :meth:`format_epilog`469 """470 self.format_usage(ctx, formatter)471 self.format_help_text(ctx, formatter)472 self.format_options(ctx, formatter)473 self.format_epilog(ctx, formatter)474475 def format_help_text(self, ctx, formatter):476 """Writes the help text to the formatter if it exists."""477 if self.help:478 formatter.write_paragraph()479 with formatter.indentation():480 formatter.write_text(self.help)481482 def format_options(self, ctx, formatter):483 """Writes all the options into the formatter if they exist."""484 opts = []485 for param in self.params:486 rv = param.get_help_record(ctx)487 if rv is not None:488 opts.append(rv)489490 if opts:491 with formatter.section('Options'):492 formatter.write_dl(opts)493494 def format_epilog(self, ctx, formatter):495 """Writes the epilog into the formatter if it exists."""496 if self.epilog:497 formatter.write_paragraph()498 with formatter.indentation():499 formatter.write_text(self.epilog)500501 def parse_args(self, ctx, args):502 parser = self.make_parser(ctx)503 opts, args, param_order = parser.parse_args(args=args)504505 for param in iter_params_for_processing(param_order, self.params):506 value, args = param.handle_parse_result(ctx, opts, args)507508 if args and not self.allow_extra_args:509 ctx.fail('Got unexpected extra argument%s (%s)'510 % (len(args) != 1 and 's' or '',511 ' '.join(map(make_str, args))))512513 ctx.args = args514515 def invoke(self, ctx):516 """Given a context, this invokes the attached callback (if it exists)517 in the right way.518 """519 if self.callback is not None:520 ctx.invoke(self.callback, **ctx.params)521522523class MultiCommand(Command):524 """A multi command is the basic implementation of a command that525 dispatches to subcommands. The most common version is the526 :class:`Command`.
613 unmodified lines
modified:docs/api.rst+3 added
49 unmodified lines
5051Commands52--------5354.. autoclass:: BaseCommand55 :members:5657.. autoclass:: Command58 :members:5960.. autoclass:: MultiCommand
82 unmodified lines
modified:tests/test_commands.py+65 added
101 unmodified lines
102103 result = runner.invoke(cli, ['obj1', 'move'])104 assert result.exit_code == 0105 assert result.output == 'obj=obj1\nmove\n'106107108def test_base_command(runner):109 import optparse110111 @click.group()112 def cli():113 pass114115 class OptParseCommand(click.BaseCommand):116117 def __init__(self, name, parser, callback):118 click.BaseCommand.__init__(self, name)119 self.parser = parser120 self.callback = callback121122 def parse_args(self, ctx, args):123 try:124 opts, args = parser.parse_args(args)125 except Exception as e:126 ctx.fail(str(e))127 ctx.args = args128 ctx.params = vars(opts)129130 def get_usage(self, ctx):131 return self.parser.get_usage()132133 def get_help(self, ctx):134 return self.parser.format_help()135136 def invoke(self, ctx):137 ctx.invoke(self.callback, ctx.args, **ctx.params)138139 parser = optparse.OptionParser(usage='Usage: foo test [OPTIONS]')140 parser.add_option("-f", "--file", dest="filename",141 help="write report to FILE", metavar="FILE")142 parser.add_option("-q", "--quiet",143 action="store_false", dest="verbose", default=True,144 help="don't print status messages to stdout")145146 def test_callback(args, filename, verbose):147 click.echo(' '.join(args))148 click.echo(filename)149 click.echo(verbose)150 cli.add_command(OptParseCommand('test', parser, test_callback))151152 result = runner.invoke(cli, ['test', '-f', 'test.txt', '-q',153 'whatever.txt', 'whateverelse.txt'])154 assert not result.exception155 assert result.output.splitlines() == [156 'whatever.txt whateverelse.txt',157 'test.txt',158 'False',159 ]160161 result = runner.invoke(cli, ['test', '--help'])162 assert not result.exception163 assert result.output.splitlines() == [164 'Usage: foo test [OPTIONS]',165 '',166 'Options:',167 ' -h, --help show this help message and exit',168 ' -f FILE, --file=FILE write report to FILE',169 ' -q, --quiet don\'t print status messages to stdout',170 ]