Using a git hook to rebuild your Hugo powered website

Yesterday I wrote about my recent migration from Wordpress to Hugo as my static website generator. All of the content, configuration and themes are stored inside a Git repository so I can keep an history of all changes and update it easily using a standard Git workflow.

In order to be as lazy as possible I wanted to be able to rebuild my website after each git push so I don’t need to ssh to the server every time I wanted to do an update.

Rebuilding a website powered by Hugo automatically on push is pretty easy actually. In the following example, the Git repository and the website are hosted on the same server. But you can customize the script to do whatever you want: uploading the file through FTP or rsync should just be few more lines of script.

The first step is to create your Git repository. I personally use Gitosis because it’s more convinient when you have to manage a lot of repositories, but you can also create a single repository by following these instructions or better, follow the one provided by your favorite distribution.

Once your repo is correctly setup, you’ll need to push your Hugo root directory (the one containing your Hugo configuration file and all subdirectories) into it. I assume you’re already familiar with those commands.

Now locate on your server your bare metal Git repository usually on the form of repo.git and containing folders like branches, objects and refs. The one we’re most interested in is hooks. It contains a bunch of sample hooks ready to executed at different stages of the workflow. Create a file post-receive in this directory containing:

mkdir -p $TMP_GIT_CLONE git clone $GIT_REPO $TMP_GIT_CLONE /usr/bin/hugo -s $TMP_GIT_CLONE -d $PUBLIC_WWW rm -Rf $TMP_GIT_CLONE exit

Finally make it executable chmod +x post-receive. Depending on your permissions you’ll maybe need to make your htdocs folder writable by the git user.

We’re almost there but first let’s to do a quick test-drive.

sudo -u git ./post-receive

If no errors are shown, congratulation! You can start editing files in your repository and push to rebuild a live, static version of your website.


Comments

comments powered by Disqus