forked from sipb/zcommit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzcommit.py
More file actions
executable file
·168 lines (146 loc) · 5.69 KB
/
Copy pathzcommit.py
File metadata and controls
executable file
·168 lines (146 loc) · 5.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
#!/usr/bin/python
import cherrypy
from flup.server.fcgi import WSGIServer
import logging
import json
import os
import subprocess
import sys
import traceback
import dateutil.parser
import zephyr
HERE = os.path.abspath(os.path.dirname(__file__))
ZWRITE = os.path.join(HERE, 'bin', 'zsend')
ZWRITE = '/usr/bin/zwrite'
LOG_FILENAME = 'logs/zcommit.log'
# Set up a specific logger with our desired output level
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# Add the log message handler to the logger
handler = logging.FileHandler(LOG_FILENAME)
logger.addHandler(handler)
formatter = logging.Formatter(fmt='%(levelname)-8s %(asctime)s %(message)s')
handler.setFormatter(formatter)
def send_zephyr(sender, klass, instance, zsig, msg):
# TODO: spoof the sender
logger.info("""About to send zephyr:
\"\"\"
sender: %(sender)s
class: %(klass)s
instance: %(instance)s
zsig: %(zsig)s
msg: %(msg)s
\"\"\"
""" % {'sender' : sender,
'klass' : klass,
'instance' : instance,
'zsig' : zsig,
'msg' : msg})
#z = zephyr.ZNotice()
#z.sender = sender
#z.cls = klass
#z.instance = instance
#z.fields = [ zsig, msg ]
#z.send()
cmd = [ZWRITE, '-c', klass, '-i', instance,
'-s', zsig, '-d', '-m', msg]
output = subprocess.check_output([p.encode('utf-8') for p in cmd])
class Application(object):
@cherrypy.expose
def index(self):
logger.debug('Hello world app reached')
return """
<p> <i>Welcome to zcommit.</i> </p>
<p> zcommit allows you to send zephyr notifications by sending an HTTP
POST request to a URL. Currently zcommit supports POST-backs from
github. If you would like it to support another form of POST-back,
please let us know (zcommit@mit.edu). </p>
<h1> URL structure </h1>
The URL you post to is structured as follows:
<tt>http://zcommit.mit.edu/$type/$key1/$value1/$key2/$value2/...</tt>.
So for example, the URL
<tt>http://zcommit.mit.edu/github/class/zcommit/instance/commit</tt>
is parsed as having type <tt>github</tt>, class <tt>zcommit</tt>, and
instance <tt>commit</tt>. Using this information, zcommit figures out
how to form a useful message which is then sends as a zephyr.
<h1> Types </h1>
<h2> Github </h2>
Set your POST-back URL to
<tt>http://zcommit.mit.edu/github/class/$classname</tt>, followed by
any of the following optional key/value parameters:
<ul>
<li> <tt>/instance/$instance</tt> </li>
<li> <tt>/zsig/$zsig</tt> (sets the prefix of the zsig; the postfix is always the branch name) </li>
<li> <tt>/sender/$sender</tt> </li>
</ul>
"""
class Github(object):
@cherrypy.expose
def default(self, *args, **query):
try:
return self._default(*args, **query)
except Exception, e:
logger.error('Caught exception %s:\n%s' % (e, traceback.format_exc()))
raise
def _default(self, *args, **query):
logger.info('A %s request with args: %r and query: %r' %
(cherrypy.request.method, args, query))
opts = {}
if len(args) % 2:
raise cherrypy.HTTPError(400, 'Invalid submission URL')
logger.debug('Passed validation')
for i in xrange(0, len(args), 2):
opts[args[i]] = unicode(args[i + 1], 'utf-8', 'replace')
logger.debug('Set opts')
if 'class' not in opts:
raise cherrypy.HTTPError(400, 'Must specify a zephyr class name')
logger.debug('Specified a class')
if cherrypy.request.method == 'POST':
logger.debug('About to load data')
payload = json.loads(query['payload'])
logger.debug('Loaded payload data')
zsig = payload['ref']
if 'zsig' in opts:
zsig = '%s: %s' % (opts['zsig'], zsig)
sender = opts.get('sender', 'daemon.zcommit')
logger.debug('Set zsig')
for c in payload['commits']:
inst = opts.get('instance', c['id'][:8])
actions = []
if c.get('added'):
actions.extend(' A %s\n' % f for f in c['added'])
if c.get('removed'):
actions.extend(' D %s\n' % f for f in c['removed'])
if c.get('modified'):
actions.extend(' M %s\n' % f for f in c['modified'])
if not actions:
actions.append('Did not add/remove/modify any nonempty files.')
info = {'name' : c['author']['name'],
'email' : c['author']['email'],
'message' : c['message'],
'timestamp' : dateutil.parser.parse(c['timestamp']).strftime('%F %T %z'),
'actions' : ''.join(actions),
'url' : c['url']}
msg = """%(url)s
Author: %(name)s <%(email)s>
Date: %(timestamp)s
%(message)s
---
%(actions)s""" % info
send_zephyr(sender, opts['class'], inst, zsig, msg)
msg = 'Thanks for posting!'
else:
msg = ('If you had sent a POST request to this URL, would have sent'
' a zephyr to -c %s' % opts['class'])
return msg
github = Github()
def main():
app = cherrypy.tree.mount(Application(), '/zcommit')
cherrypy.server.unsubscribe()
cherrypy.engine.start()
try:
WSGIServer(app, environ={'SCRIPT_NAME' : '/zcommit'}).run()
finally:
cherrypy.engine.stop()
if __name__ == '__main__':
sys.exit(main())