How to create a "master" branch in a Git repo after an initial commit has been made?

Viewed 1992

I've created a feature branch in an empty Git repo and pushed it to Github. Now I can't create a PR from it as it's considered a "default" branch and there's no master branch. How can update the repo so that:

  • There's a master branch (say, pointing to a commit adding an empty README file)
  • There's a feature branch with my change, which can be used to create a PR ?

Any help would be appreciated.

2 Answers

Based on your question, your repository now looks like this:

o
^
feature

and you want to make it look like this:

o-------o
^       ^
master  feature

while also making master the new default branch on GitHub, instead of feature.

One way to go about it is to create a new "initial" commit on the feature branch, move it to the beginning of the history and create a new master branch that points to it.

Here are the steps:

git checkout feature
git commit --allow-empty -m "Initial commit" (you can create the README file here, instead)
git rebase -i --root

# The TODO file will look something like this:

pick 1234abc Adds the feature
pick 5678edg Initial commit

# Move the "Initial commit" line to the top of the file

pick 5678edg Initial commit
pick 1234abc Adds the feature

# Then save and close

At this point, your history will look like this:

o-------o
        ^
        feature

Now, create the master branch pointing to the commit before the one referenced by feature:

git checkout -b master feature^

At this point, all you have to do is push master to GitHub with:

git push -u origin master

Finally, you'll have to go to your repository's settings on GitHub to make master the new default branch. See GitHub's documentation on how to do that.

If your repository only has a feature branch, and that branch only has a single commit, and the repository in GitHub has no commits, just rename your feature branch to master and push it. No need for a pull request.

Everything has to start somewhere. The first commit to a new repository doesn't need a pull request. A pull request needs two branches so you can view the changes introduced. Since this is a new repository, there are no new changes.

Related