Skip to content

Instantly share code, notes, and snippets.

@robertobatts
Last active April 6, 2020 09:23
Show Gist options
  • Save robertobatts/75135abe865a110f963c85a5ef012688 to your computer and use it in GitHub Desktop.
Save robertobatts/75135abe865a110f963c85a5ef012688 to your computer and use it in GitHub Desktop.
Automatically add/update a webhook in all your Bitbucket repositories
const fetch = require('node-fetch')
const base64 = require('base-64')
const OWNER = 'robertobattaglia'
const USERNAME = 'robertobattaglia'
const PASSWORD = 'PASSWORD'
const numberOfPages=4
updateAllWebhooks()
async function updateAllWebhooks() {
const repositories = await getAllRepositories()
for (let i = 0; i< repositories.length; ++i) {
let hookUrl = repositories[i].links.hooks.href
const jenkinsHook = await getJenkinsWebhook(hookUrl)
if (jenkinsHook) {
updateWebhook(hookUrl, jenkinsHook.uuid)
} else {
postWebhook(hookUrl)
}
}
}
function updateWebhook(url, uuid) {
fetch(url + "/" + uuid, {
method: 'PUT',
headers: getHeaders(),
body: createWebhookBody()
})
.then((response) => response.json())
.then((data) => {
console.log('Success PUT:', url);
})
.catch((error) => {
console.error('Error PUT:', url);
});
}
function postWebhook(url) {
fetch(url, {
method: 'POST',
headers: getHeaders(),
body: createWebhookBody()
})
.then((response) => response.json())
.then((data) => {
console.log('Success POST:', url);
})
.catch((error) => {
console.error('Error POST:', url);
});
}
async function getJenkinsWebhook(url) {
return await fetch(url, {
method: 'GET',
headers: getHeaders()
})
.then(res => res.json())
.then(data => {
var jenkinsHook = data.values.find(hook => hook.description === 'JENKINS')
return jenkinsHook
})
}
async function getAllRepositories() {
let repositories = []
for (var i = 1; i <= numberOfPages; i++) {
let newRepos = await getRepositoriesByPageNumber(i)
Array.prototype.push.apply(repositories, newRepos)
}
return repositories
}
async function getRepositoriesByPageNumber(pageNumber) {
const url = 'https://api.bitbucket.org/2.0/repositories/' + OWNER + '?pagelen=100&page=' + pageNumber
return await fetch(url, {
method: 'GET',
headers: getHeaders()
})
.then(res => res.json())
.then(data => {
console.log("retrieved " + data.values.length + " repositories")
return data.values
})
.catch((error) => {
console.error('Error:', url);
});
}
function getHeaders() {
return {
'Authorization': 'Basic ' + base64.encode(USERNAME + ":" + PASSWORD)
}
}
function createWebhookBody() {
return JSON.stringify({
"description": "JENKINS",
"url": "http://JENKINS_IP:8080/bitbucket-hook/",
"active": true,
"events": ["repo:push"]
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment