Rewrite Commands and Groups docs. (#2838)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Rename commands and groups -> Advanced Groups and Context Add basic commands, groups, context doc collects up and add sections for basic command and groups stuff such as renaming, deprecating Add sections for group separation, arbitrary nesting, and lazily attaching Moved custom groups section to Advanced patterns Remove sections from Advanced Groups and Context to rewrite them better in basic commands, groups, context doc passing parameters group invocation without command
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+290 added−117 removed
- other:+290 added−117 removed
Provenance
- Commit
0bf333e- Tree
abb266f- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
854cfb1- Parent 2
9b640af
5 files changed+290 added−117 removed
modified:docs/advanced.rst+63 added
5 unmodified lines6 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: 112+ :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 ---------------487 unmodified linesadded:docs/commands-and-groups.rst+218 added
1+Basic Commands, Groups, Context2+================================3+4+.. currentmodule:: click5+6+Commands and Groups are the building blocks for Click applications. :class:`Command` wraps a function to make it into a cli command. :class:`Group` wraps Commands and Groups to make them into applications. :class:`Context` is how groups and commands communicate.7+8+.. contents::9+ :depth: 110+ :local:11+12+Basic Command Example13+----------------------14+A simple command decorator takes no arguments.15+16+.. click:example::17+ @click.command()18+ @click.option('--count', default=1)19+ def hello(count):20+ for x in range(count):21+ click.echo("Hello!")22+23+.. click:run::24+ invoke(hello, args=['--count', '2',])25+26+Renaming Commands27+------------------28+By default the command is the function name with underscores replaced by dashes. To change this pass the desired name into the first positional argument.29+30+.. click:example::31+ @click.command('say-hello')32+ @click.option('--count', default=1)33+ def hello(count):34+ for x in range(count):35+ click.echo("Hello!")36+37+.. click:run::38+ invoke(hello, args=['--count', '2',])39+40+Deprecating Commands41+---------------------42+To mark a command as deprecated pass in ``deprecated=True``43+44+.. click:example::45+ @click.command('say-hello', deprecated=True)46+ @click.option('--count', default=1)47+ def hello(count):48+ for x in range(count):49+ click.echo("Hello!")50+51+.. click:run::52+ invoke(hello, args=['--count', '2',])53+54+Basic Group Example55+---------------------56+A group wraps one or more commands. After being wrapped, the commands are nested under that group. You can see that on the help pages and in the execution. By default, invoking the group with no command shows the help page.57+58+.. click:example::59+ @click.group()60+ def greeting():61+ click.echo('Starting greeting ...')62+63+ @greeting.command('say-hello')64+ @click.option('--count', default=1)65+ def hello(count):66+ for x in range(count):67+ click.echo("Hello!")68+69+At the top level:70+71+.. click:run::72+73+ invoke(greeting)74+75+At the command level:76+77+.. click:run::78+79+ invoke(greeting, args=['say-hello'])80+ invoke(greeting, args=['say-hello', '--help'])81+82+As you can see from the above example, the function wrapped by the group decorator executes unless it is interrupted (for example by calling the help).83+84+Renaming Groups85+-----------------86+To have a name other than the decorated function name as the group name, pass it in as the first positional argument.87+88+.. click:example::89+ @click.group('greet-someone')90+ def greeting():91+ click.echo('Starting greeting ...')92+93+ @greeting.command('say-hello')94+ @click.option('--count', default=1)95+ def hello(count):96+ for x in range(count):97+ click.echo("Hello!")98+99+.. click:run::100+101+ invoke(greeting, args=['say-hello'])102+103+Group Invocation Without Command104+--------------------------------105+106+By default, if a group is passed without a command, the group is not invoked and a command automatically passes ``--help``. To change this, pass ``invoke_without_command=True`` to the group. The context object also includes information about whether or not the group invocation would go to a command nested under it.107+108+.. click:example::109+110+ @click.group(invoke_without_command=True)111+ @click.pass_context112+ def cli(ctx):113+ if ctx.invoked_subcommand is None:114+ click.echo('I was invoked without subcommand')115+ else:116+ click.echo(f"I am about to invoke {ctx.invoked_subcommand}")117+118+ @cli.command()119+ def sync():120+ click.echo('The subcommand')121+122+.. click:run::123+124+ invoke(cli, prog_name='tool', args=[])125+ invoke(cli, prog_name='tool', args=['sync'])126+127+128+129+Group Separation130+--------------------------131+Command :ref:`parameters` attached to a command belong only to that command.132+133+.. click:example::134+ @click.group()135+ def greeting():136+ pass137+138+ @greeting.command()139+ @click.option('--count', default=1)140+ def hello(count):141+ for x in range(count):142+ click.echo("Hello!")143+144+ @greeting.command()145+ @click.option('--count', default=1)146+ def goodbye(count):147+ for x in range(count):148+ click.echo("Goodbye!")149+150+.. click:run::151+152+ invoke(greeting, args=['hello', '--count', '2'])153+ invoke(greeting, args=['goodbye', '--count', '2'])154+ invoke(greeting)155+156+Additionally parameters for a given group belong only to that group and not to the commands under it. What this means is that options and arguments for a specific command have to be specified *after* the command name itself, but *before* any other command names.157+158+This behavior is observable with the ``--help`` option. Suppose we have a group called ``tool`` containing a command called ``sub``.159+160+- ``tool --help`` returns the help for the whole program (listing subcommands).161+- ``tool sub --help`` returns the help for the ``sub`` subcommand.162+- But ``tool --help sub`` treats ``--help`` as an argument for the main program. Click then invokes the callback for ``--help``, which prints the help and aborts the program before click can process the subcommand.163+164+Arbitrary Nesting165+------------------166+:class:`Commands <Command>` are attached to a :class:`Group`. Multiple groups can be attached to another group. Groups containing multiple groups can be attached to a group, and so on. To invoke a command nested under multiple groups, all the groups under which it is nested must be invoked.167+168+.. click:example::169+170+ @click.group()171+ def cli():172+ pass173+174+ # Not @click so that the group is registered now.175+ @cli.group()176+ def session():177+ click.echo('Starting session')178+179+ @session.command()180+ def initdb():181+ click.echo('Initialized the database')182+183+ @session.command()184+ def dropdb():185+ click.echo('Dropped the database')186+187+.. click:run::188+189+ invoke(cli, args=['session', 'initdb'])190+191+Lazily Attaching Commands192+--------------------------193+Most examples so far have attached the commands to a group immediately, but commands may be registered later. This could be used to split commands into multiple Python modules. Regardless of how they are attached, the commands are invoked identically.194+195+.. click:example::196+197+ @click.group()198+ def cli():199+ pass200+201+ @cli.command()202+ def initdb():203+ click.echo('Initialized the database')204+205+ @click.command()206+ def dropdb():207+ click.echo('Dropped the database')208+209+ cli.add_command(dropdb)210+211+.. click:run::212+213+ invoke(cli, args=['initdb'])214+ invoke(cli, args=['dropdb'])215+216+Context Object217+-------------------218+The :class:`Context` object is how commands and groups communicate.modified:docs/commands.rst+6 added-117 removed
1-Commands and Groups2-===================1+Advanced Groups and Context2+=============================3 4 .. currentmodule:: click5 6-The structure of a Click application is defined with :class:`Command`, which7-defines an individual named command, and :class:`Group`, which defines a nested8-collection of commands (or more groups) under a name.6+In addition to the capabilities covered in the previous section, Groups have more advanced capabilities that leverage the Context.7 8+.. contents::9+ :depth: 110+ :local:11 12 Callback Invocation13 -------------------14 24 unmodified lines39 invoke(cli, prog_name='tool.py')40 println()41 invoke(cli, prog_name='tool.py', args=['--debug', 'sync'])42 42-Passing Parameters43-------------------44-45-Click strictly separates parameters between commands and subcommands. What this46-means is that options and arguments for a specific command have to be specified47-*after* the command name itself, but *before* any other command names.48-49-This behavior is already observable with the predefined ``--help`` option.50-Suppose we have a program called ``tool.py``, containing a subcommand called51-``sub``.52-53-- ``tool.py --help`` will return the help for the whole program (listing54- subcommands).55-56-- ``tool.py sub --help`` will return the help for the ``sub`` subcommand.57-58-- But ``tool.py --help sub`` will treat ``--help`` as an argument for the main59- program. Click then invokes the callback for ``--help``, which prints the60- help and aborts the program before click can process the subcommand.61-43 Nested Handling and Contexts44 ----------------------------45 46 As you can see from the earlier example, the basic command group accepts a77 unmodified lines124 125 This is a very powerful concept that can be used to build very complex126 nested applications; see :ref:`complex-guide` for more information.127 147-148-Group Invocation Without Command149---------------------------------150-151-By default, a group is not invoked unless a subcommand is passed. In fact, not152-providing a command automatically passes ``--help`` by default. This behavior153-can be changed by passing ``invoke_without_command=True`` to a group. In that154-case, the callback is always invoked instead of showing the help page. The155-context object also includes information about whether or not the invocation156-would go to a subcommand.157-158-.. click:example::159-160- @click.group(invoke_without_command=True)161- @click.pass_context162- def cli(ctx):163- if ctx.invoked_subcommand is None:164- click.echo('I was invoked without subcommand')165- else:166- click.echo(f"I am about to invoke {ctx.invoked_subcommand}")167-168- @cli.command()169- def sync():170- click.echo('The subcommand')171-172-.. click:run::173-174- invoke(cli, prog_name='tool', args=[])175- invoke(cli, prog_name='tool', args=['sync'])176-177-178-.. _custom-groups:179-180-Custom Groups181--------------182-183-You can customize the behavior of a group beyond the arguments it accepts by184-subclassing :class:`click.Group`.185-186-The most common methods to override are :meth:`~click.Group.get_command` and187-:meth:`~click.Group.list_commands`.188-189-The following example implements a basic plugin system that loads commands from190-Python files in a folder. The command is lazily loaded to avoid slow startup.191-192-.. code-block:: python193-194- import importlib.util195- import os196- import click197-198- class PluginGroup(click.Group):199- def __init__(self, name=None, plugin_folder="commands", **kwargs):200- super().__init__(name=name, **kwargs)201- self.plugin_folder = plugin_folder202-203- def list_commands(self, ctx):204- rv = []205-206- for filename in os.listdir(self.plugin_folder):207- if filename.endswith(".py"):208- rv.append(filename[:-3])209-210- rv.sort()211- return rv212-213- def get_command(self, ctx, name):214- path = os.path.join(self.plugin_folder, f"{name}.py")215- spec = importlib.util.spec_from_file_location(name, path)216- module = importlib.util.module_from_spec(spec)217- spec.loader.exec_module(module)218- return module.cli219-220- cli = PluginGroup(221- plugin_folder=os.path.join(os.path.dirname(__file__), "commands")222- )223-224- if __name__ == "__main__":225- cli()226-227-Custom classes can also be used with decorators:228-229-.. code-block:: python230-231- @click.group(232- cls=PluginGroup,233- plugin_folder=os.path.join(os.path.dirname(__file__), "commands")234- )235- def cli():236- pass237-238-128 .. _command-chaining:129 130 Command Chaining131 ----------------297 unmodified linesmodified:docs/index.rst+1 added
74 unmodified lines75 parameter-types76 options77 option-decorators78 arguments79+ commands-and-groups80 commands81 documentation82 prompts83 complex28 unmodified linesmodified:docs/parameters.rst+2 added
1+.. _parameters:2+3 Parameters4 ==========5 6 .. currentmodule:: click52 unmodified lines