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
Provenance
- Commit
8512acd- Tree
78ff22a- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
083d566
4 files changed+155 added−7 removed
modified:click/core.py+9 added
131 unmodified lines132 if isinstance(node.obj, object_type):133 return node.obj134 node = node.parent135 136+ 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 rv144+145 def fail(self, message):146 """Aborts the execution of the program with a specific error147 message.148 796 unmodified linesmodified:click/decorators.py+9 added-2 removed
23 unmodified lines24 return ctx.invoke(f, ctx.obj, *args[1:], **kwargs)25 return update_wrapper(new_func, f)26 27 28-def make_pass_decorator(object_type):28+def 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 lines41 obj = ctx.find_object(object_type)42 return ctx.invoke(f, obj, *args, **kwargs)43 return update_wrapper(new_func, f)44 return decorator45+46+ :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 linesmodified:docs/complex.rst+44 added-5 removed
80 unmodified lines81 import click82 83 84 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 = debug88 89 90 @click.group()67 unmodified lines158 created our repo. Because of that we can start a search for the last159 level where the object stored on the context was a repo.160 161 Built-in support for this is provided by the :func:`make_pass_decorator`162-factory which will create decorators for us that find objects. So in our163-case we know that we want to find the closest ``Repo`` object. So let's164-make a decorator for this:162+factory which will create decorators for us that find objects (it163+internally calls into :meth:`Context.find_object`). So in our case we164+know that we want to find the closest ``Repo`` object. So let's make a165+decorator for this:166 167 .. click:example::168 169 pass_repo = click.make_pass_decorator(Repo)8 unmodified lines178 @click.argument('dest', required=False)179 @pass_repo180 def clone(repo, src, dest):181 pass182+183+Ensuring Objects184+````````````````185+186+The 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 use188+cases this might be a problem for you. The default behavior of189+:func:`make_pass_decorator` is to call into :meth:`Context.find_object`190+which will find the object. If it can't find the object it will raise an191+error. The alternative behavior is to use :meth:`Context.ensure_object`192+which will find the object, or if it cannot find it, will create one and193+store it on the innermost context. This behavior can also be enabled for194+:func:`make_pass_decorator` by passing ``ensure=True``:195+196+.. click:example::197+198+ pass_repo = click.make_pass_decorator(Repo, ensure=True)199+200+In this case the innermost context gets such an object created if it's201+missing. This might replace objects being placed there earlier. In this202+case the command stays executable, even if the outer command does not run.203+For this to work the object type needs to have a constructor that accepts204+no arguments.205+206+As such it runs standalone:207+208+.. click:example::209+210+ @click.command()211+ @pass_repo212+ def cp(repo):213+ click.echo(repo)214+215+As you can see:216+217+.. click:run::218+219+ invoke(cp, [])added:tests/test_context.py+93 added
1+# -*- coding: utf-8 -*-2+import click3+4+5+def test_ensure_context_objects(runner):6+ class Foo(object):7+ def __init__(self):8+ self.title = 'default'9+10+ pass_foo = click.make_pass_decorator(Foo, ensure=True)11+12+ @click.group()13+ @pass_foo14+ def cli(foo):15+ pass16+17+ @cli.command()18+ @pass_foo19+ def test(foo):20+ click.echo(foo.title)21+22+ result = runner.invoke(cli, ['test'])23+ assert not result.exception24+ assert result.output == 'default\n'25+26+27+def test_get_context_objects(runner):28+ class Foo(object):29+ def __init__(self):30+ self.title = 'default'31+32+ pass_foo = click.make_pass_decorator(Foo, ensure=True)33+34+ @click.group()35+ @click.pass_context36+ def cli(ctx):37+ ctx.obj = Foo()38+ ctx.obj.title = 'test'39+40+ @cli.command()41+ @pass_foo42+ def test(foo):43+ click.echo(foo.title)44+45+ result = runner.invoke(cli, ['test'])46+ assert not result.exception47+ assert result.output == 'test\n'48+49+50+def test_get_context_objects_no_ensuring(runner):51+ class Foo(object):52+ def __init__(self):53+ self.title = 'default'54+55+ pass_foo = click.make_pass_decorator(Foo)56+57+ @click.group()58+ @click.pass_context59+ def cli(ctx):60+ ctx.obj = Foo()61+ ctx.obj.title = 'test'62+63+ @cli.command()64+ @pass_foo65+ def test(foo):66+ click.echo(foo.title)67+68+ result = runner.invoke(cli, ['test'])69+ assert not result.exception70+ assert result.output == 'test\n'71+72+73+def test_get_context_objects_missing(runner):74+ class Foo(object):75+ pass76+77+ pass_foo = click.make_pass_decorator(Foo)78+79+ @click.group()80+ @click.pass_context81+ def cli(ctx):82+ pass83+84+ @cli.command()85+ @pass_foo86+ def test(foo):87+ click.echo(foo.title)88+89+ 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)