-
Notifications
You must be signed in to change notification settings - Fork 3
/
gh-hook.cgi
executable file
·115 lines (87 loc) · 2.76 KB
/
gh-hook.cgi
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
#!/usr/bin/env python3
import cgitb
import hashlib
import hmac
import json
import os
import re
import sys
import time
import traceback
import carpetbag
basedir = os.path.dirname(os.path.realpath(__file__))
secretfile = os.path.join(basedir, 'secret')
def parse_iso8601_time(s):
time_format = '%Y-%m-%dT%H:%M:%SZ' # e.g. "2021-05-27T20:38:23Z"
st = time.strptime(s, time_format)
t = time.mktime(st)
return int(t)
def process(data):
j = json.loads(data)
with open(os.path.join(basedir, 'last.json'), 'w') as f:
print(json.dumps(j, sort_keys=True, indent=4), file=f)
if j.get('action', '') != 'completed':
return None
# ensure this event is for the repository we are installed on
if j.get('repository', {}).get('full_name', '') != 'cygwin/scallywag':
return None
wfr = j.get('workflow_run', None)
if not wfr:
return None
u = carpetbag.Update()
u.backend_id = wfr['id']
u.buildurl = wfr['html_url']
u.duration = parse_iso8601_time(wfr['updated_at']) - parse_iso8601_time(wfr['created_at'])
# extract build_id from the title
title = wfr['display_title']
match = re.search(r'\((.*)\)', title)
if match:
u.buildnumber = int(match.group(1))
if wfr['conclusion'] == 'success':
u.status = 'build succeeded'
elif wfr['conclusion'] == 'cancelled':
u.status = 'cancelled'
else:
u.status = 'build failed'
return u
def hook():
if os.environ['REQUEST_METHOD'] != 'POST':
return '400 Bad Request', ''
if not os.path.exists(secretfile):
return '401 Unauthorized', ''
with open(secretfile) as f:
secret = f.read().strip()
data = sys.stdin.read()
sig = 'sha256=' + hmac.new(secret.encode(), data.encode(),
hashlib.sha256).hexdigest()
trysig = os.environ.get('HTTP_X_HUB_SIGNATURE_256', '')
if trysig != sig:
return '401 Unauthorized', ''
u = process(data)
if u:
# ensure backend_id is set, if it was previously unknown due to timeout waiting for it to be assigned
if hasattr(u, 'buildnumber'):
carpetbag.update_backend_id(u)
carpetbag.update_status(u)
return '200 OK', ''
def test():
with open(os.path.join(basedir, 'last.json')) as f:
data = f.read()
u = process(data)
if u:
carpetbag.update_status(u)
if __name__ == '__main__':
cgitb.enable()
try:
status, content = hook()
print('Status: %s' % status)
print()
print(content)
except BaseException:
# log exception to stderr
traceback.print_exc()
# allow cgitb to do it's thing
print('Content-Type: text/plain')
print('Status: 422')
print()
raise