Skip to content

Instantly share code, notes, and snippets.

@jossef
Created September 15, 2017 11:26
Show Gist options
  • Select an option

  • Save jossef/684d578c026c0b59ee277d3379bf4fdb to your computer and use it in GitHub Desktop.

Select an option

Save jossef/684d578c026c0b59ee277d3379bf4fdb to your computer and use it in GitHub Desktop.
simple github branch creation functions via rest api
import requests
class GitHubClient(object):
def __init__(self, api_token, verify_ssl=True):
self.api_token = api_token
self.headers = {'Authorization': 'token {}'.format(api_token)}
self.verify_ssl = verify_ssl
def get_branches(self, username, repository):
url = 'https://api.github.com/repos/{username}/{repository}/branches'.format(username=username, repository=repository)
r = requests.get(url, headers=self.headers, verify=self.verify_ssl)
r.raise_for_status()
result = r.json()
result = map(lambda x: x['name'], result)
return result
def create_branch(self, username, repository, new_branch_name, from_branch_name='master'):
from_branch_info = self.get_branch_info(username, repository, from_branch_name)
new_branch_info = self.get_branch_info(username, repository, new_branch_name)
if not self._is_branch_exists(from_branch_info):
raise Exception('branch "{}" does not exist'.format(from_branch_name))
if self._is_branch_exists(new_branch_info):
raise Exception('branch "{}" already exist'.format(new_branch_name))
data = {
'ref': 'refs/heads/{}'.format(new_branch_name),
'sha': from_branch_info['commit']['sha']
}
url = 'https://api.github.com/repos/{username}/{repository}/git/refs'.format(username=username, repository=repository)
r = requests.post(url, headers=self.headers, json=data, verify=self.verify_ssl)
r.raise_for_status()
def delete_branch(self, username, repository, branch_name):
url = 'https://api.github.com/repos/{username}/{repository}/git/refs/heads/{branch_name}'.format(username=username, repository=repository, branch_name=branch_name)
r = requests.delete(url, headers=self.headers, verify=self.verify_ssl)
r.raise_for_status()
def get_branch_info(self, username, repository, branch_name):
url = 'https://api.github.com/repos/{username}/{repository}/branches/{branch_name}'.format(username=username, repository=repository, branch_name=branch_name)
r = requests.get(url, headers=self.headers, verify=self.verify_ssl)
try:
utils.raise_for_status(r)
result = r.json()
return result
except:
return {}
def is_branch_exists(self, username, repository, branch_name):
branch_info = self.get_branch_info(username, repository, branch_name)
return self._is_branch_exists(branch_info)
def _is_branch_exists(self, branch_info):
branch_sha = branch_info.get('commit', {}).get('sha')
return bool(branch_sha)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment