Skip to content

Instantly share code, notes, and snippets.

@jamezrin jamezrin/orphan.py
Last active Mar 15, 2019

Embed
What would you like to do?
Python script to create an orphan branch
import requests
def create_orphan_branch(repository, authentication, branch_name,
github_api_path='https://api.github.com'):
res1 = requests.get(
github_api_path + '/repos/{0}/{1}/git/refs/heads/{2}'.format(
repository['owner'],
repository['name'],
branch_name
),
auth=(
authentication['user'],
authentication['pass'],
),
)
if res1.status_code == 404:
print('Creating the initial tree...', end='')
res2 = requests.post(
github_api_path + '/repos/{0}/{1}/git/trees'.format(
repository['owner'],
repository['name'],
),
json={
'tree': [{
'path': '_orphan',
'mode': '100644',
'type': 'blob',
'content': branch_name,
}]
},
auth=(
authentication['user'],
authentication['pass'],
)
)
if res2.status_code == 201:
print(' SUCCESS ')
print('Creating the initial commit...', end='')
res3 = requests.post(
github_api_path + '/repos/{0}/{1}/git/commits'.format(
repository['owner'],
repository['name'],
),
json={
'message': 'Initial commit',
'tree': res2.json().get('sha'),
'parents': [],
},
auth=(
authentication['user'],
authentication['pass'],
)
)
if res3.status_code == 201:
print(' SUCCESS ')
print('Creating the orphan branch...', end='')
res4 = requests.post(
github_api_path + '/repos/{0}/{1}/git/refs'.format(
repository['owner'],
repository['name'],
),
json={
'ref': 'refs/heads/{0}'.format(branch_name),
'sha': res3.json().get('sha'),
},
auth=(
authentication['user'],
authentication['pass'],
)
)
if res4.status_code == 201:
print(' SUCCESS ')
print('Successfully created the orphan branch {0}'.format(branch_name))
else:
print(' FAILED ')
print('Could not create the orphan branch, error: {0}'.format(res4.json()))
else:
print(' FAILED ')
print('Could not create the initial commit, error: {0}'.format(res3.json()))
else:
print(' FAILED ')
print('Could not create the initial tree, error: {0}'.format(res2.json()))
else:
print('The branch {0} already exists'.format(branch_name))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.