Say you just deleted a branch or did a git reset --hard <earlier commit>
and in the process lost a commit which you intended to keep.
Well, the good news is that unless you have run git gc
to run a pass of garbage collection over your repo and get rid of objects which aren't linked to anymore, the objects for your lost commits should still be in the repo.
If you remember the SHA-1 IDs then you can simply use git cherry-pick
to apply them to the current branch. However, if you don't have these commit IDs anymore, there is still a way to get to them.
This command will display all commits from the most recent to the oldest one:
git log -g
This feature is brough to you by the reflog. Git gc will trucate the reflog to 90 days by default (can be changed or turned off) and commits referenced by reflog will not be pruned until the reflog itself is truncated.
Note, that the reflog keeps complete history of the ref, so this way you can ask what state your branch was before a pull, rebase, n days ago etc.