advanced.rst
This file
Path
docs/advanced.rst
162 lines · 5.7 KiB
Last changed by
Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
History of this fileTake it
1Advanced Patterns2=================34.. currentmodule:: click56In addition to common functionality that is implemented in the library7itself, there are countless of patterns that can be implemented by extending8click. This page should give some inspiration of what can be9accomplished.1011.. _aliases:1213Command Aliases14---------------1516Many tools support aliases for commands. For instance, you can configure17``git`` to accept ``git ci`` as alias for ``git commit``. Other tools18also support auto discovery for aliases by automatically shortening them.1920Click does not support this out of the box but it's very easy to customize21the :class:`Group` or any other :class:`MultiCommand` to provide this22functionality.2324As explained in :ref:`custom-multi-commands`, a multi command can provide25two methods: :meth:`~MultiCommand.list_commands` and26:meth:`~MultiCommand.get_command`. In this particular case you only need27to override the latter as you generally don't want to enumerate the28aliases on the help page to avoid confusion.2930This following example implements a subclass of :class:`Group` that31accepts a prefix for a command. If there is a command called32``push`` it would accept ``pus`` as an alias if it's unique:3334.. click:example::3536 class AliasedGroup(click.Group):3738 def get_command(self, ctx, cmd_name):39 rv = click.Group.get_command(self, ctx, cmd_name)40 if rv is not None:41 return rv42 matches = [x for x in self.list_commands(ctx)43 if x.startswith(cmd_name)]44 if not matches:45 return None46 elif len(matches) == 1:47 return click.Group.get_command(self, ctx, matches[0])48 ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))4950And it can then be used like this:5152.. click:example::5354 @click.command(cls=AliasedGroup)55 def cli():56 pass5758 @cli.command()59 def push():60 pass6162 @cli.command()63 def pop():64 pass6566Invoking Other Commands67-----------------------6869Sometimes, it might be interesting to invoke one command from another70command. This is a pattern that is generally discouraged with click but71possible nonetheless. For this you can use the :func:`Context.invoke`72or :func:`Context.forward` methods.7374They work similarly, but the difference is that :func:`Context.invoke` merely75invokes another command with the arguments you provide as a caller,76whereas :func:`Context.forward` fills in the arguments from the current77command. Both accept the command as the first argument and everything else78is passed onwards as you would expect.7980Example:8182.. click:example::8384 cli = click.Group()8586 @cli.command()87 @click.option('--count', default=1)88 def test(count):89 click.echo('Count: %d' % count)9091 @cli.command()92 @click.option('--count', default=1)93 @click.pass_context94 def dist(ctx, count):95 ctx.forward(test)96 ctx.invoke(test, count=42)9798And what it looks like:99100.. click:run::101102 invoke(cli, prog_name='cli', args=['dist'])103104105.. _callback-evaluation-order:106107Callback Evaluation Order108-------------------------109110Click works a bit different than some other command line parsers in that111it attempts to reconcile the order of arguments as defined by the112programmer with the order of arguments as defined by the user before113invoking any callbacks.114115This is an important concept to understand when implementing complex116patterns ported from optparse or other systems to click. A parameter117callback invocation in optparse happens as part of the parsing step118whereas a callback invocation in click happens after the parsing.119120The main difference is that in optparse callbacks are invoked with the raw121value as it happens, whereas a callback in click is invoked after the122value has been fully converted.123124Generally, the order of invocation is driven by the order in which the user125provides the arguments to the script; if there is an option called ``--foo``126and an option called ``--bar`` and the user calls it as ``--bar127--foo``, then the callback for ``bar`` will fire before the one for ``foo``.128129There are two exceptions to this rule which are important to know:130131Eagerness:132 An option can be set to be "eager". All eager parameters are133 evaluated before all non-eager parameters, but again in the order as134 they were provided on the command line by the user.135136 This is important for parameters that execute and exit like ``--help``137 and ``--version``. Both are eager parameters, but whatever parameter138 comes first on the command line will win and exit the program.139140Repeated parameters:141 If an option or argument is split up on the command line into multiple142 places because it's repeated (for instance ``--exclude foo --include143 baz --exclude bar``), the callback will fire based on the position of144 the first option. In this case, the callback will fire for145 ``exclude`` and it will be passed both options (``foo`` and146 ``bar``), then the callback for ``include`` will fire with ``baz``147 only.148149 Note that even if a parameter does not allow multiple versions, click150 will still accept the position of the first, but it will ignore every151 value except the first. The reason for this is to allow composability152 through shell aliases that set defaults.153154Missing parameters:155 If a parameter is not defined on the command line, the callback will156 still fire. This is different from how it works in optparse where157 undefined values do not fire the callback. Missing parameters fire158 their callbacks at the very end which makes it possible for them to159 default to values from a parameter that came before.160161Most of the time you don't need to be concerned about any of this stuff,162but it's important to know how it works for some advanced cases.