forked from sigmavirus24/github3.py
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbranch.py
More file actions
548 lines (416 loc) · 18.2 KB
/
Copy pathbranch.py
File metadata and controls
548 lines (416 loc) · 18.2 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
# -*- coding: utf-8 -*-
"""Implementation of a branch on a repository."""
from __future__ import unicode_literals
from json import dumps
from . import commit
from .. import decorators
from .. import models
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 '<{0} [{1}]>'.format(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
"""
# If-None-Match returns 200 instead of 304 value does not have quotes
headers = {
'Accept': 'application/vnd.github.v3.sha',
'If-None-Match': '"{0}"'.format(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.content
return None
@decorators.requires_auth
def protection(self):
"""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)
headers_map = BranchProtection.PREVIEW_HEADERS_MAP
headers = headers_map['required_approving_review_count']
resp = self._get(url, headers=headers)
json = self._json(resp, 200)
return BranchProtection(json, self)
@decorators.requires_auth
def protect(self, enforcement=None, status_checks=None):
"""Enable force push protection and configure status check enforcement.
See: http://git.io/v4Gvu
:param str enforcement:
(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 status_checks:
(optional), An list of strings naming status checks that must pass
before merging. Use `None` or omit to use the already associated
value.
:returns:
True if successful, False otherwise
:rtype:
bool
"""
previous_values = None
if self.protection:
previous_values = self.protection['required_status_checks']
if enforcement is None and previous_values:
enforcement = previous_values['enforcement_level']
if status_checks is None and previous_values:
status_checks = previous_values['contexts']
edit = {'protection': {'enabled': True, 'required_status_checks': {
'enforcement_level': enforcement, 'contexts': status_checks}}}
json = self._json(self._patch(self._api, data=dumps(edit),
headers=self.PREVIEW_HEADERS), 200)
self._update_attributes(json)
return True
@decorators.requires_auth
def unprotect(self):
"""Disable force push protection on this branch."""
edit = {'protection': {'enabled': False}}
json = self._json(self._patch(self._api, data=dumps(edit),
headers=self.PREVIEW_HEADERS), 200)
self._update_attributes(json)
return True
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(Branch, self)._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
class BranchProtection(models.GitHubCore):
"""The representation of a branch's protection.
.. seealso::
`Branch protection API documentation`_
GitHub's documentation of branch protection
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.
.. links
.. _Branch protection API documentation:
https://developer.github.com/v3/repos/branches/#get-branch-protection
"""
PREVIEW_HEADERS_MAP = {
'required_approving_review_count': {
'Accept': 'application/vnd.github.luke-cage-preview+json',
},
'requires_signed_commits': {
'Accept': 'application/vnd.github.zzzax-preview+json',
},
'nested_teams': {
'Accept': 'application/vnd.github.hellcat-preview+json',
},
}
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)
class ProtectionEnforceAdmins(models.GitHubCore):
"""The representation of a sub-portion of branch protection.
.. seealso::
`Branch protection API documentation`_
GitHub's documentation of branch protection
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
"""
def _update_attributes(self, protection):
self._api = protection['url']
self.enabled = protection['enabled']
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 orgs, users
self._api = protection['url']
self.users_url = protection['users_url']
self.teams_url = protection['teams_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
]
def teams(self, number=-1):
"""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=-1):
"""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
.. links
.. _Branch protection API documentation:
https://developer.github.com/v3/repos/branches/#get-branch-protection
"""
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 = ProtectionRestrictions(
protection['dismissal_restrictions'],
self,
)
class ProtectionRequiredStatusChecks(models.GitHubCore):
"""The representation of a sub-portion of branch protection.
.. seealso::
`Branch protection API documentation`_
GitHub's documentation of branch protection
`Required Status Checks documentation`_
GitHub's description of required status checks
.. links
.. _Branch protection API documentation:
https://developer.github.com/v3/repos/branches/#get-branch-protection
.. _Required Status Checks documentation:
https://help.github.com/articles/about-required-status-checks
"""
def _update_attributes(self, protection):
self._api = protection['url']
self.strict = protection['strict']
self.original_contexts = protection['contexts']
self.contexts_url = protection['contexts_url']
@decorators.requires_auth
def add_contexts(self, contexts):
"""Add contexts to the existing list of required contexts.
See:
https://developer.github.com/v3/repos/branches/#add-required-status-checks-contexts-of-protected-branch
:param list contexts:
The list of contexts to append to the existing list.
:returns:
The updated list of contexts.
:rtype:
list
"""
resp = self._post(self.contexts_url, json=contexts)
json = self._json(resp, 200)
return json
@decorators.requires_auth
def contexts(self):
"""Retrieve the list of contexts required as status checks.
See:
https://developer.github.com/v3/repos/branches/#list-required-status-checks-contexts-of-protected-branch
:returns:
A list of context names which are required status checks.
:rtype:
list
"""
resp = self._get(self.contexts_url)
json = self._json(resp, 200)
return json
@decorators.requires_auth
def remove_contexts(self, contexts):
"""Remove the specified contexts from the list of required contexts.
See:
https://developer.github.com/v3/repos/branches/#remove-required-status-checks-contexts-of-protected-branch
:param list contexts:
The context names to remove
:returns:
The updated list of contexts required as status checks.
:rtype:
list
"""
resp = self._delete(self.contexts_url, json=contexts)
json = self._json(resp, 200)
return json
@decorators.requires_auth
def replace_contexts(self, contexts):
"""Replace the existing contexts required as status checks.
See:
https://developer.github.com/v3/repos/branches/#replace-required-status-checks-contexts-of-protected-branch
:param list contexts:
The names of the contexts to be required as status checks
:returns:
The updated list of contexts required as status checks.
:rtype:
list
"""
resp = self._put(self.contexts_url, json=contexts)
json = self._json(resp, 200)
return json
@decorators.requires_auth
def update(self, strict=None, contexts=None):
"""Update required status checks for the branch.
This requires admin or owner permissions to the repository and
branch protection to be enabled.
.. seealso::
`API docs`_
Descrption of how to update the required status checks.
:param bool strict:
Whether this should be strict protection or not.
:param list contexts:
A list of context names that should be required.
:returns:
A new instance of this class with the updated information
:rtype:
:class:`~github3.repos.branch.ProtectionRequiredStatusChecks`
.. links
.. _API docs:
https://developer.github.com/v3/repos/branches/#update-required-status-checks-of-protected-branch
"""
update_data = {}
if strict is not None:
update_data['strict'] = strict
if contexts is not None:
update_data['contexts'] = contexts
if update_data:
resp = self._patch(self.url, json=update_data)
json = self._json(resp, 200)
return ProtectionRequiredStatusChecks(json, self)
@decorators.requires_auth
def delete(self):
"""Remove required status checks from this branch.
See:
https://developer.github.com/v3/repos/branches/#remove-required-status-checks-of-protected-branch
:returns:
True if successful, False otherwise
:rtype:
bool
"""
resp = self._delete(self.url)
return self._boolean(resp, 204, 404)