In this article we are going to learn how to restrict direct commits to any branch using Azure DevOps policies.
Introduction
One of the best practices when using git is to maintain a branch called master. In the recent years, people have started using main branch instead of master.
It makes sense to maintain this branch as clean as possible. Every commit that you make to this branch should be meaningful. However, in real time scenarios. When multiple team members have to work in a project, it doesn’t make sense to directly work on the main branch. Instead, each team member should create their own branch (called as Feature Branch) and once each developer complete their work, they can then merge their changes to the main branch.
Azure DevOps allows us to restrict direct commits to the main branch using a feature called Branch Policies. Azure DevOps supports multiple types of policies. In this article, we will learn about the very simple policy which restricts direct commits to the main branch.
Once the policy has been applied, the only way to merge the feature branch to the main branch is via Pull Requests. Let’s now understand how to configure the Branch Policies on a branch.
Configure Branch Policies
Navigate to All Repositories list by clicking on the Manage Repositories as shown below.

In the All Repositories, select the Repository, click on Policies and then select the branch on which you would like to apply branch policies (in our case, it’s main branch) as shown below.

Once you select the branch, you will be taken to the Branch Policies when you turn on the first policy as shown below and change the value of Required a minimum number of reviewers.

The changes will be saved automatically and you are done. Going forward, it’s not possible to directly make changes to the main branch of the Repo1 repo. Any required changes must go via Pull Request (in short a PR)
Let’s test now and see if we can commit any change to the main branch directly. As shown below, I was now able to make changes to the main branch directly. It throws an error TF402455: Pushes to this branch are not permitted; you must use a pull request to update this branch.

Summary
In this article, we have learnt how to secure main branch by restricting direct commits by configuring the Branch Policies
Do you like this article? If you want to get more updates about these kind of articles, you can join my Learning Groups
This was a great article and exactly what I needed. ADO docs don’t seem to explain this issue as clearly as you did. Thanks!
LikeLike