Today I Learned

A Zero One initiative

Prevent commits to main/master with git hooks!

You can use git hooks to keep you safe when you aren’t thinking properly and decide to commit something to main/master.

It would be nice if we could create a hook which would prevent commits to main/master unless we give it some override. Like a crimesjohnson prefix.

As a start I decided to make a global hook for all of my projects with this command:

git config --global core.hooksPath ~/githooks

I then created a file (within ~/githooks) for a special kind of git hook and named it commit-msg.

#!/bin/sh

commit_msg=$(cat "${1:?Missing commit message file}")
branch="$(git rev-parse --abbrev-ref HEAD)"

if ([ "$branch" = "main" ] || [ "$branch" = "master" ]) && [[ "$commit_msg" != *"crimesjohnson:"* ]]; then
  echo "You can't commit directly to main/master branch"
  exit 1
fi

Don’t forget to make it executable: chmod +x ~/githooks/commit-msg

When you create a commit message, it seems like the message is saved to a temp file while the commit-msg hook runs. We get the commit message by cating it.

We also use a git command to get the name of our branch.

Using these 2 bits of info, we can then write a simple if statement to keep us safe!