-
Notifications
You must be signed in to change notification settings - Fork 407
/
Copy pathbranch.py
1337 lines (1062 loc) · 45.3 KB
/
branch.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
"""Implementation of a branch on a repository."""
import typing as t
from . import commit
from .. import decorators
from .. import models
if t.TYPE_CHECKING:
from .. import apps as tapps
from .. import users as tusers
from . import orgs
class _Branch(models.GitHubCore):
"""A representation of a branch on a repository.
See also https://developer.github.com/v3/repos/branches/
This object has the following attributes:
"""
# The Accept header will likely be removable once the feature is out of
# preview mode. See: http://git.io/v4O1e
PREVIEW_HEADERS = {"Accept": "application/vnd.github.loki-preview+json"}
class_name = "Repository Branch"
def _update_attributes(self, branch):
self.commit = commit.MiniCommit(branch["commit"], self)
self.name = branch["name"]
base = self.commit.url.split("/commit", 1)[0]
self._api = self._build_url("branches", self.name, base_url=base)
def _repr(self):
return f"<{self.class_name} [{self.name}]>"
def latest_sha(self, differs_from=""):
"""Check if SHA-1 is the same as the remote branch.
See: https://git.io/vaqIw
:param str differs_from:
(optional), sha to compare against
:returns:
string of the SHA or None
:rtype:
str on Python 3
"""
# If-None-Match returns 200 instead of 304 value does not have quotes
headers = {
"Accept": "application/vnd.github.v3.sha",
"If-None-Match": f'"{differs_from}"',
}
base = self._api.split("/branches", 1)[0]
url = self._build_url("commits", self.name, base_url=base)
resp = self._get(url, headers=headers)
if self._boolean(resp, 200, 304):
return resp.text
return None
@decorators.requires_auth
def protection(self) -> "BranchProtection":
"""Retrieve the protections enabled for this branch.
See:
https://developer.github.com/v3/repos/branches/#get-branch-protection
:returns:
The protections enabled for this branch.
:rtype:
:class:`~github3.repos.branch.BranchProtection`
"""
url = self._build_url("protection", base_url=self._api)
resp = self._get(url)
json = self._json(resp, 200)
return BranchProtection(json, self)
@decorators.requires_auth
def protect(
self,
required_status_checks: t.Optional[t.Mapping[str, t.Any]],
enforce_admins: t.Optional[bool],
required_pull_request_reviews: t.Optional[t.Mapping[str, t.Any]],
restrictions: t.Optional[t.Mapping[str, t.Sequence[str]]],
required_linear_history: t.Optional[bool] = None,
allow_force_pushes: t.Optional[bool] = None,
allow_deletions: t.Optional[bool] = None,
required_conversation_resolution: t.Optional[bool] = None,
) -> "BranchProtection":
"""Enable force push protection and configure status check enforcement.
See also:
https://docs.github.com/en/rest/reference/repos#update-branch-protection
.. versionchanged:: 3.0.0
The GitHub API changed since the last release this was updated in.
As such the parameters have to change here.
:param requireed_status_checks:
Required. Require status checks to pass before merging. Set to null
to disable.
:param enforce_admins:
Required. Enforce all configured restrictions for administrators.
Set to true to enforce required status checks for repository
administrators. Set to null to disable.
:param required_pull_request_reviews:
Required. Require at least one approving review on a pull request,
before merging. Set to null to disable.
:param restrictions:
Required. Restrict who can push to the protected branch. User,
app, and team restrictions are only available for
organization-owned repositories. Set to null to disable.
:param required_linear_history:
Enforces a linear commit Git history, which prevents anyone from
pushing merge commits to a branch. Set to true to enforce a linear
commit history. Set to false to disable a linear commit Git
history. Your repository must allow squash merging or rebase
merging before you can enable a linear commit history. Default:
false. For more information, see "Requiring a linear commit
history" in the GitHub Help documentation.
:param allow_force_pushes:
Permits force pushes to the protected branch by anyone with write
access to the repository. Set to true to allow force pushes. Set
to false or null to block force pushes. Default: false. For more
information, see "Enabling force pushes to a protected branch" in
the GitHub Help documentation."
:param allow_deletions:
Allows deletion of the protected branch by anyone with write
access to the repository. Set to false to prevent deletion of the
protected branch. Default: false. For more information, see
"Enabling force pushes to a protected branch" in the GitHub Help
documentation.
:param required_conversation_resolution:
Requires all conversations on code to be resolved before a pull
request can be merged into a branch that matches this rule. Set to
false to disable. Default: false.
:returns:
BranchProtection if successful
:rtype:
:class:`BranchProtection`
"""
edit = {
"required_status_checks": required_status_checks,
"enforce_admins": enforce_admins,
"required_pull_request_reviews": required_pull_request_reviews,
"restrictions": restrictions,
}
if required_linear_history is not None:
edit["required_linear_history"] = required_linear_history
if allow_force_pushes is not None:
edit["allow_force_pushes"] = allow_force_pushes
if allow_deletions is not None:
edit["allow_deletions"] = allow_deletions
if required_conversation_resolution is not None:
edit[
"required_conversation_resolution"
] = required_conversation_resolution
url = self._build_url("protection", base_url=self._api)
resp = self._put(url, json=edit)
json = self._json(resp, 200)
return BranchProtection(json, self)
@decorators.requires_auth
def sync_with_upstream(self) -> t.Mapping[str, str]:
"""Synchronize this branch with the upstream.
.. warning::
This API endpoint is still in Beta per gitHub
.. versionadded:: 3.0.0
Sync a branch of a forked repository to keep it up-to-date with the
upstream repository.
See also:
https://docs.github.com/en/rest/reference/repos#sync-a-fork-branch-with-the-upstream-repository
:returns:
The dictionary described in the documentation
:rtype:
dict
"""
base = self._api.split("/branches", 1)[0]
url = self._build_url("merge-upstream", base_url=base)
json = self._json(self._post(url), 200)
return json
@decorators.requires_auth
def unprotect(self) -> bool:
"""Disable protections on this branch."""
return self._boolean(
self._delete(self._build_url("protection", base_url=self._api)),
200,
403,
)
class Branch(_Branch):
"""The representation of a branch returned in a collection.
GitHub's API returns different amounts of information about repositories
based upon how that information is retrieved. This object exists to
represent the limited amount of information returned for a specific
branch in a collection. For example, you would receive this class when
calling :meth:`~github3.repos.repo.Repository.branches`. To provide a
clear distinction between the types of branches, github3.py uses different
classes with different sets of attributes.
This object has the same attributes as a
:class:`~github3.repos.branch.ShortBranch` as well as the following:
.. attribute:: links
The dictionary of URLs returned by the API as ``_links``.
.. attribute:: protected
A boolean attribute that describes whether this branch is protected or
not.
.. attribute:: original_protection
.. versionchanged:: 1.1.0
To support a richer branch protection API, this is the new name
for the information formerly stored under the attribute
``protection``.
A dictionary with details about the protection configuration of this
branch.
.. attribute:: protection_url
The URL to access and manage details about this branch's protection.
"""
class_name = "Repository Branch"
def _update_attributes(self, branch):
super()._update_attributes(branch)
self.commit = commit.ShortCommit(branch["commit"], self)
#: Returns '_links' attribute.
self.links = branch["_links"]
#: Provides the branch's protection status.
self.protected = branch["protected"]
self.original_protection = branch["protection"]
self.protection_url = branch["protection_url"]
if self.links and "self" in self.links:
self._api = self.links["self"]
class ShortBranch(_Branch):
"""The representation of a branch returned in a collection.
GitHub's API returns different amounts of information about repositories
based upon how that information is retrieved. This object exists to
represent the limited amount of information returned for a specific
branch in a collection. For example, you would receive this class when
calling :meth:`~github3.repos.repo.Repository.branches`. To provide a
clear distinction between the types of branches, github3.py uses different
classes with different sets of attributes.
This object has the following attributes:
.. attribute:: commit
A :class:`~github3.repos.commit.MiniCommit` representation of the
newest commit on this branch with the associated repository metadata.
.. attribute:: name
The name of this branch.
"""
class_name = "Short Repository Branch"
_refresh_to = Branch
@t.overload
def refresh(self, conditional: bool = False) -> Branch: # noqa: D102
...
class BranchProtection(models.GitHubCore):
"""The representation of a branch's protection.
.. seealso::
`Branch protection API documentation`_
GitHub's documentation of branch protection
.. versionchanged:: 3.0.0
Added ``required_linear_history``, ``allow_force_pushes``,
``allow_deletions``, and ``required_conversation_resolution``.
This object has the following attributes:
.. attribute:: enforce_admins
A :class:`~github3.repos.branch.ProtectionEnforceAdmins` instance
representing whether required status checks are required for admins.
.. attribute:: restrictions
A :class:`~github3.repos.branch.ProtectionRestrictions` representing
who can push to this branch. Team and user restrictions are only
available for organization-owned repositories.
.. attribute:: required_pull_request_reviews
A :class:`~github3.repos.branch.ProtectionRequiredPullRequestReviews`
representing the protection provided by requiring pull request
reviews.
.. attribute:: required_status_checks
A :class:`~github3.repos.branch.ProtectionRequiredStatusChecks`
representing the protection provided by requiring status checks.
.. attribute:: required_linear_history
.. versionadded:: 3.0.0
A :class:`~github3.repos.branch.ProtectionRequiredLinearHistory`
representing the information returned by the API about this
protection.
.. attribute:: allow_force_pushes
.. versionadded:: 3.0.0
A :class:`~github3.repos.branch.ProtectionAllowForcePushes`
representing the information returned by the API about this
protection.
.. attribute:: allow_deletions
.. versionadded:: 3.0.0
A :class:`~github3.repos.branch.ProtectionAllowDeletions`
representing the information returned by the API about this
protection.
.. attribute:: required_conversation_resolution
.. versionadded:: 3.0.0
A
:class:`~github3.repos.branch.ProtectionRequiredConversationResolution`
representing the information returned by the API about this
protection.
.. links
.. _Branch protection API documentation:
https://developer.github.com/v3/repos/branches/#get-branch-protection
"""
def _update_attributes(self, protection):
self._api = protection["url"]
def _set_conditional_attr(name, cls):
value = protection.get(name)
setattr(self, name, value)
if getattr(self, name):
setattr(self, name, cls(value, self))
_set_conditional_attr("enforce_admins", ProtectionEnforceAdmins)
_set_conditional_attr("restrictions", ProtectionRestrictions)
_set_conditional_attr(
"required_pull_request_reviews",
ProtectionRequiredPullRequestReviews,
)
_set_conditional_attr(
"required_status_checks", ProtectionRequiredStatusChecks
)
_set_conditional_attr(
"required_linear_history", ProtectionRequiredLinearHistory
)
_set_conditional_attr(
"allow_force_pushes", ProtectionAllowForcePushes
)
_set_conditional_attr("allow_deleteions", ProtectionAllowDeletions)
_set_conditional_attr(
"required_conversation_resolution",
ProtectionRequiredConversationResolution,
)
@decorators.requires_auth
def update(
self,
enforce_admins=None,
required_status_checks=None,
required_pull_request_reviews=None,
restrictions=None,
):
"""Enable force push protection and configure status check enforcement.
See: http://git.io/v4Gvu
:param str enforce_admins:
(optional), Specifies the enforcement level of the status checks.
Must be one of 'off', 'non_admins', or 'everyone'. Use `None` or
omit to use the already associated value.
:param list required_status_checks:
(optional), A list of strings naming status checks that must pass
before merging. Use `None` or omit to use the already associated
value.
:param obj required_pull_request_reviews:
(optional), Object representing the configuration of Request Pull
Request Reviews settings. Use `None` or omit to use the already
associated value.
:param obj restrictions:
(optional), Object representing the configuration of Restrictions.
Use `None` or omit to use the already associated value.
:returns:
Updated branch protection
:rtype:
:class:`~github3.repos.branch.BranchProtection`
"""
current_status = {
"enforce_admins": getattr(self.enforce_admins, "enabled", False),
"required_status_checks": (
self.required_status_checks.as_dict()
if self.required_status_checks is not None
else None
),
"required_pull_request_reviews": (
self.required_pull_request_reviews.as_dict()
if self.required_pull_request_reviews is not None
else None
),
"restrictions": (
self.restrictions.as_dict()
if self.restrictions is not None
else None
),
}
edit = {
"enabled": True,
"enforce_admins": (
enforce_admins
if enforce_admins is not None
else current_status["enforce_admins"]
),
"required_status_checks": (
required_status_checks
if required_status_checks is not None
else current_status["required_status_checks"]
),
"required_pull_request_reviews": (
required_pull_request_reviews
if required_pull_request_reviews is not None
else current_status["required_pull_request_reviews"]
),
"restrictions": (
restrictions
if restrictions is not None
else current_status["restrictions"]
),
}
json = self._json(self._put(self._api, json=edit), 200)
self._update_attributes(json)
return self
@decorators.requires_auth
def delete(self) -> bool:
"""Remove branch protection.
:returns:
True if successful, False otherwise
:rtype:
bool
"""
resp = self._delete(self._api)
return self._boolean(resp, 204, 404)
@decorators.requires_auth
def requires_signatures(self) -> bool:
"""Check if commit signatures are presently required.
:returns:
True if enabled, False otherwise
:rtype:
bool
"""
url = self._build_url("required_signatures", base_url=self._api)
resp = self._get(url)
if resp.status_code == 200:
return resp.json()["enabled"]
return False
@decorators.requires_auth
def require_signatures(self) -> bool:
"""Require commit signatures for commits to this branch.
:returns:
True if successful, False otherwise
:rtype:
bool
"""
url = self._build_url("required_signatures", base_url=self._api)
resp = self._post(url)
return self._boolean(resp, 200, 404)
@decorators.requires_auth
def delete_signature_requirements(self) -> bool:
"""Stop requiring commit signatures for commits to this branch.
:returns:
True if successful, False otherwise
:rtype:
bool
"""
url = self._build_url("required_signatures", base_url=self._api)
resp = self._delete(url)
return self._boolean(resp, 200, 404)
class ProtectionEnforceAdmins(models.GitHubCore):
"""The representation of a sub-portion of branch protection.
.. seealso::
`Branch protection API documentation`_
GitHub's documentation of branch protection
`Admin enforcement of protected branch`_
GitHub's documentation of protecting a branch with admins
This object has the following attributes:
.. attribute:: enabled
A boolean attribute indicating whether the ``enforce_admins``
protection is enabled or disabled.
.. links
.. _Branch protection API documentation:
https://developer.github.com/v3/repos/branches/#get-branch-protection
.. _Admin enforcement of protected branch:
https://developer.github.com/v3/repos/branches/#get-admin-enforcement-of-protected-branch
"""
def _update_attributes(self, protection):
self._api = protection["url"]
self.enabled = protection["enabled"]
@decorators.requires_auth
def enable(self):
"""Enable Admin enforcement for protected branch."""
resp = self._post(self._api)
return self._boolean(resp, 200, 404)
@decorators.requires_auth
def disable(self):
"""Disable Admin enforcement for protected branch."""
resp = self._delete(self._api)
return self._boolean(resp, 204, 404)
class ProtectionRestrictions(models.GitHubCore):
"""The representation of a sub-portion of branch protection.
.. seealso::
`Branch protection API documentation`_
GitHub's documentation of branch protection
`Branch restriction documentation`_
GitHub's description of branch restriction
This object has the following attributes:
.. attribute:: original_teams
List of :class:`~github3.orgs.ShortTeam` objects representing
the teams allowed to push to the protected branch.
.. attribute:: original_users
List of :class:`~github3.users.ShortUser` objects representing
the users allowed to push to the protected branch.
.. attribute:: teams_url
The URL to retrieve the list of teams allowed to push to the
protected branch.
.. attribute:: users_url
The URL to retrieve the list of users allowed to push to the
protected branch.
.. links
.. _Branch protection API documentation:
https://developer.github.com/v3/repos/branches/#get-branch-protection
.. _Branch restriction documentation:
https://help.github.com/articles/about-branch-restrictions
"""
def _update_attributes(self, protection):
from .. import apps, orgs, users
self._api = protection["url"]
self.users_url = protection["users_url"]
self.teams_url = protection["teams_url"]
self.apps_url = protection.get("apps_url")
self.original_users = protection["users"]
if self.original_users:
self.original_users = [
users.ShortUser(user, self) for user in self.original_users
]
self.original_teams = protection["teams"]
if self.original_teams:
self.original_teams = [
orgs.ShortTeam(team, self) for team in self.original_teams
]
self.original_apps = protection.get("apps")
if self.original_apps:
self.original_apps = [
apps.App(app, self) for app in self.original_apps
]
@decorators.requires_auth
def add_teams(
self, teams: t.Sequence[str]
) -> t.Sequence["orgs.ShortTeam"]:
"""Add teams to the protected branch.
See:
https://developer.github.com/v3/repos/branches/#add-team-restrictions-of-protected-branch
.. warning::
This will not update the object to replace the ``original_teams``
attribute.
:param list teams:
The list of the team names to have access to interact with
protected branch.
:returns:
List of added teams
:rtype:
List[github3.orgs.ShortTeam]
"""
from .. import orgs
resp = self._post(self.teams_url, data=teams)
json = self._json(resp, 200)
return [orgs.ShortTeam(team, self) for team in json] if json else []
@decorators.requires_auth
def add_users(
self, users: t.Sequence[str]
) -> t.Sequence["tusers.ShortUser"]:
"""Add users to protected branch.
See
https://developer.github.com/v3/repos/branches/#add-user-restrictions-of-protected-branch
.. warning::
This will not update the object to replace the ``original_users``
attribute.
:param list users:
The list of the user logins to have access to interact with
protected branch.
:returns:
List of added users
:rtype:
List[github3.users.ShortUser]
"""
from .. import users as _users
json = self._json(self._post(self.users_url, data=users), 200)
return [_users.ShortUser(user, self) for user in json] if json else []
@decorators.requires_auth
def apps(self, number: int = -1) -> t.Generator["tapps.App", None, None]:
"""Retrieve current list of apps with access to the protected branch.
See
https://docs.github.com/en/rest/reference/repos#get-apps-with-access-to-the-protected-branch
.. warning::
This will not update the object to replace the ``original_apps``
attribute.
:param int number:
Limit the number of apps returned
:returns:
An iterator of apps
:rtype:
:class:`~github3.apps.App`
"""
from .. import apps
return self._iter(int(number), self.apps_url, apps.App)
@decorators.requires_auth
def add_app_restrictions(
self, apps: t.Sequence[t.Union["tapps.App", str]]
) -> t.List["tapps.App"]:
"""Grant app push access to the current branch.
See
https://docs.github.com/en/rest/reference/repos#add-app-access-restrictions
Per GitHub's documentation above:
Grants the specified apps push access for this branch. Only
installed GitHub Apps with write access to the contents permission
can be added as authorized actors on a protected branch.
:param list apps:
List of slugs of apps to grant push access to the protected
branch. If you pass a list of :class:`~github3.apps.App` then the
library will retrieve the slug for you.
:returns:
List of apps with push access to the protected branch
:rtype:
List[:class:`~github3.apps.App`]
"""
from .. import apps as _apps
apps = [getattr(a, "slug", a) for a in apps]
json = self._json(self._post(self.apps_url, data=apps), 200)
return [_apps.App(a, self) for a in json]
@decorators.requires_auth
def replace_app_restrictions(
self, apps: t.Sequence[t.Union["tapps.App", str]]
) -> t.List["tapps.App"]:
"""Replace existing app push access with only those specified.
See
https://docs.github.com/en/rest/reference/repos#set-app-access-restrictions
Per GitHub's documentation above:
Replaces the list of apps that have push access to this branch.
This removes all apps that previously had push access and grants
push access to the new list of apps. Only installed GitHub Apps
with write access to the contents permission can be added as
authorized actors on a protected branch.
:param list apps:
List of slugs of apps to grant push access to the protected
branch. If you pass a list of :class:`~github3.apps.App` then the
library will retrieve the slug for you.
:returns:
List of apps with push access to the protected branch
:rtype:
List[:class:`~github3.apps.App`]
"""
from .. import apps as _apps
apps = [getattr(a, "slug", a) for a in apps]
json = self._json(self._put(self.apps_url, data=apps), 200)
return [_apps.App(a, self) for a in json]
@decorators.requires_auth
def remove_app_restrictions(
self, apps: t.Sequence[t.Union["tapps.App", str]]
) -> t.List["tapps.App"]:
"""Remove the apps' push access to the protected branch.
See
https://docs.github.com/en/rest/reference/repos#remove-app-access-restrictions
:param list apps:
List of slugs of apps to revoke push access to the protected
branch. If you pass a list of :class:`~github3.apps.App` then the
library will retrieve the slug for you.
:returns:
List of apps that still have push access
:rtype:
List[:class:`~github3.apps.App`]
"""
from .. import apps as _apps
apps = [getattr(a, "slug", a) for a in apps]
json = self._json(self._delete(self.apps_url, data=apps), 200)
return [_apps.App(a, self) for a in json]
@decorators.requires_auth
def delete(self) -> bool:
"""Completely remove restrictions of the protected branch.
See
https://developer.github.com/v3/repos/branches/#remove-user-restrictions-of-protected-branch
:returns:
True if successful, False otherwise.
:rtype:
bool
"""
resp = self._delete(self._api)
return self._boolean(resp, 204, 404)
@decorators.requires_auth
def remove_teams(
self, teams: t.Sequence[str]
) -> t.Sequence["orgs.ShortTeam"]:
"""Remove teams from protected branch.
See
https://developer.github.com/v3/repos/branches/#remove-team-restrictions-of-protected-branch
:param list teams:
The list of the team names to stop having access to interact with
protected branch.
:returns:
List of removed teams
:rtype:
List[github3.orgs.ShortTeam]
"""
from .. import orgs
resp = self._delete(self.teams_url, json=teams)
json = self._json(resp, 200)
return [orgs.ShortTeam(team, self) for team in json] if json else []
@decorators.requires_auth
def remove_users(
self, users: t.Sequence[str]
) -> t.Sequence["tusers.ShortUser"]:
"""Remove users from protected branch.
See
https://developer.github.com/v3/repos/branches/#remove-user-restrictions-of-protected-branch
:param list users:
The list of the user logins to stop having access to interact with
protected branch.
:returns:
List of removed users
:rtype:
List[github3.users.ShortUser]
"""
resp = self._delete(self.users_url, json=users)
json = self._json(resp, 200)
from .. import users as _users
return [_users.ShortUser(user, self) for user in json] if json else []
@decorators.requires_auth
def replace_teams(
self, teams: t.Sequence[str]
) -> t.Sequence["orgs.ShortTeam"]:
"""Replace teams that will have access to protected branch.
See
https://developer.github.com/v3/repos/branches/#replace-team-restrictions-of-protected-branch
:param list teams:
The list of the team names to have access to interact with
protected branch.
:returns:
List of teams that now have access to the protected branch
:rtype:
List[github3.orgs.ShortTeam]
"""
from .. import orgs
resp = self._put(self.teams_url, json=teams)
json = self._json(resp, 200)
return [orgs.ShortTeam(team, self) for team in json] if json else []
@decorators.requires_auth
def replace_users(
self, users: t.Sequence[str]
) -> t.Sequence["tusers.ShortUser"]:
"""Replace users that will have access to protected branch.
See
https://developer.github.com/v3/repos/branches/#replace-user-restrictions-of-protected-branch
:param list users:
The list of the user logins to have access to interact with
protected branch.
:returns:
List of users that now have access to the protected branch
:rtype:
List[github3.users.ShortUser]
"""
users_resp = self._put(self.users_url, json=users)
return self._boolean(users_resp, 200, 404)
def teams(
self, number: int = -1
) -> t.Generator["orgs.ShortTeam", None, None]:
"""Retrieve an up-to-date listing of teams.
:returns:
An iterator of teams
:rtype:
:class:`~github3.orgs.ShortTeam`
"""
from .. import orgs
return self._iter(
int(number),
self.teams_url,
orgs.ShortTeam,
)
def users(
self, number: int = -1
) -> t.Generator["tusers.ShortUser", None, None]:
"""Retrieve an up-to-date listing of users.
:returns:
An iterator of users
:rtype:
:class:`~github3.users.ShortUser`
"""
from .. import users
return self._iter(int(number), self.users_url, users.ShortUser)
class ProtectionRequiredPullRequestReviews(models.GitHubCore):
"""The representation of a sub-portion of branch protection.
.. seealso::
`Branch protection API documentation`_
GitHub's documentation of branch protection.
`Branch Required Pull Request Reviews`_
GitHub's documentation of required pull request review protections
This object has the folllowing attributes:
.. attribute:: dismiss_stale_reviews
A boolean attribute describing whether stale pull request reviews
should be automatically dismissed by GitHub.
.. attribute:: dismissal_restrictions
If specified, a :class:`~github3.repos.branch.ProtectionRestrictions`
object describing the dismissal restrictions for pull request reviews.
.. attribute:: require_code_owner_reviews
A boolean attribute describing whether to require "code owners" to
review a pull request before it may be merged.
.. attribute:: required_approving_review_count
An integer describing the number (between 1 and 6) of reviews required
before a pull request may be merged.
.. links
.. _Branch protection API documentation:
https://developer.github.com/v3/repos/branches/#get-branch-protection
.. _Branch Required Pull Request Reviews:
https://developer.github.com/v3/repos/branches/#get-pull-request-review-enforcement-of-protected-branch
"""
def _update_attributes(self, protection):
self._api = protection["url"]
self.dismiss_stale_reviews = protection["dismiss_stale_reviews"]
# Use a temporary value to stay under line-length restrictions
value = protection["require_code_owner_reviews"]
self.require_code_owner_reviews = value
# Use a temporary value to stay under line-length restrictions
value = protection["required_approving_review_count"]
self.required_approving_review_count = value
self.dismissal_restrictions = None
if "dismissal_restrictions" in protection:
self.dismissal_restrictions = ProtectionRestrictions(
protection["dismissal_restrictions"], self
)
@decorators.requires_auth
def update(
self,
dismiss_stale_reviews=None,
require_code_owner_reviews=None,
required_approving_review_count=None,
dismissal_restrictions=None,
):
"""Update the configuration for the Required Pull Request Reviews.
:param bool dismiss_stale_reviews:
Whether or not to dismiss stale pull request reviews automatically
:param bool require_code_owner_reviews:
Blocks merging pull requests until code owners review them
:param int required_approving_review_count:
The number of reviewers required to approve pull requests.
Acceptable values are between 1 and 6.