forked from metajack/notify-webhook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotify-webhook.py
executable file
·152 lines (127 loc) · 4.29 KB
/
notify-webhook.py
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
#!/usr/bin/env python
import sys
import urllib, urllib2
import re
import os
import subprocess
from datetime import datetime
import simplejson as json
def git(args):
args = ['git'] + args
git = subprocess.Popen(args, stdout = subprocess.PIPE)
details = git.stdout.read()
details = details.strip()
return details
def get_config(key):
details = git(['config', '%s' % (key)])
if len(details) > 0:
return details
else:
return None
def get_repo_name():
if git(['rev-parse','--is-bare-repository']) == 'true':
name = os.path.basename(os.getcwd())
if name.endswith('.git'):
name = name[:-4]
return name
else:
return os.path.basename(os.path.dirname(os.getcwd()))
POST_URL = get_config('hooks.webhookurl')
POST_USER = get_config('hooks.authuser')
POST_PASS = get_config('hooks.authpass')
REPO_URL = get_config('meta.url')
COMMIT_URL = get_config('meta.commiturl')
if COMMIT_URL == None and REPO_URL != None:
COMMIT_URL = REPO_URL + r'/commit/%s'
REPO_NAME = get_repo_name()
REPO_DESC = ""
try:
REPO_DESC = get_config('meta.description') or open('description', 'r').read()
except Exception:
pass
REPO_OWNER_NAME = get_config('meta.ownername')
REPO_OWNER_EMAIL = get_config('meta.owneremail')
if REPO_OWNER_NAME is None:
REPO_OWNER_NAME = git(['log','--reverse','--format=%an']).split("\n")[0]
if REPO_OWNER_EMAIL is None:
REPO_OWNER_EMAIL = git(['log','--reverse','--format=%ae']).split("\n")[0]
EMAIL_RE = re.compile("^(.*) <(.*)>$")
def get_revisions(old, new):
git = subprocess.Popen(['git', 'rev-list', '--pretty=medium', '--reverse', '%s..%s' % (old, new)], stdout=subprocess.PIPE)
sections = git.stdout.read().split('\n\n')[:-1]
revisions = []
s = 0
while s < len(sections):
lines = sections[s].split('\n')
# first line is 'commit HASH\n'
props = {'id': lines[0].strip().split(' ')[1]}
# read the header
for l in lines[1:]:
key, val = l.split(' ', 1)
props[key[:-1].lower()] = val.strip()
# read the commit message
props['message'] = sections[s+1]
# use github time format
basetime = datetime.strptime(props['date'][:-6], "%a %b %d %H:%M:%S %Y")
tzstr = props['date'][-5:]
props['date'] = basetime.strftime('%Y-%m-%dT%H:%M:%S') + tzstr
# split up author
m = EMAIL_RE.match(props['author'])
if m:
props['name'] = m.group(1)
props['email'] = m.group(2)
else:
props['name'] = 'unknown'
props['email'] = 'unknown'
del props['author']
revisions.append(props)
s += 2
return revisions
def make_json(old, new, ref):
data = {
'before': old,
'after': new,
'ref': ref,
'repository': {
'url': REPO_URL,
'name': REPO_NAME,
'description': REPO_DESC,
'owner': {
'name': REPO_OWNER_NAME,
'email': REPO_OWNER_EMAIL
}
}
}
revisions = get_revisions(old, new)
commits = []
for r in revisions:
url = None
if COMMIT_URL != None:
url = COMMIT_URL % r['id']
commits.append({'id': r['id'],
'author': {'name': r['name'], 'email': r['email']},
'url': url,
'message': r['message'],
'timestamp': r['date']
})
data['commits'] = commits
return json.dumps(data)
def post(url, data):
if POST_USER is not None or POST_PASS is not None:
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, POST_URL, POST_USER, POST_PASS)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(handler)
u = opener.open(POST_URL, urllib.urlencode({'payload': data}))
else:
u = urllib2.urlopen(POST_URL, urllib.urlencode({'payload': data}))
u.read()
u.close()
if __name__ == '__main__':
for line in sys.stdin.xreadlines():
old, new, ref = line.strip().split(' ')
data = make_json(old, new, ref)
if POST_URL:
post(POST_URL, data)
else:
print(data)