|
1 | 1 | # -*- coding: utf-8 -*-
|
2 | 2 | from __future__ import unicode_literals
|
3 | 3 |
|
| 4 | +from json import dumps |
4 | 5 | from ..models import GitHubCore
|
5 | 6 | from .commit import RepoCommit
|
6 | 7 |
|
@@ -28,5 +29,51 @@ def _update_attributes(self, branch):
|
28 | 29 | #: Provides the branch's protection status.
|
29 | 30 | self.protection = branch.get('protection')
|
30 | 31 |
|
| 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 | + |
31 | 38 | def _repr(self):
|
32 | 39 | 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