Undo-ing ‘git reset hard’
Chances are, you’re here because like me, you ran git reset --hard HEAD on your last hour or two’s worth of work. If you’re lucky then hopefully you ran git add . or added your files to the staging area. Providing a git clean (git gc) hasn’t been run, there may be light at the end of the tunnel!
$> git add .
Lots of lovely work added to your commit – then you decide, for whatever reason, to not commit. In my case probably down to lack of coffee or that I suddenly decided to slip back to the SVN way of things ; ).
$> git pull origin master
From this pull I got merge problems (obviously due to the lack of a commit). Then cleverly I decided to run:
$> git reset --hard HEAD
Oops! Panic – I’ve just reset my last two hours’ worth of development!
Consider any object recorded in the index also as a head node for an unreachability trace.
Do not consider commits that are referenced only by an entry in a reflog to be reachable. This option is meant only to search for commits that used to be in a ref, but now aren’t, but are still in that corresponding reflog.
Write dangling objects into .git/lost-found/commit/ or .git/lost-found/other/, depending on type. If the object is a blob, the contents are written into the file, rather than its object name.
$> git fsck –cache –no-reflogs –lost-found
Checking object directories: 100% (256/256), done. Checking objects: 100% (571/571), done. dangling tree 9f43ffdc200878fefaab63b7c15c58f1da73ba5d dangling blob 837052b45a69934c822e832d5d01f81bb7cde437 dangling blob b1d0f0ceb214ba28f16826103d2a85ed6f90838b dangling blob da70731ebc23a477994cf65dd51f951b5546cedd dangling blob 09312824523012ba5ea0aab54093eb8df567ffc4 dangling tree 25f11f2af6addf4e6c4004481b34f5017cbc052e dangling blob cc3a137f831e26e091265cdce3c6f7d224cf8961
$> ls -l .git/lost-found/other/
-rw-r--r-- 1 alex alex 2230 Feb 4 13:44 09312824523012ba5ea0aab54093eb8df567ffc4 -rw-r--r-- 1 alex alex 41 Feb 4 13:44 25f11f2af6addf4e6c4004481b34f5017cbc052e -rw-r--r-- 1 alex alex 1714 Feb 4 13:44 837052b45a69934c822e832d5d01f81bb7cde437 -rw-r--r-- 1 alex alex 41 Feb 4 13:44 9f43ffdc200878fefaab63b7c15c58f1da73ba5d -rw-r--r-- 1 alex alex 17281 Feb 4 13:44 b1d0f0ceb214ba28f16826103d2a85ed6f90838b -rw-r--r-- 1 alex alex 20586 Feb 4 13:44 cc3a137f831e26e091265cdce3c6f7d224cf8961 -rw-r--r-- 1 alex alex 20855 Feb 4 13:44 da70731ebc23a477994cf65dd51f951b5546cedd
Now you should have reasonable success in identifying which file is which and you can diff them to check that these are indeed your changes.
Good luck! And don’t do it again.