10000 Merge pull request #480 from bboe/setprotection · degustaf/github3.py@e42049b · GitHub
[go: up one dir, main page]

Skip to content

Commit e42049b

Browse files
committed
Merge pull request sigmavirus24#480 from bboe/setprotection
Add protect and unprotect methods to Branch.
2 parents 01fd26e + 52c4c55 commit e42049b

File tree

4 files changed

+105
-0
lines changed

4 files changed

+105
-0
lines changed

github3/repos/branch.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# -*- coding: utf-8 -*-
22
from __future__ import unicode_literals
33

4+
from json import dumps
45
from ..models import GitHubCore
56
from .commit import RepoCommit
67

@@ -28,5 +29,51 @@ def _update_attributes(self, branch):
2829
#: Provides the branch's protection status.
2930
self.protection = branch.get('protection')
3031

32+
if 'self' in self.links:
33+
self._api = self.links['self']
34+
else: # Branches obtained via `repo.branches` don't have links.
35+
base = self.commit.url.split('/commit', 1)[0]
36+
self._api = self._build_url('branches', self.name, base_url=base)
37+
3138
def _repr(self):
3239
return '<Repository Branch [{0}]>'.format(self.name)
40+
41+
def protect(self, enforcement=None, status_checks=None):
42+
"""Enable force push protection and configure status check enforcement.
43+
44+
See: http://git.io/v4Gvu
45+
46+
:param str enforcement: (optional), Specifies the enforcement level of
47+
the status checks. Must be one of 'off', 'non_admins', or
48+
'everyone'. Use `None` or omit to use the already associated value.
49+
:param list status_checks: (optional), An list of strings naming
50+
status checks that must pass before merging. Use `None` or omit to
51+
use the already associated value.
52+
"""
53+
previous_values = self.protection['required_status_checks']
54+
if enforcement is None:
55+
enforcement = previous_values['enforcement_level']
56+
if status_checks is None:
57+
status_checks = previous_values['contexts']
58+
59+
edit = {'protection': {'enabled': True, 'required_status_checks': {
60+
'enforcement_level': enforcement, 'contexts': status_checks}}}
61+
json = self._json(self._patch(self._api, data=dumps(edit),
62+
headers=self.PREVIEW_HEADERS), 200)
63+
64+
# When attempting to clear `contexts`, the reply from github doesn't
65+
# currently reflect the actual value. Let's fix that for now.
66+
cur_contexts = self.protection['required_status_checks']['contexts']
67+
if status_checks == [] != cur_contexts:
68+
json['protection']['required_status_checks']['contexts'] = []
69+
70+
self._update_attributes(json)
71+
return True
72+
73+
def unprotect(self):
74+
"""Disable force push protection on this branch."""
75+
edit = {'protection': {'enabled': False}}
76+
json = self._json(self._patch(self._api, data=dumps(edit),
77+
headers=self.PREVIEW_HEADERS), 200)
78+
self._update_attributes(json)
79+
return True

0 commit comments

Comments
 (0)
0