Skip to content

Instantly share code, notes, and snippets.

@moqada
Created October 24, 2012 06:45
Show Gist options
  • Save moqada/3944428 to your computer and use it in GitHub Desktop.
Save moqada/3944428 to your computer and use it in GitHub Desktop.
Server for GitLab hooks
# -*- coding: utf-8 -*-
"""
=======================
Server for GitLab hooks
=======================
notifications via email
Usage::
pip install gunicorn
gunicorn hooks:app -D
"""
import os
import json
import smtplib
from email.MIMEText import MIMEText
from email.Utils import formatdate
from wsgiref.simple_server import make_server
SERVER_PORT = 8080
FROM_ADDR = os.environ['GITLABHOOKS_FROM_ADDR']
TO_ADDR = os.environ['GITLABHOOKS_TO_ADDR']
def parse_json(request_json):
""" GitLab's pushed json
"""
data = json.loads(request_json)
username = data['user_name']
branch = data['ref'].split('/', 2)[-1]
commits_count = data['total_commits_count']
return {
'username': username,
'branch': branch,
'commits': data['commits'],
'commits_count': commits_count
}
def generate_subject(data):
""" Generage email subject
"""
if data['commits_count'] > 0:
return "#gitlog: %(username)s pushed %(commits_count)s commits to %(branch)s" % data
else:
return "#gitlog: %(username)s pushed new branch %(branch)s" % data
def generate_body(data):
""" Generate email body
"""
rows = []
for ci in data['commits']:
msg = ci['message'].split('\n', 1)[0]
if len(msg) > 60:
msg = u'%s...' % msg[:60]
msg = u'[%s] %s - %s' % (data['branch'], msg, ci['author']['name'])
msg = u'%s\n%s' % (msg, ci['url'])
rows.append(msg)
data.update(commits='\n'.join(rows))
body = u"""
%(commits)s""" % data
return body
def sendmail(subject, body):
""" Send email
"""
s = smtplib.SMTP()
s.connect()
msg = MIMEText(body.encode('utf-8'))
msg['Subject'] = subject
msg['Form'] = FROM_ADDR
msg['To'] = TO_ADDR
msg['Date'] = formatdate()
s.sendmail(FROM_ADDR, [TO_ADDR], msg.as_string())
s.close()
def app(environ, start_response):
""" WSGI Server
@ref: http://stackoverflow.com/questions/775396/how-to-catch-post-using-wsgiref
"""
method = environ['REQUEST_METHOD']
status = '200 OK'
if method == 'POST':
request_body_size = int(environ['CONTENT_LENGTH'])
request_body = environ['wsgi.input'].read(request_body_size)
data = parse_json(request_body)
sendmail(generate_subject(data), generate_body(data))
response_body = str(request_body)
headers = [('Content-type', 'text/plain')]
start_response(status, headers)
return [response_body]
response_body = 'Success'
headers = [
('Content-type', 'text/html'),
('Content-Length', str(len(response_body)))
]
start_response(status, headers)
return [response_body]
httpd = make_server('', SERVER_PORT, app)
print 'Serviing HTTP on port %s...' % SERVER_PORT
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment