Jason Connery

no time.

Recovering Old Files in Git

We had a relatively minor problem this week in work. Previously, we replaced an image with a newer version with different dimensions, assuming the old one was no longer needed. a few days (and git commits) later we realised that we could actually use both versions of the image.

Now, not a hard problem to solve. We probably had an old copy lying around in email from our designer. We could just as easily check out an old commit from the repo, copy the file to a tmp location, go back to HEAD commit copy in the file from the temp location. Any many more ways.

but I wanted to avoid the reliance on temporary files, emails, etc. Surely there was someway to easily get back the file we overwrote? Some git magic? A bit of googling revealed an answer.

First. Find when we altered the image.

git log -p some-image.png

This gives us the logs relating to that file. From this, we get our commit where the image was changed. In my case 656d674d3a7a568bac7cd0fc8cf45172da50ddee

Sweet. now we can use git’s cat-file option to get the contents at the revision.

git cat-file blob REVHASH:path/to/file.png > newfile.png

So in our case (watch out for the ~1 in the commit hash):

git cat-file blob 656d674d3a7a568bac7cd0fc8cf45172da50ddee~1:some-image.png > alt-image.png

And now we have the old image in the file alt-image! straight from git history into our working copy. Don’t forget to commit.

Notice the ~1 after the revision hash. This is a handy shortcut to the revision before the one from the log. We don’t actually want the image from the commit where it changed, but rather we want the way it was before. So ~1 gives us the previous commit.

And that’s how we restored an old git file into a new file!