Skip to content

Instantly share code, notes, and snippets.

@lucien144
Created July 17, 2015 13:05
Show Gist options
  • Save lucien144/6a44601d477784669aab to your computer and use it in GitHub Desktop.
Save lucien144/6a44601d477784669aab to your computer and use it in GitHub Desktop.
Autodeploy from Bitbucket using new webhooks and Pushbullet notifications
<?php
# Install
# sudo chown -R :apache ./*
# sudo chmod 0775 -R ./*
# sudo -u apache git pull # Optional
# sed -i 's/filemode\ =\ true/filemode\ =\ false/g' .git/config
if (!isset($_GET['token']) || $_GET['token'] != md5('*****')) {
exit('Wrong token. Terminating.');
}
$production_branch = 'production';
$repo_dir = __DIR__ . '/../';
$git_bin_path = '/usr/bin/git';
$push_id = '****';
// Parse data from Bitbucket hook payload
$payload = json_decode(file_get_contents('php://input'));
$update = false;
if (isset($payload->push) && isset($payload->push->changes)){
foreach ($payload->push->changes as $change) {
if ($change->new->type == 'branch') {
$branch = $change->new->name;
if ($branch === $production_branch) {
$update = true;
break;
}
}
}
}
if ($update) {
$status = '';
$status .= shell_exec('cd ' . $repo_dir . ' && ' . $git_bin_path . ' checkout ' . $production_branch) . "\n";
$status .= shell_exec('cd ' . $repo_dir . ' && ' . $git_bin_path . ' pull 2>&1') . "\n";
$commit_hash = shell_exec('cd ' . $repo_dir . ' && ' . $git_bin_path . ' rev-parse --short HEAD');
file_put_contents(__DIR__ . '/../log/deploy.log', date('m/d/Y h:i:s a') . " Deployed branch: " . $branch . " Commit: " . $commit_hash . "\n", FILE_APPEND);
$status .= "Branch: {$branch}\n";
$status .= "Commit: {$commit_hash}\n";
echo $status;
$data = ["type" => "note", "title" => "Autodeploy result: {$payload->repository->slug}", "body" => $status];
$data = (object) $data;
$data = json_encode($data);
$headers = [
"Content-Type: application/json",
"Content-Length: " . strlen($data)
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.pushbullet.com/v2/pushes");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERPWD, $push_id);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$response = curl_exec($ch);
curl_close($ch);
} else {
echo 'Nothing pulled.';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment