thiagowfx's avatar

Β¬ just serendipity πŸ€ (not just serendipity)

pre-commit: no-commit-to-branch hook

β€’ 154 words β€’ 1 min

⚠️ This post is over one year old. It may no longer be up to date or relevant. Opinions may have changed.

Problem statement: prevent developers from committing directly to master (or main) in git.

You can do so server-side e.g. on GitHub via branch protection rules.

How to address it client-side though?

Countless times have I accidentally committed to master locally without creating a branch first, only to have git push fail.

I wanted git commit to fail early – this is better than having git push fail later.

pre-commit.com provides an out-of-the-box hook called no-commit-to-branch, which addresses exactly this use case.

I adopted it in our .pre-commit-config.yaml. It worked as intended locally.

There was a problem though: the pre-commit CI pipeline / workflow in main / master would fail, because…errrr, there’s a commit there. When you think of it, it’s working as intended, even though it comes across as unexpected.

The solution: skip the hook in CI. Which is also the official recommendation:

shell
SKIP=no-commit-to-branch pre-commit run

I wish this would be done out-of-the-box.