How to lose a commit with a combination of git-merge, git-rebase, and git-amend

10 Sep 2015

Note: git's version is 2.3.2 (Apple Git-55)

I have encountered a way to lose a commit by accident. If you're using a combination of git-merge, git-rebase, and git-amend, you should read on.

I haven't figured out the explanation yet, but here are the steps to lose a commit.

[master] > echo "aaa" >> test1 [master] > git add test1; git commit -m "Add test1" [master] > git checkout -b master-2 [master-2] > echo "bbb" >> test2 [master-2] > git add test2; git commit -m "Add test2" [master-2] > git checkout master [master] > echo "ccc" >> test3 [master] > git add test3; git commit -m "Add test3" [master] > git checkout master-2 [master-2] > git merge master # Please note that the latest commit is a merge from master [master-2] > echo "ddd" >> test4 [master-2] > git add test4; git commit --amend -m "Some new commit" [master-2] > ls test1 test2 test3 test4 [master-2] > git rebase -i master # Only the commit "Add test2" appears in the editor. "Some new commit" doesn't appear [master-2] > ls test1 test2 test3

test4 disappears.


There are 2 lessons here:

  1. A normal commit and a merged commit are viewed and treated differently by git. It might make sense because git-rebase and git-merge achieve the same goal. git-rebase shouldn't consider the changes from git-merge because those changes are redundant. This can be the reason why there are 2 types of commits, so that git-rebase can choose to discard merged commits.
  2. Never ever mix git-rebase and git-merge. Only choose one.