util

Helpers and decorators, primarily for internal or advanced use.

patchwork.util.set_runner(f)

Set 2nd posarg of decorated function to some callable runner.

The final value of runner depends on other args given to the decorated function (note: not the decorator itself!) as follows:

  • By default, runner is set to the run method of the first positional arg, which is expected to be a Context (or subclass). Thus the default runner is Context.run (or, if the function was given a Fabric Connection, Connection.run).
  • You can override which method on the context is selected, by handing an attribute name string to runner_method.
  • Since the common case for overriding the runner is to trigger use of sudo, there is a convenient shorthand: giving sudo=True.
  • Finally, you may give a callable object to runner directly, in which case nothing special really happens (it’s largely as if you called the function undecorated, albeit with a kwarg instead of a positional argument). This is mostly useful for cases where you’re calling one decorated function from within another.

Given this function:

@set_runner
def function(c, runner, arg1, arg2=None):
    runner("some command based on arg1 and arg2")

one may call it without any runner-related arguments, in which case runner ends up being a reference to c.run:

function(c, "my-arg1", arg2="my-arg2")

or one may specify sudo to trigger use of c.sudo:

function(c, "my-arg1", arg2="my-arg2", sudo=True)

If one is using a custom Context subclass with other command runner methods, one may give runner_method explicitly:

class AdminContext(Context):
    def run_admin(self, *args, **kwargs):
        kwargs["user"] = "admin"
        return self.sudo(*args, **kwargs)

function(AdminContext(), "my-arg1", runner_method="run_admin")

As noted above, you can always give runner (as a kwarg) directly to avoid most special processing:

function(c, "my-arg1", runner=some_existing_runner_object)

Note

If more than one of the runner_method, sudo or runner kwargs are given simultaneously, only one will win, in the following order: runner, then runner_method, then sudo.

Note

As part of the signature modification, set_runner also modifies the resulting value’s docstring as follows:

  • Prepends a Sphinx autodoc compatible signature string, which is stripped out automatically on doc builds; see the Sphinx autodoc_docstring_signature setting.
  • Adds trailing :param: annotations for the extra args as well.