Skip to content
Myr

extending-click.md

This file

Path

docs/extending-click.md

132 lines · 3.7 KiB · Markdown

Last changed by

Move Extending-click page from reST to MyST (#3106)Rowlando13before adoptiona2623d0

History of this file

Take it

Move Extending-click page from reST to MyST (#3106)Rowlando13before adoptiona2623d0

lines 1–132why, one step back
1# Extending Click
23```{currentmodule} click4```56In addition to common functionality that is implemented in the library itself, there are countless patterns that can be7implemented by extending Click. This page should give some insight into what can be accomplished.89```{contents}10:depth: 211:local: true12```1314(custom-groups)=1516## Custom Groups1718You can customize the behavior of a group beyond the arguments it accepts by subclassing {class}`click.Group`.1920The most common methods to override are {meth}`~click.Group.get_command` and {meth}`~click.Group.list_commands`.2122The following example implements a basic plugin system that loads commands from Python files in a folder. The command is23lazily loaded to avoid slow startup.2425```python26import importlib.util27import os28import click2930class PluginGroup(click.Group):31 def __init__(self, name=None, plugin_folder="commands", **kwargs):32 super().__init__(name=name, **kwargs)33 self.plugin_folder = plugin_folder3435 def list_commands(self, ctx):36 rv = []3738 for filename in os.listdir(self.plugin_folder):39 if filename.endswith(".py"):40 rv.append(filename[:-3])4142 rv.sort()43 return rv4445 def get_command(self, ctx, name):46 path = os.path.join(self.plugin_folder, f"{name}.py")47 spec = importlib.util.spec_from_file_location(name, path)48 module = importlib.util.module_from_spec(spec)49 spec.loader.exec_module(module)50 return module.cli5152cli = PluginGroup(53 plugin_folder=os.path.join(os.path.dirname(__file__), "commands")54)5556if __name__ == "__main__":57 cli()58```5960Custom classes can also be used with decorators:6162```python63@click.group(64 cls=PluginGroup,65 plugin_folder=os.path.join(os.path.dirname(__file__), "commands")66)67def cli():68 pass69```7071(aliases)=7273## Command Aliases7475Many tools support aliases for commands. For example, you can configure `git` to accept `git ci` as alias for76`git commit`. Other tools also support auto-discovery for aliases by automatically shortening them.7778It's possible to customize {class}`Group` to provide this functionality. As explained in {ref}`custom-groups`, a group79provides two methods: {meth}`~Group.list_commands` and {meth}`~Group.get_command`. In this particular case, you only80need to override the latter as you generally don't want to enumerate the aliases on the help page in order to avoid81confusion.8283The following example implements a subclass of {class}`Group` that accepts a prefix for a command. If there was a84command called `push`, it would accept `pus` as an alias (so long as it was unique):8586```{eval-rst}87.. click:example::8889 class AliasedGroup(click.Group):90 def get_command(self, ctx, cmd_name):91 rv = super().get_command(ctx, cmd_name)9293 if rv is not None:94 return rv9596 matches = [97 x for x in self.list_commands(ctx)98 if x.startswith(cmd_name)99 ]100101 if not matches:102 return None103104 if len(matches) == 1:105 return click.Group.get_command(self, ctx, matches[0])106107 ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")108109 def resolve_command(self, ctx, args):110 # always return the full command name111 _, cmd, args = super().resolve_command(ctx, args)112 return cmd.name, cmd, args113```114115It can be used like this:116117```python118119 @click.group(cls=AliasedGroup)120 def cli():121 pass122123 @cli.command124 def push():125 pass126127 @cli.command128 def pop():129 pass130```131132See the [alias example](https://github.com/pallets/click/tree/main/examples/aliases) in Click's repository for another example.