sbin/sync/fabfile.py
author ymh <ymh.work@gmail.com>
Tue, 06 Jan 2015 13:26:14 +0100
changeset 27 42e4b9c433cc
child 33 eb73a4e6881e
permissions -rw-r--r--
add deploy script

from fabric.api import env, local, put, run, cd, lcd, task, prefix
from fabric.contrib.files import exists
from fabric.colors import green
import tempfile
import shutil
import os
import settings


def __init():
    if not env.get('temp_folder', None):
        env['temp_folder'] = tempfile.mkdtemp()
        print(green("working folder is %s" % env['temp_folder']))

def __clean():
    if env.get('temp_folder', None):
        print(green("Removing %s" % env['temp_folder']))
        shutil.rmtree(env['temp_folder'])

def get_version_path():
    return os.path.join(env['temp_folder'], env['version'])

def export():
    local('hg archive -r %s %s' % (env['version'], get_version_path()) )

def pack():
    # create a new source distribution as tarball
    with lcd(get_version_path()):
        local('python setup.py sdist --formats=gztar', capture=False)

def create_virtualenv():
    with lcd(get_version_path()):
        tmpd = run('mktemp -d').strip()
        put('virtualenv/*.txt', tmpd)
        run('virtualenv -p /usr/bin/python3 %s' % env.srv_venv_path)
        with prefix('source %s/bin/activate' % env.srv_venv_path):
            run('pip install -r %s/requirements.txt' % tmpd)
            run('pip install -r %s/requirements_srvr.txt' % tmpd)
        run('rm -fr %s' % tmpd)


def deploy():
    # figure out the release name and version
    with lcd(get_version_path()):
        dist = local('python setup.py --fullname', capture=True).strip()
        print(green("dist is %s" % dist))

        # upload the source tarball to the temporary folder on the server
        put('dist/%s.tar.gz' % dist, '/tmp/%s.tar.gz' % dist)
        # create a place where we can unzip the tarball, then enter
        # that directory and unzip it
        # now setup the package with our virtual environment's
        # python interpreter
        with prefix('source %s/bin/activate' % env.srv_venv_path):
            run('pip install -U --force-reinstall /tmp/%s.tar.gz' % dist)
        # now that all is set up, delete the folder again

        run('rm -rf /tmp/%s.tar.gz' % dist)
        # # and finally touch the .wsgi file so that mod_wsgi triggers
        # # a reload of the application
        # run('touch /var/www/yourapplication.wsgi')

@task(default=True)
def deploy_version(version='tip'):
    env['version'] = version
    __init()
    export()
    pack()
    if not exists(env.srv_venv_path):
        create_virtualenv()
    deploy()
    __clean()