/
validate.py
199 lines (156 loc) · 5.25 KB
/
validate.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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import os
import random
import re
import requests
import subprocess
import time
def request(url):
request_headers = {'User-Agent': 'jeffkaufman/nomic'}
response = requests.get(url, headers=request_headers)
for header in ['X-RateLimit-Limit',
'X-RateLimit-Remaining',
'X-RateLimit-Reset']:
if header in response.headers:
print(' > %s: %s' % (header, response.headers[header]))
if response.status_code != 200:
print(' > %s' % response.content)
response.raise_for_status()
return response
def get_repo():
return os.environ['TRAVIS_REPO_SLUG']
def get_pr():
return os.environ['TRAVIS_PULL_REQUEST']
def get_commit():
return os.environ['TRAVIS_PULL_REQUEST_SHA']
def base_pr_url():
# This is configured in nginx like:
#
# location /nomic-github/repos/jeffkaufman/nomic {
# proxy_pass https://api.github.com/repos/jeffkaufman/nomic;
# proxy_set_header
# Authorization
# "Basic [base64 of 'username:token']";
# }
#
# Where the token is a github personal access token:
# https://github.com/settings/tokens
#
# There's an API limit of 60/hr per IP by default, and 5000/hr by
# user, and we need the higher limit.
return 'https://www.jefftk.com/nomic-github/repos/%s/pulls/%s' % (
get_repo(), get_pr())
def get_author():
response = request(base_pr_url())
return response.json()['user']['login']
def get_reviews():
target_commit = get_commit()
print('Considering reviews at commit %s' % target_commit)
url = '%s/reviews' % base_pr_url()
reviews = {}
while True:
response = request(url)
for review in response.json():
user = review['user']['login']
commit = review['commit_id']
state = review['state']
print(' %s: %s at %s' % (user, state, commit))
if state == 'APPROVED' and commit != target_commit:
# Only accept approvals for the most recent commit, but have rejections
# last until overridden.
continue
if state == 'COMMENTED':
continue # Ignore comments.
reviews[user] = state
if 'next' in response.links:
url = response.links['next']['url']
else:
return reviews
def get_users():
return list(sorted(os.listdir('players/')))
def get_user_points():
points = {}
for user in get_users():
points[user] = 0
with open(os.path.join('players', user)) as inf:
try:
points[user] += int(inf.read())
except ValueError:
pass
cmd = ['git', 'log', 'master', '--first-parent', '--format=%s']
completed_process = subprocess.run(cmd, stdout=subprocess.PIPE)
if completed_process.returncode != 0:
raise Exception(completed_process)
process_output = completed_process.stdout.decode('utf-8')
merge_regexp = '^Merge pull request #[\\d]* from ([^/]*)/'
for commit_subject in process_output.split('\n'):
match = re.match(merge_regexp, commit_subject)
if match:
commit_username, = match.groups()
if commit_username in points:
points[commit_username] += 1
return points
def last_commit_ts():
# When was the last commit on master?
cmd = ['git', 'log', 'master', '-1', '--format=%ct']
completed_process = subprocess.run(cmd, stdout=subprocess.PIPE)
if completed_process.returncode != 0:
raise Exception(completed_process)
return int(completed_process.stdout)
def seconds_since_last_commit():
return int(time.time() - last_commit_ts())
def days_since_last_commit():
return int(seconds_since_last_commit() / 60 / 60 / 24)
def determine_if_mergeable():
users = get_users()
print('Users:')
for user in users:
print(' %s' % user)
author = get_author()
print('\nAuthor: %s' % author)
reviews = get_reviews()
if author in users:
reviews[author] = 'APPROVED'
print('\nReviews:')
for user, state in sorted(reviews.items()):
print (' %s: %s' % (user, state))
approvals = []
rejections = []
for user in users:
if user in reviews:
review = reviews[user]
if review == 'APPROVED':
approvals.append(user)
else:
rejections.append(user)
if rejections:
raise Exception('Rejected by: %s' % (' '.join(rejections)))
required_approvals = len(users)
# Allow three days to go by with no commits, but if longer happens then start
# lowering the threshold for allowing a commit.
approvals_to_skip = days_since_last_commit() - 3
if approvals_to_skip > 0:
print("Skipping up to %s approvals, because it's been %s days"
" since the last commit." % (approvals_to_skip,
days_since_last_commit()))
required_approvals -= approvals_to_skip
print('Approvals: got %s (%s) needed %s' % (
len(approvals), ' '.join(approvals), required_approvals))
if len(approvals) < required_approvals:
raise Exception('Insufficient approval')
print('\nPASS')
def determine_if_winner():
print('Points:')
for user, user_points in get_user_points().items():
print(' %s: %s' % (user, user_points))
users = get_users()
for user in users:
if random.random() < 0.0001:
raise RuntimeException('%s wins!' % user)
print('The game continues.')
def start():
if get_pr() == 'false':
determine_if_winner()
else:
determine_if_mergeable()
if __name__ == '__main__':
start()