-
Notifications
You must be signed in to change notification settings - Fork 19
/
commands.py
870 lines (757 loc) · 29.5 KB
/
commands.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
"""
Define a few commands
"""
import random
import os
import re
import subprocess
import git
import pipes
import mock
import keen
import time
import traceback
import sys
from textwrap import dedent
# from friendlyautopep8 import run_on_cwd
from .utils import Session, fix_issue_body, fix_comment_body
from .scopes import admin, everyone, write
green = "\033[0;32m"
yellow = "\033[0;33m"
red = "\033[0;31m"
blue = "\x1b[0;34m"
normal = "\033[0m"
@everyone
def replyuser(*, session, payload, arguments, local_config=None):
print("I'm replying to a user, look at me.")
comment_url = payload["issue"]["comments_url"]
user = payload["comment"]["user"]["login"]
c = random.choice(
(
"Helloooo @{user}, I'm Mr. Meeseeks! Look at me!",
"Look at me, @{user}, I'm Mr. Meeseeks! ",
"I'm Mr. Meeseek, @{user}, Look at meee ! ",
)
)
session.post_comment(comment_url, c.format(user=user))
@write
def say(*, session, payload, arguments, local_config=None):
print("Oh, got local_config", local_config)
comment_url = payload.get("issue", payload.get("pull_request"))["comments_url"]
session.post_comment(comment_url, "".join(arguments))
@write
def debug(*, session, payload, arguments, local_config=None):
print("DEBUG")
print("session", session)
print("payload", payload)
print("arguments", arguments)
print("local_config", local_config)
@everyone
def party(*, session, payload, arguments, local_config=None):
comment_url = payload.get("issue", payload.get("pull_request"))["comments_url"]
parrot = "![party parrot](http://cultofthepartyparrot.com/parrots/hd/parrot.gif)"
session.post_comment(comment_url, parrot * 10)
@everyone
def zen(*, session, payload, arguments, local_config=None):
comment_url = payload.get("issue", payload.get("pull_request"))["comments_url"]
session.post_comment(
comment_url,
dedent(
"""
Zen of Python ([pep 20](https://www.python.org/dev/peps/pep-0020/))
```
>>> import this
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
```
"""
),
)
@admin
def replyadmin(*, session, payload, arguments, local_config=None):
comment_url = payload["issue"]["comments_url"]
user = payload["issue"]["user"]["login"]
session.post_comment(
comment_url, "Hello @{user}. Waiting for your orders.".format(user=user)
)
@admin
def pep8ify(*, session, payload, arguments, local_config=None):
print("===== pe8ifying =====")
print(payload)
print("===== ========= =====")
# collect initial payload
prnumber = payload["issue"]["number"]
prtitle = payload["issue"]["title"]
org_name = payload["repository"]["owner"]["login"]
repo_name = payload["repository"]["name"]
# collect extended payload on the PR
print("== Collecting data on Pull-request...")
r = session.ghrequest(
"GET",
"https://api.github.com/repos/{}/{}/pulls/{}".format(
org_name, repo_name, prnumber
),
json=None,
)
pr_data = r.json()
head_sha = pr_data["head"]["sha"]
base_sha = pr_data["base"]["sha"]
branch = pr_data["head"]["ref"]
author_login = pr_data["head"]["repo"]["owner"]["login"]
repo_name = pr_data["head"]["repo"]["name"]
# that will likely fail, as if PR, we need to bypass the fact that the
# requester has technically no access to committer repo.
target_session = yield "{}/{}".format(author_login, repo_name)
if not target_session:
comment_url = payload["issue"]["comments_url"]
session.post_comment(
comment_url,
body="I'm afraid I can't do that. Maybe I need to be installed on target repository ?\n"
"Click [here](https://github.com/integrations/meeseeksdev/installations/new) to do that.".format(
botname="meeseeksdev"
),
)
return
# clone locally
# this process can take some time, regen token
atk = target_session.token()
if os.path.exists(repo_name):
print("== Cleaning up previsous work... ")
subprocess.run("rm -rf {}".format(repo_name).split(" "))
print("== Done cleaning ")
print("== Cloning current repository, this can take some time..")
process = subprocess.run(
[
"git",
"clone",
"https://x-access-token:{}@github.com/{}/{}".format(
atk, author_login, repo_name
),
]
)
print("== Cloned..")
process.check_returncode()
subprocess.run("git config --global user.email meeseeksbot@jupyter.org".split(" "))
subprocess.run("git config --global user.name FriendlyBot".split(" "))
# do the pep8ify on local filesystem
repo = git.Repo(repo_name)
print("== Fetching branch to pep8ify on ...")
repo.remotes.origin.fetch("{}:workbranch".format(branch))
repo.git.checkout("workbranch")
print("== Fetching Commits to pep8ify...")
repo.remotes.origin.fetch("{head_sha}".format(head_sha=head_sha))
print("== All has been fetched correctly")
os.chdir(repo_name)
subprocess.run("pep8radius --in-place".split(" ") + [base_sha])
os.chdir("..")
# write the commit message
msg = "Autofix pep 8 of #%i: %s" % (prnumber, prtitle) + "\n\n"
repo.git.commit("-am", msg)
# Push the pep8ify work
print("== Pushing work....:")
repo.remotes.origin.push("workbranch:{}".format(branch))
repo.git.checkout("master")
repo.branches.workbranch.delete(repo, "workbranch", force=True)
@write
def safe_backport(session, payload, arguments, local_config=None):
"""[to] {branch}"""
import builtins
print = lambda *args, **kwargs: builtins.print(" [backport]", *args, **kwargs)
s_clone_time = 0
s_success = False
s_reason = "unknown"
s_fork_time = 0
s_clean_time = 0
s_ff_time = 0
def keen_stats():
nonlocal s_slug
nonlocal s_clone_time
nonlocal s_success
nonlocal s_reason
nonlocal s_fork_time
nonlocal s_clean_time
nonlocal s_ff_time
keen.add_event(
"backport_stats",
{
"slug": s_slug,
"clone_time": s_clone_time,
"fork_time": s_fork_time,
"clean_time": s_clean_time,
"success": s_success,
"fast_forward_opt_time": s_ff_time,
"reason": s_reason,
},
)
if arguments is None:
arguments = ""
target_branch = arguments
if target_branch.startswith("to "):
target_branch = target_branch[3:].strip()
# collect initial payload
if "issue" not in payload:
print(
green
+ 'debug safe_autobackport, "issue" not in payload, likely trigerd by milisetone merge.'
+ normal
)
prnumber = payload.get("issue", payload).get("number")
prtitle = payload.get("issue", payload.get("pull_request", {})).get("title")
org_name = payload["repository"]["owner"]["login"]
repo_name = payload["repository"]["name"]
comment_url = payload.get("issue", payload.get("pull_request"))["comments_url"]
maybe_wrong_named_branch = False
s_slug = f"{org_name}/{repo_name}"
try:
existing_branches = session.ghrequest(
"GET", f"https://api.github.com/repos/{org_name}/{repo_name}/branches"
).json()
existing_branches_names = {b["name"] for b in existing_branches}
if target_branch not in existing_branches_names:
print(
red
+ f"Request to backport to `{target_branch}`, which does not seem to exist. Known : {existing_branches_names}"
)
maybe_wrong_named_branch = True
else:
print(green + f"found branch {target_branch}")
except Exception:
import traceback
traceback.print_exc()
s_reason = "Exception line 256"
keen_stats()
try:
# collect extended payload on the PR
print("== Collecting data on Pull-request...")
r = session.ghrequest(
"GET",
"https://api.github.com/repos/{}/{}/pulls/{}".format(
org_name, repo_name, prnumber
),
json=None,
)
pr_data = r.json()
merge_sha = pr_data["merge_commit_sha"]
body = pr_data["body"]
milestone = pr_data["milestone"]
if milestone:
milestone_number = pr_data["milestone"].get("number", None)
else:
milestone_number = None
print("----------------------------------------")
# print('milestone data :', pr_data['milestone'])
print("----------------------------------------")
if not target_branch.strip():
milestone_title = pr_data["milestone"]["title"]
parts = milestone_title.split(".")
parts[-1] = "x"
infered_target_branch = ".".join(parts)
print("inferring branch....", infered_target_branch)
target_branch = infered_target_branch
keen.add_event("backport_infering_branch", {"infering_remove_x": 1})
if milestone_number:
milestone_number = int(milestone_number)
labels_names = []
try:
label_names = [l["name"] for l in pr_data["labels"]]
if not label_names and ("issue" in payload.keys()):
labels_names = [l["name"] for l in payload["issue"]["labels"]]
except KeyError:
print("Did not find labels|", pr_data)
# clone locally
# this process can take some time, regen token
atk = session.token()
# FORK it.
fork_epoch = time.time()
frk = session.personal_request(
"POST", f"https://api.github.com/repos/{org_name}/{repo_name}/forks"
).json()
for i in range(5):
ff = session.personal_request("GET", frk["url"], raise_for_status=False)
if ff.status_code == 200:
keen.add_event("fork_wait", {"n": i})
break
time.sleep(1)
s_fork_time = time.time() - fork_epoch
## optimize-fetch-experiment
print("Attempting FF")
if os.path.exists(repo_name):
try:
re_fetch_epoch = time.time()
print("FF: Git set-url origin")
subprocess.run(
[
"git",
"remote",
"set-url",
"origin",
f"https://x-access-token:{atk}@github.com/{org_name}/{repo_name}",
],
cwd=repo_name,
).check_returncode()
repo = git.Repo(repo_name)
print("FF: Git fetch master")
repo.remotes.origin.fetch("master")
repo.git.checkout("master")
print("FF: Reset hard origin/master")
subprocess.run(
["git", "reset", "--hard", "origin/master"], cwd=repo_name
).check_returncode()
print("FF: Git describe tags....")
subprocess.run(["git", "describe", "--tag"], cwd=repo_name)
re_fetch_delta = time.time() - re_fetch_epoch
print(blue + f"FF took {re_fetch_delta}s")
s_ff_time = re_fetch_delta
except Exception as e:
# something went wrong. Kill repository it's going to be
# recloned.
clean_epoch = time.time()
if os.path.exists(repo_name):
print("== Cleaning up previsous work... ")
subprocess.run("rm -rf {}".format(repo_name).split(" "))
print("== Done cleaning ")
s_clean_time = time.time() - clean_epoch
import traceback
traceback.print_exc()
## end optimise-fetch-experiment
clone_epoch = time.time()
action = "set-url"
what_was_done = "Fast-Forwarded"
if not os.path.exists(repo_name):
print("== Cloning current repository, this can take some time..")
process = subprocess.run(
[
"git",
"clone",
"https://x-access-token:{}@github.com/{}/{}".format(
atk, org_name, repo_name
),
]
)
process.check_returncode()
action = "add"
what_was_done = "Cloned"
s_clone_time = time.time() - clone_epoch
process = subprocess.run(
[
"git",
"remote",
action,
session.personnal_account_name,
f"https://x-access-token:{session.personnal_account_token}@github.com/{session.personnal_account_name}/{repo_name}",
],
cwd=repo_name,
)
print("==", what_was_done)
process.check_returncode()
subprocess.run(
"git config --global user.email meeseeksdevbot@jupyter.org".split(" ")
)
subprocess.run("git config --global user.name MeeseeksDev[bot]".split(" "))
# do the backport on local filesystem
repo = git.Repo(repo_name)
print("== Fetching branch to backport on ... {}".format(target_branch))
repo.remotes.origin.fetch("refs/heads/{}:workbranch".format(target_branch))
repo.git.checkout("workbranch")
print(
"== Fetching Commits to {mergesha} backport...".format(mergesha=merge_sha)
)
repo.remotes.origin.fetch("{mergesha}".format(num=prnumber, mergesha=merge_sha))
print("== All has been fetched correctly")
# remove mentions from description, to avoid pings:
description = body.replace("@", " ").replace("#", " ")
print("Cherry-picking %s" % merge_sha)
args = ("-m", "1", merge_sha)
msg = "Backport PR #%i: %s" % (prnumber, prtitle)
remote_submit_branch = f"auto-backport-of-pr-{prnumber}-on-{target_branch}"
try:
with mock.patch.dict("os.environ", {"GIT_EDITOR": "true"}):
try:
repo.git.cherry_pick(*args)
except git.GitCommandError as e:
if "is not a merge." in e.stderr:
print(
"Likely not a merge PR...Attempting squash and merge picking."
)
args = (merge_sha,)
repo.git.cherry_pick(*args)
else:
raise
except git.GitCommandError as e:
if ("git commit --allow-empty" in e.stderr) or (
"git commit --allow-empty" in e.stdout
):
session.post_comment(
comment_url,
"Can't Dooooo.... It seem like this is already backported (commit is empty)."
"I won't do anything. MrMeeseeks out.",
)
print(e.stderr)
print("----")
print(e.stdout)
print("----")
s_reason = "empty commit"
keen_stats()
return
elif "after resolving the conflicts" in e.stderr:
# TODO, here we should also do a git merge --abort
# to avoid thrashing the cache at next backport request.
cmd = " ".join(pipes.quote(arg) for arg in sys.argv)
print(
"\nPatch did not apply. Resolve conflicts (add, not commit), then re-run `%s`"
% cmd,
file=sys.stderr,
)
session.post_comment(
comment_url,
f"""Owee, I'm MrMeeseeks, Look at me.
There seem to be a conflict, please backport manually. Here are approximate instructions:
1. Checkout backport branch and update it.
```
$ git checkout {target_branch}
$ git pull
```
2. Cherry pick the first parent branch of the this PR on top of the older branch:
```
$ git cherry-pick -m1 {merge_sha}
```
3. You will likely have some merge/cherry-pick conflict here, fix them and commit:
```
$ git commit -am {msg!r}
```
4. Push to a named branch :
```
git push YOURFORK {target_branch}:{remote_submit_branch}
```
5. Create a PR against branch {target_branch}, I would have named this PR:
> "Backport PR #{prnumber} on branch {target_branch}"
And apply the correct labels and milestones.
Congratulation you did some good work ! Hopefully your backport PR will be tested by the continuous integration and merged soon!
If these instruction are inaccurate, feel free to [suggest an improvement](https://github.com/MeeseeksBox/MeeseeksDev).
""",
)
org = payload["repository"]["owner"]["login"]
repo = payload["repository"]["name"]
num = payload.get("issue", payload).get("number")
url = f"https://api.github.com/repos/{org}/{repo}/issues/{num}/labels"
print("trying to apply still needs manual backport")
reply = session.ghrequest(
"POST", url, json=["Still Needs Manual Backport"]
)
print("Should be applied:", reply)
s_reason = "conflicts"
keen_stats()
return
else:
session.post_comment(
comment_url,
"Oops, something went wrong applying the patch... Please have a look at my logs.",
)
print(e.stderr)
print("----")
print(e.stdout)
print("----")
s_reason = "Unknown error line 491"
keen_stats()
return
except Exception as e:
session.post_comment(
comment_url, "Hum, I actually crashed, that should not have happened."
)
print("\n" + e.stderr.decode("utf8", "replace"), file=sys.stderr)
print("\n" + repo.git.status(), file=sys.stderr)
keen.add_event("error", {"git_crash": 1})
s_reason = "Unknown error line 501"
keen_stats()
return
# write the commit message
repo.git.commit("--amend", "-m", msg)
print("== PR #%i applied, with msg:" % prnumber)
print()
print(msg)
print("== ")
# Push the backported work
print("== Pushing work....:")
try:
print(
f"Tryign to push to {remote_submit_branch} of {session.personnal_account_name}"
)
repo.remotes[session.personnal_account_name].push(
"workbranch:{}".format(remote_submit_branch)
)
except Exception as e:
import traceback
traceback.print_exc()
print("could not push to self remote")
s_reason = "Could not push"
keen_stats()
# TODO comment on issue
print(e)
repo.git.checkout("master")
repo.branches.workbranch.delete(repo, "workbranch", force=True)
# TODO checkout master and get rid of branch
# Make the PR on GitHub
print(
"try to create PR with milestone",
milestone_number,
"and labels",
labels_names,
)
new_pr = session.personal_request(
"POST",
"https://api.github.com/repos/{}/{}/pulls".format(org_name, repo_name),
json={
"title": f"Backport PR #{prnumber} on branch {target_branch} ({prtitle})",
"body": msg,
"head": "{}:{}".format(
session.personnal_account_name, remote_submit_branch
),
"base": target_branch,
},
).json()
new_number = new_pr["number"]
resp = session.ghrequest(
"PATCH",
"https://api.github.com/repos/{}/{}/issues/{}".format(
org_name, repo_name, new_number
),
json={"milestone": milestone_number, "labels": labels_names},
)
# print(resp.json())
except Exception as e:
extra_info = ""
if maybe_wrong_named_branch:
extra_info = "\n\n It seem that the branch you are trying to backport to does not exists."
session.post_comment(
comment_url,
"Something went wrong ... Please have a look at my logs." + extra_info,
)
keen.add_event("error", {"unknown_crash": 1})
print("Something went wrong")
print(e)
s_reason = "Remote branches does not exists"
keen_stats()
raise
resp.raise_for_status()
print("Backported as PR", new_number)
s_reason = "Success"
s_success = True
keen_stats()
return new_pr
@admin
def tag(session, payload, arguments, local_config=None):
"tag[, tag, [...] ]"
print("Got local config for tag: ", local_config)
org = payload["repository"]["owner"]["login"]
repo = payload["repository"]["name"]
num = payload.get("issue", payload.get("pull_request")).get("number")
url = f"https://api.github.com/repos/{org}/{repo}/issues/{num}/labels"
arguments = arguments.replace("'", '"')
quoted = re.findall(r'\"(.+?)\"',arguments.replace("'", '"'))
for q in quoted:
arguments = arguments.replace('"%s"' % q, '')
tags = [arg.strip() for arg in arguments.split(",") if arg.strip()] + quoted
print('raw tags:', tags)
to_apply = []
not_applied = []
try:
label_payload = session.ghrequest(
"GET", f"https://api.github.com/repos/{org}/{repo}/labels"
)
label_payloads = [label_payload]
def get_next_link(req):
all_links = req.headers.get('Link')
if 'rel="next"' in all_links:
links = all_links.split(',')
next_link = [l for l in links if 'next' in l][0] # assume only one.
if next_link:
return next_link.split(';')[0].strip(' <>')
# let's assume no more than 200 labels
resp = label_payload
try:
for i in range(10):
print('get labels page',i)
next_link = get_next_link(resp)
if next_link:
resp = session.ghrequest( "GET", next_link)
label_payloads.append(resp)
else:
break
except Exception:
traceback.print_exc()
know_labels = []
for p in label_payloads:
know_labels.extend([label["name"] for label in p.json()])
print('known labels', know_labels)
not_known_tags = [t for t in tags if t not in know_labels]
known_tags = [t for t in tags if t in know_labels]
print('known tags', known_tags)
print('known labels', not_known_tags)
# try to look at casing
nk = []
known_lower_normal = {l.lower(): l for l in know_labels}
print('known labels lower', known_lower_normal)
for t in not_known_tags:
target = known_lower_normal.get(t.lower())
print('mapping t', t, target)
if target:
known_tags.append(t)
else:
print('will not apply', t)
nk.append(t)
to_apply = known_tags
not_applied = nk
except Exception:
print(red + "something went wrong getting labels" + normal)
traceback.print_exc()
if local_config:
only = set(local_config.get("only", []))
any_tags = local_config.get("any", False)
if any_tags:
print("not filtering, any tags set")
elif only:
allowed_tags = [t for t in to_apply if t.lower() in only]
not_allowed_tags = [t for t in to_apply if t.lower() not in only]
print("will only allow", allowed_tags)
print("will refuse", not_allowed_tags)
to_apply = allowed_tags
not_applied.extend(not_allowed_tags)
if to_apply:
session.ghrequest("POST", url, json=to_apply)
if not_applied:
comment_url = payload.get("issue", payload.get("pull_request"))["comments_url"]
lf = "`,`".join(not_applied)
user = payload.get("comment", {}).get("user", {}).get("login", None)
session.post_comment(
comment_url,
f"Aww {user}, I was not able to apply the following label(s): `{lf}`. Either "
"because they are not existing labels on this repository or because you do not have the permission to apply these."
"I tried my best to guess by looking at the casing, but was unable to find matching labels.",
)
@admin
def untag(session, payload, arguments, local_config=None):
"tag[, tag, [...] ]"
org = payload["repository"]["owner"]["login"]
repo = payload["repository"]["name"]
num = payload.get("issue", payload.get("pull_request")).get("number")
tags = [arg.strip() for arg in arguments.split(",")]
name = "{name}"
url = "https://api.github.com/repos/{org}/{repo}/issues/{num}/labels/{name}".format(
**locals()
)
no_untag = []
for tag in tags:
try:
session.ghrequest("DELETE", url.format(name=tag))
except Exception:
no_untag.append(tag)
print("was not able to remove tags:", no_untag)
@write
def migrate_issue_request(
*, session: Session, payload: dict, arguments: str, local_config=None
):
"""Todo:
- Works through pagination of comments
- Works through pagination of labels
Link to non-migrated labels.
"""
if arguments.startswith("to "):
arguments = arguments[3:]
org_repo = arguments
org, repo = arguments.split("/")
target_session = yield org_repo
if not target_session:
session.post_comment(
payload["issue"]["comments_url"], "It appears that I can't do that"
)
return
issue_title = payload["issue"]["title"]
issue_body = payload["issue"]["body"]
original_org = payload["repository"]["owner"]["login"]
original_repo = payload["repository"]["name"]
original_poster = payload["issue"]["user"]["login"]
original_number = payload["issue"]["number"]
migration_requester = payload["comment"]["user"]["login"]
request_id = payload["comment"]["id"]
original_labels = [l["name"] for l in payload["issue"]["labels"]]
if original_labels:
available_labels = target_session.ghrequest(
"GET",
"https://api.github.com/repos/{org}/{repo}/labels".format(
org=org, repo=repo
),
None,
).json()
available_labels = [l["name"] for l in available_labels]
migrate_labels = [l for l in original_labels if l in available_labels]
not_set_labels = [l for l in original_labels if l not in available_labels]
new_response = target_session.create_issue(
org,
repo,
issue_title,
fix_issue_body(
issue_body,
original_poster,
original_repo,
original_org,
original_number,
migration_requester,
),
labels=migrate_labels,
)
new_issue = new_response.json()
new_comment_url = new_issue["comments_url"]
original_comments = session.ghrequest(
"GET", payload["issue"]["comments_url"], None
).json()
for comment in original_comments:
if comment["id"] == request_id:
continue
body = comment["body"]
op = comment["user"]["login"]
url = comment["html_url"]
target_session.post_comment(
new_comment_url,
body=fix_comment_body(body, op, url, original_org, original_repo),
)
if not_set_labels:
body = "I was not able to apply the following label(s): %s " % ",".join(
not_set_labels
)
target_session.post_comment(new_comment_url, body=body)
session.post_comment(
payload["issue"]["comments_url"],
body="Done as {}/{}#{}.".format(org, repo, new_issue["number"]),
)
session.ghrequest("PATCH", payload["issue"]["url"], json={"state": "closed"})
@write
def quote(*, session, payload, arguments, local_config=None):
if arguments.lower() == "over the world":
comment_url = payload["issue"]["comments_url"]
user = payload["issue"]["user"]["login"]
session.post_comment(
comment_url,
"""
> MeeseeksDev: Gee, {user}, what do you want to do tonight?
{user}: The same thing we do every night, MeeseeksDev - try to take over the world!
""".format(
user=user
),
)