Prevent Direct Merges to Master with Branch Protection in GitHub

Leave a comment

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:

remote: error: GH006: Protected branch update failed for refs/heads/main.
remote: error: At least 1 approving review is required by reviewers with write access

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:

 

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

Leave a Reply

Your email address will not be published. Required fields are marked *