Skip to content

Instantly share code, notes, and snippets.

@Robdel12
Forked from luketheobscure/lambda.js
Created May 2, 2019 14:38
Show Gist options
  • Save Robdel12/9d39b30dea739168a5ab4f2e0fbb0e7b to your computer and use it in GitHub Desktop.
Save Robdel12/9d39b30dea739168a5ab4f2e0fbb0e7b to your computer and use it in GitHub Desktop.
Percy Bitbucket AWS Lambda
const https = require('https');
const AUTHORIZATION = ''; // base 64 of user:password
const BITBUCKET_USER = ''; // either the user or the org that owns the repo
const PERCY_USER = ''; // the name of your percy user or org
exports.handler = (event, context, callback) => {
/**
We need to post to a URL like this:
https://api.bitbucket.org/2.0/repositories/<user>/<repo>/commit/<hash>/statuses/build
A payload that looks like this:
{
"state": "<INPROGRESS|SUCCESSFUL|FAILED>",
"key": "<build-key>",
"name": "<build-name>",
"url": "<build-url>",
"description": "<build-description>"
}
*/
const {
data,
included,
} = event;
const eventName = data.attributes.event;
let state;
let description;
switch (eventName) {
case 'build_created':
state = 'INPROGRESS';
description = 'Processing visual diff.';
break;
case 'build_approved':
state = 'SUCCESSFUL';
description = 'Success!';
break;
case 'build_finished':
if(included[0].attributes['review-state'] === 'approved'){
state = 'SUCCESSFUL';
description = 'No diffs detected.';
} else {
state = 'STOPPED';
description = 'Build needs manual review.';
}
break;
}
const commitHash = included[1].attributes.sha;
const url = included[0].attributes['web-url'];
const repo = url.replace(`https://percy.io/${PERCY_USER}/`, '').split('/')[0];
const key = included[0].id;
const name = 'Percy!';
const postBody = {
state,
key,
name,
url,
description,
};
const postRequest = https.request({
host: 'api.bitbucket.org',
path: `/2.0/repositories/${BITBUCKET_USER}/${repo}/commit/${commitHash}/statuses/build`,
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Basic ${AUTHORIZATION}`,
},
}, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
const response = {
statusCode: 200,
body: JSON.stringify({
state,
key,
name,
url,
description,
}),
};
callback(null, response);
return response;
});
postRequest.write(JSON.stringify(postBody));
postRequest.end();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment