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
Provenance
- Commit
a2623d0- Tree
2afc4ef- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
6707116- Parent 2
2d1c49d
2 files changed+132 added−138 removed
added:docs/extending-click.md+132 added
1+# Extending Click2+3+```{currentmodule} click4+```5+6+In addition to common functionality that is implemented in the library itself, there are countless patterns that can be7+implemented by extending Click. This page should give some insight into what can be accomplished.8+9+```{contents}10+:depth: 211+:local: true12+```13+14+(custom-groups)=15+16+## Custom Groups17+18+You can customize the behavior of a group beyond the arguments it accepts by subclassing {class}`click.Group`.19+20+The most common methods to override are {meth}`~click.Group.get_command` and {meth}`~click.Group.list_commands`.21+22+The following example implements a basic plugin system that loads commands from Python files in a folder. The command is23+lazily loaded to avoid slow startup.24+25+```python26+import importlib.util27+import os28+import click29+30+class PluginGroup(click.Group):31+ def __init__(self, name=None, plugin_folder="commands", **kwargs):32+ super().__init__(name=name, **kwargs)33+ self.plugin_folder = plugin_folder34+35+ def list_commands(self, ctx):36+ rv = []37+38+ for filename in os.listdir(self.plugin_folder):39+ if filename.endswith(".py"):40+ rv.append(filename[:-3])41+42+ rv.sort()43+ return rv44+45+ 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.cli51+52+cli = PluginGroup(53+ plugin_folder=os.path.join(os.path.dirname(__file__), "commands")54+)55+56+if __name__ == "__main__":57+ cli()58+```59+60+Custom classes can also be used with decorators:61+62+```python63+@click.group(64+ cls=PluginGroup,65+ plugin_folder=os.path.join(os.path.dirname(__file__), "commands")66+)67+def cli():68+ pass69+```70+71+(aliases)=72+73+## Command Aliases74+75+Many 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.77+78+It's possible to customize {class}`Group` to provide this functionality. As explained in {ref}`custom-groups`, a group79+provides two methods: {meth}`~Group.list_commands` and {meth}`~Group.get_command`. In this particular case, you only80+need to override the latter as you generally don't want to enumerate the aliases on the help page in order to avoid81+confusion.82+83+The following example implements a subclass of {class}`Group` that accepts a prefix for a command. If there was a84+command called `push`, it would accept `pus` as an alias (so long as it was unique):85+86+```{eval-rst}87+.. click:example::88+89+ class AliasedGroup(click.Group):90+ def get_command(self, ctx, cmd_name):91+ rv = super().get_command(ctx, cmd_name)92+93+ if rv is not None:94+ return rv95+96+ matches = [97+ x for x in self.list_commands(ctx)98+ if x.startswith(cmd_name)99+ ]100+101+ if not matches:102+ return None103+104+ if len(matches) == 1:105+ return click.Group.get_command(self, ctx, matches[0])106+107+ ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")108+109+ 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+```114+115+It can be used like this:116+117+```python118+119+ @click.group(cls=AliasedGroup)120+ def cli():121+ pass122+123+ @cli.command124+ def push():125+ pass126+127+ @cli.command128+ def pop():129+ pass130+```131+132+See 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
1-Extending Click2-=================3-4-.. currentmodule:: click5-6-In addition to common functionality that is implemented in the library7-itself, there are countless patterns that can be implemented by extending8-Click. This page should give some insight into what can be accomplished.9-10-.. contents::11- :depth: 212- :local:13-14-.. _custom-groups:15-16-Custom Groups17--------------18-19-You can customize the behavior of a group beyond the arguments it accepts by20-subclassing :class:`click.Group`.21-22-The most common methods to override are :meth:`~click.Group.get_command` and23-:meth:`~click.Group.list_commands`.24-25-The following example implements a basic plugin system that loads commands from26-Python files in a folder. The command is lazily loaded to avoid slow startup.27-28-.. code-block:: python29-30- import importlib.util31- import os32- import click33-34- 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_folder38-39- def list_commands(self, ctx):40- rv = []41-42- for filename in os.listdir(self.plugin_folder):43- if filename.endswith(".py"):44- rv.append(filename[:-3])45-46- rv.sort()47- return rv48-49- 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.cli55-56- cli = PluginGroup(57- plugin_folder=os.path.join(os.path.dirname(__file__), "commands")58- )59-60- if __name__ == "__main__":61- cli()62-63-Custom classes can also be used with decorators:64-65-.. code-block:: python66-67- @click.group(68- cls=PluginGroup,69- plugin_folder=os.path.join(os.path.dirname(__file__), "commands")70- )71- def cli():72- pass73-74-.. _aliases:75-76-Command Aliases77----------------78-79-Many tools support aliases for commands. For example, you can configure80-``git`` to accept ``git ci`` as alias for ``git commit``. Other tools also81-support auto-discovery for aliases by automatically shortening them.82-83-It's possible to customize :class:`Group` to provide this functionality. As84-explained in :ref:`custom-groups`, a group provides two methods:85-:meth:`~Group.list_commands` and :meth:`~Group.get_command`. In this particular86-case, you only need to override the latter as you generally don't want to87-enumerate the aliases on the help page in order to avoid confusion.88-89-The following example implements a subclass of :class:`Group` that accepts a90-prefix for a command. If there was a command called ``push``, it would accept91-``pus`` as an alias (so long as it was unique):92-93-.. click:example::94-95- class AliasedGroup(click.Group):96- def get_command(self, ctx, cmd_name):97- rv = super().get_command(ctx, cmd_name)98-99- if rv is not None:100- return rv101-102- matches = [103- x for x in self.list_commands(ctx)104- if x.startswith(cmd_name)105- ]106-107- if not matches:108- return None109-110- if len(matches) == 1:111- return click.Group.get_command(self, ctx, matches[0])112-113- ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")114-115- 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, args119-120-It can be used like this:121-122-.. click:example::123-124- @click.group(cls=AliasedGroup)125- def cli():126- pass127-128- @cli.command129- def push():130- pass131-132- @cli.command133- def pop():134- pass135-136-See the `alias example`_ in Click's repository for another example.137-138-.. _alias example: https://github.com/pallets/click/tree/main/examples/aliases