]> andersk Git - zcommit.git/blob - zcommit.py
71984c7ef298bcf5f5e9f4167867787d78e4c8fa
[zcommit.git] / zcommit.py
1 #!/usr/bin/python
2
3 import cherrypy
4 from flup.server.fcgi import WSGIServer
5 import logging
6 import json
7 import os
8 import subprocess
9 import sys
10 import traceback
11
12 HERE = os.path.dirname(__file__)
13 os.environ['KRBTKFILE'] = os.path.join(HERE, 'tkt')
14 LOG_FILENAME = 'logs/zcommit.log'
15
16 # Set up a specific logger with our desired output level
17 logger = logging.getLogger(__name__)
18 logger.setLevel(logging.DEBUG)
19
20 # Add the log message handler to the logger
21 handler = logging.FileHandler(LOG_FILENAME)
22 logger.addHandler(handler)
23
24 def zephyr(klass, instance, zsig, msg):
25     # TODO: spoof the sender
26     logger.info("""About to send zephyr:
27 class: %(klass)s
28 instance: %(instance)s
29 zsig: %(zsig)s
30 msg: %(msg)s""" % {'klass' : klass, 'instance' : instance,
31                  'zsig' : zsig, 'msg' : msg})
32     cmd = ['zwrite', '-c', klass, '-i', instance,
33            '-s', zsig, '-d', '-m', msg]
34     subprocess.check_call(cmd)
35
36 class Application(object):
37     @cherrypy.expose
38     def index(self):
39         logger.debug('Hello world app reached')
40         return 'Hello world!'
41
42     class Github(object):
43         @cherrypy.expose
44         def default(self, *args, **query):
45             try:
46                 return self._default(*args, **query)
47             except Exception, e:
48                 logger.error('Caught exception %s:\n%s' % (e, traceback.format_exc()))
49                 raise
50
51         def _default(self, *args, **query):
52             logger.info('A %s request with args: %r and query: %r' %
53                         (cherrypy.request.method, args, query))
54             opts = {}
55             if len(args) % 2:
56                 raise cherrypy.HTTPError(400, 'Invalid submission URL')
57             logger.debug('Passed validation')
58             for i in xrange(0, len(args), 2):
59                 opts[args[i]] = args[i + 1]
60             logger.debug('Set opts')
61             if 'class' not in opts:
62                 raise cherrypy.HTTPError(400, 'Must specify a zephyr class name')
63             logger.debug('Specified a class')
64             if cherrypy.request.method == 'POST':
65                 logger.debug('About to load data')
66                 payload = json.loads(query['payload'])
67                 logger.debug('Loaded payload data')
68                 zsig = payload['ref']
69                 if 'zsig' in opts:
70                     zsig = '%s: %s' % (opts['zsig'], zsig)
71                 logger.debug('Set zsig')
72                 for c in reversed(payload['commits']):
73                     inst = opts.get('instance', c['id'][:8])
74                     actions = []
75                     if c.get('added'):
76                         actions.append('Added: %s\n' % ', '.join(c['added']))
77                     if c.get('removed'):
78                         actions.append('Removed: %s\n' % ', '.join(c['removed']))
79                     if c.get('modified'):
80                         actions.append('Modified: %s\n' % ', '.join(c['modified']))
81                     if not actions:
82                         actions.append('Something weird happened... could not figure out what action to take')
83                     info = {'name' : c['author']['name'],
84                             'email' : c['author']['email'],
85                             'message' : c['message'],
86                             'timestamp' : c['timestamp'],
87                             'actions' : '\n--\n'.join(actions)}
88                     
89                     msg = """%(name)s <%(email)s>
90 %(message)s
91 %(timestamp)s
92 --
93 %(actions)s""" % info
94                     zephyr(opts['class'], inst, zsig, msg)
95                 msg = 'Thanks for posting!'
96             else:
97                 msg = ('If you had sent a POST request to this URL, would have sent'
98                        ' a zepyhr to -c %s' % opts['class'])
99             return msg
100
101     github = Github()
102
103 def main():
104     app = cherrypy.tree.mount(Application(), '/zcommit')
105     cherrypy.server.unsubscribe()
106     cherrypy.engine.start()
107     try:
108         WSGIServer(app, environ={'SCRIPT_NAME' : '/zcommit'}).run()
109     finally:
110         cherrypy.engine.stop()
111
112 if __name__ == '__main__':
113     sys.exit(main())
This page took 0.107122 seconds and 3 git commands to generate.