To find it go to Settings > Branches > Branch Protection Rules and click 'Add Rule'. Then, enter the name of the branch you want to protect and click the checkbox to require pull request reviews before merging.
Yes, it is possible. You must create a pre-commit hook which rejects commits to the master branch. Git doesn't call a pre-commit hook when you call the merge command, so this hook will be rejecting only regular commits.
Go to your repository.
Create a file, .git/hooks/pre-commit, with the following content:
#!/bin/sh
branch="$(git rev-parse --abbrev-ref HEAD)"
if [ "$branch" = "master" ]; then
echo "You can't commit directly to master branch"
exit 1
fi
Make it executable (not required on Windows):
chmod +x .git/hooks/pre-commit
To disable fast-forward merges, you must also add the following option to your .git/config file:
[branch "master"]
mergeoptions = --no-ff
If you want also protect the master branch on your remote, check this answer: How to restrict access to master branch in Git
You can use the pre-commit utility 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.
The basic setup process is:
.pre-commit-config.yaml
file in the root of your project (see below for a first draft)pre-commit install
.Here is a basic configuration that includes just the no-commit-to-branch
hook:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.3.0
hooks:
- id: no-commit-to-branch
args: ['--branch', 'master']
If you want to protect multiple branches, you can use include multiple --branch
arguments in the argument list:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.3.0
hooks:
- id: no-commit-to-branch
args: ['--branch', 'master', '--branch', 'staging']
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.
It may make sense to install it globally via
git config --global core.hooksPath ~/githooks
and moving that pre-commit
file into that directory
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With