Skip to content

Instantly share code, notes, and snippets.

@KevinBrogan
Created March 2, 2018 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KevinBrogan/9c1119e327d05338aadab3a2e425fa1a to your computer and use it in GitHub Desktop.
Save KevinBrogan/9c1119e327d05338aadab3a2e425fa1a to your computer and use it in GitHub Desktop.
bitbucket webhook deployment script
<?php
$payload = json_decode(file_get_contents('php://input'));
if(!$payload)
{
http_response_code(404);
exit();
}
$branch = trim(`git branch | grep "\* \K.*$" -oP`);
$branches = new stdClass;
if(property_exists($payload,'push'))
{
echo "push\n";
foreach($payload->push->changes as $change)
{
if(property_exists($change,'old'))
{
$branches->{$change->old->name} = true;
}
if(property_exists($change,'new'))
{
$branches->{$change->new->name} = true;
}
}
}
else if(property_exists($payload,'pullrequest'))
{
echo "pullrequest\n";
$branches->{$payload->pullrequest->destination->branch->name} = true;
}
else
{
http_response_code(403);
exit('Unsupported web hook. Not a push or a merged pull request.');
}
if(!property_exists($branches,$branch))
{
http_response_code(200);
exit("No changes made to the deployed branch\n");
}
else
{
http_response_code(201);
}
$commands = array
(
"git fetch -f",
"git reset --hard origin/$branch",
"git status"
);
foreach($commands AS $command)
{
exec("$command 2>&1",$cmdOutput,$errorStatus);
$cmdOutput = htmlentities(trim(implode("\n",$cmdOutput)));
if(strlen($cmdOutput))
{
$cmdOutput.="\n";
}
if($errorStatus)
{
http_response_code(500);
}
$errorText = $errorStatus?'FAILURE':'SUCCESS';
echo
<<<EOF
$ $command
--- $errorText ---
$cmdOutput
EOF;
if($errorStatus)
{
break;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment