Fill in a lot of missing command and group docs.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Edward G · committed by Edward G · parent 8a47580 · Browse files · 5 files·+292 added−117 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+292 added−117 removed
- other:+292 added−117 removed
Provenance
- Commit
e2f2d84- Tree
88bec35- Author
Edward G <edward.g2013@gmail.com>- Committer
Edward G <edward.g2013@gmail.com>- Parent
8a47580
5 files changed+292 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+220 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 command(s). 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, a group is not invoked unless a subcommand is passed. In fact, not107+providing a command automatically passes ``--help`` by default. This behavior108+can be changed by passing ``invoke_without_command=True`` to a group. In that109+case, the callback is always invoked instead of showing the help page. The110+context object also includes information about whether or not the invocation111+would go to a subcommand.112+113+.. click:example::114+115+ @click.group(invoke_without_command=True)116+ @click.pass_context117+ def cli(ctx):118+ if ctx.invoked_subcommand is None:119+ click.echo('I was invoked without subcommand')120+ else:121+ click.echo(f"I am about to invoke {ctx.invoked_subcommand}")122+123+ @cli.command()124+ def sync():125+ click.echo('The subcommand')126+127+.. click:run::128+129+ invoke(cli, prog_name='tool', args=[])130+ invoke(cli, prog_name='tool', args=['sync'])131+132+133+134+Group Separation135+--------------------------136+Within a group, command :ref:`parameters` attached to a command belong only to that command.137+138+.. click:example::139+ @click.group()140+ def greeting():141+ pass142+143+ @greeting.command()144+ @click.option('--count', default=1)145+ def hello(count):146+ for x in range(count):147+ click.echo("Hello!")148+149+ @greeting.command()150+ @click.option('--count', default=1)151+ def goodbye(count):152+ for x in range(count):153+ click.echo("Goodbye!")154+155+.. click:run::156+157+ invoke(greeting, args=['hello', '--count', '2'])158+ invoke(greeting, args=['goodbye', '--count', '2'])159+ invoke(greeting)160+161+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.162+163+This behavior is observable with the ``--help`` option. Suppose we have a group called ``tool`` containing a command called ``sub``.164+165+- ``tool --help`` returns the help for the whole program (listing subcommands).166+- ``tool sub --help`` returns the help for the ``sub`` subcommand.167+- But ``tool.py --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.168+169+Arbitrary Nesting170+------------------171+Commands are attached to a group. Multiple groups can be attached to another group. Groups containing multiple groups can be attached to a group, and so on.172+To invoke a command nest under multiple groups, all the above groups must added.173+174+.. click:example::175+176+ @click.group()177+ def cli():178+ pass179+180+ # Not @click so that the group is registered now.181+ @cli.group()182+ def session():183+ click.echo('Starting session')184+185+ @session.command()186+ def initdb():187+ click.echo('Initialized the database')188+189+ @session.command()190+ def dropdb():191+ click.echo('Dropped the database')192+193+.. click:run::194+195+ invoke(cli, args=['session', 'initdb'])196+197+Lazily Attaching Commands198+--------------------------199+Most examples so far have attached the the commands and group immediately, but commands may be registered later. This could be used to split command into multiple Python modules.200+201+.. click:example::202+203+ @click.group()204+ def cli():205+ pass206+207+ @click.command()208+ def initdb():209+ click.echo('Initialized the database')210+211+ @click.command()212+ def dropdb():213+ click.echo('Dropped the database')214+215+ cli.add_command(initdb)216+ cli.add_command(dropdb)217+218+Context Object219+-------------------220+The :class:`Context` object ...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
72 unmodified lines73 setuptools74 parameters75 arguments76 options77+ commands-and-groups78 commands79 documentation80 prompts81 complex28 unmodified linesmodified:docs/parameters.rst+2 added
1+.. _parameters:2+3 Parameters4 ==========5 6 .. currentmodule:: click133 unmodified lines