-
Notifications
You must be signed in to change notification settings - Fork 249
/
Copy pathprocess_pr.py
2698 lines (2459 loc) · 105 KB
/
process_pr.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 copy
from categories import (
CMSSW_L2,
CMSSW_ORP,
TRIGGER_PR_TESTS,
CMSSW_ISSUES_TRACKERS,
PR_HOLD_MANAGERS,
EXTERNAL_REPOS,
CMSDIST_REPOS,
)
from categories import CMSSW_CATEGORIES
from releases import RELEASE_BRANCH_MILESTONE, RELEASE_BRANCH_PRODUCTION, CMSSW_DEVEL_BRANCH
from cms_static import (
VALID_CMSDIST_BRANCHES,
NEW_ISSUE_PREFIX,
NEW_PR_PREFIX,
ISSUE_SEEN_MSG,
BUILD_REL,
GH_CMSSW_REPO,
GH_CMSDIST_REPO,
CMSBOT_IGNORE_MSG,
VALID_CMS_SW_REPOS_FOR_TESTS,
CREATE_REPO,
CMSBOT_TECHNICAL_MSG,
)
from cms_static import BACKPORT_STR, GH_CMSSW_ORGANIZATION, CMSBOT_NO_NOTIFY_MSG
from githublabels import TYPE_COMMANDS, TEST_IGNORE_REASON
from repo_config import GH_REPO_ORGANIZATION
import re, time
from collections import defaultdict
import zlib, base64
from datetime import datetime
from os.path import join, exists, dirname
from os import environ
from github_utils import (
edit_pr,
api_rate_limits,
get_pr_commits_reversed,
get_commit,
)
from github_utils import set_gh_user, get_gh_user
from socket import setdefaulttimeout
from _py2with3compatibility import run_cmd
from json import dumps, dump, load, loads
import yaml
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
try:
from categories import CATS_TO_APPROVE_ON_TEST
except:
CATS_TO_APPROVE_ON_TEST = []
try:
from categories import CMSSW_LABELS
except:
CMSSW_LABELS = {}
try:
from categories import get_dpg_pog
except:
def get_dpg_pog(*args):
return {}
try:
from categories import external_to_package
except:
def external_to_package(*args):
return ""
try:
from releases import get_release_managers, is_closed_branch
except:
def get_release_managers(*args):
return []
def is_closed_branch(*args):
return False
setdefaulttimeout(300)
CMSDIST_REPO_NAME = join(GH_REPO_ORGANIZATION, GH_CMSDIST_REPO)
CMSSW_REPO_NAME = join(GH_REPO_ORGANIZATION, GH_CMSSW_REPO)
# Prepare various comments regardless of whether they will be made or not.
def format(s, **kwds):
return s % kwds
BOT_CACHE_TEMPLATE = {"emoji": {}, "signatures": {}, "commits": {}}
TRIGERING_TESTS_MSG = "The tests are being triggered in jenkins."
TRIGERING_TESTS_MSG1 = "Jenkins tests started for "
TRIGERING_STYLE_TEST_MSG = "The project style tests are being triggered in jenkins."
IGNORING_TESTS_MSG = "Ignoring test request."
TESTS_RESULTS_MSG = "^\\s*([-|+]1|I had the issue.*)\\s*$"
FAILED_TESTS_MSG = "The jenkins tests job failed, please try again."
PUSH_TEST_ISSUE_MSG = "^\\[Jenkins CI\\] Testing commit: [0-9a-f]+$"
HOLD_MSG = "Pull request has been put on hold by "
# Regexp to match the test requests
CODE_CHECKS_REGEXP = re.compile(
r"code-checks(\s+with\s+cms.week[0-9].PR_[0-9a-f]{8}/[^\s]+|)(\s+and\s+apply\s+patch|)$"
)
WF_PATTERN = r"[1-9][0-9]*(\.[0-9]+|)"
CMSSW_QUEUE_PATTERN = "CMSSW_[0-9]+_[0-9]+_(X|[A-Z][A-Z0-9]+_X|[0-9]+(_[a-zA-Z0-9_]+|))"
CMSSW_PACKAGE_PATTERN = "[A-Z][a-zA-Z0-9]+(/[a-zA-Z0-9]+|)"
ARCH_PATTERN = "[a-z0-9]+_[a-z0-9]+_[a-z0-9]+"
CMSSW_RELEASE_QUEUE_PATTERN = format(
"(%(cmssw)s|%(arch)s|%(cmssw)s/%(arch)s)", cmssw=CMSSW_QUEUE_PATTERN, arch=ARCH_PATTERN
)
RELVAL_OPTS = r"[-][a-zA-Z0-9_.,\s/'-]+"
CLOSE_REQUEST = re.compile(r"^\s*((@|)cmsbuild\s*[,]*\s+|)(please\s*[,]*\s+|)close\s*$", re.I)
REOPEN_REQUEST = re.compile(r"^\s*((@|)cmsbuild\s*[,]*\s+|)(please\s*[,]*\s+|)(re|)open\s*$", re.I)
CMS_PR_PATTERN = format(
"(#[1-9][0-9]*|(%(cmsorgs)s)/+[a-zA-Z0-9_-]+#[1-9][0-9]*|https://+github.com/+(%(cmsorgs)s)/+[a-zA-Z0-9_-]+/+pull/+[1-9][0-9]*)",
cmsorgs="|".join(EXTERNAL_REPOS),
)
TEST_REGEXP = format(
r"^\s*((@|)cmsbuild\s*[,]*\s+|)(please\s*[,]*\s+|)test(\s+workflow(s|)\s+(%(workflow)s(\s*,\s*%(workflow)s|)*)|)(\s+with\s+(%(cms_pr)s(\s*,\s*%(cms_pr)s)*)|)(\s+for\s+%(release_queue)s|)(\s+using\s+full\s+cmssw|\s+using\s+(cms-|)addpkg\s+(%(pkg)s(,%(pkg)s)*)|)\s*$",
workflow=WF_PATTERN,
cms_pr=CMS_PR_PATTERN,
pkg=CMSSW_PACKAGE_PATTERN,
release_queue=CMSSW_RELEASE_QUEUE_PATTERN,
)
AUTO_TEST_REPOS = ["cms-sw/cmssw"]
REGEX_TEST_REG = re.compile(TEST_REGEXP, re.I)
REGEX_TEST_ABORT = re.compile(
r"^\s*((@|)cmsbuild\s*[,]*\s+|)(please\s*[,]*\s+|)abort(\s+test|)$", re.I
)
REGEX_TEST_IGNORE = re.compile(
r"^\s*(?:(?:@|)cmsbuild\s*[,]*\s+|)(?:please\s*[,]*\s+|)ignore\s+tests-rejected\s+(?:with|)([a-z -]+)$",
re.I,
)
REGEX_COMMITS_CACHE = re.compile(r"<!-- (?:commits|bot) cache: (.*) -->", re.DOTALL)
REGEX_IGNORE_COMMIT_COUNT = r"\+commit-count"
REGEX_IGNORE_FILE_COUNT = r"\+file-count"
TEST_WAIT_GAP = 720
ALL_CHECK_FUNCTIONS = None
ALL_GPU_FLAVORS = [
x.strip() for x in open(join(dirname(__file__), "gpu_flavors.txt"), "r").read().splitlines()
]
EXTRA_RELVALS_TESTS = ["threading", "gpu", "high_stats", "nano"] + ALL_GPU_FLAVORS
EXTRA_RELVALS_TESTS_OPTS = "_" + "|_".join(EXTRA_RELVALS_TESTS)
EXTRA_TESTS = (
"|".join(EXTRA_RELVALS_TESTS)
+ "|hlt_p2_integration|hlt_p2_timing|profiling|none|multi_microarchs"
)
SKIP_TESTS = "|".join(["static", "header"])
ENABLE_TEST_PTRN = "enable(_test(s|)|)"
JENKINS_NODES = r"[a-zA-Z0-9_|&\s()-]+"
MULTILINE_COMMENTS_MAP = {
"(workflow|relval)(s|)("
+ EXTRA_RELVALS_TESTS_OPTS
+ "|)": [format(r"%(workflow)s(\s*,\s*%(workflow)s|)*", workflow=WF_PATTERN), "MATRIX_EXTRAS"],
"(workflow|relval)(s|)_profiling": [
format(r"%(workflow)s(\s*,\s*%(workflow)s|)*", workflow=WF_PATTERN),
"PROFILING_WORKFLOWS",
],
"pull_request(s|)": [
format("%(cms_pr)s(,%(cms_pr)s)*", cms_pr=CMS_PR_PATTERN),
"PULL_REQUESTS",
],
"full_cmssw|full": ["true|false", "BUILD_FULL_CMSSW"],
"disable_poison": ["true|false", "DISABLE_POISON"],
"use_ib_tag": ["true|false", "USE_IB_TAG"],
"baseline": ["self|default", "USE_BASELINE"],
"set_env": [r"[A-Z][A-Z0-9_]+(\s*,\s*[A-Z][A-Z0-9_]+|)*", "CMSBOT_SET_ENV"],
"skip_test(s|)": [format(r"(%(tests)s)(\s*,\s*(%(tests)s))*", tests=SKIP_TESTS), "SKIP_TESTS"],
"dry_run": ["true|false", "DRY_RUN"],
"jenkins_(slave|node)": [JENKINS_NODES, "RUN_ON_SLAVE"],
"(arch(itecture(s|))|release|release/arch)": [CMSSW_RELEASE_QUEUE_PATTERN, "RELEASE_FORMAT"],
ENABLE_TEST_PTRN: [
format(r"(%(tests)s)(\s*,\s*(%(tests)s))*", tests=EXTRA_TESTS),
"ENABLE_BOT_TESTS",
],
"ignore_test(s|)": ["build-warnings|clang-warnings", "IGNORE_BOT_TESTS"],
"container": [
"[a-zA-Z][a-zA-Z0-9_-]+/[a-zA-Z][a-zA-Z0-9_-]+(:[a-zA-Z0-9_-]+|)",
"DOCKER_IMGAGE",
],
"cms-addpkg|addpkg": [
format("%(pkg)s(,%(pkg)s)*", pkg=CMSSW_PACKAGE_PATTERN),
"EXTRA_CMSSW_PACKAGES",
],
"build_verbose": ["true|false", "BUILD_VERBOSE"],
"(workflow|relval)(s|)_opt(ion|)(s|)("
+ EXTRA_RELVALS_TESTS_OPTS
+ "|_input|)": [RELVAL_OPTS, "EXTRA_MATRIX_ARGS", True],
"(workflow|relval)(s|)_command_opt(ion|)(s|)("
+ EXTRA_RELVALS_TESTS_OPTS
+ "|_input|)": [RELVAL_OPTS, "EXTRA_MATRIX_COMMAND_ARGS", True],
}
BOT_CACHE_CHUNK_SIZE = 55000
TOO_MANY_COMMITS_WARN_THRESHOLD = 150
TOO_MANY_COMMITS_FAIL_THRESHOLD = 240
TOO_MANY_FILES_WARN_THRESHOLD = 1500
TOO_MANY_FILES_FAIL_THRESHOLD = 3001
CHANGED_FILES_FROM_DIFF_THRESHOLD = 500
L2_DATA = {}
def update_CMSSW_LABELS(repo_config):
try:
check_dpg_pog = repo_config.CHECK_DPG_POG
except:
check_dpg_pog = False
dpg_pog = {} if not check_dpg_pog else get_dpg_pog()
for l in CMSSW_LABELS.keys():
if check_dpg_pog and (not l in dpg_pog) and (not l in TYPE_COMMANDS):
del CMSSW_LABELS[l]
else:
CMSSW_LABELS[l] = [
re.compile("^(" + p + ").*$") if isinstance(p, str) else p for p in CMSSW_LABELS[l]
]
return
def init_l2_data(repo_config, cms_repo):
l2_data = {}
if cms_repo:
with open(join(dirname(__file__), "cmssw_l2", "l2.json")) as ref:
default_l2_data = load(ref)
l2_data = read_repo_file(repo_config, "l2.json", default_l2_data, False)
for user in CMSSW_L2:
if (user in l2_data) and ("end_date" in l2_data[user][-1]):
del l2_data[user][-1]["end_date"]
else:
for user in CMSSW_L2:
l2_data[user] = [{"start_date": 0, "category": CMSSW_L2[user]}]
return l2_data
def collect_commit_cache(bot_cache):
REGEX_COMMIT_SHA = re.compile("^[a-f0-9]{40}$", re.IGNORECASE)
commit_cache = {k: v for k, v in bot_cache.items() if REGEX_COMMIT_SHA.match(k)}
if commit_cache:
for k in commit_cache:
del bot_cache[k]
bot_cache["commits"] = commit_cache
def read_bot_cache(data):
print("Loading bot cache")
res = loads_maybe_decompress(data)
for k, v in BOT_CACHE_TEMPLATE.items():
if k not in res:
res[k] = copy.deepcopy(v)
collect_commit_cache(res)
return res
def extract_bot_cache(comment_msgs):
print(
"Reading bot cache from technical comment(s):",
",".join(str(c) for c in comment_msgs),
)
data = ""
for comment_msg in comment_msgs:
seen_commits_match = REGEX_COMMITS_CACHE.search(comment_msg.body)
if seen_commits_match:
data += seen_commits_match[1]
if data:
return read_bot_cache(data)
return {}
def prepare_bot_cache(bot_cache):
res = []
data = dumps_maybe_compress(bot_cache)
while data:
# The limit is 65535 chars, and minimal bot cache comment is
# `cms-bot internal usage<!-- bot cache: -->`, 42 characters.
# But since the cache can be embedded in an "already seen" comment, whose length is not
# known in advance, we limit the amout of (encoded cache) data per comment
# to BOT_CACHE_CHUNK_SIZE chars.
part, data = data[:BOT_CACHE_CHUNK_SIZE], data[BOT_CACHE_CHUNK_SIZE:]
res.append(part)
return res
def write_bot_cache(bot_cache, cache_comments, issue, dryRun):
data = prepare_bot_cache(bot_cache)
for i, part in enumerate(data):
try:
cache_comment = cache_comments[i]
except (TypeError, IndexError):
cache_comment = None
old_body = cache_comment.body if cache_comment else CMSBOT_TECHNICAL_MSG
new_body = REGEX_COMMITS_CACHE.sub("", old_body) + "<!-- bot cache: " + part + " -->"
if old_body == new_body:
continue
print("Saving bot cache ({0}/{1})".format(i + 1, len(data)))
if not dryRun:
if cache_comment:
cache_comment.edit(new_body)
else:
issue.create_comment(new_body)
else:
if cache_comment:
print("DRY RUN: Updating existing comment with text")
else:
print("DRY RUN: Creating technical comment with text")
print(new_body.encode("ascii", "ignore").decode())
# If new commit cache is smaller than previous one, cleanup old technical comments
if len(data) < len(cache_comments):
for i in range(len(data), len(cache_comments)):
print(
"Deleting bot cache comment ({0}/{1})".format(
i + 1 - len(data), len(cache_comments) - len(data)
)
)
if not dryRun:
cache_comments[i].delete()
def get_commenter_categories(commenter, comment_date):
if commenter not in L2_DATA:
return []
for item in L2_DATA[commenter]:
if comment_date < item["start_date"]:
return []
if ("end_date" not in item) or (comment_date < item["end_date"]):
return item["category"]
return []
def get_package_categories(package):
cats = []
for cat, packages in list(CMSSW_CATEGORIES.items()):
if package in packages:
cats.append(cat)
return cats
# Read a yaml file
def read_repo_file(repo_config, repo_file, default=None, is_yaml=True):
file_path = join(repo_config.CONFIG_DIR, repo_file)
contents = default
if exists(file_path):
with open(file_path, "r") as f:
if is_yaml:
contents = yaml.load(f, Loader=Loader)
else:
contents = load(f)
if not contents:
contents = default
return contents
#
# creates a properties file to trigger the test of the pull request
#
def create_properties_file_tests(
repository, pr_number, parameters, dryRun, abort=False, req_type="tests", repo_config=None
):
if abort:
req_type = "abort"
repo_parts = repository.split("/")
if req_type in "tests":
try:
if not repo_parts[0] in EXTERNAL_REPOS:
req_type = "user-" + req_type
elif not repo_config.CMS_STANDARD_TESTS:
req_type = "user-" + req_type
except:
pass
out_file_name = "trigger-%s-%s-%s.properties" % (
req_type,
repository.replace("/", "-"),
pr_number,
)
try:
if repo_config.JENKINS_SLAVE_LABEL:
parameters["RUN_LABEL"] = repo_config.JENKINS_SLAVE_LABEL
except:
pass
print("PropertyFile: ", out_file_name)
print("Data:", parameters)
create_property_file(out_file_name, parameters, dryRun)
def create_property_file(out_file_name, parameters, dryRun):
if dryRun:
print("Not creating properties file (dry-run): %s" % out_file_name)
return
print("Creating properties file %s" % out_file_name)
out_file = open(out_file_name, "w")
for k in parameters:
out_file.write("%s=%s\n" % (k, parameters[k]))
out_file.close()
# Update the milestone for a given issue.
def updateMilestone(repo, issue, pr, dryRun):
milestoneId = RELEASE_BRANCH_MILESTONE.get(pr.base.label.split(":")[1], None)
if not milestoneId:
print("Unable to find a milestone for the given branch")
return
if pr.state != "open":
print("PR not open, not setting/checking milestone")
return
if issue.milestone and issue.milestone.number == milestoneId:
return
milestone = repo.get_milestone(milestoneId)
print("Setting milestone to %s" % milestone.title)
if dryRun:
return
issue.edit(milestone=milestone)
def find_last_comment(issue, user, match):
last_comment = None
for comment in issue.get_comments():
if (user != comment.user.login) or (not comment.body):
continue
if not re.match(
match, comment.body.encode("ascii", "ignore").decode().strip("\n\t\r "), re.MULTILINE
):
continue
last_comment = comment
print("Matched comment from ", comment.user.login + " with comment id ", comment.id)
return last_comment
def modify_comment(comment, match, replace, dryRun):
comment_msg = comment.body.encode("ascii", "ignore").decode() if comment.body else ""
if match:
new_comment_msg = re.sub(match, replace, comment_msg)
else:
new_comment_msg = comment_msg + "\n" + replace
if new_comment_msg != comment_msg:
if not dryRun:
comment.edit(new_comment_msg)
print("Message updated")
return 0
# github_utils.set_issue_emoji -> https://github.com/PyGithub/PyGithub/blob/v1.56/github/Issue.py#L569
# github_utils.set_comment_emoji -> https://github.com/PyGithub/PyGithub/blob/v1.56/github/IssueComment.py#L149
# github_utils.delete_issue_emoji -> https://github.com/PyGithub/PyGithub/blob/v1.56/github/Issue.py#L587
# github_utils.delete_comment_emoji -> https://github.com/PyGithub/PyGithub/blob/v1.56/github/IssueComment.py#L168
def set_emoji(repository, comment, emoji, reset_other):
if reset_other:
for e in comment.get_reactions():
login = e.user.login.encode("ascii", "ignore").decode()
if login == get_gh_user() and e.content != emoji:
comment.delete_reaction(e.id)
comment.create_reaction(emoji)
def set_comment_emoji_cache(dryRun, bot_cache, comment, repository, emoji="+1", reset_other=True):
if dryRun:
return
comment_id = str(comment.id)
if (
(not comment_id in bot_cache["emoji"])
or (bot_cache["emoji"][comment_id] != emoji)
or (comment.reactions[emoji] == 0)
):
set_emoji(repository, comment, emoji, reset_other)
bot_cache["emoji"][comment_id] = emoji
return
def has_user_emoji(bot_cache, comment, repository, emoji, user):
e = None
comment_id = str(comment.id)
if (comment_id in bot_cache["emoji"]) and (comment.reactions[emoji] > 0):
e = bot_cache["emoji"][comment_id]
else:
# github_utils.get_issue_emojis -> https://github.com/PyGithub/PyGithub/blob/v1.56/github/Issue.py#L556
# github_utils.get_comment_emojis -> https://github.com/PyGithub/PyGithub/blob/v1.56/github/IssueComment.py#L135
emojis = comment.get_reactions()
for x in emojis:
if x["user"]["login"].encode("ascii", "ignore").decode() == user:
e = x["content"]
bot_cache["emoji"][comment_id] = x
break
return e and e == emoji
def get_assign_categories(line, extra_labels):
m = re.match(
r"^\s*(New categories assigned:\s*|(unassign|assign)\s+(from\s+|package\s+|))([a-zA-Z0-9/,\s-]+)\s*$",
line,
re.I,
)
if m:
assgin_type = m.group(1).lower()
if m.group(2):
assgin_type = m.group(2).lower()
new_cats = []
for ex_cat in m.group(4).replace(" ", "").split(","):
if "/" in ex_cat:
new_cats += get_package_categories(ex_cat)
add_nonblocking_labels([ex_cat], extra_labels)
continue
if not ex_cat in CMSSW_CATEGORIES:
continue
new_cats.append(ex_cat)
return (assgin_type.strip(), new_cats)
return ("", [])
def ignore_issue(repo_config, repo, issue):
ig_issues = getattr(repo_config, "IGNORE_ISSUES", {})
if issue.number in ig_issues:
return True
if (repo.full_name in ig_issues) and (issue.number in ig_issues[repo.full_name]):
return True
if re.match(BUILD_REL, issue.title):
return True
if issue.body:
if re.search(
CMSBOT_IGNORE_MSG,
issue.body.encode("ascii", "ignore").decode().split("\n", 1)[0].strip(),
re.I,
):
return True
return False
def notify_user(issue):
if issue.body and re.search(
CMSBOT_NO_NOTIFY_MSG,
issue.body.encode("ascii", "ignore").decode().split("\n", 1)[0].strip(),
re.I,
):
return False
return True
def check_extra_labels(first_line, extra_labels):
if "urgent" in first_line:
extra_labels["urgent"] = ["urgent"]
elif "backport" in first_line:
bp_pr = ""
if "#" in first_line:
bp_pr = first_line.split("#", 1)[1].strip()
else:
bp_pr = first_line.split("/pull/", 1)[1].strip("/").strip()
extra_labels["backport"] = ["backport", bp_pr]
def check_type_labels(first_line, extra_labels, state_labels):
ex_labels = {}
rem_labels = {}
for type_cmd in [x.strip() for x in first_line.split(" ", 1)[-1].split(",") if x.strip()]:
valid_lab = False
rem_lab = type_cmd[0] == "-"
if type_cmd[0] in ["-", "+"]:
type_cmd = type_cmd[1:]
for lab in TYPE_COMMANDS:
if re.match("^%s$" % TYPE_COMMANDS[lab][1], type_cmd, re.I):
lab_type = TYPE_COMMANDS[lab][2]
obj_labels = rem_labels if rem_lab else ex_labels
if lab_type not in obj_labels:
obj_labels[lab_type] = []
if (len(TYPE_COMMANDS[lab]) > 4) and TYPE_COMMANDS[lab][4] == "state":
state_labels[lab] = type_cmd
elif (len(TYPE_COMMANDS[lab]) > 3) and TYPE_COMMANDS[lab][3]:
obj_labels[lab_type].append(type_cmd)
else:
obj_labels[lab_type].append(lab)
valid_lab = True
break
if not valid_lab:
return valid_lab
for ltype in ex_labels:
if not ltype in extra_labels:
extra_labels[ltype] = []
for lab in ex_labels[ltype]:
extra_labels[ltype].append(lab)
for ltype in rem_labels:
if ltype not in extra_labels:
continue
for lab in rem_labels[ltype]:
if lab not in extra_labels[ltype]:
continue
while lab in extra_labels[ltype]:
extra_labels[ltype].remove(lab)
if not extra_labels[ltype]:
del extra_labels[ltype]
break
return True
def check_ignore_bot_tests(first_line, *args):
return first_line.upper().replace(" ", ""), None
def check_enable_bot_tests(first_line, *args):
tests = first_line.upper().replace(" ", "")
if "NONE" in tests:
tests = "NONE"
return tests, None
def check_extra_matrix_args(first_line, repo, params, mkey, param, *args):
kitem = mkey.split("_")
print(first_line, repo, params, mkey, param)
if kitem[-1] in ["input"] + EXTRA_RELVALS_TESTS:
param = param + "_" + kitem[-1].upper().replace("-", "_")
print(first_line, param)
return first_line, param
def check_matrix_extras(first_line, repo, params, mkey, param, *args):
kitem = mkey.split("_")
print(first_line, repo, params, mkey, param)
if kitem[-1] in EXTRA_RELVALS_TESTS:
param = param + "_" + kitem[-1].upper().replace("-", "_")
print(first_line, param)
return first_line, param
def check_pull_requests(first_line, repo, *args):
return " ".join(get_prs_list_from_string(first_line, repo)), None
def check_release_format(first_line, repo, params, *args):
rq = first_line
ra = ""
if "/" in rq:
rq, ra = rq.split("/", 1)
elif re.match("^" + ARCH_PATTERN + "$", rq):
ra = rq
rq = ""
params["ARCHITECTURE_FILTER"] = ra
return rq, None
def check_test_cmd(first_line, repo, params):
m = REGEX_TEST_REG.match(first_line)
if m:
wfs = ""
prs = []
cmssw_que = ""
print(m.groups())
if m.group(6):
wfs = ",".join(set(m.group(6).replace(" ", "").split(",")))
if m.group(11):
prs = get_prs_list_from_string(m.group(11), repo)
if m.group(20):
cmssw_que = m.group(20)
if m.group(25):
if "addpkg" in m.group(25):
params["EXTRA_CMSSW_PACKAGES"] = m.group(27).strip()
else:
params["BUILD_FULL_CMSSW"] = "true"
return (True, " ".join(prs), wfs, cmssw_que)
return (False, "", "", "")
def get_prs_list_from_string(pr_string="", repo_string=""):
prs = []
for pr in [
x.strip().split("/github.com/", 1)[-1].replace("/pull/", "#").strip("/")
for x in pr_string.split(",")
if x.strip()
]:
while "//" in pr:
pr = pr.replace("//", "/")
if pr.startswith("#"):
pr = repo_string + pr
prs.append(pr)
return prs
def parse_extra_params(full_comment, repo):
global ALL_CHECK_FUNCTIONS
xerrors = {"format": [], "key": [], "value": []}
matched_extra_args = {}
if ALL_CHECK_FUNCTIONS is None:
all_globals = globals()
ALL_CHECK_FUNCTIONS = dict(
[
(f, all_globals[f])
for f in all_globals
if f.startswith("check_") and callable(all_globals[f])
]
)
for l in full_comment[1:]:
l = l.strip()
if l.startswith("-"):
l = l[1:]
elif l.startswith("*"):
l = l[1:]
l = l.strip()
if l == "":
continue
if not "=" in l:
xerrors["format"].append("'%s'" % l)
continue
line_args = l.split("=", 1)
line_args[0] = line_args[0].replace(" ", "")
line_args[1] = line_args[1].strip()
found = False
for k, pttrn in MULTILINE_COMMENTS_MAP.items():
if not re.match("^(%s)$" % k, line_args[0], re.I):
continue
if (len(pttrn) < 3) or (not pttrn[2]):
line_args[1] = line_args[1].replace(" ", "")
param = pttrn[1]
if not re.match("^(%s)$" % pttrn[0], line_args[1], re.I):
xerrors["value"].append(line_args[0])
found = True
break
try:
func = "check_%s" % param.lower()
if func in ALL_CHECK_FUNCTIONS:
line_args[1], new_param = ALL_CHECK_FUNCTIONS[func](
line_args[1], repo, matched_extra_args, line_args[0], param
)
if new_param:
param = new_param
except:
pass
matched_extra_args[param] = line_args[1]
found = True
break
if not found:
xerrors["key"].append(line_args[0])
error_lines = []
for k in sorted(xerrors.keys()):
if xerrors[k]:
error_lines.append("%s:%s" % (k, ",".join(xerrors[k])))
if error_lines:
matched_extra_args = {"errors": "ERRORS: " + "; ".join(error_lines)}
return matched_extra_args
def multiline_check_function(first_line, comment_lines, repository):
if first_line.lower() not in ["test parameters", "test parameters:"]:
return False, {}, ""
extra_params = parse_extra_params(comment_lines, repository)
print(extra_params)
if "errors" in extra_params:
return False, {}, extra_params["errors"]
return True, extra_params, ""
def get_changed_files(repo, pr, use_gh_patch=False):
if (not use_gh_patch) and (pr.changed_files <= CHANGED_FILES_FROM_DIFF_THRESHOLD):
pr_files = []
for f in pr.get_files():
pr_files.append(f.filename)
try:
if f.previous_filename:
pr_files.append(f.previous_filename)
except:
pass
print("PR Files: ", pr_files)
return pr_files
cmd = (
"curl -s -L https://patch-diff.githubusercontent.com/raw/%s/pull/%s.diff | grep '^diff --git ' | sed 's|.* a/||;s| *b/| |' | tr ' ' '\n' | sort | uniq"
% (repo.full_name, pr.number)
)
e, o = run_cmd(cmd)
if e:
print(
"ERROR: Request to https://patch-diff.githubusercontent.com/raw/%s/pull/%s.diff failed"
% (repo.full_name, pr.number)
)
print(e)
exit(1)
if o:
return o.split("\n")
else:
print(
"ERROR: Request to https://patch-diff.githubusercontent.com/raw/%s/pull/%s.diff did not return any changes, is the PR too big?"
% (repo.full_name, pr.number)
)
exit(1)
def get_backported_pr(msg):
if BACKPORT_STR in msg:
bp_num = msg.split(BACKPORT_STR, 1)[-1].split("\n", 1)[0].strip()
if re.match("^[1-9][0-9]*$", bp_num):
return bp_num
return ""
def cmssw_file2Package(repo_config, filename):
try:
return repo_config.file2Package(filename)
except:
return "/".join(filename.split("/", 2)[0:2])
def get_jenkins_job(issue):
test_line = ""
for line in [l.strip() for l in issue.body.encode("ascii", "ignore").decode().split("\n")]:
if line.startswith("Build logs are available at:"):
test_line = line
if test_line:
test_line = test_line.split("Build logs are available at: ", 1)[-1].split("/")
if test_line[-4] == "job" and test_line[-1] == "console":
return test_line[-3], test_line[-2]
return "", ""
def get_status(context, statuses):
for s in statuses:
if s.context == context:
return s
return None
def get_status_state(context, statuses):
s = get_status(context, statuses)
if s:
return s.state
return ""
def dumps_maybe_compress(value):
json_ = dumps(value, separators=(",", ":"), sort_keys=True)
if len(json_) > BOT_CACHE_CHUNK_SIZE:
return "b64:" + base64.encodebytes(zlib.compress(json_.encode())).decode("ascii", "ignore")
else:
return json_
def loads_maybe_decompress(data):
if data.startswith("b64:"):
data = zlib.decompress(base64.decodebytes(data[4:].encode())).decode()
return loads(data)
def add_nonblocking_labels(chg_files, extra_labels):
for pkg_file in chg_files:
for ex_lab, pkgs_regexp in list(CMSSW_LABELS.items()):
for regex in pkgs_regexp:
if regex.match(pkg_file):
if not "mtype" in extra_labels:
extra_labels["mtype"] = []
extra_labels["mtype"].append(ex_lab)
print("Non-Blocking label:%s:%s:%s" % (ex_lab, regex.pattern, pkg_file))
break
if ("mtype" in extra_labels) and (not extra_labels["mtype"]):
del extra_labels["mtype"]
print("Extra non-blocking labels:", extra_labels)
return
# TODO: remove once we update pygithub
def get_commit_files(repo_, commit):
return (x["filename"] for x in get_commit(repo_.full_name, commit.sha)["files"])
def on_labels_changed(added_labels, removed_labels):
# Placeholder function replaced during testing
pass
def fetch_pr_result(url):
e, o = run_cmd("curl -k -s -L --max-time 60 %s" % url)
return e, o
def process_pr(repo_config, gh, repo, issue, dryRun, cmsbuild_user=None, force=False):
global L2_DATA
if (not force) and ignore_issue(repo_config, repo, issue):
return
gh_user_char = "@"
if not notify_user(issue):
gh_user_char = ""
api_rate_limits(gh)
prId = issue.number
repository = repo.full_name
repo_org, repo_name = repository.split("/", 1)
auto_test_repo = AUTO_TEST_REPOS
try:
if repo_config.AUTO_TEST_REPOS:
auto_test_repo = [repository]
else:
auto_test_repo = []
except:
pass
if not cmsbuild_user:
cmsbuild_user = repo_config.CMSBUILD_USER
print("Working on ", repo.full_name, " for PR/Issue ", prId, "with admin user", cmsbuild_user)
print("Notify User: ", gh_user_char)
update_CMSSW_LABELS(repo_config)
set_gh_user(cmsbuild_user)
cmssw_repo = repo_name == GH_CMSSW_REPO
cms_repo = repo_org in EXTERNAL_REPOS
external_repo = (repository != CMSSW_REPO_NAME) and (
len([e for e in EXTERNAL_REPOS if repo_org == e]) > 0
)
create_test_property = False
repo_cache = {repository: repo}
packages = set([])
chg_files = []
package_categories = {}
extra_labels = {"mtype": []}
state_labels = {}
add_external_category = False
signing_categories = set([])
new_package_message = ""
mustClose = False
reOpen = False
releaseManagers = []
signatures = {}
watchers = []
# Process Pull Request
pkg_categories = set([])
REGEX_TYPE_CMDS = (
r"^(type|(build-|)state)\s+(([-+]|)[a-z][a-z0-9_-]+)(\s*,\s*([-+]|)[a-z][a-z0-9_-]+)*$"
)
REGEX_EX_CMDS = r"^urgent$|^backport\s+(of\s+|)(#|http(s|):/+github\.com/+%s/+pull/+)\d+$" % (
repo.full_name
)
known_ignore_tests = "%s" % MULTILINE_COMMENTS_MAP["ignore_test(s|)"][0]
REGEX_EX_IGNORE_CHKS = r"^ignore\s+((%s)(\s*,\s*(%s))*|none)$" % (
known_ignore_tests,
known_ignore_tests,
)
REGEX_EX_ENABLE_TESTS = r"^enable\s+(%s)$" % MULTILINE_COMMENTS_MAP[ENABLE_TEST_PTRN][0]
L2_DATA = init_l2_data(repo_config, cms_repo)
last_commit_date = None
last_commit_obj = None
push_test_issue = False
requestor = issue.user.login.encode("ascii", "ignore").decode()
ignore_tests = ""
enable_tests = ""
commit_statuses = None
bot_status_name = "bot/jenkins"
bot_ack_name = "bot/ack"
bot_test_param_name = "bot/test_parameters"
cms_status_prefix = "cms"
bot_status = None
code_checks_status = []
pre_checks_state = {}
default_pre_checks = ["code-checks"]
# For future pre_checks
# if prId>=somePRNumber: default_pre_checks+=["some","new","checks"]
pre_checks_url = {}
events = defaultdict(list)
all_commits = []
all_commit_shas = set()
ok_too_many_commits = False
warned_too_many_commits = False
ok_too_many_files = False
warned_too_many_files = False
is_draft_pr = False
if issue.pull_request:
pr = repo.get_pull(prId)
if pr.changed_files == 0:
print("Ignoring: PR with no files changed")
return
if pr.draft:
print("Draft PR, mentions turned off")
is_draft_pr = True
gh_user_char = ""
if cmssw_repo and cms_repo and (pr.base.ref == CMSSW_DEVEL_BRANCH):
if pr.state != "closed":
print("This pull request must go in to master branch")
if not dryRun:
edit_pr(repo.full_name, prId, base="master")
msg = format(
"%(gh_user_char)s%(user)s, %(dev_branch)s branch is closed for direct updates. cms-bot is going to move this PR to master branch.\n"
"In future, please use cmssw master branch to submit your changes.\n",
user=requestor,
gh_user_char=gh_user_char,
dev_branch=CMSSW_DEVEL_BRANCH,
)
issue.create_comment(msg)
return
# A pull request is by default closed if the branch is a closed one.
if is_closed_branch(pr.base.ref):
mustClose = True
# Process the changes for the given pull request so that we can determine the