import click
import functools


def pass_runtime(func=None, require_project=True, require_keychain=False):
    """Decorator which passes the CCI runtime object as the first arg to a click command."""

    def decorate(func):
        @click.pass_context
        def new_func(ctx, *args, **kw):
            runtime = ctx.obj
            if require_project and runtime.project_config is None:
                raise runtime.project_config_error
            if require_keychain:
                runtime._load_keychain()
            func(runtime, *args, **kw)

        return functools.update_wrapper(new_func, func)

    if func is None:
        return decorate
    else:
        return decorate(func)