Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a custom decorator to a fabric task

Well, I must admit I'm new to fabric and even python but I'm interested in doing it the right way, so... I want to decorate some of my tasks with a prepare function which adds some vars to env depending on those already given. Have a look:

from fabric.api import *
import fabstork.project.base as base
import fabstork.utils.drupal as utils

def prepare(task):
    """ Decorator to set some additional environment variables """
    def prepared(*args, **kwargs):
        env.sites_folder = env.sites_folder if 'sites_folder' in env else 'default'
        env.settings_file = "%s/www/sites/%s/settings.php" % (env.build_path, env.sites_folder)
        # more to come
        return task(*args, **kwargs)

    return prepared


@task
@prepare
def push(ref='HEAD'):
    """
    Deploy a commit to a host
    """
    base.push(ref)
    utils.settings_php()
    utils.link_files()
    utils.set_perms()

The above example fails for that push is no task anymore, its not in the list of available tasks when doing a fab --list at the command line. Omitting the decorator leads to a perfect task. What am I doing wrong?

like image 278
aaki Avatar asked Jun 20 '13 18:06

aaki


1 Answers

from fabric.decorators import task
from functools import wraps

def custom_decorator(func):
    @wraps(func)
    def decorated(*args, **kwargs):
        print "this function is decorated."
        return func(*args, **kwargs)
    return decorated

@task
@custom_decorator
def some_function():
    print "this is function"

result:

# fab -l
>Available commands:
>
>    some_function

# fab some_function
>this function is decorated.
>this is function
>
>Done.
like image 89
Yuichiro Avatar answered Sep 19 '22 16:09

Yuichiro