bainternet
4/26/2015 - 1:24 PM

post-receive.py

#!/usr/bin/env python

"""
To use this you have to include the task ID on the commit message.
Example: Fixing typo, #9283764018

You can as well close a task within the commit message.
Example: Improving the docs, closes #9823761989
"""

import sys
import subprocess
import re
from asana import asana

API_KEY = 'YOURKEY'

def get_commit_info(hash):
    p = subprocess.Popen(['git', 'show', '--pretty=format:%cn%n%B', '-s', hash], 
                         stdout=subprocess.PIPE)

    lines = p.stdout.read().strip().split("\n")

    author = lines[0].strip()
    description = "\n".join([l.strip() for l in lines[1:]])

    task = re.findall('#(\d+)', description)
    closes = re.findall('closes #(\d+)', description)

    if len(task) > 0:
        task = int(task[0])
    else:
        return None

    closes = len(closes) > 0

    return dict(
        author = author,
        task = task,
        description = description,
        closes = closes,
    )

def post_to_asana(task, hash, author, description, ref, close=False):
    api = asana.AsanaAPI(API_KEY, debug=False)
    message = "%s commited on %s branch\n%s\nhttp://gitlist.example.com/repository.git/commit/%s" % (author, ref, description, hash)
    api.add_story(task, message)

    if close:
        api.update_task(task, completed=True)

if __name__ == '__main__':
    for line in sys.stdin.xreadlines():
        old, new, ref = line.strip().split(' ')

        commit = get_commit_info(new)

        if commit != None:
            post_to_asana(task=commit['task'], author=commit['author'], hash=new, close=commit['closes'],
                description=commit['description'], ref=ref.replace('refs/heads/', ''))