Skip to content

Instantly share code, notes, and snippets.

@dracos
Created Aug 18, 2017
Embed
What would you like to do?
Hook that passes/fails a PR based upon whether we updated the changelog
<?php
$secret = '...';
$token = '...';
$payload = $_POST['payload'];
$signature_header = $_SERVER['HTTP_X_HUB_SIGNATURE'];
$signature_calc = 'sha1=' . hash_hmac('sha1', 'payload=' . urlencode($payload), $secret, false);
if (!hash_equals($signature_header, $signature_calc)) {
exit("Signature did not match");
}
$data = json_decode($payload);
if (!$data) {
exit("No JSON data");
}
$actions = array('opened', 'reopened', 'synchronize', 'edited');
if (!in_array($data->action, $actions)) {
exit("Ignored action");
}
$pr = $data->pull_request;
if (want_to_check($pr)) {
print "Checking PR\n";
if (want_to_skip($pr)) {
$result = 'skip';
} elseif (changelog_changed($pr)) {
$result = 'pass';
} else {
$result = 'fail';
}
print "PR $result\n";
set_changelog_status($pr, $result);
print "Status set\n";
} else {
print "Ignoring PR\n";
}
function want_to_check($pr) {
return $pr->state == 'open' && $pr->base->ref == 'master';
}
function want_to_skip($pr) {
return preg_match('#\[skip changelog\]#', $pr->body);
}
function changelog_changed($pr) {
$diff = file_get_contents($pr->diff_url);
if (preg_match('#diff --git a/CHANGELOG.md#', $diff)) {
return true;
}
return false;
}
function set_changelog_status($pr, $result) {
$msgs = array(
'fail' => 'No changelog update found',
'pass' => 'Changelog update found',
'skip' => 'Changelog check skipped',
);
set_commit_status($pr->statuses_url, $result != 'fail' ? 'success' : 'failure', $msgs[$result], 'changelog');
}
function set_commit_status($url, $state, $desc, $context) {
global $token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERAGENT, "mySociety Changelog bot");
$data = array(
'state' => $state,
'description' => $desc,
'context' => $context,
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
"Authorization: token $token",
));
curl_exec($ch);
curl_close($ch);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment