Skip to content

Instantly share code, notes, and snippets.

@rbellamy
Created September 20, 2015 23:10
Show Gist options
  • Save rbellamy/0d192729ad2e04803ce0 to your computer and use it in GitHub Desktop.
Save rbellamy/0d192729ad2e04803ce0 to your computer and use it in GitHub Desktop.
BitBucket to GitHub
#! /usr/bin/env python
from sys import exit, stderr
from subprocess import Popen, PIPE
import json
import urllib
# Run this on the command line to get an access token
# paste in your OAuth consumer key and secret
# paste in your username and password
#
# curl -X POST -u "{key}:{secret}" \
# https://bitbucket.org/site/oauth2/access_token
# -d grant_type=password
# -d username={username} -d password={password}
# paste in the access token
access_token = 'o64yvyRU95Aw394eJWeBUnF3eEr9_UjMlledMtU2m1jYAsvx-jLokIDMEO-vObb5TMeNOuDqxWmgwpV8ow=='
# paste in the team, group, and access-level
team = 'terradatum'
group = 'administrators'
access_level = 'read' # or 'write' or 'admin'
urlfmtargs = dict(team=team, group=group)
def list_repos(page):
if page != "":
url = page
else:
url = "https://api.bitbucket.org/2.0/repositories/{team}".format(**urlfmtargs)
print url
args = ["curl", "-s", "-v", url,
"-H", "Authorization: Bearer {}".format(access_token)]
p = Popen(args, stdout=PIPE, stderr=PIPE)
stdoutdata, stderrdata = p.communicate()
if p.returncode != 0:
print >>stderr, stderrdata
exit(p.returncode)
try:
for repo in json.loads(stdoutdata)['values']:
yield repo['name']
next_page = json.loads(stdoutdata)['next']
if next_page != "":
#print previous_page
for repo in list_repos(next_page):
yield repo
except:
for line in stderrdata.splitlines():
if line.startswith('< HTTP'):
print >>stderr, line
print stdoutdata
exit(1)
def assign_permission(repo):
print "Assigning {} permission on {}".format(access_level, repo)
url = "https://api.bitbucket.org/1.0/group-privileges/{team}/{repo}/{team}/{group}".format(repo=repo, **urlfmtargs)
args = ["curl", "-s", "-v", url,
"-X", "PUT",
"-d", access_level,
"-H", "Authorization: Bearer {}".format(access_token)]
p = Popen(args, stdout=PIPE, stderr=PIPE)
stdoutdata, stderrdata = p.communicate()
if p.returncode != 0:
print >>stderr, stderrdata
exit(p.returncode)
for line in stderrdata.splitlines():
if line.startswith('< HTTP'):
print line
if '404' in line:
print url
for repo in list_repos(""):
repo = repo.lower().replace(' ', '+')
assign_permission(repo)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment