Recover Deleted Files with Git

I started a new project and made my first commit, but accidentally added a file which hadn’t been finished yet. No worries, according to this site it is easy to undo commit:

$ git commit -m 'initial commit'
$ git add forgotten_file
$ git commit --amend

I was still sleepy so I just changed the add to rm and committed my changes again. In retrospect, this was a bad idea, because my file was gone. I remembered that git keeps every single commit even after git reset until a git gc is performed. So my original commit - the one before the git commit –amend - must be there somewhere. The commits after git reset become dangling commits and one way to find them is to use git fsck –no-reflog:

~/Code/java/arithmetic.expression.evaluator % git fsck --no-reflog
dangling commit 13599c5f2d3f862f9bfd33fcfead61d31ee7ea7e
~/Code/java/arithmetic.expression.evaluator %

Huh, it is there. I’m looking for the build.xml:

~/Code/java/arithmetic.expression.evaluator % git show --name-only
    13599c5f2d3f862f9bfd33fcfead61d31ee7ea7e | grep '^build.xml$'
build.xml
~/Code/java/arithmetic.expression.evaluator %

Excellent, let’s get it with git checkout:

~/Code/java/arithmetic.expression.evaluator % git checkout
  13599c5f2d3f862f9bfd33fcfead61d31ee7ea7e build.xml
~/Code/java/arithmetic.expression.evaluator %

Does it work?

~/Code/java/arithmetic.expression.evaluator % ant crap4j findbugs pmd
Buildfile: /Users/zsolt/Code/java/arithmetic.expression.evaluator/build.xml
...
BUILD SUCCESSFUL
Total time: 12 seconds
~/Code/java/arithmetic.expression.evaluator %

Yes, it does. I feel that this time I was lucky. So, no more git rm, git commit –amend or git reset for me without thinking through what is going to happen.


comments powered by Disqus