convert from reST to MyST
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by denuoweb · committed by denuoweb · parent f734063 · Browse files · 1 file·+65 added−71 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+65 added−71 removed
- other:+65 added−71 removed
Provenance
- Commit
2d1c49d- Tree
e2dbd3f- Author
denuoweb <jaron@rosenau.info>- Committer
denuoweb <jaron@rosenau.info>- Parent
f734063
1 file changed+65 added−71 removed
modified:docs/extending-click.md+65 added-71 removed
1212434567867810111291011121314141516171617192018192223202125262223242825262728293031323031323334343536373536373940383940414243444243444647454647484950514950515253545253545556575856575859606162606165626364656667686970676869707172717274737476777576777980817879808182838485868783848589909192868788899018 unmodified lines1091101111121131141151161221171181191201214 unmodified lines126127128129130131136137138132Extending Click=================# Extending Click
.. currentmodule:: click```{currentmodule} click```
In addition to common functionality that is implemented in the libraryitself, there are countless patterns that can be implemented by extendingClick. This page should give some insight into what can be accomplished.In addition to common functionality that is implemented in the library itself, there are countless patterns that can beimplemented by extending Click. This page should give some insight into what can be accomplished.
.. contents:: :depth: 2 :local:```{contents}:depth: 2:local: true```
.. _custom-groups:(custom-groups)=
Custom Groups-------------## Custom Groups
You can customize the behavior of a group beyond the arguments it accepts bysubclassing :class:`click.Group`.You can customize the behavior of a group beyond the arguments it accepts by subclassing {class}`click.Group`.
The most common methods to override are :meth:`~click.Group.get_command` and:meth:`~click.Group.list_commands`.The most common methods to override are {meth}`~click.Group.get_command` and {meth}`~click.Group.list_commands`.
The following example implements a basic plugin system that loads commands fromPython files in a folder. The command is lazily loaded to avoid slow startup.The following example implements a basic plugin system that loads commands from Python files in a folder. The command islazily loaded to avoid slow startup.
.. code-block:: python```pythonimport importlib.utilimport osimport click
import importlib.util import os import clickclass PluginGroup(click.Group): def __init__(self, name=None, plugin_folder="commands", **kwargs): super().__init__(name=name, **kwargs) self.plugin_folder = plugin_folder
class PluginGroup(click.Group): def __init__(self, name=None, plugin_folder="commands", **kwargs): super().__init__(name=name, **kwargs) self.plugin_folder = plugin_folder def list_commands(self, ctx): rv = []
def list_commands(self, ctx): rv = [] for filename in os.listdir(self.plugin_folder): if filename.endswith(".py"): rv.append(filename[:-3])
for filename in os.listdir(self.plugin_folder): if filename.endswith(".py"): rv.append(filename[:-3]) rv.sort() return rv
rv.sort() return rv def get_command(self, ctx, name): path = os.path.join(self.plugin_folder, f"{name}.py") spec = importlib.util.spec_from_file_location(name, path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module.cli
def get_command(self, ctx, name): path = os.path.join(self.plugin_folder, f"{name}.py") spec = importlib.util.spec_from_file_location(name, path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module.clicli = PluginGroup( plugin_folder=os.path.join(os.path.dirname(__file__), "commands"))
cli = PluginGroup( plugin_folder=os.path.join(os.path.dirname(__file__), "commands") )if __name__ == "__main__": cli()```
if __name__ == "__main__": cli()
Custom classes can also be used with decorators:
.. code-block:: python```python@click.group( cls=PluginGroup, plugin_folder=os.path.join(os.path.dirname(__file__), "commands"))def cli(): pass```
@click.group( cls=PluginGroup, plugin_folder=os.path.join(os.path.dirname(__file__), "commands") ) def cli(): pass(aliases)=
.. _aliases:## Command Aliases
Command Aliases---------------Many tools support aliases for commands. For example, you can configure `git` to accept `git ci` as alias for`git commit`. Other tools also support auto-discovery for aliases by automatically shortening them.
Many tools support aliases for commands. For example, you can configure``git`` to accept ``git ci`` as alias for ``git commit``. Other tools alsosupport auto-discovery for aliases by automatically shortening them.It's possible to customize {class}`Group` to provide this functionality. As explained in {ref}`custom-groups`, a groupprovides two methods: {meth}`~Group.list_commands` and {meth}`~Group.get_command`. In this particular case, you onlyneed to override the latter as you generally don't want to enumerate the aliases on the help page in order to avoidconfusion.
It's possible to customize :class:`Group` to provide this functionality. Asexplained in :ref:`custom-groups`, a group provides two methods::meth:`~Group.list_commands` and :meth:`~Group.get_command`. In this particularcase, you only need to override the latter as you generally don't want toenumerate the aliases on the help page in order to avoid confusion.The following example implements a subclass of {class}`Group` that accepts a prefix for a command. If there was acommand called `push`, it would accept `pus` as an alias (so long as it was unique):
The following example implements a subclass of :class:`Group` that accepts aprefix for a command. If there was a command called ``push``, it would accept``pus`` as an alias (so long as it was unique):
```{eval-rst}.. click:example::
class AliasedGroup(click.Group): def get_command(self, ctx, cmd_name):18 unmodified lines def resolve_command(self, ctx, args): # always return the full command name _, cmd, args = super().resolve_command(ctx, args) return cmd.name, cmd, args```
It can be used like this:
.. click:example::```python
@click.group(cls=AliasedGroup) def cli(): pass4 unmodified lines
@cli.command def pop(): pass```
See the `alias example`_ in Click's repository for another example.
.. _alias example: https://github.com/pallets/click/tree/main/examples/aliasesSee the [alias example](https://github.com/pallets/click/tree/main/examples/aliases) in Click's repository for another example.