Skip to content

Instantly share code, notes, and snippets.

@edbighead
Created May 30, 2019 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edbighead/9a592b1db237a4fa3f61539a5d9311bc to your computer and use it in GitHub Desktop.
Save edbighead/9a592b1db237a4fa3f61539a5d9311bc to your computer and use it in GitHub Desktop.
import requests
import os
import argparse
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
repoList = config['bitbucket']['repo'].split(",")
usersList = config['bitbucket']['users'].split(",")
branch = config['branch']['name']
pattern = config['pattern']['name']
urlPattern = config['bitbucket']['url']
owner = config['bitbucket']['owner']
permission_type = {'read-only':usersList,'fast-forward-only':None,'no-deletes':None,'pull-request-only':None}
token = os.environ.get('BITBUCKET_TOKEN')
headers = {
'Authorization': "Bearer {}".format(token),
'content-type' : "application/json"
}
if not token:
raise ValueError('You must have "BITBUCKET_TOKEN" variable')
parser = argparse.ArgumentParser(description='This scripts sets permissions to prevent: All changes(except specified users), Rewriting history, Changes without a pull request, Deletion')
parser.add_argument(
'choices',
help="Set permission for branch or pattern or both",
nargs='+'
)
args = parser.parse_args()
def api_call(permission_type, type_refs, type, choice, users, repo):
url = urlPattern + "/rest/branch-permissions/2.0/projects/{}/repos/{}".format(owner,repo) + "/restrictions"
typeDict = dict(id=choice.upper(), name=choice)
matcherDict = dict(id=type_refs, displayId=type, type=typeDict, active='true')
dataDict = dict(type=permission_type,matcher=matcherDict,users=users)
r = requests.post(url, headers=headers, json=dataDict)
if r.status_code == 200:
return print("Succesfully created {} {} on {} for {}".format(type, permission_type, repo, users))
else:
return print("Couldn't create permission: ", (r.content).decode("utf-8"))
for choice in args.choices:
for repo in repoList:
for permission in permission_type.keys():
if 'branch' == choice:
api_call(permission, 'refs/heads/'+branch, branch, choice, permission_type[permission], repo)
if 'pattern' == choice:
api_call(permission, pattern, pattern, choice, permission_type[permission], repo)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment