A background image for the simonporter blog

Pre-Push Time Saver

A little time saver using the git pre-push hook

2 min read

Using git "pre-push" to save some time

Git has a range of hooks that you can use to protect yourself against mistakes, or ensure code standards across your team. I recently had a need to add a pre-push hook to save myself some time when pushing up new PR's.

Our test suite can take quite a while to run, so I'll typically push up, and then move onto other things to come back in a little bit after CI in case tweaks are needed that I missed locally.

Occasionally I'll be working on a part of the code that looks okay in VSCode, but then fails typechecking because a part of my change broke a file I didn't have open. This pre-push hook makes sure I don't forget to run typechecking before I push up any changes, and will block the push if it fails.

How to install

This can be as simple as creating a file in .git/hooks/pre-push within your repo, and making it executable chmod +x .git/hooks/pre-push:

SH
#!/bin/zsh

cmd="yarn run typecheck"

echo "running typecheck before push..."
eval $cmd
result=$?
if ! eval "$cmd"; then
echo "Failed typecheck! Fix before pushing or force push: `git push --no-verify`" >&2
exit 1
fi

exit 0

To get this working in VSCode, I also needed to add the push command to the git.commandsToLog setting inside VSCode preferences.

With this in place, you're off to the races!