Search code examples
gitgit-mergegit-reset

Fixing a merge commit in git


I messed up. I merged other branch to my branch. Changes on both sides were substantial so I spent extremely long time resolving conflicts. After committing the merge, I realized I had forgotten to add one file, so the merge was committed incomplete. I didn't want to pollute the history with a "forgotten changes" commit so I decided to fix it before pushing. I called

git reset --soft HEAD~

Then I added the missed change and wanted to re-commit. However, git no longer knows it should be a merge commit. Is there any way out without re-doing the entire merge?


Solution

  • What I would do, if I wanted to amend my last commit (whether it is a merge commit or a normal commit):

    1. Do the change (in your case add the file)
    2. Stage the change. E.g. with git add .
    3. Add the change to last commit with

      git commit --amend

    And you're done

    Since you aren't at that point anymore, first you have to go back there. How?

    1. List the last references you had in order to find out what was the hash of the merge commit you want to restore. Execute

      git reflog

    2. Search in that list and copy the hash of the merge commit. Look for something like [...] merge origin/blablabal, just below something like [...]reset moving to HEAD~

    3. Reset to that commit (as if you haven't done the git reset --soft HEAD~)

      git reset --hard HASH_FROM_BULLET_2

    Now you are at the point you just commited the original merge and now you can proceed with 4, 5 and 6 from the beginning.