Git Hooks and Shell Scripts

I’ve recently got into using Git Hooks with my projects as a way of deploying the build/public directory to a server so that my clients can preview the work on a nice URL link without public/ or build/ at the end of it making it messy, so I get http://example.com/project-name.

This is simplified, but typical project setup:

src/
index.html
public/
index.html
gulpfile.js
package.json
README.md

I read a few articles, such as this one from Digital Ocean and got basically what I needed.

Is that tree working?

#!/bin/bash
while read oldrev newrev ref
do
if [[ $ref =~ .*/deploy$ ]];
then
echo "Deploy ref received. Deploying branch to preview..."
git --work-tree=/var/www/html/project-name --git-dir=/var/www/html/project-name/git checkout -f deploy
else
echo "Ref $ref successfully received. Doing nothing: no work-tree with that branch name found on this server."
fi
done

I wasn’t paying attention at first and so it took me a while to realise that the work-tree was essentially where my files would end up and the git-dir is the part that I could use as my remote URL.

git remote add preview git@example.com:project-name/git

Git Subtree

But with this setup I would still get that messy public/ directory at the end of the URL. So, say hello to git subtree, with git subtree you can push a part of your repo, in this case the public/ directory to a remote.

git subtree push --prefix=public preview deploy

Now, once I’ve done this, I normally let my colleagues know that I’ve got something for them to take a look at, comment on and make suggestions for improvements. Or just that vital extra set of eyes to make sure I haven’t missed anything.

Tell others its ready!

I’m quite terrible at this, I get really excited about the work, so when I finish it all and I’ve deployed it successfully, I sometimes forget to let the rest of my team know; I might have gotten distracted or something. So why don’t I automate that too?
We normally use Asana as our task management system, so I added a simple curl command that would POST a message with the preview URL into the task as a comment, you could probably change this for any other service that uses a RESTful API.

Now I could just leave it like that, save that code snippet some place and copy/edit/paste wherever necessary, right? Sure, but I’ve taken those steps, I could go one further and create another script that would help me auto-generate this once I SSH into my server.

Yo dawg, I heard you like Shell Scripts…

This is my first real attempt at automating my shell script processes, so any comments on how I could write it better would be a great help. And if you’ve found it useful, let me know!