Some time ago, I had deleted a file in git along with renaming the directory it was in. I had wanted to rename the file rather than delete it. So now I needed it back. This took a few steps so I decided to blog what I did.
Step 1 – find the command to get the commit number for my deletion
I had no idea how to do this so I googled it. A comment on this post was really helpful. On OSX, I ran:
git log --diff-filter=D --summary | sed -n -e '/^commit/h' -e '\:/:{' -e G -e 's/\ncommit \(.*\)/ /gp' -e }
While I understand this, I never would have thought to write it.
This gave me a list of all my commits. Then I added | grep myFileName to it and I got the commit where this file was deleted.
Step 2 – Look at commit details
Next I did a git show to see whether it was me or my teammate that
git show myCommitId
It was me. I didn’t know that at the start. Oops!
Step 3 – Retrieve the file
It is possible to do a git checkout of just one file. However the folder structure doesn’t exist anymore in the latest, so this would be a pain. I decided to just get the file from the github UI. I ran the following (with real values for myRepo and myCommitId).
https://github.com/boyarsky/myRepo/commit/myCommitId
Then I viewed and downloaded it. Yay. My image file is back.
Step 4 – Commit again
I renamed the file again and added/committed normally.
Done! It’s now like this mistake never happened. Except in git history!