jens.feodor.dk

Using git hooks to publish a static website

Last modified 2025-01-08 09:59.

  1. Introduction
  2. Setting up a git remote
  3. Creating a post-receive hook
  4. Troubleshooting
    1. Permissions on work tree directory
    2. OpenSSH on Git with Windows

1. Introduction

What better way to get started writing a blog, than to document its beginnings? I can hardly think of any — at least not without making an effort — and that is why we are here, now.

I wanted to create a static website for my personal presence on the internet, and wanted to publish the website by simply pushing to a git remote.

2. Setting up a git remote

First we need to initialize a git repository on the remote. I assume that an SSH server is running on the remote, and that an SSH key, that is authorized on the SSH server, has been added to the ssh-agent of the client machine.

Then we only need to initialize a "bare" repository on the server, as done below:

git init --bare ~/static_website.git

This will create a git repository that does not contain a working directory, eg. more or less equivalent to just the .git folder in a "regular" git repository. [1]

3. Creating a post-receive hook

When a client calls git push, the post-receive hook[2] is executed once after all refs (eg. branches and tags) have been updated on the remote. All output from the hook is sent back to the client. Using the regular git command, output will be displayed prefixed with "remote:".

We can use this hook to update a static website, and even run build scripts, that generate the actual static content.

#!/bin/bash
BRANCH="main"
while read oldrev newrev ref
do
    if [[ "$ref" = "refs/heads/${BRANCH}" ]]
    then
        echo "Starting deployment of ${BRANCH}"
    else
        echo "Ref $ref is not configured for deployment."
    fi
done
        

4. Troubleshooting

When setting up the git remote for myself, I stumbled upon a few things that I needed to take care of.

Permissions on work tree directory

OpenSSH on Git with Windows

Using Git for Windows, you may experience the following error message, trying to interact with the remote, where GIT_REMOTE_HOST is the hostname of your server:
git@GIT_REMOTE_HOST: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
        

This may be caused by git defaulting to an OpenSSH installation that is included with Git for Windows, rather than the OpenSSH installation on your Windows system.

The following command amends the global git configuration to use the built-in OpenSSH from the Windows installation.

git config --global core.sshcommand "'C:\Windows\System32\OpenSSH\ssh.exe'"
References
  1. https://git-scm.com/book/en/v2/Git-on-the-Server-Getting-Git-on-a-Server
  2. https://git-scm.com/docs/githooks#post-receive