Creating an empty branch from a populated one

Getting into a mess

At work we use Azure DevOps for our Git repositories. When creating a new repository we have to specify the default branch. The default branch is used when raising pull requests, so to avoid mistakenly raising a pull request to merge a feature branch into the master branch, we set the default branch to be develop. However, this has the drawback of creating the repository without a master branch. While it’s possible to create the master branch immediately after creating the repository, the developers often forget to do this and we find ourselves in a position where the repository has had many feature branches already merged into develop and then needing to create the master branch. This leaves us with 2 choices:

  1. Create the master branch from develop, including all the code as it currently is
  2. Create the master branch almost empty, as it would be if it had been created immediately after the repository had been created

Of these two, the latter is preferable as I’ve always been of the mindset that the master branch should be what is (or will soon be) in the live environment.

Creating the empty master branch

Fortunately, there is a fairly simple way to do this.

$ git checkout --orphan master
$ git rm --cached -r . 

The first of these commands creates the branch and switches you to it. The orphan parameter means that the branch starts with a disconnected history, however the files remain in the index. The second command removes the entries for the files from the repository index, leaving the files themselves intact. You can then choose which files to remove manually.