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
Provenance
- Commit
8d0dfa5- Tree
d47cc2e- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
252fdf3
6 files changed+293 added−27 removed
modified:click/core.py+115 added-26 removed
14 unmodified lines15 16 _missing = object()17 18 19+SUBCOMMAND_METAVAR = 'COMMAND [ARGS]...'20+SUBCOMMANDS_METAVAR = 'COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...'21+22+23 def _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 lines101 .. versionadded:: 2.0102 Added the `resilient_parsing`, `help_option_names`,103 `token_normalize_func` parameters.104 105+ .. versionadded:: 3.0106+ Added the `allow_extra_args` and `allow_interspersed_args`107+ parameters.108+109 :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 or15 unmodified lines128 :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 to4 unmodified lines147 148 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 lines160 #: 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 = obj3 unmodified lines171 and parent.default_map is not None:172 default_map = parent.default_map.get(info_name)173 self.default_map = default_map174 175+ #: 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 = []183+184 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_width188 189+ 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_args196+197+ 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_args204+205 if help_option_names is None:206 if parent is not None:207 help_option_names = parent.help_option_names208 else:33 unmodified lines242 243 def __exit__(self, exc_type, exc_value, tb):244 self.close()245 246+ 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.252+253+ 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_subcommand268+269 def make_formatter(self):270 """Creates the formatter for the help and usage output."""271 return HelpFormatter(width=self.terminal_width)272 149 unmodified lines422 :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 = True428 429 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 name137 unmodified lines569 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 = False573 574 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 lines641 642 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 lines703 for param in iter_params_for_processing(704 param_order, self.get_params(ctx)):705 value, args = param.handle_parse_result(ctx, opts, args)706 647- 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))))711 712 ctx.args = args713+ return args714 715 def invoke(self, ctx):716 """Given a context, this invokes the attached callback (if it exists)717 in the right way.17 unmodified lines735 ``--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 = False746 747 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 = chain762 691- def make_parser(self, ctx):692- parser = Command.make_parser(self, ctx)693- parser.allow_interspersed_args = False694- return parser695-763 def collect_usage_pieces(self, ctx):764 rv = Command.collect_usage_pieces(self, ctx)765 rv.append(self.subcommand_metavar)766 return rv31 unmodified lines798 if self.invoke_without_command:799 return Command.invoke(self, ctx)800 ctx.fail('Missing command.')801 802+ args = ctx.args803+804+ # 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)813+814+ # 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.args822+823+ # 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 rv831+832+ 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_name835 836 # Get the command837 cmd = self.get_command(ctx, cmd_name)14 unmodified lines852 if split_opt(cmd_name)[0]:853 self.parse_args(ctx, ctx.args)854 ctx.fail('No such command "%s".' % original_cmd_name)855 758- return self.invoke_subcommand(ctx, cmd, cmd_name, ctx.args[1:])856+ return cmd.make_context(cmd_name, args[1:], parent=ctx, **extra)857 760- 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)765-766- with cmd.make_context(cmd_name, args, parent=ctx) as cmd_ctx:767- return cmd.invoke(cmd_ctx)768-858 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 linesmodified:docs/commands.rst+46 added
271 unmodified lines272 invoke(cli, prog_name='cli', args=['--help'])273 274 In case a command exists in more than one source, the first source wins.275 276+Multi Command Chaining277+----------------------278+279+.. versionadded:: 3.0280+281+Sometimes it is useful to be allowed to invoke more than one subcommand in282+one go. For instance if you have installed a setuptools package before283+ouy might be familiar with the ``setup.py sdist bdist_wheel upload``284+command chain which invokes ``dist`` before ``bdist_wheel`` before285+``upload``. Starting with Click 3.0 this is very simple to implement.286+All you have to do is to pass ``chain=True`` to your multicommand:287+288+.. click:example::289+290+ @click.group(chain=True)291+ def cli():292+ pass293+294+295+ @cli.command('sdist')296+ def sdist():297+ click.echo('sdist called')298+299+300+ @cli.command('bdist_wheel')301+ def bdist_wheel():302+ click.echo('bdist_wheel called')303+304+Now you can invoke it like this:305+306+.. click:run::307+308+ invoke(cli, prog_name='setup.py', args=['sdist', 'bdist_wheel'])309+310+When using multi command chaining you can only have one command (the last)311+use ``nargs=-1`` on an argument. Other than that there are no312+restrictions on how they work. They can accept options and arguments as313+normal.314+315+Another note: the :attr:`Context.invoked_subcommand` attribute is a bit316+useless for multi commands as it will give ``'*'`` as value if more than317+one command is invoked. Instead you should be using the318+:attr:`Context.invoked_subcommands` attribute instead which is a list319+(note the trailing "s").320+321+322 Overriding Defaults323 -------------------324 325 By default, the default value for a parameter is pulled from the83 unmodified linesmodified:tests/test_basic.py+1 added
34 unmodified lines35 click.echo('SUBCOMMAND EXECUTED')36 37 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.output346 unmodified linesadded:tests/test_chain.py+129 added
1+import click2+3+4+def test_basic_chaining(runner):5+ @click.group(chain=True)6+ def cli():7+ pass8+9+ @cli.command('sdist')10+ def sdist():11+ click.echo('sdist called')12+13+ @cli.command('bdist')14+ def bdist():15+ click.echo('bdist called')16+17+ 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+ ]24+25+26+def test_chaining_help(runner):27+ @click.group(chain=True)28+ def cli():29+ """ROOT HELP"""30+ pass31+32+ @cli.command('sdist')33+ def sdist():34+ """SDIST HELP"""35+ click.echo('sdist called')36+37+ @cli.command('bdist')38+ def bdist():39+ """BDIST HELP"""40+ click.echo('bdist called')41+42+ result = runner.invoke(cli, ['--help'])43+ assert not result.exception44+ assert 'COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...' in result.output45+ assert 'ROOT HELP' in result.output46+47+ result = runner.invoke(cli, ['sdist', '--help'])48+ assert not result.exception49+ assert 'SDIST HELP' in result.output50+51+ result = runner.invoke(cli, ['bdist', '--help'])52+ assert not result.exception53+ assert 'BDIST HELP' in result.output54+55+ result = runner.invoke(cli, ['bdist', 'sdist', '--help'])56+ assert not result.exception57+ assert 'SDIST HELP' in result.output58+59+60+def test_chaining_with_options(runner):61+ @click.group(chain=True)62+ def cli():63+ pass64+65+ @cli.command('sdist')66+ @click.option('--format')67+ def sdist(format):68+ click.echo('sdist called %s' % format)69+70+ @cli.command('bdist')71+ @click.option('--format')72+ def bdist(format):73+ click.echo('bdist called %s' % format)74+75+ 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+ ]81+82+83+def test_chaining_with_arguments(runner):84+ @click.group(chain=True)85+ def cli():86+ pass87+88+ @cli.command('sdist')89+ @click.argument('format')90+ def sdist(format):91+ click.echo('sdist called %s' % format)92+93+ @cli.command('bdist')94+ @click.argument('format')95+ def bdist(format):96+ click.echo('bdist called %s' % format)97+98+ 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+ ]104+105+106+def test_context_subcommand_info_sync():107+ @click.command()108+ def cli():109+ pass110+111+ ctx = click.Context(cli, info_name='cli')112+113+ assert ctx.invoked_subcommand is None114+115+ ctx.invoked_subcommand = 'foo'116+ assert ctx.invoked_subcommand == 'foo'117+ assert ctx.invoked_subcommands == ['foo']118+119+ ctx.invoked_subcommands = ['foo']120+ assert ctx.invoked_subcommand == 'foo'121+ assert ctx.invoked_subcommands == ['foo']122+123+ ctx.invoked_subcommands = []124+ assert ctx.invoked_subcommand is None125+ assert ctx.invoked_subcommands == []126+127+ ctx.invoked_subcommands = ['foo', 'bar']128+ assert ctx.invoked_subcommand == '*'129+ assert ctx.invoked_subcommands == ['foo', 'bar']modified:CHANGES+1 added
20 unmodified lines21 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.26 27 Version 2.628 -----------29 111 unmodified linesmodified:Makefile+1 added-1 removed
1 test:2- @cd tests; PYTHONPATH=.. py.test2+ @cd tests; PYTHONPATH=.. py.test --tb=short3 4 upload-docs:5 $(MAKE) -C docs dirhtml6 rsync -a docs/_build/dirhtml/* flow.srv.pocoo.org:/srv/websites/click.pocoo.org/static/2 unmodified lines