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