Tuesday, April 20, 2010

Recover a deleted branch from a Git repository

So I thought I would quickly note this since I managed to reach into a Git repo and pull out code that I thought I had foolishly deleted. I was in a rush during a release two weeks ago and in a fit to clean up the repo I was working in trashed a feature branch for code I was working on.

My colleague Evan said there was a way to grab the branch since it's still in the .git objects (since I had not done a ``git-gc``). But the method for that was left as an exercise for me, the reader.

I used the command suggested by Iamamac on Stack Overflow.

So here's what I did:

$> git fsck --full --no-reflogs | grep commit

This finds the "dangling commits" in the repository. Again, the commit for the HEAD of the branch is still there - but it's just not listed as a ref/head. This will get you a list like so:

dangling commit 0c91cb293..
dangling commit 1896a7b7f..
dangling commit ec9ac3cd..
dangling commit 5c6a8f1af..
dangling commit fd729386..

Then just use ``git-log`` w/ some extra verbosity to find the HEAD commit you're looking for:

$> git log --stat 5c6a8f1af

Which gives you output like:

commit 5c6a8f1af
Author: lenards
Date: Wed Mar 24 08:56:20 2010 -0700

Test new version of gwtupload

pom.xml | 2 +-
1 files changed, 1 insertions(+), 1 deletions(-)

I hope that helps someone out...

(and thanks to Scott Chacon and everyone in the Git community for sharing tutorials, advice, and wisdom)