forked from barosl/homu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1660 lines (1356 loc) · 53.9 KB
/
main.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import github3
import toml
import json
import re
import functools
from . import utils
import logging
from threading import Thread, Lock
import time
import traceback
import sqlite3
import requests
from contextlib import contextmanager
from itertools import chain
from queue import Queue
import os
import sys
from enum import IntEnum
import subprocess
from .git_helper import SSH_KEY_FILE
import shlex
import random
STATUS_TO_PRIORITY = {
'success': 0,
'pending': 1,
'approved': 2,
'': 3,
'error': 4,
'failure': 5,
}
INTERRUPTED_BY_HOMU_FMT = 'Interrupted by Homu ({})'
INTERRUPTED_BY_HOMU_RE = re.compile(r'Interrupted by Homu \((.+?)\)')
TEST_TIMEOUT = 3600 * 10
global_cfg = {}
@contextmanager
def buildbot_sess(repo_cfg):
sess = requests.Session()
sess.post(
repo_cfg['buildbot']['url'] + '/login',
allow_redirects=False,
data={
'username': repo_cfg['buildbot']['username'],
'passwd': repo_cfg['buildbot']['password'],
})
yield sess
sess.get(repo_cfg['buildbot']['url'] + '/logout', allow_redirects=False)
db_query_lock = Lock()
def db_query(db, *args):
with db_query_lock:
db.execute(*args)
class Repository:
treeclosed = -1
gh = None
label = None
db = None
def __init__(self, gh, repo_label, db):
self.gh = gh
self.repo_label = repo_label
self.db = db
db_query(
db,
'SELECT treeclosed FROM repos WHERE repo = ?',
[repo_label]
)
row = db.fetchone()
if row:
self.treeclosed = row[0]
else:
self.treeclosed = -1
def update_treeclosed(self, value):
self.treeclosed = value
db_query(
self.db,
'DELETE FROM repos where repo = ?',
[self.repo_label]
)
if value > 0:
db_query(
self.db,
'INSERT INTO repos (repo, treeclosed) VALUES (?, ?)',
[self.repo_label, value]
)
def __lt__(self, other):
return self.gh < other.gh
class PullReqState:
num = 0
priority = 0
rollup = False
title = ''
body = ''
head_ref = ''
base_ref = ''
assignee = ''
delegate = ''
def __init__(self, num, head_sha, status, db, repo_label, mergeable_que,
gh, owner, name, repos):
self.head_advanced('', use_db=False)
self.num = num
self.head_sha = head_sha
self.status = status
self.db = db
self.repo_label = repo_label
self.mergeable_que = mergeable_que
self.gh = gh
self.owner = owner
self.name = name
self.repos = repos
self.test_started = time.time() # FIXME: Save in the local database
def head_advanced(self, head_sha, *, use_db=True):
self.head_sha = head_sha
self.approved_by = ''
self.status = ''
self.merge_sha = ''
self.build_res = {}
self.try_ = False
self.mergeable = None
if use_db:
self.set_status('')
self.set_mergeable(None)
self.init_build_res([])
def __repr__(self):
fmt = 'PullReqState:{}/{}#{}(approved_by={}, priority={}, status={})'
return fmt.format(
self.owner,
self.name,
self.num,
self.approved_by,
self.priority,
self.status,
)
def sort_key(self):
return [
STATUS_TO_PRIORITY.get(self.get_status(), -1),
1 if self.mergeable is False else 0,
0 if self.approved_by else 1,
1 if self.rollup else 0,
-self.priority,
self.num,
]
def __lt__(self, other):
return self.sort_key() < other.sort_key()
def get_issue(self):
issue = getattr(self, 'issue', None)
if not issue:
issue = self.issue = self.get_repo().issue(self.num)
return issue
def add_comment(self, text):
self.get_issue().create_comment(text)
def set_status(self, status):
self.status = status
db_query(
self.db,
'UPDATE pull SET status = ? WHERE repo = ? AND num = ?',
[self.status, self.repo_label, self.num]
)
# FIXME: self.try_ should also be saved in the database
if not self.try_:
db_query(
self.db,
'UPDATE pull SET merge_sha = ? WHERE repo = ? AND num = ?',
[self.merge_sha, self.repo_label, self.num]
)
def get_status(self):
if self.status == '' and self.approved_by:
if self.mergeable is not False:
return 'approved'
return self.status
def set_mergeable(self, mergeable, *, cause=None, que=True):
if mergeable is not None:
self.mergeable = mergeable
db_query(
self.db,
'INSERT OR REPLACE INTO mergeable (repo, num, mergeable) VALUES (?, ?, ?)', # noqa
[self.repo_label, self.num, self.mergeable]
)
else:
if que:
self.mergeable_que.put([self, cause])
else:
self.mergeable = None
db_query(
self.db,
'DELETE FROM mergeable WHERE repo = ? AND num = ?',
[self.repo_label, self.num]
)
def init_build_res(self, builders, *, use_db=True):
self.build_res = {x: {
'res': None,
'url': '',
} for x in builders}
if use_db:
db_query(
self.db,
'DELETE FROM build_res WHERE repo = ? AND num = ?',
[self.repo_label, self.num]
)
def set_build_res(self, builder, res, url):
if builder not in self.build_res:
raise Exception('Invalid builder: {}'.format(builder))
self.build_res[builder] = {
'res': res,
'url': url,
}
db_query(
self.db,
'INSERT OR REPLACE INTO build_res (repo, num, builder, res, url, merge_sha) VALUES (?, ?, ?, ?, ?, ?)', # noqa
[
self.repo_label,
self.num,
builder,
res,
url,
self.merge_sha,
])
def build_res_summary(self):
return ', '.join('{}: {}'.format(builder, data['res'])
for builder, data in self.build_res.items())
def get_repo(self):
repo = self.repos[self.repo_label].gh
if not repo:
repo = self.gh.repository(self.owner, self.name)
self.repos[self.repo_label].gh = repo
assert repo.owner.login == self.owner
assert repo.name == self.name
return repo
def save(self):
db_query(
self.db,
'INSERT OR REPLACE INTO pull (repo, num, status, merge_sha, title, body, head_sha, head_ref, base_ref, assignee, approved_by, priority, try_, rollup, delegate) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', # noqa
[
self.repo_label,
self.num,
self.status,
self.merge_sha,
self.title,
self.body,
self.head_sha,
self.head_ref,
self.base_ref,
self.assignee,
self.approved_by,
self.priority,
self.try_,
self.rollup,
self.delegate,
])
def refresh(self):
issue = self.get_repo().issue(self.num)
self.title = issue.title
self.body = issue.body
def fake_merge(self, repo_cfg):
if not repo_cfg.get('linear', False):
return
if repo_cfg.get('autosquash', False):
return
issue = self.get_issue()
title = issue.title
# We tell github to close the PR via the commit message, but it
# doesn't know that constitutes a merge. Edit the title so that it's
# clearer.
merged_prefix = '[merged] '
if not title.startswith(merged_prefix):
title = merged_prefix + title
issue.edit(title=title)
def change_treeclosed(self, value):
self.repos[self.repo_label].update_treeclosed(value)
def blocked_by_closed_tree(self):
treeclosed = self.repos[self.repo_label].treeclosed
return treeclosed if self.priority < treeclosed else None
def sha_cmp(short, full):
return len(short) >= 4 and short == full[:len(short)]
def sha_or_blank(sha):
return sha if re.match(r'^[0-9a-f]+$', sha) else ''
class AuthState(IntEnum):
# Higher is more privileged
REVIEWER = 3
TRY = 2
NONE = 1
def verify_auth(username, repo_cfg, state, auth, realtime, my_username):
# In some cases (e.g. non-fully-qualified r+) we recursively talk to
# ourself via a hidden markdown comment in the message. This is so that
# when re-synchronizing after shutdown we can parse these comments and
# still know the SHA for the approval.
#
# So comments from self should always be allowed
if username == my_username:
return True
is_reviewer = False
auth_collaborators = repo_cfg.get('auth_collaborators', False)
if auth_collaborators:
is_reviewer = state.get_repo().is_collaborator(username)
if not is_reviewer:
is_reviewer = username in repo_cfg.get('reviewers', [])
if not is_reviewer:
is_reviewer = username.lower() == state.delegate.lower()
if is_reviewer:
have_auth = AuthState.REVIEWER
elif username in repo_cfg.get('try_users', []):
have_auth = AuthState.TRY
else:
have_auth = AuthState.NONE
if have_auth >= auth:
return True
else:
if realtime:
reply = '@{}: :key: Insufficient privileges: '.format(username)
if auth == AuthState.REVIEWER:
if auth_collaborators:
reply += 'Collaborator required'
else:
reply += 'Not in reviewers'
elif auth == AuthState.TRY:
reply += 'and not in try users'
state.add_comment(reply)
return False
PORTAL_TURRET_DIALOG = ["Target acquired", "Activated", "There you are"]
PORTAL_TURRET_IMAGE = "https://cloud.githubusercontent.com/assets/1617736/22222924/c07b2a1c-e16d-11e6-91b3-ac659550585c.png" # noqa
def parse_commands(body, username, repo_cfg, state, my_username, db, states,
*, realtime=False, sha=''):
global global_cfg
state_changed = False
_reviewer_auth_verified = functools.partial(
verify_auth,
username,
repo_cfg,
state,
AuthState.REVIEWER,
realtime,
my_username,
)
_try_auth_verified = functools.partial(
verify_auth,
username,
repo_cfg,
state,
AuthState.TRY,
realtime,
my_username,
)
words = list(chain.from_iterable(re.findall(r'\S+', x) for x in body.splitlines() if '@' + my_username in x)) # noqa
if words[1:] == ["are", "you", "still", "there?"] and realtime:
state.add_comment(
":cake: {}\n\n![]({})".format(
random.choice(PORTAL_TURRET_DIALOG), PORTAL_TURRET_IMAGE)
)
for i, word in reversed(list(enumerate(words))):
found = True
if word == 'r+' or word.startswith('r='):
if not _reviewer_auth_verified():
continue
if not sha and i + 1 < len(words):
cur_sha = sha_or_blank(words[i + 1])
else:
cur_sha = sha
approver = word[len('r='):] if word.startswith('r=') else username
# Ignore "r=me"
if approver == 'me':
continue
# Ignore WIP PRs
if any(map(state.title.startswith, [
'WIP', 'TODO', '[WIP]', '[TODO]',
])):
if realtime:
state.add_comment(':clipboard: Looks like this PR is still in progress, ignoring approval') # noqa
continue
# Sometimes, GitHub sends the head SHA of a PR as 0000000
# through the webhook. This is called a "null commit", and
# seems to happen when GitHub internally encounters a race
# condition. Last time, it happened when squashing commits
# in a PR. In this case, we just try to retrieve the head
# SHA manually.
if all(x == '0' for x in state.head_sha):
if realtime:
state.add_comment(
':bangbang: Invalid head SHA found, retrying: `{}`'
.format(state.head_sha)
)
state.head_sha = state.get_repo().pull_request(state.num).head.sha # noqa
state.save()
assert any(x != '0' for x in state.head_sha)
if state.approved_by and realtime and username != my_username:
for _state in states[state.repo_label].values():
if _state.status == 'pending':
break
else:
_state = None
lines = []
if state.status in ['failure', 'error']:
lines.append('- This pull request previously failed. You should add more commits to fix the bug, or use `retry` to trigger a build again.') # noqa
if _state:
if state == _state:
lines.append('- This pull request is currently being tested. If there\'s no response from the continuous integration service, you may use `retry` to trigger a build again.') # noqa
else:
lines.append('- There\'s another pull request that is currently being tested, blocking this pull request: #{}'.format(_state.num)) # noqa
if lines:
lines.insert(0, '')
lines.insert(0, ':bulb: This pull request was already approved, no need to approve it again.') # noqa
state.add_comment('\n'.join(lines))
if sha_cmp(cur_sha, state.head_sha):
state.approved_by = approver
state.try_ = False
state.set_status('')
state.save()
elif realtime and username != my_username:
if cur_sha:
msg = '`{}` is not a valid commit SHA.'.format(cur_sha)
state.add_comment(
':scream_cat: {} Please try again with `{:.7}`.'
.format(msg, state.head_sha)
)
else:
state.add_comment(
':pushpin: Commit {:.7} has been approved by `{}`\n\n<!-- @{} r={} {} -->' # noqa
.format(
state.head_sha,
approver,
my_username,
approver,
state.head_sha,
))
treeclosed = state.blocked_by_closed_tree()
if treeclosed:
state.add_comment(
':evergreen_tree: The tree is currently closed for pull requests below priority {}, this pull request will be tested once the tree is reopened' # noqa
.format(treeclosed)
)
elif word == 'r-':
if not verify_auth(username, repo_cfg, state, AuthState.REVIEWER,
realtime, my_username):
continue
state.approved_by = ''
state.save()
elif word.startswith('p='):
if not verify_auth(username, repo_cfg, state, AuthState.TRY,
realtime, my_username):
continue
try:
pvalue = int(word[len('p='):])
except ValueError:
continue
if pvalue > global_cfg['max_priority']:
if realtime:
state.add_comment(
':stop_sign: Priority higher than {} is ignored.'
.format(global_cfg['max_priority'])
)
continue
state.priority = pvalue
state.save()
elif word.startswith('delegate='):
if not verify_auth(username, repo_cfg, state, AuthState.REVIEWER,
realtime, my_username):
continue
state.delegate = word[len('delegate='):]
state.save()
if realtime:
state.add_comment(
':v: @{} can now approve this pull request'
.format(state.delegate)
)
elif word == 'delegate-':
# TODO: why is this a TRY?
if not _try_auth_verified():
continue
state.delegate = ''
state.save()
elif word == 'delegate+':
if not _reviewer_auth_verified():
continue
state.delegate = state.get_repo().pull_request(state.num).user.login # noqa
state.save()
if realtime:
state.add_comment(
':v: @{} can now approve this pull request'
.format(state.delegate)
)
elif word == 'retry' and realtime:
if not _try_auth_verified():
continue
state.set_status('')
elif word in ['try', 'try-'] and realtime:
if not _try_auth_verified():
continue
state.try_ = word == 'try'
state.merge_sha = ''
state.init_build_res([])
state.save()
elif word in ['rollup', 'rollup-']:
if not _try_auth_verified():
continue
state.rollup = word == 'rollup'
state.save()
elif word == 'force' and realtime:
if not _try_auth_verified():
continue
if 'buildbot' in repo_cfg:
with buildbot_sess(repo_cfg) as sess:
res = sess.post(
repo_cfg['buildbot']['url'] + '/builders/_selected/stopselected', # noqa
allow_redirects=False,
data={
'selected': repo_cfg['buildbot']['builders'],
'comments': INTERRUPTED_BY_HOMU_FMT.format(int(time.time())), # noqa
})
if 'authzfail' in res.text:
err = 'Authorization failed'
else:
mat = re.search('(?s)<div class="error">(.*?)</div>', res.text)
if mat:
err = mat.group(1).strip()
if not err:
err = 'Unknown error'
else:
err = ''
if err:
state.add_comment(
':bomb: Buildbot returned an error: `{}`'.format(err)
)
elif word == 'clean' and realtime:
if not _try_auth_verified():
continue
state.merge_sha = ''
state.init_build_res([])
state.save()
elif (word == 'hello?' or word == 'ping') and realtime:
state.add_comment(":sleepy: I'm awake I'm awake")
elif word.startswith('treeclosed='):
if not _reviewer_auth_verified():
continue
try:
treeclosed = int(word[len('treeclosed='):])
state.change_treeclosed(treeclosed)
except ValueError:
pass
state.save()
elif word == 'treeclosed-':
if not _reviewer_auth_verified():
continue
state.change_treeclosed(-1)
state.save()
elif 'hooks' in global_cfg:
hook_found = False
for hook in global_cfg['hooks']:
hook_cfg = global_cfg['hooks'][hook]
if hook_cfg['realtime'] and not realtime:
continue
if word == hook or word.startswith('%s=' % hook):
if hook_cfg['access'] == "reviewer":
if not _reviewer_auth_verified():
continue
else:
if not _try_auth_verified():
continue
hook_found = True
extra_data = ""
if word.startswith('%s=' % hook):
extra_data = word.split("=")[1]
Thread(
target=handle_hook_response,
args=[state, hook_cfg, body, extra_data]
).start()
if not hook_found:
found = False
else:
found = False
if found:
state_changed = True
words[i] = ''
return state_changed
def handle_hook_response(state, hook_cfg, body, extra_data):
post_data = {}
post_data["pull"] = state.num
post_data["body"] = body
post_data["extra_data"] = extra_data
print(post_data)
response = requests.post(hook_cfg['endpoint'], json=post_data)
print(response.text)
# We only post a response if we're configured to have a response
# non-realtime hooks cannot post
if hook_cfg['has_response'] and hook_cfg['realtime']:
state.add_comment(response.text)
def git_push(git_cmd, branch, state):
merge_sha = subprocess.check_output(git_cmd('rev-parse', 'HEAD')).decode('ascii').strip() # noqa
if utils.silent_call(git_cmd('push', '-f', 'origin', branch)):
utils.logged_call(git_cmd('branch', '-f', 'homu-tmp', branch))
utils.logged_call(git_cmd('push', '-f', 'origin', 'homu-tmp'))
def inner():
utils.github_create_status(
state.get_repo(),
merge_sha,
'success',
'',
'Branch protection bypassed',
context='homu',
)
def fail(err):
state.add_comment(
':boom: Unable to create a status for {} ({})'
.format(merge_sha, err)
)
utils.retry_until(inner, fail, state)
utils.logged_call(git_cmd('push', '-f', 'origin', branch))
return merge_sha
def init_local_git_cmds(repo_cfg, git_cfg):
fpath = 'cache/{}/{}'.format(repo_cfg['owner'], repo_cfg['name'])
url = 'git@github.com:{}/{}.git'.format(repo_cfg['owner'], repo_cfg['name']) # noqa
if not os.path.exists(SSH_KEY_FILE):
os.makedirs(os.path.dirname(SSH_KEY_FILE), exist_ok=True)
with open(SSH_KEY_FILE, 'w') as fp:
fp.write(git_cfg['ssh_key'])
os.chmod(SSH_KEY_FILE, 0o600)
if not os.path.exists(fpath):
utils.logged_call(['git', 'init', fpath])
utils.logged_call(['git', '-C', fpath, 'remote', 'add', 'origin', url]) # noqa
return lambda *args: ['git', '-C', fpath] + list(args)
def branch_equal_to_merge(git_cmd, state, branch):
utils.logged_call(git_cmd('fetch', 'origin',
'pull/{}/merge'.format(state.num)))
return utils.silent_call(git_cmd('diff', '--quiet', 'FETCH_HEAD', branch)) == 0 # noqa
def create_merge(state, repo_cfg, branch, git_cfg, ensure_merge_equal=False):
base_sha = state.get_repo().ref('heads/' + state.base_ref).object.sha
state.refresh()
merge_msg = 'Auto merge of #{} - {}, r={}\n\n{}\n\n{}'.format(
state.num,
state.head_ref,
'<try>' if state.try_ else state.approved_by,
state.title,
state.body)
desc = 'Merge conflict'
if git_cfg['local_git']:
git_cmd = init_local_git_cmds(repo_cfg, git_cfg)
utils.logged_call(git_cmd('fetch', 'origin', state.base_ref,
'pull/{}/head'.format(state.num)))
utils.silent_call(git_cmd('rebase', '--abort'))
utils.silent_call(git_cmd('merge', '--abort'))
if repo_cfg.get('linear', False):
utils.logged_call(
git_cmd('checkout', '-B', branch, state.head_sha))
try:
args = [base_sha]
if repo_cfg.get('autosquash', False):
args += ['-i', '--autosquash']
utils.logged_call(git_cmd('-c',
'user.name=' + git_cfg['name'],
'-c',
'user.email=' + git_cfg['email'],
'rebase',
*args))
except subprocess.CalledProcessError:
if repo_cfg.get('autosquash', False):
utils.silent_call(git_cmd('rebase', '--abort'))
if utils.silent_call(git_cmd('rebase', base_sha)) == 0:
desc = 'Auto-squashing failed'
else:
ap = '<try>' if state.try_ else state.approved_by
text = '\nCloses: #{}\nApproved by: {}'.format(state.num, ap)
msg_code = 'cat && echo {}'.format(shlex.quote(text))
env_code = 'export GIT_COMMITTER_NAME={} && export GIT_COMMITTER_EMAIL={} && unset GIT_COMMITTER_DATE'.format(shlex.quote(git_cfg['name']), shlex.quote(git_cfg['email'])) # noqa
utils.logged_call(git_cmd('filter-branch', '-f',
'--msg-filter', msg_code,
'--env-filter', env_code,
'{}..'.format(base_sha)))
if ensure_merge_equal:
if not branch_equal_to_merge(git_cmd, state, branch):
return ''
return git_push(git_cmd, branch, state)
else:
utils.logged_call(git_cmd(
'checkout',
'-B',
'homu-tmp',
state.head_sha))
ok = True
if repo_cfg.get('autosquash', False):
try:
merge_base_sha = subprocess.check_output(
git_cmd(
'merge-base',
base_sha,
state.head_sha)).decode('ascii').strip()
utils.logged_call(git_cmd(
'-c',
'user.name=' + git_cfg['name'],
'-c',
'user.email=' + git_cfg['email'],
'rebase',
'-i',
'--autosquash',
'--onto',
merge_base_sha, base_sha))
except subprocess.CalledProcessError:
desc = 'Auto-squashing failed'
ok = False
if ok:
utils.logged_call(git_cmd('checkout', '-B', branch, base_sha))
try:
utils.logged_call(git_cmd(
'-c',
'user.name=' + git_cfg['name'],
'-c',
'user.email=' + git_cfg['email'],
'merge',
'heads/homu-tmp',
'--no-ff',
'-m',
merge_msg))
except subprocess.CalledProcessError:
pass
else:
if ensure_merge_equal:
if not branch_equal_to_merge(git_cmd, state, branch):
return ''
return git_push(git_cmd, branch, state)
else:
if repo_cfg.get('linear', False) or repo_cfg.get('autosquash', False):
raise RuntimeError('local_git must be turned on to use this feature') # noqa
# if we're merging using the GitHub API, we have no way to predict
# with certainty what the final result will be so make sure the caller
# isn't asking us to keep any promises (see also discussions at
# https://github.com/servo/homu/pull/57)
assert ensure_merge_equal is False
if branch != state.base_ref:
utils.github_set_ref(
state.get_repo(),
'heads/' + branch,
base_sha,
force=True,
)
try:
merge_commit = state.get_repo().merge(
branch,
state.head_sha,
merge_msg)
except github3.models.GitHubError as e:
if e.code != 409:
raise
else:
return merge_commit.sha if merge_commit else ''
state.set_status('error')
utils.github_create_status(
state.get_repo(),
state.head_sha,
'error',
'',
desc,
context='homu')
state.add_comment(':lock: ' + desc)
return ''
def pull_is_rebased(state, repo_cfg, git_cfg, base_sha):
assert git_cfg['local_git']
git_cmd = init_local_git_cmds(repo_cfg, git_cfg)
utils.logged_call(git_cmd('fetch', 'origin', state.base_ref,
'pull/{}/head'.format(state.num)))
return utils.silent_call(git_cmd('merge-base', '--is-ancestor',
base_sha, state.head_sha)) == 0
# We could fetch this from GitHub instead, but that API is being deprecated:
# https://developer.github.com/changes/2013-04-25-deprecating-merge-commit-sha/
def get_github_merge_sha(state, repo_cfg, git_cfg):
assert git_cfg['local_git']
git_cmd = init_local_git_cmds(repo_cfg, git_cfg)
if state.mergeable is not True:
return None
utils.logged_call(git_cmd('fetch', 'origin',
'pull/{}/merge'.format(state.num)))
return subprocess.check_output(git_cmd('rev-parse', 'FETCH_HEAD')).decode('ascii').strip() # noqa
def do_exemption_merge(state, repo_cfg, git_cfg, url, check_merge, reason):
try:
merge_sha = create_merge(
state,
repo_cfg,
state.base_ref,
git_cfg,
check_merge)
except subprocess.CalledProcessError:
print('* Unable to create a merge commit for the exempted PR: {}'.format(state)) # noqa
traceback.print_exc()
return False
if not merge_sha:
return False
desc = 'Test exempted'
state.set_status('success')
utils.github_create_status(state.get_repo(), state.head_sha, 'success',
url, desc, context='homu')
state.add_comment(':zap: {}: {}.'.format(desc, reason))
state.merge_sha = merge_sha
state.save()
state.fake_merge(repo_cfg)
return True
def try_travis_exemption(state, repo_cfg, git_cfg):
travis_info = None
for info in utils.github_iter_statuses(state.get_repo(), state.head_sha):
if info.context == 'continuous-integration/travis-ci/pr':
travis_info = info
break
if travis_info is None or travis_info.state != 'success':
return False
mat = re.search('/builds/([0-9]+)$', travis_info.target_url)
if not mat:
return False
url = 'https://api.travis-ci.org/{}/{}/builds/{}'.format(state.owner,
state.name,
mat.group(1))
try:
res = requests.get(url)
except Exception as ex:
print('* Unable to gather build info from Travis CI: {}'.format(ex))
return False
travis_sha = json.loads(res.text)['commit']
travis_commit = state.get_repo().commit(travis_sha)
if not travis_commit:
return False
base_sha = state.get_repo().ref('heads/' + state.base_ref).object.sha
if (travis_commit.parents[0]['sha'] == base_sha and
travis_commit.parents[1]['sha'] == state.head_sha):
# make sure we check against the github merge sha before pushing
return do_exemption_merge(state, repo_cfg, git_cfg,
travis_info.target_url, True,
"merge already tested by Travis CI")
return False
def try_status_exemption(state, repo_cfg, git_cfg):
# If all the builders are status-based, then we can do some checks to
# exempt testing under the following cases:
# 1. The PR head commit has the equivalent statuses set to 'success' and