Git hooks are a useful way to automatically highlight/fix issues before you submit your code changes for review. For example git hooks can stop you accidentally including secrets (e.g. passwords) in your commits.
There are different types of git hooks,
pre-push…and etc, of which the
pre-commit hooks are arguable the most popular type. These get run whenever a user runs
git commit. A commit gets aborted if a
pre-commit hook exits with a non-zero exit code, although you can bypass that with
git commit --no-verify.
In this article I’m going to set up 2
pre-commit hooks, they are:
- A hook that prevents me making commits directly on the
main) branch. This hook is useful for me, because sometimes I forget to create a new dev branch before committing my changes. Worse still, sometimes I even ended up pushing code up directly to the
mainbranch. You can configure github branch protection rules to prevent this from happening, but if you’re the git repo’s admin, then those branch protection rules get ignored.
- A hook that prevents me from accidentally including secrets (e.g. passwords) in my commits.
Creating Custom hooks
In the past, most people used to create their own custom hooks using some
.sampletemplate scripts files that git itself provided, you can view these files looking inside a git repo’s
$ ls -lart .git/hooks/
-rwxr-xr-x 1 sher staff 896 24 Apr 13:32 commit-msg.sample
-rwxr-xr-x 1 sher staff 4898 24 Apr 13:32 pre-rebase.sample
-rwxr-xr-x 1 sher staff 1643 24 Apr 13:32 pre-commit.sample
-rwxr-xr-x 1 sher staff 478 24 Apr 13:32 applypatch-msg.sample
-rwxr-xr-x 1 sher staff 4726 24 Apr 13:32 fsmonitor-watchman.sample
-rwxr-xr-x 1 sher staff 544 24 Apr 13:32 pre-receive.sample
-rwxr-xr-x 1 sher staff 1492 24 Apr 13:32 prepare-commit-msg.sample
-rwxr-xr-x 1 sher staff 189 24 Apr 13:32 post-update.sample
-rwxr-xr-x 1 sher staff 416 24 Apr 13:32 pre-merge-commit.sample
-rwxr-xr-x 1 sher staff 424 24 Apr 13:32 pre-applypatch.sample
-rwxr-xr-x 1 sher staff 1374 24 Apr 13:32 pre-push.sample
-rwxr-xr-x 1 sher staff 3650 24 Apr 13:32 update.sample…