You can use pre-commit to do this. It has a built in no-commit-to-branch
hook that can be used to prevent commits to one or more branches.
Setup
The basic setup process is:
- Install using pip or brew (instructions at https://pre-commit.com/#install)
- Create a
.pre-commit-config.yaml
file in the root of your project (see below for a first draft)
- Install the hooks into your git config by running
pre-commit install
.
Basic config for protecting branches
Here is a basic config that includes just the no-commit-to-branch
hook:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.2.5
hooks:
- id: no-commit-to-branch
args: ['--branch', 'master']
If you want to protect multiple branches you can use include multiple --branch
args in the argument list:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.2.5
hooks:
- id: no-commit-to-branch
args: ['--branch', 'master', '--branch', 'staging']
Isn't this all overkill?
Pre-commit has many other built-in hooks, and a large collection of community-built hooks that will transform the way you clean-up and validate your commits. The reason I mention this is because, while this tool may be overkill for just preventing commits to a protected branch, it has many other features that make it a compelling and simple addition to any git project.