Hugo on GitHub Pages

Last updated on .

I was looking to switch hosting provider for my server; so my website needed to move, or at least have an interim space. Figured I’d just try GitHub pages again since they enabled (at some point in time since I last used it) HTTPS on custom domains.

For ‘user’ oriented pages, GitHub will just directly publish off the master branch. This is hardcoded, and won’t change even if the default branch changes–this means you can do some useful things with git-worktree(1).

Create your hugo source repository as normal (if you don’t have one already) and then rename the master branch to source or whatever you would prefer to call the branch holding the hugo source:

git branch -m source

Then create a new branch called master and make sure it is empty and orphaned:

git checkout --orphan master
git reset --hard
git commit --allow-empty -m "Init"

Afterwards you want to switch back to your source branch and then setup git worktree in the public directory (where hugo outputs built websites):

git checkout source
git worktree add public master

The last setup task is to setup remotes so that both branches push to the correct upstream branches:

git branch -u origin/source
git -C public branch -u origin/master

I then created a couple scripts for building the website and pushing it to the master branch.

git -C public add -A
git -C public commit --amend --no-edit >/dev/null

This script edits the same commit to ensure that over time the repository itself does not get too big, though if you have a massive site you may want to just create new commits every time.

git -C public push --force
git push

So you don’t forgot to push both the development and the live html branches.

Anyway, that’s all on how to setup a relatively simple git hack for easing the pain of using hugo + GitHub pages.

Update: I now just use a makefile instead of multiple scripts

# -*- mode: makefile-gmake -*-

.PHONY: default
default: all

	git worktree add -b master public

.PHONY: serve
	hugo serve --disableFastRender

.PHONY: build
build: public/ clean
	git -C public add -A
	git -C public commit --amend --no-edit >/dev/null

.PHONY: push
push: build
	git push source origin && git -C public push source master --force

.PHONY: clean
	rm -rf public/*

.PHONY: distclean
	rm -rf public/

all: build

Update v2:

I now use a GitHub Action to build the site instead of having to do it locally. This is my action file below. It requires you to setup the ACTIONS_DEPLOY_KEY see the GitHub Pages Action in the marketplace.

name: GitHub Pages

    - source

    runs-on: ubuntu-18.04
    - uses: actions/checkout@v1
        ref: source

    - name: Setup Hugo
      uses: peaceiris/actions-hugo@v2
        extended: true

    - name: Build
      run: hugo

    - name: Deploy
      uses: peaceiris/actions-gh-pages@v2
        PUBLISH_BRANCH: master
        PUBLISH_DIR: ./public