Typically a Git commit has exactly one parent, however a Git merge commit has two parents (see A Commit with Two Parents). The problem this creates with Git revert, is it is unclear which commit we want to revert to.
* 154382e (HEAD -> main) Merge branch 'feat/d' into main
|\
| * 163fe29 (feat/d) D
* | 5d408f9 C
|/
* 2b3a38b B
* ec6a2c7 A
If you run git revert HEAD
, does Git revert to 163fe29
or to 5d408f9
?
Revert to Before the Merge Commit
Literally every time I have reverted a Git Merge commit I want to go back to the commit before the merge commit (in this case 5d408f9
). To get this behavior we pass -m 1
to Git revert.
git revert -m 1 HEAD
After this command, your history will look something like
* b35e2ac (HEAD -> main) Revert "Merge branch 'feat/d' into main"
* 154382e Merge branch 'feat/d' into main
|\
| * 163fe29 (feat/d) D
* | 5d408f9 C
|/
* 2b3a38b B
* ec6a2c7 A
The state of HEAD (b35e2ac
) will now be identical to before the merge commit (5d408f9
C).
When working with Git and you want to revert a merge commit, you need to indicate which parent commit you want to revert to.
Further Reading on Reverting Merge Commits
- How to revert a merge commit that’s already pushed to remote branch?
- See the
How to Undo a Pushed Merge
section on How to Undo a Merge in Git
How can we undo all parent commits of amerge commit, using git revert
If I understand correctly, it sounds like you want to use `-m 1` in your revert command as described in the “Revert to Before the Merge Commit” section above.