Thursday, April 18, 2013

Nerd Food: Restoring a file from Git history

Nerd Food: Restoring a file from Git history

A common problem I've had with git in the past is how to restore a file from history. As it turns out, like with many things in git, it is quite easy once you know what you're looking for.

First we need to locate the file. For this we look at all paths affected by the commits we have done over time, so git log is a perfect suitor:

$ git log --all --name-only --pretty=format: | grep -i ecore
diagrams/other/Ecore.dia
diagrams/Ecore.dia
diagrams/other/Ecore.dia
diagrams/Ecore.dia
doc/diagrams/Ecore.dia
doc/diagrams/Ecore.dia

As I'm not really bothered as to which commit did what to this file, I just picked one of these paths. You may need to look into history and try to figure out which version is the one you're after. Now we need to figure out the SHA key:

$ git log -- diagrams/Ecore.dia | grep commit
commit f2d763df8b3775a9370ed43e00e3c28a07190932
commit a183879d848f32cd0f8b14c3b4b707f2b4946ca5

I'm sure you could do both of these steps in one go, but I'm too lazy to find out how. Finally, just checkout the blob from the object database:

$ git checkout a183879d848f32cd0f8b14c3b4b707f2b4946ca5 -- diagrams/Ecore.dia
$ head diagrams/Ecore.dia
<?xml version="1.0" encoding="UTF-8"?>
<dia:diagram xmlns:dia="http://www.lysator.liu.se/~alla/dia/">
  <dia:diagramdata>
    <dia:attribute name="background">
      <dia:color val="#ffffff"/>
    </dia:attribute>
    <dia:attribute name="pagebreak">
      <dia:color val="#000099"/>
    </dia:attribute>
    <dia:attribute name="paper">

It's that easy!

Date: 2013-04-18 23:51:11 BST

Org version 7.8.02 with Emacs version 23

Validate XHTML 1.0

No comments: