In this post, we will look at branch protection and how to use it to prevent users from merging code directly to the master or main branch in GitHub.
I have a GitHub repo that looks like below. Let’s go do its Settings:
And select Branches. We can see there are no Branch Protection Rules.
At this point, I am able to merge code directly into the Master/Main branch.
Let’s add a rule. First we will add the name of branch as main, which is my main branch (yours may be master). Next, we will check the Require pull request reviews before merging, and we will set the number of required reviewers to 1:
I’m also going to check Include administrators, then click Create. Note there are many other rules you may want to enable:
Now when I push a code update from Visual Studio Code directly to the main branch, I see Can’t push refs to remote. Let’s click on Open Git Log:
We see the error message:
Let’s create a new branch from main:
In VS Code, fetch and switch to the new branch:
And commit and push our code to GitHub:
We can now open a pull request to merge mybranch into main:
If we try to create the PR, we get an error:
And our merge is blocked:
Let’s add a reviewer:
Once the approver approves the pull request, it will allow you to merge, and Main is updated: