Skip to content

Instantly share code, notes, and snippets.

@phptek
Last active August 29, 2015 14:02
Show Gist options
  • Save phptek/fdcc7c53efedb2cd51fd to your computer and use it in GitHub Desktop.
Save phptek/fdcc7c53efedb2cd51fd to your computer and use it in GitHub Desktop.
BitBucket post-push hook
<?php
/**
*
* Receive POST requests from bitbucket.org and pull latest based on incoming branch filtering.
* Note: You'll need to setup www-data user (Debian) with SSH keys in the /var/www/.ssh dir and add the public key to bitbucket's UI.
*/
class bitbucketGit {
/**
*
* @var string
*/
protected static $document_root = '/var/www/my-site';
/**
* Example array output from bog-standard BitBucket post-push POST request:
* array (
* 'payload' => '{"repository": {"website": "http://my-site/", "fork": false, "name": "my-site", "scm": "git", "owner": "phptek", "absolute_url": "/phptek/my-site.com/", "slug": "my-site.com", "is_private": true}, "truncated": false, "commits": [{"node": "70fee6925a4e", "files": [{"type": "added", "file": "htdocs/bitbucket-post-push.php"}], "raw_author": "Russell Michell <[email protected]>", "utctimestamp": "2014-05-17 09:07:01+00:00", "author": "phptek", "timestamp": "2014-05-17 11:07:01", "raw_node": "70fee6925a4e9bf1567acf4b256174aea5c1ed7a", "parents": ["1b9c2f650309"], "branch": "master-bitbucket-test", "message": "Added another test\\n", "revision": null, "size": -1}], "canon_url": "https://bitbucket.org", "user": "phptek"}',
* )
*
*/
public function bitbucket() {
if(!$this->checkInput()) {
$this->log("Incoming payload was empty.");
exit(1);
}
$incoming = json_decode($_POST['payload'], true);
// Discard data for any other branch than the following
$branchMap = array(
'live' => 'live/htdocs',
'staging' => 'stage/htdocs'
);
$incoming_branch = $incoming['commits'][0]['branch'];
if(!in_array($incoming_branch, array_keys($branchMap))) {
$this->log("Incoming branch wasn't one of the desired branches: " . $incoming_branch);
exit(1);
}
$path = self::$document_root . '/' . $branchMap[$incoming_branch];
// Data is cosha. Next steps, change to correct dir
if(!chdir($path)) {
$this->log("Couldn't change dir to: " . $path);
exit(1);
}
// We're in, now pull latest codebase onto the server from BitBucket
$cmd = 'git pull bitbucket ' . $incoming['branch'];
if(!system($cmd)) {
$this->log("Couldn't execute command: " . $cmd);
exit(1);
}
}
/**
* Check incoming data
*
* @return boolean
*/
protected function checkInput() {
$isPostEmpty = (!count($_POST));
$isNoPayload = (isset($_POST['payload']) && !strlen($_POST['payload']));
if($isPostEmpty || $isNoPayload) {
return false;
}
return true;
}
/**
*
* @param string $msg
* @return void
*/
protected function log($msg) {
file_put_contents('./bb.out', $msg . PHP_EOL, FILE_APPEND);
}
}
$bb = new bitbucketGit();
$bb->bitbucket();
~
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment