How to reset master branch in gitlab

In this article I will explain you how to reset master branch in gitlab. deleting a master branch directly is not possible in gitlab because the master branch is the default branch and its normally a protected branch.

My use case : I had done some research and development works for a project and my technical architect needed to review the code before push the code to master branch but I already committed to all code in to master branch so I had to clean up the master branch and raise a PR from develop branch to master. I have added the steps below how to do this

Prerequisites : You need to access gitlab with maintainer permission and also git bash need to be installed to your computer. Its better to backup master branch and the local code folder since we are going to delete the master branch and map a new master branch.

1. create a new branch from the master branch (ex : develop)

you can log in to gitlab dashboard –> repository –> branches –> new branch — > select the parent as master –> give a name (Ex: develop) and create a new branch

create new branch

2. Make the default and protected branch as your newly created branch

got to settings — > repository and follow the below steps

change default branch gitlab

3. Now you can delete the old master branch

after moving the default branch to new newly created branch the master/main branch delete option will enable and you can delete it from the UI. check the below screen shot

delete a branch gitlab

4. Create a new master/main branch using the same name which you already deleted using GIT bash command

open the git bash terminal and run the bellow command to create a branch without parent mapping

  • git checkout –orphan master (An orphan branch is a separate branch that starts with a different root commit)
  • git commit –allow-empty -m ‘Initial empty commit’ (you can add something before commit Ex : readme.md file)
  • git push –set-upstream origin master
  • git push –set-upstream origin master

using this command you will have a new master/main branch without any commit history you can follow the step 02 and make this as the default and protected branch

Now you can raise a pull request from your develop branch to newly created main/master branch and all changes will included to your PR and you can share the PR to review

this was the easy way to do this to delete the master and branch and create a new one for me there are some other ways to do the same.

happy cording !

Add a Comment

Your email address will not be published.