Skip to content
Myr

Added subcommand chaining.

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 252fdf3 · Browse files · 6 files+293 added−27 removed
This commit

State

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

Diff stats

6 files+293 added−27 removed

  • tests:+130 added−0 removed
  • other:+163 added−27 removed

6 files+293 added−27 removed

modified:click/core.py+115 added-26 removed
14 unmodified lines
1516_missing = object()171819SUBCOMMAND_METAVAR = 'COMMAND [ARGS]...'20SUBCOMMANDS_METAVAR = 'COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...'212223def _bashcomplete(cmd, prog_name, complete_var=None):24 """Internal handler for the bash completion support."""25 if complete_var is None:26 complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper()
74 unmodified lines
101 .. versionadded:: 2.0102 Added the `resilient_parsing`, `help_option_names`,103 `token_normalize_func` parameters.104105 .. versionadded:: 3.0106 Added the `allow_extra_args` and `allow_interspersed_args`107 parameters.108109 :param command: the command class for this context.110 :param parent: the parent context.111 :param info_name: the info name for this invokation. Generally this112 is the most descriptive name for the script or
15 unmodified lines
128 :param resilient_parsing: if this flag is enabled then Click will129 parse without any interactivity or callback130 invocation. This is useful for implementing131 things such as completion support.132 :param allow_extra_args: if this is set to `True` then extra arguments133 at the end will not raise an error and will be134 kept on the context. The default is to inherit135 from the command.136 :param allow_interspersed_args: if this is set to `False` then options137 and arguments cannot be mixed. The138 default is to inherit from the command.139 :param help_option_names: optionally a list of strings that define how140 the default help parameter is named. The141 default is ``['--help']``.142 :param token_normalize_func: an optional function that is used to
4 unmodified lines
147148 def __init__(self, command, parent=None, info_name=None, obj=None,149 auto_envvar_prefix=None, default_map=None,150 terminal_width=None, resilient_parsing=False,151 allow_extra_args=None, allow_interspersed_args=None,152 help_option_names=None, token_normalize_func=None):153 #: the parent context or `None` if none exists.154 self.parent = parent155 #: the :class:`Command` for this context.
4 unmodified lines
160 #: case it's not remembered.161 self.params = {}162 #: the leftover arguments.163 self.args = []148 #: this flag indicates if a subcommand is going to be executed.149 #: a group callback can use this information to figure out if it's150 #: being executed directly or because the execution flow passes151 #: onwards to a subcommand. By default it's `None`, but it can be152 #: the name of the subcommand to execute.153 self.invoked_subcommand = None164 if obj is None and parent is not None:165 obj = parent.obj166 #: the user object stored.167 self.obj = obj
3 unmodified lines
171 and parent.default_map is not None:172 default_map = parent.default_map.get(info_name)173 self.default_map = default_map174175 #: This is similar to :attr:`invoked_subcommand` but it holds a176 #: list of multiple subcommand names. This is useful if multi command177 #: chaining is enabled.178 #:179 #: This property and :attr:`invoked_subcommand` are synchronized.180 #:181 #: .. versionadded:: 3.0182 self.invoked_subcommands = []183184 if terminal_width is None and parent is not None:185 terminal_width = parent.terminal_width186 #: The width of the terminal (None is autodetection).187 self.terminal_width = terminal_width188189 if allow_extra_args is None:190 allow_extra_args = command.allow_extra_args191 #: Indicates if the context allows extra args or if it should192 #: fail on parsing.193 #:194 #: .. versionadded:: 3.0195 self.allow_extra_args = allow_extra_args196197 if allow_interspersed_args is None:198 allow_interspersed_args = command.allow_interspersed_args199 #: Indicates if the context allows mixing of arguments and200 #: options or not.201 #:202 #: .. versionadded:: 3.0203 self.allow_interspersed_args = allow_interspersed_args204205 if help_option_names is None:206 if parent is not None:207 help_option_names = parent.help_option_names208 else:
33 unmodified lines
242243 def __exit__(self, exc_type, exc_value, tb):244 self.close()245246 def _get_invoked_subcommand(self):247 """This flag indicates if a subcommand is going to be executed. A248 group callback can use this information to figure out if it's249 being executed directly or because the execution flow passes250 onwards to a subcommand. By default it's `None`, but it can be251 the name of the subcommand to execute.252253 If chaining is enabled and more than one subcommand is invoked254 then the value will be the string ``'*'``. For chaining you255 should be using :attr:`invoked_subcommands` instead.256 """257 if len(self.invoked_subcommands) == 1:258 return self.invoked_subcommands[0]259 if len(self.invoked_subcommands) > 1:260 return '*'261 def _set_invoked_subcommand(self, value):262 if value is not None:263 value = [value]264 self.invoked_subcommands = value265 invoked_subcommand = property(_get_invoked_subcommand,266 _set_invoked_subcommand)267 del _get_invoked_subcommand, _set_invoked_subcommand268269 def make_formatter(self):270 """Creates the formatter for the help and usage output."""271 return HelpFormatter(width=self.terminal_width)272
149 unmodified lines
422 :param name: the name of the command to use unless a group overrides it.423 :param context_settings: an optional dictionary with defaults that are424 passed to the context object.425 """426 allow_extra_args = False427 allow_interspersed_args = True428429 def __init__(self, name, context_settings=None):430 #: the name the command thinks it has. Upon registering a command431 #: on a :class:`Group` the group will default the command name
137 unmodified lines
569 shown on the command listing of the parent command.570 :param add_help_option: by default each command registers a ``--help``571 option. This can be disabled by this parameter.572 """513 allow_extra_args = False573574 def __init__(self, name, context_settings=None, callback=None,575 params=None, help=None, epilog=None, short_help=None,576 options_metavar='[OPTIONS]', add_help_option=True):
64 unmodified lines
641642 def make_parser(self, ctx):643 """Creates the underlying option parser for this command."""644 parser = OptionParser(ctx)645 parser.allow_interspersed_args = ctx.allow_interspersed_args646 for param in self.get_params(ctx):647 param.add_to_parser(parser, ctx)648 return parser649
53 unmodified lines
703 for param in iter_params_for_processing(704 param_order, self.get_params(ctx)):705 value, args = param.handle_parse_result(ctx, opts, args)706647 if args and not self.allow_extra_args and not ctx.resilient_parsing:707 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:708 ctx.fail('Got unexpected extra argument%s (%s)'709 % (len(args) != 1 and 's' or '',710 ' '.join(map(make_str, args))))711712 ctx.args = args713 return args714715 def invoke(self, ctx):716 """Given a context, this invokes the attached callback (if it exists)717 in the right way.
17 unmodified lines
735 ``--help`` as argument if no arguments are736 passed.737 :param subcommand_metavar: the string that is used in the documentation738 to indicate the subcommand place.739 :param chain: if this is set to `True` chaining of multiple subcommands740 is enabled. This restricts the form of commands in that741 they cannot have optional arguments but it allows742 multiple commands to be chained together.743 """744 allow_extra_args = True745 allow_interspersed_args = False746747 def __init__(self, name=None, invoke_without_command=False,682 no_args_is_help=None, subcommand_metavar='COMMAND [ARGS]...',683 **attrs):748 no_args_is_help=None, subcommand_metavar=None,749 chain=False, **attrs):750 Command.__init__(self, name, **attrs)751 if no_args_is_help is None:752 no_args_is_help = not invoke_without_command753 self.no_args_is_help = no_args_is_help754 self.invoke_without_command = invoke_without_command755 if subcommand_metavar is None:756 if chain:757 subcommand_metavar = SUBCOMMANDS_METAVAR758 else:759 subcommand_metavar = SUBCOMMAND_METAVAR760 self.subcommand_metavar = subcommand_metavar761 self.chain = chain762691 def make_parser(self, ctx):692 parser = Command.make_parser(self, ctx)693 parser.allow_interspersed_args = False694 return parser695763 def collect_usage_pieces(self, ctx):764 rv = Command.collect_usage_pieces(self, ctx)765 rv.append(self.subcommand_metavar)766 return rv
31 unmodified lines
798 if self.invoke_without_command:799 return Command.invoke(self, ctx)800 ctx.fail('Missing command.')801802 args = ctx.args803804 # If we're not in chain mode, we only allow the invocation of a805 # single command but we also inform the current context about the806 # name of the command to invoke.807 if not self.chain:808 sub_ctx = self.handle_subcommand(ctx, args)809 ctx.invoked_subcommands = [sub_ctx.info_name]810 Command.invoke(self, ctx)811 with sub_ctx:812 return sub_ctx.command.invoke(sub_ctx)813814 # Otherwise we make every single context and invoke them in a815 # chain.816 contexts = []817 while args:818 sub_ctx = self.handle_subcommand(ctx, args, allow_extra_args=True,819 allow_interspersed_args=False)820 contexts.append(sub_ctx)821 args = sub_ctx.args822823 # Now that we have all contexts, we can invoke them.824 ctx.invoked_subcommands = [x.info_name for x in contexts]825 Command.invoke(self, ctx)826 rv = []827 for sub_ctx in contexts:828 with sub_ctx:829 rv.append(sub_ctx.command.invoke(sub_ctx))830 return rv831832 def handle_subcommand(self, ctx, args, **extra):735 cmd_name = make_str(ctx.args[0])833 cmd_name = make_str(args[0])834 original_cmd_name = cmd_name835836 # Get the command837 cmd = self.get_command(ctx, cmd_name)
14 unmodified lines
852 if split_opt(cmd_name)[0]:853 self.parse_args(ctx, ctx.args)854 ctx.fail('No such command "%s".' % original_cmd_name)855758 return self.invoke_subcommand(ctx, cmd, cmd_name, ctx.args[1:])856 return cmd.make_context(cmd_name, args[1:], parent=ctx, **extra)857760 def invoke_subcommand(self, ctx, cmd, cmd_name, args):761 # Whenever we dispatch to a subcommand we also invoke the regular762 # callback. This is done so that parameters can be handled.763 ctx.invoked_subcommand = cmd_name764 Command.invoke(self, ctx)765766 with cmd.make_context(cmd_name, args, parent=ctx) as cmd_ctx:767 return cmd.invoke(cmd_ctx)768858 def get_command(self, ctx, cmd_name):859 """Given a context and a command name, this returns a860 :class:`Command` object if it exists or returns `None`.861 """
570 unmodified lines
modified:docs/commands.rst+46 added
271 unmodified lines
272 invoke(cli, prog_name='cli', args=['--help'])273274In case a command exists in more than one source, the first source wins.275276Multi Command Chaining277----------------------278279.. versionadded:: 3.0280281Sometimes it is useful to be allowed to invoke more than one subcommand in282one go. For instance if you have installed a setuptools package before283ouy might be familiar with the ``setup.py sdist bdist_wheel upload``284command chain which invokes ``dist`` before ``bdist_wheel`` before285``upload``. Starting with Click 3.0 this is very simple to implement.286All you have to do is to pass ``chain=True`` to your multicommand:287288.. click:example::289290 @click.group(chain=True)291 def cli():292 pass293294295 @cli.command('sdist')296 def sdist():297 click.echo('sdist called')298299300 @cli.command('bdist_wheel')301 def bdist_wheel():302 click.echo('bdist_wheel called')303304Now you can invoke it like this:305306.. click:run::307308 invoke(cli, prog_name='setup.py', args=['sdist', 'bdist_wheel'])309310When using multi command chaining you can only have one command (the last)311use ``nargs=-1`` on an argument. Other than that there are no312restrictions on how they work. They can accept options and arguments as313normal.314315Another note: the :attr:`Context.invoked_subcommand` attribute is a bit316useless for multi commands as it will give ``'*'`` as value if more than317one command is invoked. Instead you should be using the318:attr:`Context.invoked_subcommands` attribute instead which is a list319(note the trailing "s").320321322Overriding Defaults323-------------------324325By default, the default value for a parameter is pulled from the
83 unmodified lines
modified:tests/test_basic.py+1 added
34 unmodified lines
35 click.echo('SUBCOMMAND EXECUTED')3637 result = runner.invoke(cli, ['--help'])38 assert not result.exception39 assert 'COMMAND [ARGS]...' in result.output40 assert 'This is the root' in result.output41 assert 'This is a subcommand.' in result.output42 assert result.exit_code == 043 assert 'ROOT EXECUTED' not in result.output
346 unmodified lines
added:tests/test_chain.py+129 added
1import click234def test_basic_chaining(runner):5 @click.group(chain=True)6 def cli():7 pass89 @cli.command('sdist')10 def sdist():11 click.echo('sdist called')1213 @cli.command('bdist')14 def bdist():15 click.echo('bdist called')1617 result = runner.invoke(cli, ['bdist', 'sdist', 'bdist'])18 assert not result.exception19 assert result.output.splitlines() == [20 'bdist called',21 'sdist called',22 'bdist called',23 ]242526def test_chaining_help(runner):27 @click.group(chain=True)28 def cli():29 """ROOT HELP"""30 pass3132 @cli.command('sdist')33 def sdist():34 """SDIST HELP"""35 click.echo('sdist called')3637 @cli.command('bdist')38 def bdist():39 """BDIST HELP"""40 click.echo('bdist called')4142 result = runner.invoke(cli, ['--help'])43 assert not result.exception44 assert 'COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...' in result.output45 assert 'ROOT HELP' in result.output4647 result = runner.invoke(cli, ['sdist', '--help'])48 assert not result.exception49 assert 'SDIST HELP' in result.output5051 result = runner.invoke(cli, ['bdist', '--help'])52 assert not result.exception53 assert 'BDIST HELP' in result.output5455 result = runner.invoke(cli, ['bdist', 'sdist', '--help'])56 assert not result.exception57 assert 'SDIST HELP' in result.output585960def test_chaining_with_options(runner):61 @click.group(chain=True)62 def cli():63 pass6465 @cli.command('sdist')66 @click.option('--format')67 def sdist(format):68 click.echo('sdist called %s' % format)6970 @cli.command('bdist')71 @click.option('--format')72 def bdist(format):73 click.echo('bdist called %s' % format)7475 result = runner.invoke(cli, ['bdist', '--format=1', 'sdist', '--format=2'])76 assert not result.exception77 assert result.output.splitlines() == [78 'bdist called 1',79 'sdist called 2',80 ]818283def test_chaining_with_arguments(runner):84 @click.group(chain=True)85 def cli():86 pass8788 @cli.command('sdist')89 @click.argument('format')90 def sdist(format):91 click.echo('sdist called %s' % format)9293 @cli.command('bdist')94 @click.argument('format')95 def bdist(format):96 click.echo('bdist called %s' % format)9798 result = runner.invoke(cli, ['bdist', '1', 'sdist', '2'])99 assert not result.exception100 assert result.output.splitlines() == [101 'bdist called 1',102 'sdist called 2',103 ]104105106def test_context_subcommand_info_sync():107 @click.command()108 def cli():109 pass110111 ctx = click.Context(cli, info_name='cli')112113 assert ctx.invoked_subcommand is None114115 ctx.invoked_subcommand = 'foo'116 assert ctx.invoked_subcommand == 'foo'117 assert ctx.invoked_subcommands == ['foo']118119 ctx.invoked_subcommands = ['foo']120 assert ctx.invoked_subcommand == 'foo'121 assert ctx.invoked_subcommands == ['foo']122123 ctx.invoked_subcommands = []124 assert ctx.invoked_subcommand is None125 assert ctx.invoked_subcommands == []126127 ctx.invoked_subcommands = ['foo', 'bar']128 assert ctx.invoked_subcommand == '*'129 assert ctx.invoked_subcommands == ['foo', 'bar']
modified:CHANGES+1 added
20 unmodified lines
21 now, Click will give an error message instead of silently22 passing. This should catch situations where users wanted to23 created arguments instead of options.24- Restructured Click internally to support vendoring.25- Added support for multi command chaining.2627Version 2.628-----------29
111 unmodified lines
modified:Makefile+1 added-1 removed
1test:2 @cd tests; PYTHONPATH=.. py.test2 @cd tests; PYTHONPATH=.. py.test --tb=short34upload-docs:5 $(MAKE) -C docs dirhtml6 rsync -a docs/_build/dirhtml/* flow.srv.pocoo.org:/srv/websites/click.pocoo.org/static/
2 unmodified lines