switch extension from .rst to .md
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by denuoweb · committed by denuoweb · parent a31eb9b · Browse files · 2 files·+138 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+138 added−138 removed
- other:+138 added−138 removed
Provenance
- Commit
f734063- Tree
f4bf1c5- Author
denuoweb <jaron@rosenau.info>- Committer
denuoweb <jaron@rosenau.info>- Parent
a31eb9b
2 files changed+138 added−138 removed
added:docs/extending-click.md+138 added
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/aliasesdeleted: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