Thursday, 27 December 2018

GIT: Recovering lost commits

32.1. Detached HEAD

If you checkout a commit or a tag, you are in the so-called detached HEAD mode. If you commit changes in this mode, you have no branch which points to this commit. After you checkout a branch you cannot see the commit you did in detached head mode in the git log command.
To find such commits you can use the git reflog command.

32.2. git reflog

Reflog is a mechanism to record the movements of the HEAD and the branches references.
The reflog command gives a history of the complete changes of the HEAD reference.
git reflog
# <output>
# ... snip ...
1f1a73a HEAD@{2}: commit: More chaanges - typo in the commit message
45ca204 HEAD@{3}: commit: These are new changes
cf616d4 HEAD@{4}: commit (initial): Initial commit
The git reflog command also list commits which you have removed.
There are multiple reflogs: one per branch and one for HEAD. For branches use the git reflog [branch] command and for HEAD use the git reflog or the git reflog HEAD command.

32.3. Example

The following example shows how you can use git reflog to reset the current local branch to a commit which isn’t reachable from the current branch anymore.
# assume the  ID for the second commit is
# 45ca2045be3aeda054c5418ec3c4ce63b5f269f7

# resets the head for your tree to the second commit
git reset --hard 45ca2045be3aeda054c5418ec3c4ce63b5f269f7

# see the log
git log

# output shows the history until the 45ca2045be commit

# see all the history including the deletion
git reflog

# <output>
cf616d4 HEAD@{1}: reset: moving to 45ca2045be3aeda054c5418ec3c4ce63b5f269f7
# ... snip ...
1f1a73a HEAD@{2}: commit: More chaanges - typo in the commit message
45ca204 HEAD@{3}: commit: These are new changes
cf616d4 HEAD@{4}: commit (initial): Initial commit

git reset --hard 1f1a73a

0 comments:

Post a Comment