complex.rst
This file
Path
docs/complex.rst
219 lines · 7.5 KiB
Last changed by
Merge pull request #63 from julen/doc-fixesArmin Ronacherbefore adoption0868754
History of this fileTake it
The walk stopped after 200 commits: lines older than 18fff34 point at it.
Added support for multiple arguments.Armin Ronacherbefore adoption18fff34
lines 1–8why, one step back1.. _complex-guide:23Complex Applications4====================56.. currentmodule:: click78Click is designed to write complex and simple CLI tools alike. HoweverMerge pull request #21 from julen/doc-fixesArmin Ronacherbefore adoptiona4b7d70
line 9why, one step back9the power of its design is the ability to arbitrarily nest systemsAdded support for multiple arguments.Armin Ronacherbefore adoption18fff34
lines 10–14why, one step back10together. For instance in case you have ever used Django you will have11realized that it provides a command line utility. But so does Celery for12instance. So when using Celery with Django there are two tools that need13to interact with each other and be cross configured.14Merge pull request #63 from julen/doc-fixesArmin Ronacherbefore adoption0868754
line 15why, one step back15In a theoretical world of two separate click command line utilities theyAdded support for multiple arguments.Armin Ronacherbefore adoption18fff34
lines 16–28why, one step back16can solve this problem by nesting one inside the other. For instance the17web framework could also load the commands for the message queue18framework.1920Basic Concepts21--------------2223To understand how this works you need to understand two concepts: contexts24and the calling convention.2526Contexts27````````28Merge pull request #63 from julen/doc-fixesArmin Ronacherbefore adoption0868754
line 29why, one step back29Whenever a click command is executed a :class:`Context` object is createdAdded support for multiple arguments.Armin Ronacherbefore adoption18fff34
lines 30–36why, one step back30which holds state for this particular invocation. For instance it31remembers parsed parameters, what command created it, which resources need32to be cleaned up at the end of the function and so forth. It also holds33an application defined object optionally.3435Context objects build a linked list until they hit top one. Each context36is linked to the parent context. This allows a command to work belowMerge pull request #21 from julen/doc-fixesArmin Ronacherbefore adoptiona4b7d70
line 37why, one step back37another command and store its own information there without having to beAdded support for multiple arguments.Armin Ronacherbefore adoption18fff34
lines 38–43why, one step back38afraid of messing up the state of the parent command.3940Because the parent data is however available it's possible to navigate to41it if needed.4243Most of the time you don't see the context object, but when writing moreMerge pull request #21 from julen/doc-fixesArmin Ronacherbefore adoptiona4b7d70
line 44why, one step back44complex applications it comes in handy. This brings us to the next point.Added support for multiple arguments.Armin Ronacherbefore adoption18fff34
lines 45–48why, one step back4546Calling Convention47``````````````````48Merge pull request #63 from julen/doc-fixesArmin Ronacherbefore adoption0868754
line 49why, one step back49When a click command callback is executed it's passed all the non hiddenAdded support for multiple arguments.Armin Ronacherbefore adoption18fff34
lines 50–70why, one step back50parameters as keyword arguments. Notably absent is the context. However51a callback can opt-into being passed the context object by marking itself52with :func:`pass_context`.5354So how do you invoke a command callback if you don't know if it should55receive the context or not? The answer is that the context itself56provides a helper function (:meth:`Context.invoke`) which can do this for57you. It accepts the callback as first argument and then invokes the58function correctly.5960Building a Git61--------------6263In this example we want to build a command line tool that resembles a64version control system a bit. Systems like git usually provide one65over-arching command that already accepts some parameters and66configuration, and then has extra subcommands that do other things.6768The Root Command69````````````````70Merge pull request #21 from julen/doc-fixesArmin Ronacherbefore adoptiona4b7d70
line 71why, one step back71At the top level we need a group that can hold all our commands. In thisAdded support for multiple arguments.Armin Ronacherbefore adoption18fff34
lines 72–75why, one step back72case we use the basic :func:`click.group` which allows us to register73other click commands below it.7475For this command we also want to accept some parameters that configure theMore automated docsArmin Ronacherbefore adoption8254b79
line 76why, one step back76state of our tool:Added support for multiple arguments.Armin Ronacherbefore adoption18fff34
line 77why, one step back77More automated docsArmin Ronacherbefore adoption8254b79
lines 78–79why, one step back78.. click:example::79Added support for multiple arguments.Armin Ronacherbefore adoption18fff34
lines 80–84why, one step back80 import os81 import click828384 class Repo(object):Added support for object ensuringArmin Ronacherbefore adoption8512acd
lines 85–86why, one step back85 def __init__(self, home=None, debug=False):86 self.home = os.path.abspath(home or '.')Added support for multiple arguments.Armin Ronacherbefore adoption18fff34
lines 87–116why, one step back87 self.debug = debug888990 @click.group()91 @click.option('--repo-home', envvar='REPO_HOME', default='.repo')92 @click.option('--debug/--no-debug', default=False,93 envvar='REPO_DEBUG')94 @click.pass_context95 def cli(ctx, repo_home, debug):96 ctx.obj = Repo(repo_home, debug)979899So let's understand what this does. We create a group command which can100have subcommands. When it is invoked it will create an instance of a101``Repo`` class. This holds the state for our command line tool. In this102case it just remembers some parameters but at this point it could also103start loading config files and so on.104105This state object is then remembered as :attr:`~Context.obj` on the106context. This is a special attribute where commands are supposed to107remember what they need to pass on to their children.108109In order for this to work we need to mark our function with110:func:`pass_context` because otherwise the context object would be111entirely hidden from us.112113The First Child Command114```````````````````````115116So let's add our first child command to it. Let's go with the cloneMore automated docsArmin Ronacherbefore adoption8254b79
line 117why, one step back117command:Added support for multiple arguments.Armin Ronacherbefore adoption18fff34
line 118why, one step back118More automated docsArmin Ronacherbefore adoption8254b79
lines 119–120why, one step back119.. click:example::120Added support for multiple arguments.Armin Ronacherbefore adoption18fff34
lines 121–131why, one step back121 @cli.command()122 @click.argument('src')123 @click.argument('dest', required=False)124 def clone(src, dest):125 pass126127So now we have a clone command, but how do we get access to the repo? As128you can imagine one way is to use the :func:`pass_context` function which129again will make our callback also get the context passed on which we130memorized the repo. Even better there is a second version of this131decorator called :func:`pass_obj` which will just pass the stored object,More automated docsArmin Ronacherbefore adoption8254b79
line 132why, one step back132in our case the repo:Added support for multiple arguments.Armin Ronacherbefore adoption18fff34
line 133why, one step back133More automated docsArmin Ronacherbefore adoption8254b79
lines 134–135why, one step back134.. click:example::135Added support for multiple arguments.Armin Ronacherbefore adoption18fff34
lines 136–148why, one step back136 @cli.command()137 @click.argument('src')138 @click.argument('dest', required=False)139 @click.pass_obj140 def clone(repo, src, dest):141 pass142143Interleaved Commands144````````````````````145146While not relevant for this particular program we want to build there is147also quite good support for interleaving systems. Imagine for instance148there would be this super cool plugin for our version control system thatMerge pull request #21 from julen/doc-fixesArmin Ronacherbefore adoptiona4b7d70
line 149why, one step back149needs a lot of configuration and wants to store its own configuration asAdded support for multiple arguments.Armin Ronacherbefore adoption18fff34
lines 150–161why, one step back150:attr:`~Context.obj`. If we would then attach another command below that,151all the sudden we would get the plugin config instead of our repo object.152153One obvious way is to store a reference to the repo on the plugin but then154a command needs to be aware that it's attached below such a plugin.155156There is a much better system by taking advantage of the linked nature of157contexts. We know that the plugin context is linked to the context that158created our repo. Because of that we can start a search for the last159level where the object stored on the context was a repo.160161Built-in support for this is provided by the :func:`make_pass_decorator`Added support for object ensuringArmin Ronacherbefore adoption8512acd
lines 162–165why, one step back162factory which will create decorators for us that find objects (it163internally calls into :meth:`Context.find_object`). So in our case we164know that we want to find the closest ``Repo`` object. So let's make a165decorator for this:Added support for multiple arguments.Armin Ronacherbefore adoption18fff34
line 166why, one step back166More automated docsArmin Ronacherbefore adoption8254b79
lines 167–168why, one step back167.. click:example::168Added support for multiple arguments.Armin Ronacherbefore adoption18fff34
lines 169–171why, one step back169 pass_repo = click.make_pass_decorator(Repo)170171If we now use ``pass_repo`` instead of ``pass_obj`` we will always get aMore automated docsArmin Ronacherbefore adoption8254b79
lines 172–174why, one step back172repo instead of something else:173174.. click:example::Added support for multiple arguments.Armin Ronacherbefore adoption18fff34
lines 175–181why, one step back175176 @cli.command()177 @click.argument('src')178 @click.argument('dest', required=False)179 @pass_repo180 def clone(repo, src, dest):181 passAdded support for object ensuringArmin Ronacherbefore adoption8512acd
lines 182–219why, one step back182183Ensuring Objects184````````````````185186The above example only works if there was an outer command that created a187``Repo`` object and stored it on the context. For some more advanced use188cases this might be a problem for you. The default behavior of189:func:`make_pass_decorator` is to call into :meth:`Context.find_object`190which will find the object. If it can't find the object it will raise an191error. The alternative behavior is to use :meth:`Context.ensure_object`192which will find the object, or if it cannot find it, will create one and193store it on the innermost context. This behavior can also be enabled for194:func:`make_pass_decorator` by passing ``ensure=True``:195196.. click:example::197198 pass_repo = click.make_pass_decorator(Repo, ensure=True)199200In this case the innermost context gets such an object created if it's201missing. This might replace objects being placed there earlier. In this202case the command stays executable, even if the outer command does not run.203For this to work the object type needs to have a constructor that accepts204no arguments.205206As such it runs standalone:207208.. click:example::209210 @click.command()211 @pass_repo212 def cp(repo):213 click.echo(repo)214215As you can see:216217.. click:run::218219 invoke(cp, [])