Skip to content
Myr

Added docs for building complex click applications

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 8259846 · Browse files · 7 files+322 added−24 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+322 added−24 removed

  • other:+322 added−24 removed

7 files+322 added−24 removed

modified:docs/api.rst+4 added
23 unmodified lines
24.. autofunction:: version_option2526.. autofunction:: help_option2728.. autofunction:: pass_context2930.. autofunction:: pass_obj3132Helper Functions33----------------3435.. autofunction:: prompt
54 unmodified lines
modified:docs/commands.rst+43 added-5 removed
63 unmodified lines
64Each time a command invokes a new context is created and linked with the65parent context. Normally you can't see these contexts, but they are66there. Contexts are passed to parameter callbacks together with the67value automatically. Commands can also ask for the context to be passed68by passing ``pass_context=True`` to the :func:`command` or :func:`group`69decorator. In that case the context is passed as first argument.68by marking themselves with the :func:`pass_context` decorator. In that69case the context is passed as first argument.7071The context can also carry a program specified object that can be72used for the program's purposes. What this means is that you can build a73script like this::7475 import click7677 @click.group(pass_context=True)77 @click.group()78 @click.option('--debug/--no-debug', default=False)79 @click.pass_context80 def cli(ctx, debug):81 ctx.obj['DEBUG'] = debug8282 @cli.command(pass_context=True)83 @cli.command()84 @click.pass_context85 def sync(ctx):86 print('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off'))8788 if __name__ == '__main__':
6 unmodified lines
95In addition to that instead of passing an object down nothing stops the96application from modifying global state. For instance you could just flip97a global ``DEBUG`` variable and be done with it.9899Decorating Commands100-------------------101102As you have seen in the earlier example a decorator can change how a103command is invoked. What actually happens behind the scenes is that104callbacks are always invoked through the :meth:`Context.invoke` method105which automatically invokes a command correctly (by either passing the106context or not).107108This is very useful when you want to write custom decorators. For109instance a common pattern would be to configure an object representing110state and then storing it on the context and then to use a custom111decorator to find the most recent object of this sort and pass it as first112argument.113114For instance the :func:`pass_obj` decorator can be implemented like this::115116 import click117 from functools import update_wrapper118119 def pass_obj(f):120 @click.pass_context121 def new_func(ctx, *args, **kwargs):122 return ctx.invoke(f, ctx.obj, *args, **kwargs)123 return update_wrapper(new_func, f)124125The :meth:`Context.invoke` command will automatically invoke the function126in the correct way. So the function will either be called with ``f(ctx,127obj)`` or ``f(obj)`` depending on if it itself is decorated with128:func:`with_context`.129130This is a very powerful context that can be used to build very complex131nested applications. See :ref:`complex-guide` for more information.132133134Group Invocation Without Command135--------------------------------136137By default a group or multi command is not invoked unless a subcommand is
7 unmodified lines
145Example::146147 import click148112 @click.group(pass_context=True, invoke_without_command=True)149 @click.group(invoke_without_command=True)150 @click.pass_context151 def cli(ctx):152 if ctx.invoked_subcommand is None:153 print('I was invoked without subcommand')154 else:
54 unmodified lines
added:docs/complex.rst+170 added
1.. _complex-guide:23Complex Applications4====================56.. currentmodule:: click78Click is designed to write complex and simple CLI tools alike. However9the power of it's design is the ability to arbitrarily nest systems10together. 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.1415In a theoretical world of two separate Click command line utilities they16can 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--------2829Whenever a Click command is executed a :class:`Context` object is created30which 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 below37another command and store it's own information there without having to be38afraid 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 more44complex applications it comes in handy. This brings is to the next point4546Calling Convention47------------------4849When a Click command callback is executed it's passed all the non hidden50parameters 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````````````````7071At the toplevel we need a group that can hold all our commands. In this72case 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 the76state of our tool::7778 import os79 import click808182 class Repo(object):83 def __init__(self, home, debug):84 self.home = os.path.abspath(home)85 self.debug = debug868788 @click.group()89 @click.option('--repo-home', envvar='REPO_HOME', default='.repo')90 @click.option('--debug/--no-debug', default=False,91 envvar='REPO_DEBUG')92 @click.pass_context93 def cli(ctx, repo_home, debug):94 ctx.obj = Repo(repo_home, debug)959697So let's understand what this does. We create a group command which can98have subcommands. When it is invoked it will create an instance of a99``Repo`` class. This holds the state for our command line tool. In this100case it just remembers some parameters but at this point it could also101start loading config files and so on.102103This state object is then remembered as :attr:`~Context.obj` on the104context. This is a special attribute where commands are supposed to105remember what they need to pass on to their children.106107In order for this to work we need to mark our function with108:func:`pass_context` because otherwise the context object would be109entirely hidden from us.110111The First Child Command112```````````````````````113114So let's add our first child command to it. Let's go with the clone115command::116117 @cli.command()118 @click.argument('src')119 @click.argument('dest', required=False)120 def clone(src, dest):121 pass122123So now we have a clone command, but how do we get access to the repo? As124you can imagine one way is to use the :func:`pass_context` function which125again will make our callback also get the context passed on which we126memorized the repo. Even better there is a second version of this127decorator called :func:`pass_obj` which will just pass the stored object,128in our case the repo::129130 @cli.command()131 @click.argument('src')132 @click.argument('dest', required=False)133 @click.pass_obj134 def clone(repo, src, dest):135 pass136137Interleaved Commands138````````````````````139140While not relevant for this particular program we want to build there is141also quite good support for interleaving systems. Imagine for instance142there would be this super cool plugin for our version control system that143needs a lot of configuration and wants to store it's own configuration as144:attr:`~Context.obj`. If we would then attach another command below that,145all the sudden we would get the plugin config instead of our repo object.146147One obvious way is to store a reference to the repo on the plugin but then148a command needs to be aware that it's attached below such a plugin.149150There is a much better system by taking advantage of the linked nature of151contexts. We know that the plugin context is linked to the context that152created our repo. Because of that we can start a search for the last153level where the object stored on the context was a repo.154155Built-in support for this is provided by the :func:`make_pass_decorator`156factory which will create decorators for us that find objects. So in our157case we know that we want to find the closest ``Repo`` object. So let's158make a decorator for this::159160 pass_repo = click.make_pass_decorator(Repo)161162If we now use ``pass_repo`` instead of ``pass_obj`` we will always get a163repo instead of something else::164165 @cli.command()166 @click.argument('src')167 @click.argument('dest', required=False)168 @pass_repo169 def clone(repo, src, dest):170 pass
modified:docs/index.rst+1 added
50 unmodified lines
51 commands52 prompts53 documentation54 setuptools55 complex5657API Reference58-------------59
7 unmodified lines
modified:docs/why.rst+3 added
39 unmodified lines
4041Click was written to support the `Flask <http://flask.pocoo.org/>`_42microframework ecosystem because no tool could provide it with the43functionality it needed.4445To get an understanding of what Click is all about I strongly recommend46looking at the :ref:`complex-guide` chapter to see what it's useful for.
modified:examples/repo/repo.py+27 added-6 removed
1import os2import click345class Repo(object):67 def __init__(self, home):8 self.home = home910 def __repr__(self):11 return '<Repo %r>' % self.home121314pass_repo = click.make_pass_decorator(Repo)151617@click.group()5@click.option('--repo-home', envvar='REPO_HOME')6def cli(repo_home):18@click.option('--repo-home', envvar='REPO_HOME', default='.repo')19@click.pass_context20def cli(ctx, repo_home):21 """Repo is a command line tool that showcases how to build complex22 command line interfaces with Click.23 """10 print('Repo home: %s' % repo_home)24 # Create a repo object and remember it as as the context object.25 ctx.obj = Repo(os.path.abspath(repo_home))262728@cli.command()29@click.argument('src')30@click.argument('dest', required=False)31@click.option('--shallow/--deep', default=False,32 help='Makes a checkout shallow or deep. Deep by default.')33@pass_repo18def clone(src, dest, shallow):34def clone(repo, src, dest, shallow):35 """Clones a repository.3637 This will clone the repository at SRC into the folder DEST. If DEST38 is not provided this will automatically use the last path component39 of SRC and create that folder.40 """41 print('Repo: %s' % repo)42 print('Source: %s' % src)43 print('Destination: %s' % dest)44 print('Shallow: %s' % shallow)454647@cli.command()48@click.confirmation_option()49@pass_repo32def delete():50def delete(repo):51 """Deletes a repository.5253 This will throw away the current repository.54 """55 print('Repo: %s' % repo)56 print('Deleted')575859@cli.command()60@click.option('--username', prompt=True, required=True)61@click.option('--email', prompt='E-Mail', required=True)62@click.password_option()63@pass_repo44def setuser(username, email, password):64def setuser(repo, username, email, password):65 """Sets the user credentials.6667 This will override the current user config.68 """69 print('Repo: %s' % repo)70 print('Username: %s' % username)71 print('E-Mail: %s' % email)72 print('Password: %s' % ('*' * len(password)))
modified:click.py+74 added-13 removed
20 unmodified lines
21import optparse22import textwrap23import struct24from itertools import chain25from functools import update_wrapper262728PY2 = sys.version_info[0] == 229if PY2:
137 unmodified lines
167 file.write('\n')168 file.flush()169170171def pass_context(f):172 """Marks a callback that it wants to receive the current context173 object as first argument.174 """175 f.__click_pass_context__ = True176 return f177178179def pass_obj(f):180 """Similar to :func:`pass_context` but only pass the object on the181 context onwards (:attr:`Context.obj`). This is useful if that object182 represents the state of a nested system.183 """184 @pass_context185 def new_func(*args, **kwargs):186 ctx = args[0]187 return ctx.invoke(f, ctx.obj, *args[1:], **kwargs)188 return update_wrapper(new_func, f)189190191def make_pass_decorator(object_type):192 """Given an object type this creates a decorator that will work193 similar to :func:`pass_obj` but instead of passing the object of the194 current context, it will find the innermost context of type195 :func:`object_type`.196197 This generates a decorator that works roughly like this::198199 from functools import update_wrapper200201 def decorator(f):202 @pass_context203 def new_func(ctx, *args, **kwargs):204 obj = ctx.find_object(object_type)205 return ctx.invoke(f, obj, *args, **kwargs)206 return update_wrapper(new_func, f)207 return decorator208 """209 def decorator(f):210 @pass_context211 def new_func(*args, **kwargs):212 ctx = args[0]213 obj = ctx.find_object(object_type)214 if obj is None:215 raise RuntimeError('Managed to invoke callback without a '216 'context object of type %r existing'217 % object_type.__name__)218 return ctx.invoke(f, obj, *args[1:], **kwargs)219 return update_wrapper(new_func, f)220 return decorator221222223class Context(object):224 """The context is a special internal object that holds state relevant225 for the script execution at every single level. It's normally invisible226 to commands unless they opt-in to getting access to it.
103 unmodified lines
330 while node.parent is not None:331 node = node.parent332 return node333334 def find_object(self, object_type):335 """Finds the closest object of a given type."""336 node = self337 while node.parent is not None:338 if isinstance(node.obj, object_type):339 return node.obj340 node = node.parent341342 def fail(self, message):343 """Aborts the execution of the program with a specific error344 message.345
20 unmodified lines
366 context and command.367 """368 return self._parser.format_help().rstrip()369370 def invoke(*args, **kwargs):371 """Invokes a command callback in exactly the way it expects.372 """373 self, callback = args[:2]374 args = args[2:]375 if getattr(callback, '__click_pass_context__', False):376 args = (self,) + args377 return callback(*args, **kwargs)378379380class UsageError(Exception):381 """An internal exception that signals a usage error. This typically382 aborts any further handling.383 """
85 unmodified lines
469 :param name: the name of the command to use unless a group overrides it.470 :param callback: the callback to invoke. This is optional.471 :param params: the parameters to register with this command. This can472 be either :class:`Option` or :class:`Argument` objects.403 :param pass_context: if this is set to `True` then the callback will404 be passed the context as first argument.405 :param pass_params: if this is set to `True` then the callback will406 be passed all non hidden parameters as keyword407 arguments.473 :param help: the help string to use for this command.474 :param short_help: the short help to use for this command. This is475 shown on the command listing of the parent command.476 :param add_help_option: by default each command registers a ``--help``477 option. This can be disabled by this parameter.478 """479 allow_extra_args = False480416 def __init__(self, name, callback=None, params=None, pass_context=False,417 pass_params=True, help=None, short_help=None,418 options_metavar='[OPTIONS]', add_help_option=True):481 def __init__(self, name, callback=None, params=None, help=None,482 short_help=None, options_metavar='[OPTIONS]',483 add_help_option=True):484 #: the name the command things it has. Upon registering a command485 #: on a :class:`Group` the group will default the command name486 #: with this information. You should instead use the487 #: :class:`Context`\'s :attr:`~Context.info_name` attribute.
4 unmodified lines
492 #: the list of parameters for this command in the order they493 #: should show up in the help page and execute. Eager parameters494 #: will automatically be handled before non eager ones.495 self.params = params or []431 self.pass_context = pass_context432 self.pass_params = pass_params496 self.help = help497 self.options_metavar = options_metavar498 if short_help is None and help:499 short_help = help.split('.')[0].strip()
59 unmodified lines
559 def invoke(self, ctx):560 """Given a context, this invokes the attached callback (if it exists)561 in the right way.562 """500 func_args = self.pass_context and (ctx,) or ()501 func_kwargs = self.pass_params and ctx.params or {}563 if self.callback is not None:503 self.callback(*func_args, **func_kwargs)564 ctx.invoke(self.callback, **ctx.params)565566 def main(self, args=None, prog_name=None, **extra):567 """This is the way to invoke a script with all the bells and568 whistles as command line application. This will always terminate
1046 unmodified lines