Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Python script to add all GitHub repositories to an organization team - permission is set to push. You'll need a file with your organization name and API key. Based off of my GitHub stats script (requirements.txt here):
# Exports a CSV of repo names, readme files, and the license of the project.
from __future__ import print_function
import requests
import json
import settings
from urlparse import urlparse, parse_qs
import sys
def getLastPage(link_header):
links = link_header.split(',')
for link in links:
link = link.split(';')
if link[1].strip() == 'rel="last"':
# Trim it for garbage, and get the url params out.
link_data = parse_qs(link[0].strip(' <>').split('?')[1])
last_page = int(link_data['page'][0])
return last_page
return 0
github_urls = {
'repos': '{org}/repos', # GET
'teams': '{org}/teams', # GET
'teamrepo': '{teamid}/repos/{org}/{repo}' # PUT
gh_payload = {'access_token': settings.GITHUB_TOKEN}
# Get our teams, let the user pick one.
teams_r = requests.get(github_urls['teams'].format(org=settings.GITHUB_ORG), gh_payload)
teams = json.loads(teams_r.text)
team_map = {}
for team in teams:
team_map[team['id']] = team['name']
team = ''
while team == '':
print('Pick a team:')
print(', '.join(team_map.values()))
team = raw_input('? ')
if team not in team_map.values():
team = ''
team_id = team_map.keys()[team_map.values().index(team)]
# Get a list of all GitHub projects.
# First off, how many pages do we have?
# Get the first page.
head = requests.get(github_urls['repos'].format(
org=settings.GITHUB_ORG), gh_payload)
# Look for the last page link in the headers
last_page = getLastPage(head.headers['link'])
if last_page != 0:
for page in range(1, last_page + 1):
repo_payload = {}
repo_payload['page'] = page
# headers = { 'Accept': 'application/vnd.github.drax-preview+json' }
headers = {}
r = requests.get(github_urls['repos'].format(
org=settings.GITHUB_ORG), repo_payload, headers=headers)
existing_projects = json.loads(r.text)
for existing_project in existing_projects:
print('Project: ' + existing_project['name'])
team_payload = gh_payload.copy()
team_payload['permissions'] = 'push'
repo_r = requests.put(github_urls['teamrepo'].format(
), params=gh_payload, data=json.dumps(team_payload))
print('Didn\'t find any existing projects.', file=sys.stderr)
Copy link

netflash commented Aug 15, 2017

Hi there,
I've spotted few issues and fixed in my fork.
Feel free to inject them back.

  1. Permission - it was a typo and it didn't work as desired.
  2. Private repos - it lacked the github token while querying the repo list

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