Created
July 17, 2020 15:23
-
-
Save finnigja/9871719f1e180b20fc8f6c9ea0eac288 to your computer and use it in GitHub Desktop.
This file contains hidden or 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/env python3 | |
# | |
# Use the GitHub API to mass-add all repos inside an org to a team. | |
# (Tweak the GH_PERM value to change the permissions that are granted.) | |
# | |
import json | |
import os | |
import requests | |
import sys | |
GH_API = 'https://api.github.com' | |
GH_ORG = '[ORGNAME]' | |
GH_TEAM = '[TEAMNAME]' | |
GH_PERM = 'pull' # pull, push, admin, maintain, triage | |
github_token = os.environ.get('GITHUB_TOKEN', '') | |
if github_token == '': | |
print('ERROR: GITHUB_TOKEN env var is not set') | |
sys.exit(2) | |
headers = { | |
'Authorization': 'token {}'.format(github_token), | |
} | |
def paginated_get(url, headers): | |
response = requests.get(url, headers=headers) | |
results = response.json() | |
while 'next' in response.links.keys(): | |
response = requests.get(response.links['next']['url'], headers=headers) | |
results.extend(response.json()) | |
return results | |
print('Getting repos in {}...'.format(GH_ORG)) | |
repos = paginated_get('{}/orgs/{}/repos?per_page=100'.format(GH_API, GH_ORG), headers) | |
print('Granting {} {} access to {} {} repos...'.format(GH_TEAM, GH_PERM, len(repos), GH_ORG)) | |
for repo in repos: | |
gh_repo_full_name = repo['full_name'] | |
# https://developer.github.com/v3/teams/#add-or-update-team-repository-permissions | |
r = requests.put( | |
'{}/orgs/{}/teams/{}/repos/{}'.format(GH_API, GH_ORG, GH_TEAM, gh_repo_full_name), | |
data=json.dumps({'permission': GH_PERM}), | |
headers=headers | |
) | |
if r.status_code == 204: | |
print('Added {} to team {}.'.format(gh_repo_full_name, GH_TEAM)) | |
else: | |
print('ERROR: could not add {} to team {} (returned {})'.format(gh_repo_full_name, GH_TEAM, r.status_code)) | |
print('Granted {} {} access to {} {} repos.'.format(GH_TEAM, GH_PERM, len(repos), GH_ORG)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment