Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bitbucket Deploy Hook
<?php
define('REPO_PATH', '/repositories/');
define('STAGING_PATH', '/htdocs/dev/');
define('PRODUCTION_PATH', '/htdocs/');
$git = 'git';
$update = false;
// Parse data from Bitbucket hook payload
$payload = json_decode( $_POST['payload'] );
if ($payload && $slug = $payload->repository->slug) {
$repo_dir = REPO_PATH . $slug . '.git';
if ( empty($payload->commits) ) {
// we recieved some POST data, but can't determine the branch
// so we are going to update the staging branch to be safe
$web_root_dir = STAGING_PATH . $slug;
$branch = 'develop';
$commit = false;
$update = true;
} else {
$commit = true;
foreach ($payload->commits as $commit) {
$branch = $commit->branch;
if ( $branch === 'master' || isset($commit->branches) && in_array('master', $commit->branches) ) {
$web_root_dir = PRODUCTION_PATH . $slug;
$update = true;
break;
} elseif ( $branch === 'develop' || isset($commit->branches) && in_array('develop', $commit->branches) ) {
$web_root_dir = STAGING_PATH . $slug;
$update = true;
break;
}
}
}
if ($update) {
// Do a git checkout to the web root
exec('cd ' . $repo_dir . ' && ' . $git . ' fetch');
exec('cd ' . $repo_dir . ' && GIT_WORK_TREE=' . $web_root_dir . ' ' . $git . ' checkout -f ' . $branch);
// Log the deployment
$commit_hash = shell_exec('cd ' . $repo_dir . ' && ' . $git . ' rev-parse --short HEAD');
deploy_log( date('d.m.Y H:i:s') . ' ' . $slug . ': ' . $branch . ($commit ? '' : '[no commit]') . " @ " . $commit_hash);
}
} else {
deploy_log("Page accessed but no valid POST data found.\r\n");
die();
}
function deploy_log($message) {
file_put_contents('/logs/git_deploy.log', $message . "\r\n", FILE_APPEND);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.