Created
August 18, 2017 12:29
-
-
Save dracos/37a444d11722acffa85aded1bb6de951 to your computer and use it in GitHub Desktop.
Hook that passes/fails a PR based upon whether we updated the changelog
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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