Random thoughts & observations

From the mundane to the profound and everything in between here’s what’s rocking our world

Undoing a local Git merge

Posted: December 10, 2015
Written by: Saints At Play
Category: Version Management

Git is a fantastic tool for managing project code within a team context but, as with any tool, there'll always be occasions when you run into problems.

One such problem might occur where you want to undo a local branch merge that hasn't been pushed to the remote repository. Sounds tricky right?

The following are ways in which this can be accomplished relatively quickly...

Hard reset

Check your git log to determine which commit preceded the merge and then reset your local repository to that specific commit sha:

git log
git reset --hard COMMIT_SHA_REFERENCE

Alternatively you can opt to roll back by a specified number of commits like so:

git log
git reset --hard HEAD~NUMBER_OF_COMMITS_TO_ROLL_BACK

Don't forget the tilde character in the above method!

The major downside of these approaches? You won't retain any local changes you've made so use with caution!

Merge reset

The following approach should retain your local changes while pointing to the last commit made before the merge took place:

git reset --merge ORIG_HEAD

This makes it an ideal method for cleaning up a merge while preserving local changes but, as you might have guessed, there are downsides to using this approach - if your local master branch is behind the remote branch by any number of commits then this method may not give the expected results.

There's also the possibility that this method could rewrite the Git history making it confusing/difficult for other developers in the team to determine the flow of changes made to the remote repository when the commit is finally pushed. We're not sure how true this is and it may only apply when reverting changes that have already been pushed to the remote repository.

So there you have it, a number of ways to accomplish undoing local merges in Git.

Whichever option you choose be aware of the consequences and, as with any tool, use wisely!

« Return to Posts

Comments

There are no comments

Posting comments after three months has been disabled.