Skip to content
Myr

Added support for object ensuring

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 083d566 · Browse files · 4 files+155 added−7 removed
This commit

State

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

Diff stats

4 files+155 added−7 removed

  • tests:+93 added−0 removed
  • other:+62 added−7 removed

4 files+155 added−7 removed

modified:click/core.py+9 added
131 unmodified lines
132 if isinstance(node.obj, object_type):133 return node.obj134 node = node.parent135136 def ensure_object(self, object_type):137 """Like :meth:`find_object` but sets the innermost object to a138 new instance of `object_type` if it does not exist.139 """140 rv = self.find_object(object_type)141 if rv is None:142 self.obj = rv = object_type()143 return rv144145 def fail(self, message):146 """Aborts the execution of the program with a specific error147 message.148
796 unmodified lines
modified:click/decorators.py+9 added-2 removed
23 unmodified lines
24 return ctx.invoke(f, ctx.obj, *args[1:], **kwargs)25 return update_wrapper(new_func, f)262728def make_pass_decorator(object_type):28def make_pass_decorator(object_type, ensure=False):29 """Given an object type this creates a decorator that will work30 similar to :func:`pass_obj` but instead of passing the object of the31 current context, it will find the innermost context of type32 :func:`object_type`.
8 unmodified lines
41 obj = ctx.find_object(object_type)42 return ctx.invoke(f, obj, *args, **kwargs)43 return update_wrapper(new_func, f)44 return decorator4546 :param object_type: the type of the object to pass.47 :param ensure: if set to `True`, a new object will be created and48 remembered on the context if it's not there yet.49 """50 def decorator(f):51 @pass_context52 def new_func(*args, **kwargs):53 ctx = args[0]54 if ensure:55 obj = ctx.ensure_object(object_type)56 else:50 obj = ctx.find_object(object_type)57 obj = ctx.find_object(object_type)58 if obj is None:59 raise RuntimeError('Managed to invoke callback without a '60 'context object of type %r existing'61 % object_type.__name__)
204 unmodified lines
modified:docs/complex.rst+44 added-5 removed
80 unmodified lines
81 import click828384 class Repo(object):85 def __init__(self, home, debug):86 self.home = os.path.abspath(home)85 def __init__(self, home=None, debug=False):86 self.home = os.path.abspath(home or '.')87 self.debug = debug888990 @click.group()
67 unmodified lines
158created 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`162factory which will create decorators for us that find objects. So in our163case we know that we want to find the closest ``Repo`` object. So let's164make a decorator for this:162factory 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:166167.. click:example::168169 pass_repo = click.make_pass_decorator(Repo)
8 unmodified lines
178 @click.argument('dest', required=False)179 @pass_repo180 def clone(repo, src, dest):181 pass182183Ensuring 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, [])
added:tests/test_context.py+93 added
1# -*- coding: utf-8 -*-2import click345def test_ensure_context_objects(runner):6 class Foo(object):7 def __init__(self):8 self.title = 'default'910 pass_foo = click.make_pass_decorator(Foo, ensure=True)1112 @click.group()13 @pass_foo14 def cli(foo):15 pass1617 @cli.command()18 @pass_foo19 def test(foo):20 click.echo(foo.title)2122 result = runner.invoke(cli, ['test'])23 assert not result.exception24 assert result.output == 'default\n'252627def test_get_context_objects(runner):28 class Foo(object):29 def __init__(self):30 self.title = 'default'3132 pass_foo = click.make_pass_decorator(Foo, ensure=True)3334 @click.group()35 @click.pass_context36 def cli(ctx):37 ctx.obj = Foo()38 ctx.obj.title = 'test'3940 @cli.command()41 @pass_foo42 def test(foo):43 click.echo(foo.title)4445 result = runner.invoke(cli, ['test'])46 assert not result.exception47 assert result.output == 'test\n'484950def test_get_context_objects_no_ensuring(runner):51 class Foo(object):52 def __init__(self):53 self.title = 'default'5455 pass_foo = click.make_pass_decorator(Foo)5657 @click.group()58 @click.pass_context59 def cli(ctx):60 ctx.obj = Foo()61 ctx.obj.title = 'test'6263 @cli.command()64 @pass_foo65 def test(foo):66 click.echo(foo.title)6768 result = runner.invoke(cli, ['test'])69 assert not result.exception70 assert result.output == 'test\n'717273def test_get_context_objects_missing(runner):74 class Foo(object):75 pass7677 pass_foo = click.make_pass_decorator(Foo)7879 @click.group()80 @click.pass_context81 def cli(ctx):82 pass8384 @cli.command()85 @pass_foo86 def test(foo):87 click.echo(foo.title)8889 result = runner.invoke(cli, ['test'])90 assert result.exception is not None91 assert isinstance(result.exception, RuntimeError)92 assert "Managed to invoke callback without a context object " \93 "of type 'Foo' existing" in str(result.exception)