Recently I was working on a codebase that had a lot of branches. Some of them had been committed to the remote github repository, others were just local. Some were current, some were stale. After looking at the madness I decided to “clean-up” some of the branches and get rid of the older ones.
In addition to the excessive amount of branches, some of them were poorly named, which led me to delete one of the branches I actually needed. This branch happened to also be committed to the remote git repository, but I also deleted it from there thinking it was something it was not! Had I not deleted the remote branch, I would have been able to just check it out again from remote. Since I couldn’t do that I had to resort to other means: git reflog!
git reflog to the rescue!
git reflog can show a history of commits, branch changes, and other information. Running it from your development directory produces output like this:
The information is displayed in reverse chronological order, so your newest changes are listed at the top. What’s cool about this is that you can read through the history, decide which commit you need to go back to, and create a new branch from it. The command to recover code is:
1 |
git checkout -b <deleted-branch-name> <sha1> |
For example, let’s say I accidentally deleted the branch “frank/super-important-branch”. Based on the screenshot above, I can see that I first created the branch (HEAD@(4)), committed some code (HEAD@(3)), then switched back to master (HEAD@(2)). Based on this, I would want to recover what was in HEAD@(3), which has a SHA1 value of a32bcb8. I could then issue the following command:
1 |
git checkout -b frank/super-important-branch a32bcb8 |
This will make a “new” branch, called “frank/super-important-branch” which should contain all of the code that was last committed. If you picked the wrong one, simply run the command again which a new branch name, or delete the wrong branch and just run the command again with a different SHA1 value (just be careful what you delete, since that’s what got us here in the first place!).
Please note that this command only works on local repositories. So, if you deleted this code locally, and then somehow lost the computer, and also didn’t commit it remotely (or deleted it remotely) you’ll be out of luck.
I hope this helps!