-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathplugin.py
More file actions
1671 lines (1434 loc) · 69.4 KB
/
plugin.py
File metadata and controls
1671 lines (1434 loc) · 69.4 KB
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
"""
.. module: hubcommander.command_plugins.github.plugin
:platform: Unix
:copyright: (c) 2017 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Mike Grima <mgrima@netflix.com>
"""
import json
import requests
import time
from tabulate import tabulate
from hubcommander.bot_components.bot_classes import BotCommander
from hubcommander.bot_components.decorators import hubcommander_command, auth
from hubcommander.bot_components.slack_comm import send_info, send_success, send_error, send_raw
from hubcommander.bot_components.parse_functions import extract_repo_name, parse_toggles, extract_multiple_repo_names
from hubcommander.command_plugins.github.config import GITHUB_URL, GITHUB_VERSION, ORGS, USER_COMMAND_DICT
from hubcommander.command_plugins.github.parse_functions import lookup_real_org, validate_homepage
from hubcommander.command_plugins.github.decorators import repo_must_exist, github_user_exists, branch_must_exist, \
team_must_exist
class GitHubPlugin(BotCommander):
def __init__(self):
super().__init__()
self.commands = {
"!ListOrgs": {
"command": "!ListOrgs",
"func": self.list_org_command,
"user_data_required": False,
"help": "Lists the GitHub organizations that are managed.",
"enabled": True
},
"!CreateRepo": {
"command": "!CreateRepo",
"func": self.create_repo_command,
"user_data_required": True,
"help": "Creates a new PRIVATE [default] repository in the specified GitHub organization.",
"enabled": True
},
"!AddCollab": {
"command": "!AddCollab",
"func": self.add_outside_collab_command,
"user_data_required": True,
"help": "Adds an outside collaborator to a specific repository in a specific GitHub organization.",
"permitted_permissions": ["push", "pull"], # To grant admin, add this to the config for
"enabled": True # this command in the config.py.
},
"!RemoveCollab": {
"command": "!RemoveCollab",
"func": self.remove_outside_collab_command,
"user_data_required": True,
"help": "Removes an outside collaborator from a specific repository in a specific GitHub organization.",
"enabled": True # this command in the config.py.
},
"!SetRepoPermissions": {
"command": "!SetRepoPermissions",
"func": self.set_repo_permissions_command,
"user_data_required": True,
"help": "Sets team permissions to a specific repository in a specific GitHub organization.",
"permitted_permissions": ["push", "pull"], # To grant admin, add this to the config for
"enabled": True # this command in the config.py.
},
"!SetDescription": {
"command": "!SetDescription",
"func": self.set_description_command,
"user_data_required": True,
"help": "Adds/Modifies a GitHub repo's description.",
"enabled": True
},
"!SetHomepage": {
"command": "!SetHomepage",
"func": self.set_repo_homepage_command,
"user_data_required": True,
"help": "Adds/Modifies a GitHub repo's homepage URL.",
"enabled": True
},
"!SetDefaultBranch": {
"command": "!SetDefaultBranch",
"func": self.set_default_branch_command,
"user_data_required": True,
"help": "Sets the default branch for a repo.",
"enabled": True # It is HIGHLY recommended you have auth enabled for this!!
},
"!ListPRs": {
"command": "!ListPRs",
"func": self.list_pull_requests_command,
"user_data_required": True,
"help": "List the Pull Requests for a repo.",
"permitted_states": ["open", "closed", "all"],
"enabled": True
},
"!DeleteRepo": {
"command": "!DeleteRepo",
"func": self.delete_repo_command,
"user_data_required": True,
"help": "Delete a GitHub repository.",
"enabled": True # It is HIGHLY recommended you have auth enabled for this!!
},
"!AddUserToTeam": {
"command": "!AddUserToTeam",
"func": self.add_user_to_team_command,
"user_data_required": True,
"help": "Adds a GitHub user to a specific team inside the organization.",
"permitted_roles": ["member", "maintainer"],
"enabled": True
},
"!SetBranchProtection": {
"command": "!SetBranchProtection",
"func": self.set_branch_protection_command,
"user_data_required": True,
"help": "Toggles the branch protection for a repo.",
"enabled": True # It is HIGHLY recommended you have auth enabled for this!!
},
"!ListKeys": {
"command": "!ListKeys",
"func": self.list_deploy_keys_command,
"user_data_required": True,
"help": "List the Deploy Keys for a repo.",
"enabled": True
},
"!AddKey": {
"command": "!AddKey",
"func": self.add_deploy_key_command,
"user_data_required": True,
"help": "Add Deploy Key for a repo.",
"enabled": True
},
"!DeleteKey": {
"command": "!DeleteKey",
"func": self.delete_deploy_key_command,
"user_data_required": True,
"help": "Delete Deploy Key from a repo.",
"enabled": True
},
"!GetKey": {
"command": "!GetKey",
"func": self.get_deploy_key_command,
"user_data_required": True,
"help": "Get Deploy Key Public Key",
"enabled": True
},
"!SetTopics": {
"command": "!SetTopics",
"func": self.set_repo_topics_command,
"user_data_required": True,
"help": "Sets the Topics for a GitHub repo",
"enabled": True
}
}
self.token = None
# For org alias lookup convenience:
self.org_lookup = None
def setup(self, secrets, **kwargs):
self.token = secrets["GITHUB"]
# Create the lookup table:
self.org_lookup = {}
for org in ORGS.items():
# The lookup table is the lowercase real name of the org, plus the aliases, along with
# a tuple containing the full real name of the org, with the org dict details:
self.org_lookup[org[0].lower()] = (org[0], org[1])
for alias in org[1]["aliases"]:
self.org_lookup[alias] = (org[0], org[1])
# Add user-configurable arguments to the command_plugins dictionary:
for cmd, keys in USER_COMMAND_DICT.items():
self.commands[cmd].update(keys)
@staticmethod
def list_org_command(data):
"""
The "!ListOrgs" command. Lists all organizations that this bot manages.
:param data:
:return:
"""
headers = ["Alias", "Organization"]
rows = []
for org in ORGS.items():
rows.append([org[0].lower(), org[0]])
for alias in org[1]["aliases"]:
rows.append([alias, org[0]])
send_info(data["channel"], "```{}```".format(tabulate(rows, headers=headers)), markdown=True, thread=data["ts"])
@hubcommander_command(
name="!SetDescription",
usage="!SetDescription <OrgWithRepo> <Repo> <\"The description in quotes\">",
description="This will set the repository's description.",
required=[
dict(name="org", properties=dict(type=str, help="The organization that contains the repo."),
validation_func=lookup_real_org, validation_func_kwargs={}),
dict(name="repo", properties=dict(type=str, help="The repository to set the description on."),
validation_func=extract_repo_name, validation_func_kwargs={}),
dict(name="description", properties=dict(type=str, help="The description to set in quotes. (Empty quotes "
"clears)"),
lowercase=False),
],
optional=[]
)
@auth()
@repo_must_exist()
def set_description_command(self, data, user_data, org, repo, description):
"""
Changes a repository description.
Command is as follows: !setdescription <organization> <repo> <description>
:param data:
:param user_data:
:param org:
:param repo:
:param description:
:return:
"""
# Output that we are doing work:
send_info(data["channel"], "@{}: Working, Please wait...".format(user_data["name"]), thread=data["ts"])
# Modify the description:
if not (self.make_repo_edit(data, user_data, repo, org, description=description)):
return
if description == "":
send_success(data["channel"],
"@{}: The {}/{} repository's description field has been cleared."
.format(user_data["name"], org, repo), markdown=True, thread=data["ts"])
else:
send_success(data["channel"],
"@{}: The {}/{} repository's description has been modified to:\n"
"`{}`.".format(user_data["name"], org, repo, description), markdown=True, thread=data["ts"])
@hubcommander_command(
name="!SetHomepage",
usage="!SetHomepage <OrgWithRepo> <Repo> <\"http://theHomePageUrlInQuotes\" - OR - \"\" to remove>",
description="This will set the repository's homepage.",
required=[
dict(name="org", properties=dict(type=str, help="The organization that contains the repo."),
validation_func=lookup_real_org, validation_func_kwargs={}),
dict(name="repo", properties=dict(type=str, help="The repository to set the homepage on."),
validation_func=extract_repo_name, validation_func_kwargs={}),
dict(name="homepage", properties=dict(type=str, help="The homepage to set in quotes. (Empty quotes "
"clears)"),
validation_func=validate_homepage, validation_func_kwargs={})
],
optional=[]
)
@auth()
@repo_must_exist()
def set_repo_homepage_command(self, data, user_data, org, repo, homepage):
"""
Changes a repository's homepage.
Command is as follows: !sethomepage <organization> <repo> <homepage>
:param data:
:param user_data:
:param org:
:param repo:
:param homepage:
:return:
"""
# Output that we are doing work:
send_info(data["channel"], "@{}: Working, Please wait...".format(user_data["name"]), thread=data["ts"])
# Modify the homepage:
if not (self.make_repo_edit(data, user_data, repo, org, homepage=homepage)):
return
# Done:
if homepage == "":
send_success(data["channel"],
"@{}: The {}/{} repository's homepage field has been cleared."
.format(user_data["name"], org, repo, homepage), markdown=True, thread=data["ts"])
else:
send_success(data["channel"],
"@{}: The {}/{} repository's homepage has been modified to:\n"
"`{}`.".format(user_data["name"], org, repo, homepage), markdown=True, thread=data["ts"])
@hubcommander_command(
name="!AddCollab",
usage="!AddCollab <OutsideCollabId> <OrgWithRepo> <Repos(Comma separated if more than 1)> <Permission>",
description="This will add an outside collaborator to a repository with the given permission.",
required=[
dict(name="collab", properties=dict(type=str, help="The outside collaborator's GitHub ID.")),
dict(name="org", properties=dict(type=str, help="The organization that contains the repo."),
validation_func=lookup_real_org, validation_func_kwargs={}),
dict(name="repos", properties=dict(type=str, help="A comma separated list (or not if just 1) of repos to "
"add the collaborator to."),
validation_func=extract_multiple_repo_names, validation_func_kwargs={}),
dict(name="permission", properties=dict(type=str.lower, help="The permission to grant, must be one "
"of: `{values}`"),
choices="permitted_permissions"),
],
optional=[]
)
@auth()
@repo_must_exist()
@github_user_exists("collab")
def add_outside_collab_command(self, data, user_data, collab, org, repos, permission):
"""
Adds an outside collaborator to repository (or multiple repos) with a specified permission.
Command is as follows: !addcollab <outside_collab_id> <organization> <repo> <permission>
:param permission:
:param repo:
:param org:
:param collab:
:param user_data:
:param data:
:return:
"""
# Output that we are doing work:
send_info(data["channel"], "@{}: Working, Please wait...".format(user_data["name"]), thread=data["ts"])
# Grant access:
try:
for r in repos:
self.add_outside_collab_to_repo(collab, r, org, permission)
except ValueError as ve:
send_error(data["channel"],
"@{}: Problem encountered adding the user as an outside collaborator.\n"
"The response code from GitHub was: {}".format(user_data["name"], str(ve)), thread=data["ts"])
return
except Exception as e:
send_error(data["channel"],
"@{}: Problem encountered adding the user as an outside collaborator.\n"
"Here are the details: {}".format(user_data["name"], str(e)), thread=data["ts"])
return
# Done:
send_success(data["channel"],
"@{}: The GitHub user: `{}` has been added as an outside collaborator with `{}` "
"permissions to {} in {}.".format(user_data["name"], collab, permission,
", ".join(repos), org),
markdown=True, thread=data["ts"])
@hubcommander_command(
name="!RemoveCollab",
usage="!RemoveCollab <OutsideCollabId> <OrgWithRepo> <Repos(Comma separated if more than 1)>",
description="This will remove an outside collaborator from a repository.",
required=[
dict(name="collab", properties=dict(type=str, help="The outside collaborator's GitHub ID.")),
dict(name="org", properties=dict(type=str, help="The organization that contains the repo."),
validation_func=lookup_real_org, validation_func_kwargs={}),
dict(name="repos", properties=dict(type=str, help="A comma separated list (or not if just 1) of repos to "
"add the collaborator to."),
validation_func=extract_multiple_repo_names, validation_func_kwargs={}),
],
optional=[]
)
@auth()
@repo_must_exist()
@github_user_exists("collab")
def remove_outside_collab_command(self, data, user_data, collab, org, repos):
"""
Removes an outside collaborator to repository (or multiple repos).
Command is as follows: !removecollab <outside_collab_id> <organization> <repo>
:param repo:
:param org:
:param collab:
:param user_data:
:param data:
:return:
"""
# Output that we are doing work:
send_info(data["channel"], "@{}: Working, Please wait...".format(user_data["name"]), thread=data["ts"])
# Grant access:
try:
for r in repos:
self.remove_outside_collab_from_repo(collab, r, org)
except ValueError as ve:
send_error(data["channel"],
"@{}: Problem encountered removing the user as an outside collaborator.\n"
"The response code from GitHub was: {}".format(user_data["name"], str(ve)), thread=data["ts"])
return
except Exception as e:
send_error(data["channel"],
"@{}: Problem encountered removing the user as an outside collaborator.\n"
"Here are the details: {}".format(user_data["name"], str(e)), thread=data["ts"])
return
# Done:
send_success(data["channel"],
"@{}: The GitHub user: `{}` has been removed as an outside collaborator "
"from {} in {}.".format(user_data["name"], collab,
", ".join(repos), org),
markdown=True, thread=data["ts"])
@hubcommander_command(
name="!SetRepoPermissions",
usage="!SetRepoPermissions <OrgWithRepo> <Repo> <Team> <Permission>",
description="This will set team permissions on a repository .",
required=[
dict(name="org", properties=dict(type=str, help="The organization that contains the repo."),
validation_func=lookup_real_org, validation_func_kwargs={}),
dict(name="repo", properties=dict(type=str, help="The repository to add the team to."),
validation_func=extract_repo_name, validation_func_kwargs={}),
dict(name="team", properties=dict(type=str, help="The team's name.")),
dict(name="permission", properties=dict(type=str.lower, help="The permission to grant, must be one "
"of: `{values}`"),
choices="permitted_permissions")
],
optional=[]
)
@auth()
@repo_must_exist()
@team_must_exist()
def set_repo_permissions_command(self, data, user_data, team, org, repo, permission):
"""
Adds a team to a repository with a specified permission.
Command is as follows: !SetRepoPermissions <Team> <OrgWithRepo> <Repo> <Permission>
:param permission:
:param repo:
:param org:
:param team:
:param user_data:
:param data:
:return:
"""
# Output that we are doing work:
send_info(data["channel"], "@{}: Working, Please wait...".format(user_data["name"]), thread=data["ts"])
# Grant access:
try:
self.set_repo_permissions(repo, org, team, permission)
except ValueError as ve:
send_error(data["channel"],
"@{}: Problem encountered adding the team.\n"
"The response code from GitHub was: {}".format(user_data["name"], str(ve)), thread=data["ts"])
return
except Exception as e:
send_error(data["channel"],
"@{}: Problem encountered adding the team.\n"
"Here are the details: {}".format(user_data["name"], str(e)), thread=data["ts"])
return
# Done:
send_success(data["channel"],
"@{}: The GitHub team: `{}` has been added to the repo with `{}` "
"permissions to {}/{}.".format(user_data["name"], team, permission,
org, repo),
markdown=True, thread=data["ts"])
@hubcommander_command(
name="!AddUserToTeam",
usage="!AddUserToTeam <UserGitHubId> <Org> <Team> <Role>",
description="This will add a GitHub user to a team with a specified role.",
required=[
dict(name="user_id", properties=dict(type=str, help="The user's GitHub ID.")),
dict(name="org", properties=dict(type=str, help="The organization that contains the team."),
validation_func=lookup_real_org, validation_func_kwargs={}),
dict(name="team", properties=dict(type=str, help="The team to add the user to.")),
dict(name="role", properties=dict(type=str.lower, help="The role to grant the user. "
"Must be one of: `{values}`"),
choices="permitted_roles"),
],
optional=[]
)
@auth()
@github_user_exists("user_id")
@team_must_exist()
def add_user_to_team_command(self, data, user_data, user_id, org, team, role):
"""
Adds a GitHub user to a team with a specified role.
Command is as follows: !addusertoteam <user_id> <organization> <team> <role>
:param role:
:param team:
:param org:
:param user_id:
:param user_data:
:param data:
:return:
"""
# Output that we are doing work:
send_info(data["channel"], "@{}: Working, Please wait...".format(user_data["name"]), thread=data["ts"])
# Do it:
try:
self.invite_user_to_gh_org_team(org, team, user_id, role)
except ValueError as ve:
send_error(data["channel"],
"@{}: Problem encountered adding the user as a team member.\n"
"The response code from GitHub was: {}".format(user_data["name"], str(ve)), thread=data["ts"])
return
except Exception as e:
send_error(data["channel"],
"@{}: Problem encountered adding the user as a team member.\n"
"Here are the details: {}".format(user_data["name"], str(e)), thread=data["ts"])
return
# Done:
send_success(data["channel"],
"@{}: The GitHub user: `{}` has been added as a team member with `{}` "
"permissions to {}/{}.".format(user_data["name"], user_id, role,
org, team),
markdown=True, thread=data["ts"])
@hubcommander_command(
name="!CreateRepo",
usage="!CreateRepo <OrgToCreateRepoIn> <NewRepoName>",
description="This will create a new repository on GitHub.",
required=[
dict(name="org", properties=dict(type=str, help="The organization to create the repo in."),
validation_func=lookup_real_org, validation_func_kwargs={}),
dict(name="repo", properties=dict(type=str, help="The name of the new repo to create."),
lowercase=False, validation_func=extract_repo_name, validation_func_kwargs={}),
],
optional=[
# TODO: Need to add support for optional teams to add. See https://github.com/Netflix/hubcommander/issues/28
]
)
@auth()
def create_repo_command(self, data, user_data, org, repo):
"""
Creates a new repository (default is private unless the org is public only).
Command is as follows: !createrepo <organization> <new_repo>
:param repo:
:param org:
:param user_data:
:param data:
:return:
"""
# Output that we are doing work:
send_info(data["channel"], "@{}: Working, Please wait...".format(user_data["name"]), thread=data["ts"])
# Check if the repo already exists:
try:
result = self.check_gh_for_existing_repo(repo, org)
if result:
# Check if the repo was renamed:
if "{}/{}".format(org, repo) == result["full_name"]:
send_error(data["channel"],
"@{}: This repository already exists in {}!".format(user_data["name"], org),
thread=data["ts"])
return
except Exception as e:
send_error(data["channel"],
"@{}: I encountered a problem:\n\n{}".format(user_data["name"], e), thread=data["ts"])
return
# Great!! Create the repository:
try:
visibility = True if not ORGS[org]["public_only"] else False
self.create_new_repo(repo, org, visibility)
except Exception as e:
send_error(data["channel"],
"@{}: I encountered a problem:\n\n{}".format(user_data["name"], e), thread=data["ts"])
return
# Need to wait a bit to ensure that the repo actually exists.
time.sleep(2)
# Grant the proper teams access to the repository:
try:
for perm_dict in ORGS[org]["new_repo_teams"]:
self.set_repo_permissions(repo, org, perm_dict["name"], perm_dict["perm"])
except Exception as e:
send_error(data["channel"],
"@{}: I encountered a problem setting repo permissions for team {team}: \n\n{exc}".format(
user_data["name"], team=perm_dict["name"], exc=e), thread=data["ts"])
return
# All done!
message = "@{}: The new repo: {} has been created in {}.\n".format(user_data["name"], repo, org)
message += "You can access the repo at: https://github.com/{org}/{repo}\n".format(org=org,
repo=repo)
visibility = "PRIVATE" if visibility else "PUBLIC"
message += "The repository is {visibility}.\n" \
"You are free to set up the repo as you like.\n".format(visibility=visibility)
send_success(data["channel"], message, thread=data["ts"])
@hubcommander_command(
name="!DeleteRepo",
usage="!DeleteRepo <OrgThatHasRepo> <RepoToDelete>",
description="This will delete a repo from a GitHub organization.",
required=[
dict(name="org", properties=dict(type=str, help="The organization that contains the repo."),
validation_func=lookup_real_org, validation_func_kwargs={}),
dict(name="repo", properties=dict(type=str, help="The name of the new repo to delete."),
validation_func=extract_repo_name, validation_func_kwargs={}),
],
optional=[]
)
@auth()
@repo_must_exist()
def delete_repo_command(self, data, user_data, org, repo):
"""
Deletes a repository.
Command is as follows: !deleterepo <organization> <repo>
:param repo:
:param org:
:param user_data:
:param data:
:return:
"""
# Output that we are doing work:
send_info(data["channel"], "@{}: Working, Please wait...".format(user_data["name"]), thread=data["ts"])
# Delete the repository:
try:
self.delete_repo(repo, org)
except Exception as e:
send_error(data["channel"],
"@{}: I encountered a problem:\n\n{}".format(user_data["name"], e), thread=data["ts"])
return
# All done!
message = "@{}: The repo: {} has been deleted from {}.\n".format(user_data["name"], repo, org)
send_success(data["channel"], message, thread=data["ts"])
@hubcommander_command(
name="!SetDefaultBranch",
usage="!SetDefaultBranch <OrgThatHasRepo> <Repo> <BranchName>",
description="This will set the default branch on a GitHub repo.\n\n"
"Please Note: GitHub prefers lowercase branch names. You may encounter issues "
"with uppercase letters.",
required=[
dict(name="org", properties=dict(type=str, help="The organization that contains the repo."),
validation_func=lookup_real_org, validation_func_kwargs={}),
dict(name="repo", properties=dict(type=str, help="The name of the repo to set the default on."),
validation_func=extract_repo_name, validation_func_kwargs={}),
dict(name="branch", properties=dict(type=str, help="The name of the branch to set as default. "
"(Case-Sensitive)"), lowercase=False),
],
optional=[]
)
@auth()
@repo_must_exist()
@branch_must_exist()
def set_default_branch_command(self, data, user_data, org, repo, branch):
"""
Sets the default branch of a repo.
Command is as follows: !setdefaultbranch <organization> <repo> <branch>
:param branch:
:param repo:
:param org:
:param user_data:
:param data:
:return:
"""
# Output that we are doing work:
send_info(data["channel"], "@{}: Working, Please wait...".format(user_data["name"]), thread=data["ts"])
# Set the default branch:
if not (self.make_repo_edit(data, user_data, repo, org, default_branch=branch)):
return
# Done:
send_success(data["channel"],
"@{}: The {}/{} repository's default branch has been set to: `{}`."
.format(user_data["name"], org, repo, branch), markdown=True, thread=data["ts"])
@hubcommander_command(
name="!SetBranchProtection",
usage="!SetBranchProtection <OrgThatHasRepo> <Repo> <BranchName> <On|Off>",
description="This will enable basic branch protection to a GitHub repo.\n\n"
"Please Note: GitHub prefers lowercase branch names. You may encounter issues "
"with uppercase letters.",
required=[
dict(name="org", properties=dict(type=str, help="The organization that contains the repo."),
validation_func=lookup_real_org, validation_func_kwargs={}),
dict(name="repo", properties=dict(type=str, help="The name of the repo to set the default on."),
validation_func=extract_repo_name, validation_func_kwargs={}),
dict(name="branch", properties=dict(type=str, help="The name of the branch to set as default. "
"(Case-Sensitive)"), lowercase=False),
dict(name="toggle", properties=dict(type=str, help="Toggle to enable or disable branch protection"),
validation_func=parse_toggles, validation_func_kwargs={})
],
optional=[]
)
@auth()
@repo_must_exist()
@branch_must_exist()
def set_branch_protection_command(self, data, user_data, org, repo, branch, toggle):
"""
Sets branch protection on a repo (CURRENTLY VERY LIMITED).
Command is as follows: !setbranchprotection <organization> <repo> <branch> <on/off>
:param toggle:
:param branch:
:param repo:
:param org:
:param user_data:
:param data:
:return:
"""
# Output that we are doing work:
send_info(data["channel"], "@{}: Working, Please wait...".format(user_data["name"]), thread=data["ts"])
# Change the protection status:
try:
self.set_branch_protection(repo, org, branch, toggle)
except requests.exceptions.RequestException as re:
send_error(data["channel"],
"@{}: Problem encountered setting branch protection.\n"
"The response code from GitHub was: {}".format(user_data["name"], str(re)), thread=data["ts"])
return
# Done:
status = "ENABLED" if toggle else "DISABLED"
send_success(data["channel"],
"@{}: The {}/{} repository's {} branch protection status is now: {}."
.format(user_data["name"], org, repo, branch, status), markdown=True, thread=data["ts"])
@hubcommander_command(
name="!ListPRs",
usage="!ListPRs <OrgThatHasRepo> <Repo> <State>",
description="This will list pull requests for a repo.",
required=[
dict(name="org", properties=dict(type=str, help="The organization that contains the repo."),
validation_func=lookup_real_org, validation_func_kwargs={}),
dict(name="repo", properties=dict(type=str, help="The name of the repo to list PRs on."),
validation_func=extract_repo_name, validation_func_kwargs={}),
dict(name="state", properties=dict(type=str.lower, help="The state of the PR. Must be one of: `{values}`"),
choices="permitted_states")
],
optional=[]
)
@auth()
@repo_must_exist()
def list_pull_requests_command(self, data, user_data, org, repo, state):
"""
List the Pull Requests for a repo.
Command is as follows: !listprs <organization> <repo> <state>
:param state:
:param repo:
:param org:
:param user_data:
:param data:
:return:
"""
# Output that we are doing work:
send_info(data["channel"], "@{}: Working, Please wait...".format(user_data["name"]), thread=data["ts"])
# Grab all PRs [All states]
pull_requests = self.get_repo_prs(data, user_data, repo, org, state)
if not pull_requests:
if isinstance(pull_requests, list):
send_info(data["channel"],
"@{}: No matching pull requests were found in *{}*.".format(user_data["name"], repo),
thread=data["ts"])
return
headers = ["#PR", "Title", "Opened by", "Assignee", "State"]
rows = []
for pr in pull_requests:
assignee = pr['assignee']['login'] if pr['assignee'] is not None else '-'
rows.append([pr['number'], pr['title'], pr['user']['login'], assignee, pr['state'].title()])
# Done:
send_raw(data["channel"], text="Repository: *{}* \n\n```{}```".format(repo, tabulate(rows, headers=headers,
tablefmt='orgtbl')),
thread=data["ts"])
@hubcommander_command(
name="!ListKeys",
usage="!ListKeys <OrgThatHasRepo> <Repo>",
description="This will list deploy keys for a repo.",
required=[
dict(name="org", properties=dict(type=str, help="The organization that contains the repo."),
validation_func=lookup_real_org, validation_func_kwargs={}),
dict(name="repo", properties=dict(type=str, help="The name of the repo to list deploy keys on."),
validation_func=extract_repo_name, validation_func_kwargs={})
],
optional=[]
)
@auth()
@repo_must_exist()
def list_deploy_keys_command(self, data, user_data, org, repo):
"""
List the Deploy Keys for a repo.
Command is as follows: !ListKeys <organization> <repo>
:param repo:
:param org:
:param user_data:
:param data:
:return:
"""
# Output that we are doing work:
send_info(data["channel"], "@{}: Working, Please wait...".format(user_data["name"]), thread=data["ts"])
# Grab all Deploy Keys
deploy_keys = self.get_repo_deploy_keys(data, user_data, repo, org)
if not (deploy_keys):
if isinstance(deploy_keys, list):
send_info(data["channel"],
"@{}: No deploy keys were found in *{}*.".format(user_data["name"], repo), thread=data["ts"])
return
headers = ["ID#", "Title", "Read-only", "Created"]
rows = []
for key in deploy_keys:
# Set a default readonly state
readonly = 'True'
if not key['read_only']:
readonly = 'False'
rows.append([key['id'], key['title'], readonly, key['created_at']])
# Done:
send_raw(data["channel"], text="Deploy Keys: *{}* \n\n```{}```".format(repo, tabulate(rows, headers=headers,
tablefmt='orgtbl')),
thread=data["ts"])
@hubcommander_command(
name="!AddKey",
usage="!AddKey <OrgThatHasRepo> <Repo> <KeyTitle> <ReadOnlyToggle on|off> <\"KeyInQuotes\">",
description="This will add a deploy key to a repo.",
required=[
dict(name="org", properties=dict(type=str, help="The organization that contains the repo."),
validation_func=lookup_real_org, validation_func_kwargs={}),
dict(name="repo", properties=dict(type=str, help="The name of the repo to add a deploy key to."),
validation_func=extract_repo_name, validation_func_kwargs={}),
dict(name="title", properties=dict(type=str, help="The name of the deploy key. (Case-Sensitive)"),
lowercase=False),
dict(name="readonly", properties=dict(type=str, help="Toggle to indicate if this key is read-only."),
validation_func=parse_toggles, validation_func_kwargs={}),
dict(name="pubkey", properties=dict(type=str, help="The SSH *PUBLIC* key in quotes. (Case-Sensitive)"),
lowercase=False)
],
optional=[]
)
@auth()
@repo_must_exist()
def add_deploy_key_command(self, data, user_data, org, repo, title, readonly, pubkey):
"""
Add a Deploy Key to a repo.
Command is as follows: !AddKey <organization> <repo> <title> <readonly> "<pubkey>"
:param pubkey:
:param title:
:param repo:
:param org:
:param user_data:
:param readonly:
:param data:
:return:
"""
# Output that we are doing work:
send_info(data["channel"], "@{}: Working, Please wait...".format(user_data["name"]), thread=data["ts"])
# Add the Deploy Key
result = self.add_repo_deploy_key(data, user_data, repo, org, title, pubkey, readonly)
# If we have an error due to invalid key, we are returning False from the API response method
if not result:
send_error(data["channel"], "@{}: The deploy key entered was invalid -- or -- it already exists."
.format(user_data["name"], repo), thread=data["ts"])
return
if not result.get('id'):
send_error(data["channel"], "@{}: Adding deploy key failed.".format(user_data["name"], repo),
thread=data["ts"])
return
# Done:
send_raw(data["channel"],
text="Deploy Key *{}* with ID *{}* successfully added to *{}*\n\n".format(result['title'],
result['id'], repo),
thread=data["ts"])
@hubcommander_command(
name="!DeleteKey",
usage="!DeleteKey <OrgThatHasRepo> <Repo> <KeyId>",
description="This will delete the specified deploy key from a repo.",
required=[
dict(name="org", properties=dict(type=str, help="The organization that contains the repo."),
validation_func=lookup_real_org, validation_func_kwargs={}),
dict(name="repo", properties=dict(type=str, help="The name of the repo to remove the deploy key from."),
validation_func=extract_repo_name, validation_func_kwargs={}),
dict(name="id", properties=dict(type=int, help="The ID of the key. Please run !ListKeys to get this."))
],
optional=[]
)
@auth()
@repo_must_exist()
def delete_deploy_key_command(self, data, user_data, org, repo, id):
"""
Delete a Deploy Key from a repo.
Command is as follows: !DeleteKey <organization> <repo> <id>
:param id:
:param repo:
:param org:
:param user_data:
:param data:
:return:
"""
# Output that we are doing work:
send_info(data["channel"], "@{}: Working, Please wait...".format(user_data["name"]), thread=data["ts"])
# Grab the Deploy Key (check that it exists)
deploy_key = self.get_repo_deploy_key_by_id(data, user_data, repo, org, id)
if not deploy_key:
if deploy_key is None:
send_error(data["channel"],
"@{}: Deploy Key with ID: `{}` is not present for the {}/{} repo.".format(user_data["name"],
id, org, repo),
markdown=True, thread=data["ts"])
else:
send_error(data["channel"], "@{}: Error Retrieving Deploy Key `{}`.".format(user_data["name"], id),
markdown=True, thread=data["ts"])
return
# Delete the Deploy Key
result = self.delete_repo_deploy_key(data, user_data, repo, org, id)
if not result:
send_info(data["channel"], "@{}: Error deleting deploy key ID *{}*.".format(user_data["name"], id),
markdown=True, thread=data["ts"])
return
# Done:
send_raw(data["channel"], text="Deploy Key ID *{}* successfully deleted from *{}*\n\n".format(id, repo),
thread=data["ts"])
@hubcommander_command(
name="!GetKey",
usage="!GetKey <OrgThatHasRepo> <Repo> <KeyId>",
description="This will fetch the details of a specified deploy key from a repo.",
required=[
dict(name="org", properties=dict(type=str, help="The organization that contains the repo."),
validation_func=lookup_real_org, validation_func_kwargs={}),
dict(name="repo", properties=dict(type=str, help="The name of the repo to fetch the deploy key "
"details from."),
validation_func=extract_repo_name, validation_func_kwargs={}),
dict(name="id", properties=dict(type=int, help="The ID of the key. Please run !ListKeys to get this."))
],
optional=[]
)
@auth()
@repo_must_exist()
def get_deploy_key_command(self, data, user_data, org, repo, id):
"""
Get a given Deploy Key.
Command is as follows: !GetKey <organization> <repo> <id>
:param id:
:param repo:
:param org:
:param user_data:
:param data:
:return:
"""
# Output that we are doing work:
send_info(data["channel"], "@{}: Working, Please wait...".format(user_data["name"]), thread=data["ts"])
# Grab the Deploy Key
deploy_key = self.get_repo_deploy_key_by_id(data, user_data, repo, org, id)
if not deploy_key:
if deploy_key is None:
send_error(data["channel"],
"@{}: Deploy Key with ID: `{}` is not present for the {}/{} repo.".format(user_data["name"],
id, org, repo),
markdown=True, thread=data["ts"])
else:
send_error(data["channel"], "@{}: Error Retrieving Deploy Key `{}`.".format(user_data["name"], id),
markdown=True, thread=data["ts"])
return
# Done:
send_info(data["channel"],
"@{}: Deploy Key ID `{}`: ```{}```".format(user_data["name"], id, deploy_key['key']), markdown=True,
thread=data["ts"])
@hubcommander_command(