Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thebrecht/16538fd4faf54d3280a67aa698db9a6d to your computer and use it in GitHub Desktop.
Save thebrecht/16538fd4faf54d3280a67aa698db9a6d to your computer and use it in GitHub Desktop.
# src: http://jonathannicol.com/blog/2013/11/19/automated-git-deployments-from-bitbucket/
#~/.ssh/config
Host bitbucket.org
IdentityFile ~/.ssh/bitbucket_rsa
# clone project
git clone --mirror git@bitbucket.org:<username>/<repo-name>.git
# checkout project
GIT_WORK_TREE=/home/<username>/www git checkout -f production
# sync bitbucket
<?php
$repo_dir = '/home/<username>/<repo-name>.git';
$web_root_dir = '/home/<username>/www';
// Full path to git binary is required if git is not in your PHP user's path. Otherwise just use 'git'.
$git_bin_path = 'git';
$update = false;
// Parse data from Bitbucket hook payload
$payload = json_decode($_POST['payload']);
if (empty($payload->commits)){
// When merging and pushing to bitbucket, the commits array will be empty.
// In this case there is no way to know what branch was pushed to, so we will do an update.
$update = true;
} else {
foreach ($payload->commits as $commit) {
$branch = $commit->branch;
if ($branch === 'production' || isset($commit->branches) && in_array('production', $commit->branches)) {
$update = true;
break;
}
}
}
if ($update) {
// Do a git checkout to the web root
exec('cd ' . $repo_dir . ' && ' . $git_bin_path . ' fetch');
exec('cd ' . $repo_dir . ' && GIT_WORK_TREE=' . $web_root_dir . ' ' . $git_bin_path . ' checkout -f');
// Log the deployment
$commit_hash = shell_exec('cd ' . $repo_dir . ' && ' . $git_bin_path . ' rev-parse --short HEAD');
file_put_contents('deploy.log', date('m/d/Y h:i:s a') . " Deployed branch: " . $branch . " Commit: " . $commit_hash . "\n", FILE_APPEND);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment