Skip to content
Myr

advanced.rst

This file

Path

docs/advanced.rst

56 lines · 1.9 KiB

Last changed by

Added an example for aliasesArmin Ronacherbefore adoptione2d388e

History of this file

Take it

Added an example for aliasesArmin Ronacherbefore adoptione2d388e

lines 1–56why, one step back
1Advanced Patterns
2=================34In addition to common functionality that is implemented in the library5itself, there are countless of patterns that can be implemented by extending6click. This page should give some inspiration of what can be7accomplished.89Command Aliases10---------------1112Many tools support aliases for commands. For instance you can configure13``git`` to accept ``git ci`` as alias for ``git commit``. Other tools14also support auto discovery for aliases by automatically shortening them.1516Click does not support this out of the box but it's very easy to customize17the :class:`Group` or any other :class:`MultiCommand` to provide this18functionality.1920As explained in :ref:`custom-multi-commands` a multi command can provide21two methods: :meth:`~MultiCommand.list_commands` and22:meth:`~MultiCommand.get_command`. In this particular case you only need23to override the latter as you generally don't want to enumerate the24aliases on the help page to avoid confusion.2526This following example implements a subclass of :class:`Group` that27accepts a prefix for a command. So if there is a command called28``push`` it would accept ``pus`` as alias if it's unique::2930 class AliasedGroup(click.Group):3132 def get_command(self, ctx, cmd_name):33 rv = click.Group.get_command(self, ctx, cmd_name)34 if rv is not None:35 return rv36 matches = [x for x in self.list_commands()37 if x.startswith(cmd_name)]38 if not matches:39 return None40 elif len(matches) == 1:41 return click.Group.get_command(self, ctx, matches[0])42 ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))4344And it can be used like this then::4546 @click.command(cls=AliasedGroup)47 def cli():48 pass4950 @cli.command()51 def push():52 pass5354 @cli.command()55 def pop():56 pass