Skip to content

Instantly share code, notes, and snippets.

@eknowlton
Created April 25, 2017 17:33
Show Gist options
  • Save eknowlton/36a1b09b028909fc745c4050e3993058 to your computer and use it in GitHub Desktop.
Save eknowlton/36a1b09b028909fc745c4050e3993058 to your computer and use it in GitHub Desktop.
Bitbucket Repository Push & Pull Webhook
<?php
/*
*
* This script manages webhooks from bitbucket.
* In order to automatically deploy updated source code
* without having to manually pull the repository.
*
* Bitbucket webhook will hit this script twice
* each time a commit is pushed to the repository.
* Once on production, and once on staging to
* insure proper user permissions.
*
*/
// Define paths to environments
define('DOCROOT_PATH', '/var/www/html');
// Define git binary path
define('GIT_BIN', '/usr/bin/git');
/**
* Pull a repository using shell exec.
* @param $directory
* @param $branch
* @return string
*/
function pullRepository($directory, $branch) {
$command = 'cd ' . $directory . ' && ' . GIT_BIN . ' pull --rebase origin '. $branch . ' 2>&1 && echo $?';
$result = shell_exec($command);
return $result;
}
/**
* Pull production repository using pullRepository()
* @return string
*/
function updateRepository() {
$result = pullRepository(DOCROOT_PATH, 'master');
return $result;
}
/*
* Begin logic to determine which repository to pull since this script
* is hosted in the repository and the bitbucket webhook hits it twice
* on both hosts lunginstitute.com and staging.lunginstitute.com
*/
$jsonBody = file_get_contents('php://input');
$data = json_decode($jsonBody, true);
$host = $_SERVER['HTTP_HOST'];
$user = get_current_user();
echo "Current user: $user \n";
$masterUpdate = false;
$stagingUpdate = false;
// grab changes pushed from bitbucket payload
$changes = $data['push']['changes']; // Branch name on new changes
echo "Number of changes: " . count($changes) . "\n";
// loop through changes to see if changes
// were pushed to master or staging branch
for ( $i = 0; $i < count($changes); $i++ ) {
// if master and staging both already marked for update
// break loop to save time
if ($masterUpdate && $stagingUpdate) {
echo "Master and staging both are flagged for update. \n";
break;
}
$branchName = $changes[$i]['new']['name'];
echo "Change found for branch: " . $branchName . "\n";
// Determine which branches matter
switch ($branchName) {
case 'master':
$masterUpdate = true;
break;
}
}
echo "Update master? ";
echo $masterUpdate ? "yes" : "no";
echo "\n";
// update master, if this is being run by production account
if ($masterUpdate) {
echo "Pull repository. \n";
echo updateRepository();
} else {
echo "No changes found on master. \n";
}
echo "-- done -- \n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment