rename 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 1a1cdcb · Browse files · 2 files·+393 added−393 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+393 added−393 removed
- other:+393 added−393 removed
Provenance
- Commit
3df7be3- Tree
87814f7- Author
denuoweb <jaron@rosenau.info>- Committer
denuoweb <jaron@rosenau.info>- Parent
1a1cdcb
2 files changed+393 added−393 removed
added:docs/complex.md+393 added
1+.. _complex-guide:2+3+Complex Applications4+====================5+6+.. currentmodule:: click7+8+Click is designed to assist with the creation of complex and simple CLI tools9+alike. However, the power of its design is the ability to arbitrarily nest10+systems together. For instance, if you have ever used Django, you will11+have realized that it provides a command line utility, but so does Celery.12+When using Celery with Django, there are two tools that need to interact with13+each other and be cross-configured.14+15+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: contexts27+and the calling convention.28+29+Contexts30+````````31+32+Whenever a Click command is executed, a :class:`Context` object is created33+which holds state for this particular invocation. It remembers parsed34+parameters, what command created it, which resources need to be cleaned up35+at the end of the function, and so forth. It can also optionally hold an36+application-defined object.37+38+Context objects build a linked list until they hit the top one. Each context39+is linked to a parent context. This allows a command to work below40+another command and store its own information there without having to be41+afraid of altering up the state of the parent command.42+43+Because the parent data is available, however, it is possible to navigate to44+it if needed.45+46+Most of the time, you do not see the context object, but when writing more47+complex applications it comes in handy. This brings us to the next point.48+49+Calling Convention50+``````````````````51+52+When a Click command callback is executed, it's passed all the non-hidden53+parameters as keyword arguments. Notably absent is the context. However,54+a callback can opt into being passed to the context object by marking itself55+with :func:`pass_context`.56+57+So how do you invoke a command callback if you don't know if it should58+receive the context or not? The answer is that the context itself59+provides a helper function (:meth:`Context.invoke`) which can do this for60+you. It accepts the callback as first argument and then invokes the61+function correctly.62+63+Building a Git Clone64+--------------------65+66+In this example, we want to build a command line tool that resembles a67+version control system. Systems like Git usually provide one68+over-arching command that already accepts some parameters and69+configuration, and then have extra subcommands that do other things.70+71+The Root Command72+````````````````73+74+At the top level, we need a group that can hold all our commands. In this75+case, we use the basic :func:`click.group` which allows us to register76+other Click commands below it.77+78+For this command, we also want to accept some parameters that configure the79+state of our tool:80+81+.. click:example::82+83+ import os84+ import click85+86+87+ class Repo(object):88+ def __init__(self, home=None, debug=False):89+ self.home = os.path.abspath(home or '.')90+ self.debug = debug91+92+93+ @click.group()94+ @click.option('--repo-home', envvar='REPO_HOME', default='.repo')95+ @click.option('--debug/--no-debug', default=False,96+ envvar='REPO_DEBUG')97+ @click.pass_context98+ def cli(ctx, repo_home, debug):99+ ctx.obj = Repo(repo_home, debug)100+101+102+Let's understand what this does. We create a group command which can103+have subcommands. When it is invoked, it will create an instance of a104+``Repo`` class. This holds the state for our command line tool. In this105+case, it just remembers some parameters, but at this point it could also106+start loading configuration files and so on.107+108+This state object is then remembered by the context as :attr:`~Context.obj`.109+This is a special attribute where commands are supposed to remember what110+they need to pass on to their children.111+112+In order for this to work, we need to mark our function with113+:func:`pass_context`, because otherwise, the context object would be114+entirely hidden from us.115+116+The First Child Command117+```````````````````````118+119+Let's add our first child command to it, the clone command:120+121+.. click:example::122+123+ @cli.command()124+ @click.argument('src')125+ @click.argument('dest', required=False)126+ def clone(src, dest):127+ pass128+129+So now we have a clone command, but how do we get access to the repo? As130+you can imagine, one way is to use the :func:`pass_context` function which131+again will make our callback also get the context passed on which we132+memorized the repo. However, there is a second version of this decorator133+called :func:`pass_obj` which will just pass the stored object, (in our case134+the repo):135+136+.. click:example::137+138+ @cli.command()139+ @click.argument('src')140+ @click.argument('dest', required=False)141+ @click.pass_obj142+ def clone(repo, src, dest):143+ pass144+145+Interleaved Commands146+````````````````````147+148+While not relevant for the particular program we want to build, there is149+also quite good support for interleaving systems. Imagine for instance that150+there was a super cool plugin for our version control system that needed a151+lot of configuration and wanted to store its own configuration as152+:attr:`~Context.obj`. If we would then attach another command below that,153+we would all of a sudden get the plugin configuration instead of our repo154+object.155+156+One obvious way to remedy this is to store a reference to the repo in the157+plugin, but then a command needs to be aware that it's attached below such a158+plugin.159+160+There is a much better system that can be built by taking advantage of the161+linked nature of contexts. We know that the plugin context is linked to the162+context that created our repo. Because of that, we can start a search for163+the last level where the object stored by the context was a repo.164+165+Built-in support for this is provided by the :func:`make_pass_decorator`166+factory, which will create decorators for us that find objects (it167+internally calls into :meth:`Context.find_object`). In our case, we168+know that we want to find the closest ``Repo`` object, so let's make a169+decorator for this:170+171+.. click:example::172+173+ pass_repo = click.make_pass_decorator(Repo)174+175+If we now use ``pass_repo`` instead of ``pass_obj``, we will always get a176+repo instead of something else:177+178+.. click:example::179+180+ @cli.command()181+ @click.argument('src')182+ @click.argument('dest', required=False)183+ @pass_repo184+ def clone(repo, src, dest):185+ pass186+187+Ensuring Object Creation188+````````````````````````189+190+The above example only works if there was an outer command that created a191+``Repo`` object and stored it in the context. For some more advanced use192+cases, this might become a problem. The default behavior of193+:func:`make_pass_decorator` is to call :meth:`Context.find_object`194+which will find the object. If it can't find the object,195+:meth:`make_pass_decorator` will raise an error.196+The alternative behavior is to use :meth:`Context.ensure_object`197+which will find the object, and if it cannot find it, will create one and198+store it in the innermost context. This behavior can also be enabled for199+:func:`make_pass_decorator` by passing ``ensure=True``:200+201+.. click:example::202+203+ pass_repo = click.make_pass_decorator(Repo, ensure=True)204+205+In this case, the innermost context gets an object created if it is206+missing. This might replace objects being placed there earlier. In this207+case, the command stays executable, even if the outer command does not run.208+For this to work, the object type needs to have a constructor that accepts209+no arguments.210+211+As such it runs standalone:212+213+.. click:example::214+215+ @click.command()216+ @pass_repo217+ def cp(repo):218+ click.echo(isinstance(repo, Repo))219+220+As you can see:221+222+.. click:run::223+224+ invoke(cp, [])225+226+Lazily Loading Subcommands227+--------------------------228+229+Large CLIs and CLIs with slow imports may benefit from deferring the loading of230+subcommands. The interfaces which support this mode of use are231+:meth:`Group.list_commands` and :meth:`Group.get_command`. A custom232+:class:`Group` subclass can implement a lazy loader by storing extra data such233+that :meth:`Group.get_command` is responsible for running imports.234+235+Since the primary case for this is a :class:`Group` which loads its subcommands lazily,236+the following example shows a lazy-group implementation.237+238+.. warning::239+240+ Lazy loading of python code can result in hard to track down bugs, circular imports241+ in order-dependent codebases, and other surprising behaviors. It is recommended that242+ this technique only be used in concert with testing which will at least run the243+ ``--help`` on each subcommand. That will guarantee that each subcommand can be loaded244+ successfully.245+246+Defining the Lazy Group247+```````````````````````248+249+The following :class:`Group` subclass adds an attribute, ``lazy_subcommands``, which250+stores a mapping from subcommand names to the information for importing them.251+252+.. code-block:: python253+254+ # in lazy_group.py255+ import importlib256+ import click257+258+ class LazyGroup(click.Group):259+ def __init__(self, *args, lazy_subcommands=None, **kwargs):260+ super().__init__(*args, **kwargs)261+ # lazy_subcommands is a map of the form:262+ #263+ # {command-name} -> {module-name}.{command-object-name}264+ #265+ self.lazy_subcommands = lazy_subcommands or {}266+267+ def list_commands(self, ctx):268+ base = super().list_commands(ctx)269+ lazy = sorted(self.lazy_subcommands.keys())270+ return base + lazy271+272+ def get_command(self, ctx, cmd_name):273+ if cmd_name in self.lazy_subcommands:274+ return self._lazy_load(cmd_name)275+ return super().get_command(ctx, cmd_name)276+277+ def _lazy_load(self, cmd_name):278+ # lazily loading a command, first get the module name and attribute name279+ import_path = self.lazy_subcommands[cmd_name]280+ modname, cmd_object_name = import_path.rsplit(".", 1)281+ # do the import282+ mod = importlib.import_module(modname)283+ # get the Command object from that module284+ cmd_object = getattr(mod, cmd_object_name)285+ # check the result to make debugging easier286+ if not isinstance(cmd_object, click.Command):287+ raise ValueError(288+ f"Lazy loading of {import_path} failed by returning "289+ "a non-command object"290+ )291+ return cmd_object292+293+Using LazyGroup To Define a CLI294+```````````````````````````````295+296+With ``LazyGroup`` defined, it's now possible to write a group which lazily loads its297+subcommands like so:298+299+.. code-block:: python300+301+ # in main.py302+ import click303+ from lazy_group import LazyGroup304+305+ @click.group(306+ cls=LazyGroup,307+ lazy_subcommands={"foo": "foo.cli", "bar": "bar.cli"},308+ help="main CLI command for lazy example",309+ )310+ def cli():311+ pass312+313+.. code-block:: python314+315+ # in foo.py316+ import click317+318+ @click.group(help="foo command for lazy example")319+ def cli():320+ pass321+322+.. code-block:: python323+324+ # in bar.py325+ import click326+ from lazy_group import LazyGroup327+328+ @click.group(329+ cls=LazyGroup,330+ lazy_subcommands={"baz": "baz.cli"},331+ help="bar command for lazy example",332+ )333+ def cli():334+ pass335+336+.. code-block:: python337+338+ # in baz.py339+ import click340+341+ @click.group(help="baz command for lazy example")342+ def cli():343+ pass344+345+346+What triggers Lazy Loading?347+```````````````````````````348+349+There are several events which may trigger lazy loading by running the350+:meth:`Group.get_command` function.351+Some are intuititve, and some are less so.352+353+All cases are described with respect to the above example, assuming the main program354+name is ``cli``.355+356+1. Command resolution. If a user runs ``cli bar baz``, this must first resolve ``bar``,357+ and then resolve ``baz``. Each subcommand resolution step does a lazy load.358+2. Helptext rendering. In order to get the short help description of subcommands,359+ ``cli --help`` will load ``foo`` and ``bar``. Note that it will still not load360+ ``baz``.361+3. Shell completion. In order to get the subcommands of a lazy command, ``cli <TAB>``362+ will need to resolve the subcommands of ``cli``. This process will trigger the lazy363+ loads.364+365+Further Deferring Imports366+`````````````````````````367+368+It is possible to make the process even lazier, but it is generally more difficult the369+more you want to defer work.370+371+For example, subcommands could be represented as a custom :class:`Command` subclass372+which defers importing the command until it is invoked, but which provides373+:meth:`Command.get_short_help_str` in order to support completions and helptext.374+More simply, commands can be constructed whose callback functions defer any actual work375+until after an import.376+377+This command definition provides ``foo``, but any of the work associated with importing378+the "real" callback function is deferred until invocation time:379+380+.. click:example::381+382+ @click.command()383+ @click.option("-n", type=int)384+ @click.option("-w", type=str)385+ def foo(n, w):386+ from mylibrary import foo_concrete387+388+ foo_concrete(n, w)389+390+Because Click builds helptext and usage info from options, arguments, and command391+attributes, it has no awareness that the underlying function is in any way handling a392+deferred import. Therefore, all Click-provided utilities and functionality will work393+as normal on such a command.deleted:docs/complex.rst-393 removed
1-.. _complex-guide:2-3-Complex Applications4-====================5-6-.. currentmodule:: click7-8-Click is designed to assist with the creation of complex and simple CLI tools9-alike. However, the power of its design is the ability to arbitrarily nest10-systems together. For instance, if you have ever used Django, you will11-have realized that it provides a command line utility, but so does Celery.12-When using Celery with Django, there are two tools that need to interact with13-each other and be cross-configured.14-15-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: contexts27-and the calling convention.28-29-Contexts30-````````31-32-Whenever a Click command is executed, a :class:`Context` object is created33-which holds state for this particular invocation. It remembers parsed34-parameters, what command created it, which resources need to be cleaned up35-at the end of the function, and so forth. It can also optionally hold an36-application-defined object.37-38-Context objects build a linked list until they hit the top one. Each context39-is linked to a parent context. This allows a command to work below40-another command and store its own information there without having to be41-afraid of altering up the state of the parent command.42-43-Because the parent data is available, however, it is possible to navigate to44-it if needed.45-46-Most of the time, you do not see the context object, but when writing more47-complex applications it comes in handy. This brings us to the next point.48-49-Calling Convention50-``````````````````51-52-When a Click command callback is executed, it's passed all the non-hidden53-parameters as keyword arguments. Notably absent is the context. However,54-a callback can opt into being passed to the context object by marking itself55-with :func:`pass_context`.56-57-So how do you invoke a command callback if you don't know if it should58-receive the context or not? The answer is that the context itself59-provides a helper function (:meth:`Context.invoke`) which can do this for60-you. It accepts the callback as first argument and then invokes the61-function correctly.62-63-Building a Git Clone64---------------------65-66-In this example, we want to build a command line tool that resembles a67-version control system. Systems like Git usually provide one68-over-arching command that already accepts some parameters and69-configuration, and then have extra subcommands that do other things.70-71-The Root Command72-````````````````73-74-At the top level, we need a group that can hold all our commands. In this75-case, we use the basic :func:`click.group` which allows us to register76-other Click commands below it.77-78-For this command, we also want to accept some parameters that configure the79-state of our tool:80-81-.. click:example::82-83- import os84- import click85-86-87- class Repo(object):88- def __init__(self, home=None, debug=False):89- self.home = os.path.abspath(home or '.')90- self.debug = debug91-92-93- @click.group()94- @click.option('--repo-home', envvar='REPO_HOME', default='.repo')95- @click.option('--debug/--no-debug', default=False,96- envvar='REPO_DEBUG')97- @click.pass_context98- def cli(ctx, repo_home, debug):99- ctx.obj = Repo(repo_home, debug)100-101-102-Let's understand what this does. We create a group command which can103-have subcommands. When it is invoked, it will create an instance of a104-``Repo`` class. This holds the state for our command line tool. In this105-case, it just remembers some parameters, but at this point it could also106-start loading configuration files and so on.107-108-This state object is then remembered by the context as :attr:`~Context.obj`.109-This is a special attribute where commands are supposed to remember what110-they need to pass on to their children.111-112-In order for this to work, we need to mark our function with113-:func:`pass_context`, because otherwise, the context object would be114-entirely hidden from us.115-116-The First Child Command117-```````````````````````118-119-Let's add our first child command to it, the clone command:120-121-.. click:example::122-123- @cli.command()124- @click.argument('src')125- @click.argument('dest', required=False)126- def clone(src, dest):127- pass128-129-So now we have a clone command, but how do we get access to the repo? As130-you can imagine, one way is to use the :func:`pass_context` function which131-again will make our callback also get the context passed on which we132-memorized the repo. However, there is a second version of this decorator133-called :func:`pass_obj` which will just pass the stored object, (in our case134-the repo):135-136-.. click:example::137-138- @cli.command()139- @click.argument('src')140- @click.argument('dest', required=False)141- @click.pass_obj142- def clone(repo, src, dest):143- pass144-145-Interleaved Commands146-````````````````````147-148-While not relevant for the particular program we want to build, there is149-also quite good support for interleaving systems. Imagine for instance that150-there was a super cool plugin for our version control system that needed a151-lot of configuration and wanted to store its own configuration as152-:attr:`~Context.obj`. If we would then attach another command below that,153-we would all of a sudden get the plugin configuration instead of our repo154-object.155-156-One obvious way to remedy this is to store a reference to the repo in the157-plugin, but then a command needs to be aware that it's attached below such a158-plugin.159-160-There is a much better system that can be built by taking advantage of the161-linked nature of contexts. We know that the plugin context is linked to the162-context that created our repo. Because of that, we can start a search for163-the last level where the object stored by the context was a repo.164-165-Built-in support for this is provided by the :func:`make_pass_decorator`166-factory, which will create decorators for us that find objects (it167-internally calls into :meth:`Context.find_object`). In our case, we168-know that we want to find the closest ``Repo`` object, so let's make a169-decorator for this:170-171-.. click:example::172-173- pass_repo = click.make_pass_decorator(Repo)174-175-If we now use ``pass_repo`` instead of ``pass_obj``, we will always get a176-repo instead of something else:177-178-.. click:example::179-180- @cli.command()181- @click.argument('src')182- @click.argument('dest', required=False)183- @pass_repo184- def clone(repo, src, dest):185- pass186-187-Ensuring Object Creation188-````````````````````````189-190-The above example only works if there was an outer command that created a191-``Repo`` object and stored it in the context. For some more advanced use192-cases, this might become a problem. The default behavior of193-:func:`make_pass_decorator` is to call :meth:`Context.find_object`194-which will find the object. If it can't find the object,195-:meth:`make_pass_decorator` will raise an error.196-The alternative behavior is to use :meth:`Context.ensure_object`197-which will find the object, and if it cannot find it, will create one and198-store it in the innermost context. This behavior can also be enabled for199-:func:`make_pass_decorator` by passing ``ensure=True``:200-201-.. click:example::202-203- pass_repo = click.make_pass_decorator(Repo, ensure=True)204-205-In this case, the innermost context gets an object created if it is206-missing. This might replace objects being placed there earlier. In this207-case, the command stays executable, even if the outer command does not run.208-For this to work, the object type needs to have a constructor that accepts209-no arguments.210-211-As such it runs standalone:212-213-.. click:example::214-215- @click.command()216- @pass_repo217- def cp(repo):218- click.echo(isinstance(repo, Repo))219-220-As you can see:221-222-.. click:run::223-224- invoke(cp, [])225-226-Lazily Loading Subcommands227---------------------------228-229-Large CLIs and CLIs with slow imports may benefit from deferring the loading of230-subcommands. The interfaces which support this mode of use are231-:meth:`Group.list_commands` and :meth:`Group.get_command`. A custom232-:class:`Group` subclass can implement a lazy loader by storing extra data such233-that :meth:`Group.get_command` is responsible for running imports.234-235-Since the primary case for this is a :class:`Group` which loads its subcommands lazily,236-the following example shows a lazy-group implementation.237-238-.. warning::239-240- Lazy loading of python code can result in hard to track down bugs, circular imports241- in order-dependent codebases, and other surprising behaviors. It is recommended that242- this technique only be used in concert with testing which will at least run the243- ``--help`` on each subcommand. That will guarantee that each subcommand can be loaded244- successfully.245-246-Defining the Lazy Group247-```````````````````````248-249-The following :class:`Group` subclass adds an attribute, ``lazy_subcommands``, which250-stores a mapping from subcommand names to the information for importing them.251-252-.. code-block:: python253-254- # in lazy_group.py255- import importlib256- import click257-258- class LazyGroup(click.Group):259- def __init__(self, *args, lazy_subcommands=None, **kwargs):260- super().__init__(*args, **kwargs)261- # lazy_subcommands is a map of the form:262- #263- # {command-name} -> {module-name}.{command-object-name}264- #265- self.lazy_subcommands = lazy_subcommands or {}266-267- def list_commands(self, ctx):268- base = super().list_commands(ctx)269- lazy = sorted(self.lazy_subcommands.keys())270- return base + lazy271-272- def get_command(self, ctx, cmd_name):273- if cmd_name in self.lazy_subcommands:274- return self._lazy_load(cmd_name)275- return super().get_command(ctx, cmd_name)276-277- def _lazy_load(self, cmd_name):278- # lazily loading a command, first get the module name and attribute name279- import_path = self.lazy_subcommands[cmd_name]280- modname, cmd_object_name = import_path.rsplit(".", 1)281- # do the import282- mod = importlib.import_module(modname)283- # get the Command object from that module284- cmd_object = getattr(mod, cmd_object_name)285- # check the result to make debugging easier286- if not isinstance(cmd_object, click.Command):287- raise ValueError(288- f"Lazy loading of {import_path} failed by returning "289- "a non-command object"290- )291- return cmd_object292-293-Using LazyGroup To Define a CLI294-```````````````````````````````295-296-With ``LazyGroup`` defined, it's now possible to write a group which lazily loads its297-subcommands like so:298-299-.. code-block:: python300-301- # in main.py302- import click303- from lazy_group import LazyGroup304-305- @click.group(306- cls=LazyGroup,307- lazy_subcommands={"foo": "foo.cli", "bar": "bar.cli"},308- help="main CLI command for lazy example",309- )310- def cli():311- pass312-313-.. code-block:: python314-315- # in foo.py316- import click317-318- @click.group(help="foo command for lazy example")319- def cli():320- pass321-322-.. code-block:: python323-324- # in bar.py325- import click326- from lazy_group import LazyGroup327-328- @click.group(329- cls=LazyGroup,330- lazy_subcommands={"baz": "baz.cli"},331- help="bar command for lazy example",332- )333- def cli():334- pass335-336-.. code-block:: python337-338- # in baz.py339- import click340-341- @click.group(help="baz command for lazy example")342- def cli():343- pass344-345-346-What triggers Lazy Loading?347-```````````````````````````348-349-There are several events which may trigger lazy loading by running the350-:meth:`Group.get_command` function.351-Some are intuititve, and some are less so.352-353-All cases are described with respect to the above example, assuming the main program354-name is ``cli``.355-356-1. Command resolution. If a user runs ``cli bar baz``, this must first resolve ``bar``,357- and then resolve ``baz``. Each subcommand resolution step does a lazy load.358-2. Helptext rendering. In order to get the short help description of subcommands,359- ``cli --help`` will load ``foo`` and ``bar``. Note that it will still not load360- ``baz``.361-3. Shell completion. In order to get the subcommands of a lazy command, ``cli <TAB>``362- will need to resolve the subcommands of ``cli``. This process will trigger the lazy363- loads.364-365-Further Deferring Imports366-`````````````````````````367-368-It is possible to make the process even lazier, but it is generally more difficult the369-more you want to defer work.370-371-For example, subcommands could be represented as a custom :class:`Command` subclass372-which defers importing the command until it is invoked, but which provides373-:meth:`Command.get_short_help_str` in order to support completions and helptext.374-More simply, commands can be constructed whose callback functions defer any actual work375-until after an import.376-377-This command definition provides ``foo``, but any of the work associated with importing378-the "real" callback function is deferred until invocation time:379-380-.. click:example::381-382- @click.command()383- @click.option("-n", type=int)384- @click.option("-w", type=str)385- def foo(n, w):386- from mylibrary import foo_concrete387-388- foo_concrete(n, w)389-390-Because Click builds helptext and usage info from options, arguments, and command391-attributes, it has no awareness that the underlying function is in any way handling a392-deferred import. Therefore, all Click-provided utilities and functionality will work393-as normal on such a command.