Make distinct sections for advanced patterns and extending click. (#2925)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
sections added: - extending click - click concepts sections moved: - custom groups (advanced patterns -> extending click) - command aliases (advanced patterns -> extending click) - callback evaluation order (advanced patterns -> click concepts) - global context access (advanced patterns -> basic commands, groups and context) - detecting source parameters (advanced patterns -> basic commands, groups and context)
authored by Rowlando13 · committed by GitHub · parents 937c68d, ab5cd75 · Browse files · 6 files·+298 added−269 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+298 added−269 removed
- other:+298 added−269 removed
Provenance
- Commit
2aecb2d- Tree
1a830fc- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
937c68d- Parent 2
ab5cd75
6 files changed+298 added−269 removed
modified:docs/advanced.rst+2 added-257 removed
1 unmodified line2 =================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.6+In addition to common functionality, Click offers some advanced features.7 8 .. contents::11- :depth: 29+ :depth: 110 :local:11 12 Callbacks and Eager Options13 ---------------------------93 unmodified lines107 invoke(roll, args=["--rolls=2d12"])108 println()109 invoke(roll, input=["42", "2d12"])110 113-.. _custom-groups:114-115-Custom Groups116--------------117-118-You can customize the behavior of a group beyond the arguments it accepts by119-subclassing :class:`click.Group`.120-121-The most common methods to override are :meth:`~click.Group.get_command` and122-:meth:`~click.Group.list_commands`.123-124-The following example implements a basic plugin system that loads commands from125-Python files in a folder. The command is lazily loaded to avoid slow startup.126-127-.. code-block:: python128-129- import importlib.util130- import os131- import click132-133- class PluginGroup(click.Group):134- def __init__(self, name=None, plugin_folder="commands", **kwargs):135- super().__init__(name=name, **kwargs)136- self.plugin_folder = plugin_folder137-138- def list_commands(self, ctx):139- rv = []140-141- for filename in os.listdir(self.plugin_folder):142- if filename.endswith(".py"):143- rv.append(filename[:-3])144-145- rv.sort()146- return rv147-148- def get_command(self, ctx, name):149- path = os.path.join(self.plugin_folder, f"{name}.py")150- spec = importlib.util.spec_from_file_location(name, path)151- module = importlib.util.module_from_spec(spec)152- spec.loader.exec_module(module)153- return module.cli154-155- cli = PluginGroup(156- plugin_folder=os.path.join(os.path.dirname(__file__), "commands")157- )158-159- if __name__ == "__main__":160- cli()161-162-Custom classes can also be used with decorators:163-164-.. code-block:: python165-166- @click.group(167- cls=PluginGroup,168- plugin_folder=os.path.join(os.path.dirname(__file__), "commands")169- )170- def cli():171- pass172-173-.. _aliases:174-175-Command Aliases176----------------177-178-Many tools support aliases for commands. For example, you can configure179-``git`` to accept ``git ci`` as alias for ``git commit``. Other tools also180-support auto-discovery for aliases by automatically shortening them.181-182-It's possible to customize :class:`Group` to provide this functionality. As183-explained in :ref:`custom-groups`, a group provides two methods:184-:meth:`~Group.list_commands` and :meth:`~Group.get_command`. In this particular185-case, you only need to override the latter as you generally don't want to186-enumerate the aliases on the help page in order to avoid confusion.187-188-The following example implements a subclass of :class:`Group` that accepts a189-prefix for a command. If there was a command called ``push``, it would accept190-``pus`` as an alias (so long as it was unique):191-192-.. click:example::193-194- class AliasedGroup(click.Group):195- def get_command(self, ctx, cmd_name):196- rv = super().get_command(ctx, cmd_name)197-198- if rv is not None:199- return rv200-201- matches = [202- x for x in self.list_commands(ctx)203- if x.startswith(cmd_name)204- ]205-206- if not matches:207- return None208-209- if len(matches) == 1:210- return click.Group.get_command(self, ctx, matches[0])211-212- ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")213-214- def resolve_command(self, ctx, args):215- # always return the full command name216- _, cmd, args = super().resolve_command(ctx, args)217- return cmd.name, cmd, args218-219-It can be used like this:220-221-.. click:example::222-223- @click.group(cls=AliasedGroup)224- def cli():225- pass226-227- @cli.command228- def push():229- pass230-231- @cli.command232- def pop():233- pass234-235-See the `alias example`_ in Click's repository for another example.236-237-.. _alias example: https://github.com/pallets/click/tree/main/examples/aliases238-239-111 Parameter Modifications112 -----------------------113 114 Parameters (options and arguments) are forwarded to the command callbacks115 unmodified lines230 231 invoke(cli, prog_name='cli', args=['dist'])232 233 363-.. _callback-evaluation-order:234 365-Callback Evaluation Order366--------------------------367-368-Click works a bit differently than some other command line parsers in that369-it attempts to reconcile the order of arguments as defined by the370-programmer with the order of arguments as defined by the user before371-invoking any callbacks.372-373-This is an important concept to understand when porting complex374-patterns to Click from optparse or other systems. A parameter375-callback invocation in optparse happens as part of the parsing step,376-whereas a callback invocation in Click happens after the parsing.377-378-The main difference is that in optparse, callbacks are invoked with the raw379-value as it happens, whereas a callback in Click is invoked after the380-value has been fully converted.381-382-Generally, the order of invocation is driven by the order in which the user383-provides the arguments to the script; if there is an option called ``--foo``384-and an option called ``--bar`` and the user calls it as ``--bar385---foo``, then the callback for ``bar`` will fire before the one for ``foo``.386-387-There are three exceptions to this rule which are important to know:388-389-Eagerness:390- An option can be set to be "eager". All eager parameters are391- evaluated before all non-eager parameters, but again in the order as392- they were provided on the command line by the user.393-394- This is important for parameters that execute and exit like ``--help``395- and ``--version``. Both are eager parameters, but whatever parameter396- comes first on the command line will win and exit the program.397-398-Repeated parameters:399- If an option or argument is split up on the command line into multiple400- places because it is repeated -- for instance, ``--exclude foo --include401- baz --exclude bar`` -- the callback will fire based on the position of402- the first option. In this case, the callback will fire for403- ``exclude`` and it will be passed both options (``foo`` and404- ``bar``), then the callback for ``include`` will fire with ``baz``405- only.406-407- Note that even if a parameter does not allow multiple versions, Click408- will still accept the position of the first, but it will ignore every409- value except the last. The reason for this is to allow composability410- through shell aliases that set defaults.411-412-Missing parameters:413- If a parameter is not defined on the command line, the callback will414- still fire. This is different from how it works in optparse where415- undefined values do not fire the callback. Missing parameters fire416- their callbacks at the very end which makes it possible for them to417- default to values from a parameter that came before.418-419-Most of the time you do not need to be concerned about any of this,420-but it is important to know how it works for some advanced cases.421-235 .. _forwarding-unknown-options:236 237 Forwarding Unknown Options238 --------------------------88 unmodified lines327 everything below a subcommand be forwarded to another application than to328 handle some arguments yourself.329 330 518-Global Context Access519----------------------520-521-.. versionadded:: 5.0522-523-Starting with Click 5.0 it is possible to access the current context from524-anywhere within the same thread through the use of the525-:func:`get_current_context` function which returns it. This is primarily526-useful for accessing the context bound object as well as some flags that527-are stored on it to customize the runtime behavior. For instance the528-:func:`echo` function does this to infer the default value of the `color`529-flag.530-531-Example usage::532-533- def get_current_command_name():534- return click.get_current_context().info_name535-536-It should be noted that this only works within the current thread. If you537-spawn additional threads then those threads will not have the ability to538-refer to the current context. If you want to give another thread the539-ability to refer to this context you need to use the context within the540-thread as a context manager::541-542- def spawn_thread(ctx, func):543- def wrapper():544- with ctx:545- func()546- t = threading.Thread(target=wrapper)547- t.start()548- return t549-550-Now the thread function can access the context like the main thread would551-do. However if you do use this for threading you need to be very careful552-as the vast majority of the context is not thread safe! You are only553-allowed to read from the context, but not to perform any modifications on554-it.555-556-557-Detecting the Source of a Parameter558------------------------------------559-560-In some situations it's helpful to understand whether or not an option561-or parameter came from the command line, the environment, the default562-value, or :attr:`Context.default_map`. The563-:meth:`Context.get_parameter_source` method can be used to find this564-out. It will return a member of the :class:`~click.core.ParameterSource`565-enum.566-567-.. click:example::568-569- @click.command()570- @click.argument('port', nargs=1, default=8080, envvar="PORT")571- @click.pass_context572- def cli(ctx, port):573- source = ctx.get_parameter_source("port")574- click.echo(f"Port came from {source.name}")575-576-.. click:run::577-578- invoke(cli, prog_name='cli', args=['8080'])579- println()580- invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"})581- println()582- invoke(cli, prog_name='cli', args=[])583- println()584-585-331 Managing Resources332 ------------------333 334 It can be useful to open a resource in a group, to be made available to74 unmodified linesadded:docs/click-concepts.rst+67 added
1+Click Concepts2+================3+4+This section covers concepts about Click's design.5+6+.. contents::7+ :depth: 18+ :local:9+10+.. _callback-evaluation-order:11+12+Callback Evaluation Order13+-------------------------14+15+Click works a bit differently than some other command line parsers in that16+it attempts to reconcile the order of arguments as defined by the17+programmer with the order of arguments as defined by the user before18+invoking any callbacks.19+20+This is an important concept to understand when porting complex21+patterns to Click from optparse or other systems. A parameter22+callback invocation in optparse happens as part of the parsing step,23+whereas a callback invocation in Click happens after the parsing.24+25+The main difference is that in optparse, callbacks are invoked with the raw26+value as it happens, whereas a callback in Click is invoked after the27+value has been fully converted.28+29+Generally, the order of invocation is driven by the order in which the user30+provides the arguments to the script; if there is an option called ``--foo``31+and an option called ``--bar`` and the user calls it as ``--bar32+--foo``, then the callback for ``bar`` will fire before the one for ``foo``.33+34+There are three exceptions to this rule which are important to know:35+36+Eagerness:37+ An option can be set to be "eager". All eager parameters are38+ evaluated before all non-eager parameters, but again in the order as39+ they were provided on the command line by the user.40+41+ This is important for parameters that execute and exit like ``--help``42+ and ``--version``. Both are eager parameters, but whatever parameter43+ comes first on the command line will win and exit the program.44+45+Repeated parameters:46+ If an option or argument is split up on the command line into multiple47+ places because it is repeated -- for instance, ``--exclude foo --include48+ baz --exclude bar`` -- the callback will fire based on the position of49+ the first option. In this case, the callback will fire for50+ ``exclude`` and it will be passed both options (``foo`` and51+ ``bar``), then the callback for ``include`` will fire with ``baz``52+ only.53+54+ Note that even if a parameter does not allow multiple versions, Click55+ will still accept the position of the first, but it will ignore every56+ value except the last. The reason for this is to allow composability57+ through shell aliases that set defaults.58+59+Missing parameters:60+ If a parameter is not defined on the command line, the callback will61+ still fire. This is different from how it works in optparse where62+ undefined values do not fire the callback. Missing parameters fire63+ their callbacks at the very end which makes it possible for them to64+ default to values from a parameter that came before.65+66+Most of the time you do not need to be concerned about any of this,67+but it is important to know how it works for some advanced cases.modified:docs/commands-and-groups.rst+84 added-11 removed
4 unmodified lines5 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: 19+ :depth: 210 :local:11 12+Commands13+--------------------14+15 Basic Command Example13-----------------------16+^^^^^^^^^^^^^^^^^^^^^^^17 A simple command decorator takes no arguments.18 19 .. click:example::20 @click.command()5 unmodified lines26 .. click:run::27 invoke(hello, args=['--count', '2',])28 29 Renaming Commands27-------------------30+^^^^^^^^^^^^^^^^^^^31 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.32 33 .. click:example::34 @click.command('say-hello')5 unmodified lines40 .. click:run::41 invoke(hello, args=['--count', '2',])42 43 Deprecating Commands41----------------------44+^^^^^^^^^^^^^^^^^^^^^^45 To mark a command as deprecated pass in ``deprecated=True``46 47 .. click:example::48 @click.command('say-hello', deprecated=True)4 unmodified lines53 54 .. click:run::55 invoke(hello, args=['--count', '2',])56 57+Groups58+------------59+60 Basic Group Example55----------------------61+^^^^^^^^^^^^^^^^^^^^^62 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.63 64 .. click:example::65 @click.group()21 unmodified lines87 88 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).89 90 Renaming Groups85------------------91+^^^^^^^^^^^^^^^^^92 To have a name other than the decorated function name as the group name, pass it in as the first positional argument.93 94 .. click:example::95 @click.group('greet-someone')10 unmodified lines106 107 invoke(greeting, args=['say-hello'])108 109 Group Invocation Without Command104---------------------------------110+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^111 112 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.113 114 .. click:example::17 unmodified lines132 133 134 135 Group Separation130---------------------------136+^^^^^^^^^^^^^^^^^^^137 Command :ref:`parameters` attached to a command belong only to that command.138 139 .. click:example::140 @click.group()26 unmodified lines167 - ``tool sub --help`` returns the help for the ``sub`` subcommand.168 - 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.169 170 Arbitrary Nesting165-------------------171+^^^^^^^^^^^^^^^^^^^172 :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.173 174 .. click:example::175 18 unmodified lines194 195 invoke(cli, args=['session', 'initdb'])196 197 Lazily Attaching Commands192---------------------------198+^^^^^^^^^^^^^^^^^^^^^^^^^^^199 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.200 201 .. click:example::202 20 unmodified lines223 -------------------224 The :class:`Context` object is how commands and groups communicate.225 226 Auto Envvar Prefix221---------------------227+^^^^^^^^^^^^^^^^^^^^228 Automatically built environment variables are supported for options only. To enable this feature, the ``auto_envvar_prefix`` parameter needs to be passed to the script that is invoked. Each command and parameter is then added as an uppercase underscore-separated variable. If you have a subcommand229 called ``run`` taking an option called ``reload`` and the prefix is ``WEB``, then the variable is ``WEB_RUN_RELOAD``.230 231 Example usage:40 unmodified lines272 273 invoke(cli, args=['greet',],274 env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},275 auto_envvar_prefix='GREETER')276+277+Global Context Access278+^^^^^^^^^^^^^^^^^^^^^^279+280+.. versionadded:: 5.0281+282+Starting with Click 5.0 it is possible to access the current context from283+anywhere within the same thread through the use of the284+:func:`get_current_context` function which returns it. This is primarily285+useful for accessing the context bound object as well as some flags that286+are stored on it to customize the runtime behavior. For instance the287+:func:`echo` function does this to infer the default value of the `color`288+flag.289+290+Example usage::291+292+ def get_current_command_name():293+ return click.get_current_context().info_name294+295+It should be noted that this only works within the current thread. If you296+spawn additional threads then those threads will not have the ability to297+refer to the current context. If you want to give another thread the298+ability to refer to this context you need to use the context within the299+thread as a context manager::300+301+ def spawn_thread(ctx, func):302+ def wrapper():303+ with ctx:304+ func()305+ t = threading.Thread(target=wrapper)306+ t.start()307+ return t308+309+Now the thread function can access the context like the main thread would310+do. However if you do use this for threading you need to be very careful311+as the vast majority of the context is not thread safe! You are only312+allowed to read from the context, but not to perform any modifications on313+it.314+315+316+Detecting the Source of a Parameter317+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^318+319+In some situations it's helpful to understand whether or not an option320+or parameter came from the command line, the environment, the default321+value, or :attr:`Context.default_map`. The322+:meth:`Context.get_parameter_source` method can be used to find this323+out. It will return a member of the :class:`~click.core.ParameterSource`324+enum.325+326+.. click:example::327+328+ @click.command()329+ @click.argument('port', nargs=1, default=8080, envvar="PORT")330+ @click.pass_context331+ def cli(ctx, port):332+ source = ctx.get_parameter_source("port")333+ click.echo(f"Port came from {source.name}")334+335+.. click:run::336+337+ invoke(cli, prog_name='cli', args=['8080'])338+ println()339+ invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"})340+ println()341+ invoke(cli, prog_name='cli', args=[])342+ println()modified:docs/complex.rst+4 added
14 unmodified lines15 In a theoretical world of two separate Click command line utilities, they16 could solve this problem by nesting one inside the other. For instance, the17 web framework could also load the commands for the message queue framework.18 19+.. contents::20+ :depth: 121+ :local:22+23 Basic Concepts24 --------------25 26 To understand how this works, you need to understand two concepts: contexts367 unmodified linesadded:docs/extending-click.rst+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/aliasesmodified:docs/index.rst+3 added-1 removed
80 unmodified lines81 .. toctree::82 :maxdepth: 183 84 why85+ click-concepts86 87 General Reference88 ^^^^^^^^^^^^^^^^^^^89 9 unmodified lines99 commands100 documentation101 prompts102 handling-files102- complex103 advanced104+ complex105+ extending-click106 testing107 utils108 shell-completion109 exceptions28 unmodified lines