Publish your Hugo site with Git

2. April 2017
hugo git gogs

In the meantime I switched to a slightly more sophisticated workflow using drone. I will use this build system for several more projects, and also switched deploying of this blog.

In this post I will show you how you can setup a comfortable environment to work with Hugo and publish the contents with Git. With this solution you get not just version control, but also an automatic way of uploading your contents to your server.

I will work with Gogs as my self-hosted Git server, but this is not a requirement. It will work with every other Git server too.

Let's start

So, first we have to install Hugo on our local machine. After choosing a theme and properly configuring the Hugo site, we can initialize a Git repo in our Hugo site folder via git init. Now we can add some content to our site with:

hugo new post/hello-world.md
vim content/post/hello-world.md

After writing some lines of text, we can head over to the next steps, now on the server.

Create server repo

In Gogs, we create a new empty repository. Afterwards you will see instructions on how you add the newly created repository as the ‘origin’ remote for our local repo. Execute the shown commands an we are ready to push our local changes to the server. But first, we need to do one more thing.

Modify server hooks

This is where the magic happens. We leverage the power of Git hooks, more specifically, we use the server hook post-receive. In the gogs UI we navigate to Git Hooks in the repository's settings and add following content:

#!/bin/bash
DEPLOYDIR='/var/www/main'

cd $DEPLOYDIR
GIT_WORK_TREE='$DEPLOYDIR' GIT_DIR='$DEPLOYDIR/.git' git pull --rebase
/usr/bin/hugo

This script will be run after the git push was successful and the server repository is properly updated. It will cd to the webroot of your site and pull the changes from the gogs repo. Afterwards hugo is executed and updates the static files.

Publish your work

Now we are good to go! Just add your local changes to git and push it to the server.

git add .
git commit
git push

You will see the outputs of the commands on the server in your git push log, so you can check if everything works. Your new post will now be visible on your website.

From now on your workflow will look something like this:

hugo new post/new-post.md
vim content/post/new-post.md
git add .
git commit
git push

This makes it comfortable to edit your site, even from different computers. There is just one caveat with this setup. Changes made in the Gogs UI do not trigger the site rebuild, because the post-receive hook is not executed. If I find a solution, I will add it here.