How to reset master branch when using Azure DevOps and git?

  • Post published:May 31, 2020

When following an Agile methodology, with a number of iterations, rapid software development is encouraged to implement or enhance features as quickly as possible. Sometimes developers are placed under a lot of pressure resulting in mistakes been made.

When using Azure Repos with git, and following a git flow process, a common mistake made is completing a pull request from a feature branch to the master branch instead of completing a pull request from the feature branch to the develop branch. This can happen when branch policies are not set up correctly or when code reviews are not done properly.

To reset a master branch to a previous state, and to remove the bad commit comments, use the below git commands in a console or terminal.

git reset --hard <enter-the-commit-number-you-want-to-reset-to>
git push --force

Note that branch policies must be turned off temporarily in order to complete the push.

Example

Consider the below commit history.

theCodeReaper

In the above commit, a mistake was made and the developer attempted to revert the changes and failed. In order to reset the master branch to a working state, click on the commit in Azure DevOps to change to. In this example, the master branch is to be reset to the Added dependency injection using awilix commit. After clicking on the commit, copy the commit identifier. In this example, the commit identifier is df0a7a11f053e34c7785fcb51132a71697d71b4c.

theCodeReaper

Open a console or terminal and navigate to the repository. Execute the below commands.

git pull
git reset --hard df0a7a11f053e34c7785fcb51132a71697d71b4c
git push --force

The below is an output using powershell.

theCodeReaper

After forcing a push, open Azure DevOps and view the commits in the master branch. The bad commits will now be removed.

theCodeReaper

Summary

By using the git command line, it is very easy to reset a master branch to a previous state. Simply navigate to the repository using a console or terminal and enter the following commands.

git reset --hard <enter-the-commit-number-you-want-to-reset-to>
git push --force

Software versions used in this article

  • git v2.26.2.windows.1