Let’s imagine you were working on your project, and you typed
git reset --hard HEAD~N
Then you tapped Enter ↩️ by mistake, maybe..
Basically this means, that you lost the last N commits, and right now you have a clean working tree.
Don’t be afraid, there is a solution for this situation.
The reflog is strictly local and isn’t part of the repository. It’s also not included in pushes, fetches, or clones. Git uses the git reflog tool to keep track of changes made to branch tips. It lets you go back to any commit, even if it isn’t referenced by any branch or tag
You can read more about reflogs in Gitprotect
To restore a lost commit, use
git reflog to see your local changes :
Here basically you can see the local logged actions by Git
Then, you can pick the SHA of the commit you want to go back to, and then run
git reset --hard e4dd6f6
git cherry-pick e4dd6f6
Don’t forget that you could use
git reflog to search by a commit message or a branch name… 😉
Reflogs or reference logs are stored only on your machine, this means you cannot push or pull them from a remote repository.
And more importantly, they get expired after a while by git-gc (git garbage collector).
The entries that have been expired are dropped, and the expiration time is taken from the configuration setting
gc.reflogExpire (90 days by default)
You can read more about this here