Hugo: Deploy Site With Post Receive Git Hook

hugo, website, git hooks

I’ve been using a post-receive git hook in the past and now I’ve just set that up again. It becomes a pain to publish a Hugo site manually all the time, luckily there is a nice little solution for that called git hooks.

Now all I have to do to deploy my changes is add them to git, commit and push, everything else is handeled by the git hook.

More on that in a bit.

Assumptions

Before starting there are a couple of things that needs to be checked.

You need to have a…:

When all of that is checked, we continue to set up our repositories.

Set up the repositories

On the local computer inside the folder of my website development I created a git repo:

git init

On my server, where I’ll publish the website I created a git bare repo:

mkdir git/odd.unover.se.git
cd git/odd.unover.se.git
git init --bare

The script

The script I created looks like this:

#!/bin/bash

DOMAIN="odd.unover.se"
GIT_REPO="$HOME/git/${DOMAIN}.git"
BUILD="$HOME/git/build"
PUBLIC="/var/www/$DOMAIN"

set -e

rm -rf "${PUBLIC:?}"/* "$BUILD"
git clone "$GIT_REPO" "$BUILD"
/usr/bin/hugo -s "$BUILD" -d "$PUBLIC"

The script is very simple, but I’ll break it down line by line.

We first create a few variables: the domain we’re using, the path to the git repo, the directory where we build the site and the location where the site will be served from:

DOMAIN="odd.unover.se"
GIT_REPO="$HOME/git/${DOMAIN}.git"
BUILD="$HOME/git/build"
PUBLIC="/var/www/$DOMAIN"

Before we start doing anything we are going to clean up both the build and public directories, just to avoid potential issues:

rm -rf "${PUBLIC:?}"/* "$BUILD"

When we’re pushing from our local development environment, we’re going to push to, in my example, odd.unover.se.git that we created earlier.

Next up is to clone the git repo (odd.unover.se.git) to the build directory:

git clone "$GIT_REPO" "$BUILD"

Now we can build the actual site with Hugo. We’re using the build dir as source and the public dir as destination:

/usr/bin/hugo -s "$BUILD" -d "$PUBLIC"

Deploy

Now on from the git repo on the local computer we need to add the repo:

oux@odd.unover.se:git/odd.unover.se.git

Where oux is the user. odd.unover.se obviosly the domain. :git/odd.unover.se.git is the path to the git repo on the remote server.

git add .
git commit -m "commit"
git push origin main

Every time I push the changes I’ve committed, it will deploy it on this website as well as give me the version control.