Moving new Git branch with different history to master

Aug 22, 2016

Today I’ve learned a new thing about Git. Actually some days back, we started re-implementation of one of our old web app. Previously, the app was written with Jquery. Some days back, we felt that, it would be better, if we could use ReactJs for the app, as it only shows updates, and each of the updates has it’s own life cycle. So, thought this would be a good use case to leverage the powerful features of ReactJs.

Anyway, as this new development happens to be completely different than the previous one, first decided to create a new repository altogether. But, after some considerations, came to the conclusion, that it would be wrong, if we create a completely new repository for a software, that will do essentially the same things as the previous one.

So, created one orphan branch from master.

git checkout master
git checkout -b --orphan new_version
git rm <all-the-unnecessary-files>
## Make changes in the code base
git add .
git commit -am "new_version: Initialize"
# Generally the remote is 'origin', if not change as required
git push origin new_version

And continued development on that.

Until this stage, there was no problem. But, problem started, when we tried to push this branch to master. We could not merge this branch to master, as that would nullify the effort to make a new commit history for the new version.

Decided to delete the master branch and create new master branch from new_version.

# Create a backup of the old version
git checkout master
git checkout -b old_version
# And push the backup to remote
git push origin old_version
# '-D' is needed instead of '-d', as current branch
# and 'master' branch has different commit history
##### Following error will come
# error: The branch 'master' is not fully merged.
# If you are sure you want to delete it, run 'git branch -D master'.
git branch -D master

Now, we can’t delete the master branch from remote straight away. It would give the following error.

To [email protected]:username/repo.git
! [remote rejected] master (refusing to delete the current branch: refs/heads/master)
error: failed to push some refs to '[email protected]:username/repo.git'

As our repository is hosted in Github, we could change the default branch temporarily to new_version in the branches tab of settings page of the repository. And delete the master branch in remote.

git push origin :master
# To [email protected]:username/repo.git
# - [deleted] master

Now, create the new master branch from new_version.

git checkout new_version
git checkout -b master
# And check-in this new master branch
git push origin master

Now, change the default branch to master in Github.

Blog comments powered by Disqus