gitbranchrebase

How to retrieve the old commit before rebase


Say, I am working on a branch called 'latest'. After finishing the task, I commit the work. When I rebase the changes from 'master' branch onto 'latest' branch, during conflict-resolution, I accidentally accept all the changes from master & as a result, by the end, when the rebase is completed, I have lost a lot of my work done in 'latest'.

Considering that I rebased within 'latest' branch, are the commits for the work I did, overwritten by the conflict resolutions I accepted? Is/ are my previous (original) commits gone? And if not, how can I retrieve them please. Thanks.


Solution

  • The original commits you made in the latest branch should still be accessible in the git reflog. The current latest branch though now has new, rewritten commits. You could try to sift through the reflog, though the fastest way out of this might be to just hard reset latest to the remote tracking branch origin/latest:

    # from latest
    git reset --hard origin/latest
    

    This option assumes that, after you made the commits in question, you pushed to the remote, thereby updating the (local) tracking branch origin/latest. If so, the tracking branch should still look the same as before the rebase.

    If you didn't push your local branch after making the commits, then the reflog may still be able to help you. Type git reflog. Then, find the commit which was the HEAD of your branch before the botched rebase. You may use the commit message to help you there. Once you have the SHA-1 of that commit, again do a hard reset:

    # from latest
    git reset --hard <SHA-1 of your old HEAD>