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
Provenance
- Commit
23d3f68- Tree
c014c84- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
8259846
7 files changed+322 added−24 removed
modified:docs/api.rst+4 added
23 unmodified lines24 .. autofunction:: version_option25 26 .. autofunction:: help_option27 28+.. autofunction:: pass_context29+30+.. autofunction:: pass_obj31+32 Helper Functions33 ----------------34 35 .. autofunction:: prompt54 unmodified linesmodified:docs/commands.rst+43 added-5 removed
63 unmodified lines64 Each time a command invokes a new context is created and linked with the65 parent context. Normally you can't see these contexts, but they are66 there. Contexts are passed to parameter callbacks together with the67 value automatically. Commands can also ask for the context to be passed68-by passing ``pass_context=True`` to the :func:`command` or :func:`group`69-decorator. In that case the context is passed as first argument.68+by marking themselves with the :func:`pass_context` decorator. In that69+case the context is passed as first argument.70 71 The context can also carry a program specified object that can be72 used for the program's purposes. What this means is that you can build a73 script like this::74 75 import click76 77- @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'] = debug82 82- @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'))87 88 if __name__ == '__main__':6 unmodified lines95 In addition to that instead of passing an object down nothing stops the96 application from modifying global state. For instance you could just flip97 a global ``DEBUG`` variable and be done with it.98 99+Decorating Commands100+-------------------101+102+As you have seen in the earlier example a decorator can change how a103+command is invoked. What actually happens behind the scenes is that104+callbacks are always invoked through the :meth:`Context.invoke` method105+which automatically invokes a command correctly (by either passing the106+context or not).107+108+This is very useful when you want to write custom decorators. For109+instance a common pattern would be to configure an object representing110+state and then storing it on the context and then to use a custom111+decorator to find the most recent object of this sort and pass it as first112+argument.113+114+For instance the :func:`pass_obj` decorator can be implemented like this::115+116+ import click117+ from functools import update_wrapper118+119+ 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)124+125+The :meth:`Context.invoke` command will automatically invoke the function126+in the correct way. So the function will either be called with ``f(ctx,127+obj)`` or ``f(obj)`` depending on if it itself is decorated with128+:func:`with_context`.129+130+This is a very powerful context that can be used to build very complex131+nested applications. See :ref:`complex-guide` for more information.132+133+134 Group Invocation Without Command135 --------------------------------136 137 By default a group or multi command is not invoked unless a subcommand is7 unmodified lines145 Example::146 147 import click148 112- @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 linesadded:docs/complex.rst+170 added
1+.. _complex-guide:2+3+Complex Applications4+====================5+6+.. currentmodule:: click7+8+Click is designed to write complex and simple CLI tools alike. However9+the power of it's design is the ability to arbitrarily nest systems10+together. For instance in case you have ever used Django you will have11+realized that it provides a command line utility. But so does Celery for12+instance. So when using Celery with Django there are two tools that need13+to interact with each other and be cross configured.14+15+In a theoretical world of two separate Click command line utilities they16+can solve this problem by nesting one inside the other. For instance the17+web framework could also load the commands for the message queue18+framework.19+20+Basic Concepts21+--------------22+23+To understand how this works you need to understand two concepts: contexts24+and the calling convention.25+26+Contexts27+--------28+29+Whenever a Click command is executed a :class:`Context` object is created30+which holds state for this particular invocation. For instance it31+remembers parsed parameters, what command created it, which resources need32+to be cleaned up at the end of the function and so forth. It also holds33+an application defined object optionally.34+35+Context objects build a linked list until they hit top one. Each context36+is linked to the parent context. This allows a command to work below37+another command and store it's own information there without having to be38+afraid of messing up the state of the parent command.39+40+Because the parent data is however available it's possible to navigate to41+it if needed.42+43+Most of the time you don't see the context object, but when writing more44+complex applications it comes in handy. This brings is to the next point45+46+Calling Convention47+------------------48+49+When a Click command callback is executed it's passed all the non hidden50+parameters as keyword arguments. Notably absent is the context. However51+a callback can opt-into being passed the context object by marking itself52+with :func:`pass_context`.53+54+So how do you invoke a command callback if you don't know if it should55+receive the context or not? The answer is that the context itself56+provides a helper function (:meth:`Context.invoke`) which can do this for57+you. It accepts the callback as first argument and then invokes the58+function correctly.59+60+Building a Git61+--------------62+63+In this example we want to build a command line tool that resembles a64+version control system a bit. Systems like git usually provide one65+over-arching command that already accepts some parameters and66+configuration, and then has extra subcommands that do other things.67+68+The Root Command69+````````````````70+71+At the toplevel we need a group that can hold all our commands. In this72+case we use the basic :func:`click.group` which allows us to register73+other click commands below it.74+75+For this command we also want to accept some parameters that configure the76+state of our tool::77+78+ import os79+ import click80+81+82+ class Repo(object):83+ def __init__(self, home, debug):84+ self.home = os.path.abspath(home)85+ self.debug = debug86+87+88+ @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)95+96+97+So let's understand what this does. We create a group command which can98+have subcommands. When it is invoked it will create an instance of a99+``Repo`` class. This holds the state for our command line tool. In this100+case it just remembers some parameters but at this point it could also101+start loading config files and so on.102+103+This state object is then remembered as :attr:`~Context.obj` on the104+context. This is a special attribute where commands are supposed to105+remember what they need to pass on to their children.106+107+In order for this to work we need to mark our function with108+:func:`pass_context` because otherwise the context object would be109+entirely hidden from us.110+111+The First Child Command112+```````````````````````113+114+So let's add our first child command to it. Let's go with the clone115+command::116+117+ @cli.command()118+ @click.argument('src')119+ @click.argument('dest', required=False)120+ def clone(src, dest):121+ pass122+123+So now we have a clone command, but how do we get access to the repo? As124+you can imagine one way is to use the :func:`pass_context` function which125+again will make our callback also get the context passed on which we126+memorized the repo. Even better there is a second version of this127+decorator called :func:`pass_obj` which will just pass the stored object,128+in our case the repo::129+130+ @cli.command()131+ @click.argument('src')132+ @click.argument('dest', required=False)133+ @click.pass_obj134+ def clone(repo, src, dest):135+ pass136+137+Interleaved Commands138+````````````````````139+140+While not relevant for this particular program we want to build there is141+also quite good support for interleaving systems. Imagine for instance142+there would be this super cool plugin for our version control system that143+needs 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,145+all the sudden we would get the plugin config instead of our repo object.146+147+One obvious way is to store a reference to the repo on the plugin but then148+a command needs to be aware that it's attached below such a plugin.149+150+There is a much better system by taking advantage of the linked nature of151+contexts. We know that the plugin context is linked to the context that152+created our repo. Because of that we can start a search for the last153+level where the object stored on the context was a repo.154+155+Built-in support for this is provided by the :func:`make_pass_decorator`156+factory which will create decorators for us that find objects. So in our157+case we know that we want to find the closest ``Repo`` object. So let's158+make a decorator for this::159+160+ pass_repo = click.make_pass_decorator(Repo)161+162+If we now use ``pass_repo`` instead of ``pass_obj`` we will always get a163+repo instead of something else::164+165+ @cli.command()166+ @click.argument('src')167+ @click.argument('dest', required=False)168+ @pass_repo169+ def clone(repo, src, dest):170+ passmodified:docs/index.rst+1 added
50 unmodified lines51 commands52 prompts53 documentation54 setuptools55+ complex56 57 API Reference58 -------------59 7 unmodified linesmodified:docs/why.rst+3 added
39 unmodified lines40 41 Click was written to support the `Flask <http://flask.pocoo.org/>`_42 microframework ecosystem because no tool could provide it with the43 functionality it needed.44+45+To get an understanding of what Click is all about I strongly recommend46+looking at the :ref:`complex-guide` chapter to see what it's useful for.modified:examples/repo/repo.py+27 added-6 removed
1+import os2 import click3 4 5+class Repo(object):6+7+ def __init__(self, home):8+ self.home = home9+10+ def __repr__(self):11+ return '<Repo %r>' % self.home12+13+14+pass_repo = click.make_pass_decorator(Repo)15+16+17 @click.group()5-@click.option('--repo-home', envvar='REPO_HOME')6-def cli(repo_home):18+@click.option('--repo-home', envvar='REPO_HOME', default='.repo')19+@click.pass_context20+def 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))26 27 28 @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_repo18-def clone(src, dest, shallow):34+def clone(repo, src, dest, shallow):35 """Clones a repository.36 37 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)45 46 47 @cli.command()48 @click.confirmation_option()49+@pass_repo32-def delete():50+def delete(repo):51 """Deletes a repository.52 53 This will throw away the current repository.54 """55+ print('Repo: %s' % repo)56 print('Deleted')57 58 59 @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_repo44-def setuser(username, email, password):64+def setuser(repo, username, email, password):65 """Sets the user credentials.66 67 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 lines21 import optparse22 import textwrap23 import struct24 from itertools import chain25+from functools import update_wrapper26 27 28 PY2 = sys.version_info[0] == 229 if PY2:137 unmodified lines167 file.write('\n')168 file.flush()169 170 171+def 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 f177+178+179+def 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)189+190+191+def 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`.196+197+ This generates a decorator that works roughly like this::198+199+ from functools import update_wrapper200+201+ 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 decorator221+222+223 class 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 lines330 while node.parent is not None:331 node = node.parent332 return node333 334+ 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.parent341+342 def fail(self, message):343 """Aborts the execution of the program with a specific error344 message.345 20 unmodified lines366 context and command.367 """368 return self._parser.format_help().rstrip()369 370+ 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)378 379+380 class UsageError(Exception):381 """An internal exception that signals a usage error. This typically382 aborts any further handling.383 """85 unmodified lines469 :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 = False480 416- 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 lines492 #: 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 lines559 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)565 566 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 terminate1046 unmodified lines