Oh, s#$t I deleted all my Git history!
Have you ever been in this situation and thought that all your hard work is gone?
If the answer to that question is yes, I feel you as I was in that same situation recently. But failing is learning and now I have the trick to get back to where you were and hopefully end a headache.
What did I do?
While trying to fix some conflicts after pulling from main I used — force/-f when pushing to my remote, which overwrote all my history with main and I ended up losing all the work I’ve been doing for the past two months.
If you are not sure what this command does (as I was), here is the definition:
The — force option for git push allows you to override this rule: the commit history on the remote will be forcefully overwritten with your own local history. This is a rather dangerous process, because it’s very easy to overwrite (and thereby lose) commits from your colleagues.
TLDR: if you see yourself in a situation where you have to use it, just stop and rethink your approach!
How did I recover all my commits?
Doing some research trying to fix my problem I found out about Reflog, which keeps track and shows all the changes you made on HEAD. But also it allows you to time travel to a previous commit where you know everything was working.
Here are the steps I follow to solve my problem and go back to a commit with all my previous changes:
git reflog
# you will see a list of every thing you've
# done in git, each one has an index and a commit number
# find the one before everything was broken
git reset commit number
git push to my branch
You may need it in different scenarios:
- If you want to restore the project’s history as it was at that moment in time use
git reset --hard <SHA>
- To recreate one or more files in your working directory as they were at that moment in time, without altering history use
git checkout <SHA> -- <filename>
Conclusion
Reflog is an excellent way of recovering all your history so you won’t be afraid to play around and make different changes. There might be some cases where the best approach is using — force, but make sure there’s no other option before using it!
Thanks for reading! if you have any questions feel free to drop me a message on LinkedIn or send me an email.
Have a wonderful day free of git problems!