Skip to content
Myr

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

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

authored by Rowlando13 · committed by GitHub · parents 6707116, 2d1c49d · Browse files · 2 files+132 added−138 removed
This commit

State

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

Diff stats

2 files+132 added−138 removed

  • other:+132 added−138 removed

2 files+132 added−138 removed

added:docs/extending-click.md+132 added
1# Extending Click23```{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.
deleted:docs/extending-click.rst-138 removed
1Extending Click2=================34.. currentmodule:: click56In addition to common functionality that is implemented in the library7itself, there are countless patterns that can be implemented by extending8Click. This page should give some insight into what can be accomplished.910.. contents::11 :depth: 212 :local:1314.. _custom-groups:1516Custom Groups17-------------1819You can customize the behavior of a group beyond the arguments it accepts by20subclassing :class:`click.Group`.2122The most common methods to override are :meth:`~click.Group.get_command` and23:meth:`~click.Group.list_commands`.2425The following example implements a basic plugin system that loads commands from26Python files in a folder. The command is lazily loaded to avoid slow startup.2728.. code-block:: python2930 import importlib.util31 import os32 import click3334 class PluginGroup(click.Group):35 def __init__(self, name=None, plugin_folder="commands", **kwargs):36 super().__init__(name=name, **kwargs)37 self.plugin_folder = plugin_folder3839 def list_commands(self, ctx):40 rv = []4142 for filename in os.listdir(self.plugin_folder):43 if filename.endswith(".py"):44 rv.append(filename[:-3])4546 rv.sort()47 return rv4849 def get_command(self, ctx, name):50 path = os.path.join(self.plugin_folder, f"{name}.py")51 spec = importlib.util.spec_from_file_location(name, path)52 module = importlib.util.module_from_spec(spec)53 spec.loader.exec_module(module)54 return module.cli5556 cli = PluginGroup(57 plugin_folder=os.path.join(os.path.dirname(__file__), "commands")58 )5960 if __name__ == "__main__":61 cli()6263Custom classes can also be used with decorators:6465.. code-block:: python6667 @click.group(68 cls=PluginGroup,69 plugin_folder=os.path.join(os.path.dirname(__file__), "commands")70 )71 def cli():72 pass7374.. _aliases:7576Command Aliases77---------------7879Many tools support aliases for commands. For example, you can configure80``git`` to accept ``git ci`` as alias for ``git commit``. Other tools also81support auto-discovery for aliases by automatically shortening them.8283It's possible to customize :class:`Group` to provide this functionality. As84explained in :ref:`custom-groups`, a group provides two methods:85:meth:`~Group.list_commands` and :meth:`~Group.get_command`. In this particular86case, you only need to override the latter as you generally don't want to87enumerate the aliases on the help page in order to avoid confusion.8889The following example implements a subclass of :class:`Group` that accepts a90prefix for a command. If there was a command called ``push``, it would accept91``pus`` as an alias (so long as it was unique):9293.. click:example::9495 class AliasedGroup(click.Group):96 def get_command(self, ctx, cmd_name):97 rv = super().get_command(ctx, cmd_name)9899 if rv is not None:100 return rv101102 matches = [103 x for x in self.list_commands(ctx)104 if x.startswith(cmd_name)105 ]106107 if not matches:108 return None109110 if len(matches) == 1:111 return click.Group.get_command(self, ctx, matches[0])112113 ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")114115 def resolve_command(self, ctx, args):116 # always return the full command name117 _, cmd, args = super().resolve_command(ctx, args)118 return cmd.name, cmd, args119120It can be used like this:121122.. click:example::123124 @click.group(cls=AliasedGroup)125 def cli():126 pass127128 @cli.command129 def push():130 pass131132 @cli.command133 def pop():134 pass135136See the `alias example`_ in Click's repository for another example.137138.. _alias example: https://github.com/pallets/click/tree/main/examples/aliases