in Code

[GIT] How to replace the master branch with another branch.

TL;DR;
git checkout master
git reset --hard fixed-master-branch
git push origin master -f

Sometimes someone may pollute the ‘master’ branch and you may have noticed this only after you’ve fetched, rebased and pushed your commits.
So your history may end up like this (I’ll use decimal numbers on the commit IDs for illustrative purposes only):

commit: 87
Author: me
A good commit

commit: 86
Author: other guy
Merge: that brought back a lot of crap because they probably used some GUI based git client and they did a git pull without your permission

commit: 85
Author: other guy
Another commit that shouldn't be here

commit: 84
Author: me
Another the last good commit

Now, your master is all effed up and you’re about to have an anxiety attack. What you want is to have this in your git log.

commit: 87
Author: me
A good commit

commit: 84
Author: me
Another the last good commit

To get back to this state is pretty easy:

  1. Check out the last good commit

git checkout 84

Now you will be detached from master, let’s name this temporary branch ‘fixed-master-branch’

git checkout -b fixed-master-branch

Now the last commit you should see should be commit 84.

Let’s now bring our commit, and skip the 2 sucky commits

git cherry-pick 87

Now your ‘fixed-master-branch’ branch looks exactly how you want the master to look like.

But now, you want to replace the old master with the new one.

Go back to the broked master

git checkout master

And fix it, and fuck all that merge –strategy ours BS advice you will find on StackOverflow as it will leave the git log history really weird.

git reset --hard fixed-master-branch

Now when you look at your history, master will be the same as ‘fixed-master’, and to fix your remote repo, you will have to make a push –force and let everyone know that you did that because you needed to clean your repository’s history

git push origin master -f

You’re done.

Write a Comment

Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.