Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Sample post-receive hook that will "update" another folder (such as a web root) on your server after a `git push` to the master branch
#!/bin/bash
# http://stackoverflow.com/a/13057643/1171790
# https://www.digitalocean.com/community/tutorials/how-to-use-git-hooks-to-automate-development-and-deployment-tasks
while read oldrev newrev ref
do
if [[ $ref =~ .*/master$ ]];
then
echo "Master branch received. Deploying master branch to production..."
git --work-tree=/home3/themes/whatever/web/root --git-dir=/home3/whatever.git checkout -f
# You can put other commands here like `npm install`
else
echo "Ref $ref successfully received. Thanks and have a great day!"
fi
done
<?php
// USAGE: yourserver.com/post-receive.php?p=hippo
// In GitHub, when setting up the webhook, use: "Content type: application/x-www-form-urlencoded"
if (!empty($_GET['p']) && $_GET['p'] == 'hippo') { // this makes the script *slightly* more obscure
if ($_POST['payload']) {
try {
$payload = json_decode($_POST['payload']);
} catch(Exception $e) {
file_put_contents('git.log', PHP_EOL.'*****An error occured getting the post payload from Github on: '.date('F j, Y, g:i a').PHP_EOL.PHP_EOL, FILE_APPEND);
exit(0);
}
file_put_contents('git.log', '--- Post payload push recieved: '.$payload->commits[0]->timestamp.' ---'.PHP_EOL, FILE_APPEND);
if ($payload->ref === 'refs/heads/master') {
`git fetch --all`;
`git reset --hard origin/master`;
file_put_contents('git.log', 'Master branch deployed to production. Log message: '.$payload->commits[0]->message.PHP_EOL, FILE_APPEND);
} else {
file_put_contents('git.log', 'The push from GitHub was to a branch other than master.'.PHP_EOL, FILE_APPEND);
}
} else {
file_put_contents('git.log', PHP_EOL.'*****This scipt was touched, but no post payload was sent. On this date: '.date('F j, Y, g:i a').PHP_EOL.PHP_EOL, FILE_APPEND);
} // no POST "payload" variable sent. check that repo is set to send 'application/x-www-form-urlencoded' data.
} // check if we have GET var 'hippo'

Push to Deploy

  1. On your server cd /your/projects/root/.git/hooks
  2. Get the post-receive file from this Gist. wget https://gist.githubusercontent.com/jonathanbell/4f08961709f9172276f9/raw/1b4ae48442c383156a04d5eb1176ab88e7eac3ee/post-receive
  3. Make sure the file can be executed: chmod +x post-receive
  4. Edit the paths in the file, relating them to your own project.

This repository also has a PHP version (post-receive.php) that you could use with a GitHub webhook. Make sure to exclude that file in your .gitignore file if you decide to use it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment