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
If you just need to reset to what the tip of the current branch was before you fucked up you can run git reset --hard HEAD@{1}
Comment by glandium

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.

Comment by Jan Hudec
git gc is not so dangerous! The newer versions will even let be unreferenced loose objects newer than 2_weeks, to be on the safe side.. which means that you have a lot of time to recover your suff.
Comment by ulrik