what the hook

Git hooks are often overlooked or underused. They can be very useful, and even used as a rudimentary CI/CD workflow.

While these tips can work for any repo, this could be viewed as an expansion on my tech_grimoire post.

For note taking I make use of the VimWiki plugin to Vim. My wiki directory is a git repository, which is then cloned on to one of my servers and using Gollum is available as a website.

This has worked well for years, but one thing I have not been good at is committing and pushing changes straight away. In order to improve my workflow I make use of two git hooks, one in the local repo and one in the remote bare repo.

Git hooks are scripts which can be run at various times in a git workflow. When they run is based on the name of the script.

If you look in the .git/hooks directory of a repo you should see some sample scripts.

──── ─ ls -1 .git/hooks
applypatch-msg.sample
commit-msg.sample
fsmonitor-watchman.sample
post-update.sample
pre-applypatch.sample
pre-commit.sample
pre-merge-commit.sample
pre-push.sample
pre-rebase.sample
pre-receive.sample
prepare-commit-msg.sample
push-to-checkout.sample
update.sample

For my wiki I make of the post-commit hook.

#!/bin/sh
git push origin master

That’s it. As soon as I make a commit the master branch is automatically pushed.

This works but I wanted to go one step further, automatically adding changed files and making the commit. The prepare-commit-msg hook is useful when you want to populate the commit message with something, but I couldn’t figure out an easy way to do what I wanted with hooks.

In the end I used a command in my ~/.vimrc

set :Gac git commit -a -m "updates"

Now, when I have finished updating my wiki I incant

:Gac

and the updates will be committed and pushed, albeit with a generic commit message.

Once the changes are pushed to my git server they hit another hook, post-receive.

#!/bin/sh
ssh wikiserver "cd /grimoire ; git pull"

When the remote bare repo receives any updates the hook will perform a git pull of my wiki on the server I host it on, causing my Gollum page to be updated.

The final thing I have done is to change the hooks directory in my local repo. With the default dir, .git/hooks, nothing can be tracked by git.

Instead I created a directory in the repo, .githooks and put my post-commit hook there. This way it can be tracked in the repo.

An update to the config is required so git knows where the hooks are

git config core.hooksPath .githooks

Note: this option was introduced in got v2.9, so make sure you have that version or higher

As far as I am aware there is no way to track hooks in a remote bare repo. If you know of a way I would be interested to hear about it.

Who needs a convoluted CI/CD pipeline when a couple of one line scripts will do? Typing :Gac is easy enough that my wiki should now stay up to date.