Posts tagged ‘oops’

11 March, 2011

git: recovering from an “accidental” branch deletion

by gorthx

I’ve been experimenting more lately with git’s branching and merging capabilities. The first time I ‘git merge [branchname]’ I was a bit flustered – was it really that easy? Yes it was.

Of course, once I get confident (to use a biking analogy), I take my hands off the brakes & make some real fun mistakes while I learn to handle the higher speed.

I’m sort of a neatnik – I like to clean up old files & such (always re-discovering the inverse relationship between how long [in days] something’s been sitting around unused before I delete it and how long [in seconds] it takes someone to ask me for it afterward), so I decided to delete a branch I’d been working on that I no longer needed. I *thought* I no longer needed it.

(master) :::-->git branch -d nme_fix
error: The branch 'nme_fix' is not fully merged.
If you are sure you want to delete it, run 'git branch -D nme_fix'.

Of course I’m sure I want to delete it!

(master) :::-->git branch -D nme_fix
Deleted branch nme_fix (was ee6cb9e).

Then I go and look at my code. Ohhhh fuuuuuuuudge.

With git, it’s not gone forever. Let’s go about recovering that deleted branch.

(master) :::-->git fsck --full --no-reflogs
dangling commit 20b606fe6e3ee48d284926d8f0fe0188060eef12
dangling blob 3e22e83e45e457b716bd0d5f1cdebf3605eceb02
dangling commit ed0475437d820a0bdf86e2b729db9a3d575ff58c
dangling commit ee6cb9e81f8a8667b05427272c06db5603a67dce
dangling blob 06ff7028cb9c9e0bc93041f7931651a958e23f6d

… long list of items. Looks like I need to run `git prune` … but let’s do that *after* I recover my stuff, eh?

(master) :::-->git show ee6cb9e

This shows me the diff from that commit. (Which I piped into a file; if I am unable to easily recover my work, I can just make a few quick edits to that file & apply it as a patch.) Since I happened to have the commitid handy from the earlier confirmation message, this was just for verification. If I didn’t have it, I’d run ‘git show [commitid]’ on all of them until I found the one I wanted.

Then, git cherry-pick [commitid] to pull the changes I’d made back in:

(master) :::-->git cherry-pick ee6cb9e

Et voila, all that hard work is back.



Note the cool git prompt. I highly recommend this to everyone who’s using git. Here’s a link for a simple way to do this.

Tags: , ,