Skip to content

Instantly share code, notes, and snippets.

@jamezrin
Last active June 25, 2022 13:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamezrin/fec71ea0e50969804e0ad46fe7737b88 to your computer and use it in GitHub Desktop.
Save jamezrin/fec71ea0e50969804e0ad46fe7737b88 to your computer and use it in GitHub Desktop.
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))
@ibakshay
Copy link

Thanks a lot for your solution. I really appreciate it 💯

@jamezrin
Copy link
Author

This wasn't my cleanest code, but I'm glad it helped you!

@pierCo
Copy link

pierCo commented Dec 22, 2020

Your code helped us a lot to create an orphan branch via the Github V3 API. Thank you very much for that.

If you want, you can include an improvement we found, which is to remove the "Create initial tree" step and use the "magic" SHA: 4b825dc642cb6eb9a060e54bf8d69288fbee4904 (More info)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment