#!/usr/bin/python
import httplib
import sys
import json
import argparse
from urlparse import urlparse
from base64 import b64encode
parser = argparse.ArgumentParser(description='Sample script to update Webhook To Bitbucket settings examples.')
parser.add_argument('--bitbucket_url', type=str, help='Url for Bitbucket instance.',
default='http://localhost:7990/bitbucket')
parser.add_argument('--username', type=str, help='Username for user with access to repository',
default='admin')
parser.add_argument('--password', type=str, help='Password for user with access to repository',
default='admin')
parser.add_argument('--project', type=str, help='Project key where repository is located',
default='PROJECT_1')
parser.add_argument('--repository', type=str, help='Repository key for the instance',
default='rep_1')
parser.add_argument('--settings', type=str, help='Path to the settings file. JSON formatted.',
default='settings.json')
args = parser.parse_args()
bb_url = args.bitbucket_url
username = args.username
password = args.password
project_key = args.project
repository_slug = args.repository
settings_path = args.settings
end_point = "/rest/api/latest/projects/{0}/repos/{1}/settings/hooks/com.nerdwin15.stash-stash-webhook-jenkins" \
"%3AjenkinsPostReceiveHook/enabled".format(project_key, repository_slug)
settings_file = open(settings_path, 'r')
try:
settings = settings_file.read()
try:
j = json.loads(settings) # just to validate
except:
print "Invalid JSON: %s" % settings
sys.exit(1)
finally:
settings_file.close()
url_obj = urlparse(bb_url)
headers = {
'authorization': "Basic " + b64encode(username + ':' + password),
'Content-Type': 'application/json'
}
connection = httplib.HTTPConnection(url_obj.hostname, url_obj.port)
try:
connection.request("PUT", url_obj.path + end_point, body=settings, headers=headers)
r1 = connection.getresponse()
print r1.status, r1.reason, r1.getheaders()
data1 = r1.read()
print data1
finally:
connection.close() |