Just another developer blog

Oops! I committed to the wrong branch

Oops! I committed to the wrong branch

It is common when working with git to use lots of branches. Occasionally you might accidentally commit to the wrong branch but thankfully git makes it easy to put these commits in the right place.

It’s worth noting that the fixes described here are only for when you haven’t pushed anything to a remote branch otherwise you will be changing history that someone else might have already pulled.You don’t want to do that.

There are two scenarios we will consider.

Move recent commits into new <branch> instead of <master>

This is when you made a couple of commits to master but now realise they should have been split into a separate branch.

This is easy to fix: first make a copy of the current state of your master branch, then roll it back to the previous commit. For example, if the commit hash before your changes was a6b4c974:

Accidentally committed on <master> instead of <branch>

This is when you should have committed to an existing branch but accidentally committed to master; a similar situation to the first but requires some different voodoo to fix.

Again, we make a copy of the current state in a tmp branch and reset master. Then we use the three argument form of git rebase –onto to remove the offending commits. We want to get the commits that are now in <tmp> into <branch>. We want to make <branch> the new base of <tmp> starting at the point where <tmp> diverged from master. We then merge these changes into <branch> where they should have been committed originally.

 



Leave a Reply

Your email address will not be published. Required fields are marked *