Last active
February 12, 2018 06:01
-
-
Save fourkbomb/2713f6405cd63306dd45e6e4ae01a908 to your computer and use it in GitHub Desktop.
python script using requests to change the default branch for all repos owned by a user/organisation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
from __future__ import print_function | |
import requests | |
BRANCH = 'cm-14.1' | |
REPO_OWNER = 'orgs/LineageOS' | |
USERNAME = 'your github username' | |
# generate this here: https://github.com/settings/tokens | |
# this script only needs the 'repo' scope | |
TOKEN = 'fill me in' | |
# authenticate all requests to avoid rate-limits | |
r = requests.get('https://api.github.com/%s/repos'%REPO_OWNER, auth = (USERNAME, TOKEN)) | |
if 'link' in r.headers: | |
# get number of pages of repos | |
last = int(r.headers['link'].split(',')[-1].split(';')[0].split('=')[-1][:-1]) | |
else: | |
# only one page of repos | |
last = 3 | |
json = r.json() | |
for page in range(2, last+2): | |
for repo in json: | |
# check the repo has the requested branch | |
r = requests.get(repo['branches_url'].replace('{/branch}', ''), auth = (USERNAME, TOKEN)) | |
if True not in [i['name'] == BRANCH for i in r.json()] or repo['default_branch'] == BRANCH: | |
# repo doesn't have matching branch, or default branch is already desired branch, skip | |
print("Skipping repo %s"%repo['full_name']) | |
continue | |
print("Setting %s default branch to %s..."%(repo['full_name'], BRANCH), end=' ') | |
r = requests.patch('https://api.github.com/repos/%s'%repo['full_name'], | |
json = { 'name': repo['name'], 'default_branch': BRANCH, | |
# set these in case github decides to overwrite the existing settings | |
'private': repo['private'], 'has_issues': repo['has_issues'], | |
'has_wiki': repo['has_wiki'], 'has_downloads': repo['has_downloads'] | |
}, auth = (USERNAME, TOKEN)) | |
if r.status_code == 200: | |
print("Success!") | |
else: | |
print("Failed.") | |
print("Response: %d, %s"%(r.status_code, r.text)) | |
json = requests.get('https://api.github.com/%s/repos?page=%d'%(REPO_OWNER, page), auth = (USERNAME, TOKEN)).json() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment