git deleted everything, how to recover files and folders

Since you've able to run git cat-file -p on the dangling tree object, you should be able to recover it. There are many ways about it, I shall describe 2 that I can quickly think of:

  • Create a new commit to bring-in the files in the dangling tree. This commit will have no parent.

    echo "A commit to recover the dangling tree." | git commit-tree bfe11a30d57a0233d3b0c840a3b66f6421987304
    
    # Output:
    <SOME_NEWLY_CREATED_COMMIT_SHA1>
    

    The new commit should contain the work-tree of the dangling tree that you just found out. The output of the above command should show the new commit SHA1 which was created.

    To switch your current work-tree to this commit:

    git checkout <SOME_NEWLY_CREATED_COMMIT_SHA1>
    

    Now you should be able to see all the files and the contents that were listed in the dangling tree commit. You can browse around, make a backup of the files, do whatever you want ;)

  • Alternative approach:

    If you would like to just get the changes on top of your current commit, this approach might be useful.

    Read the contents of the tree into git's index (i.e. into the staging area for this case).

    git read-tree bfe11a30d57a0233d3b0c840a3b66f6421987304
    

    Now commit the changes in the staging area on top of the currently checked out branch:

    git commit -m "Recover the lost files."
    

And for the future:

  • Always commit your changes, it is much easier to get to them (using reflogs) even if the commit gets dangling in the future. When in doubt go ahead with a git commit, you can always ammend the commit, make changes, rewrite history, etc. Especially before running commands like git pull or git push, you should be committing your changes so that they do not get lost.

  • Do not run git init twice on a repository, although git is smart enough to know that the repo has already been initialized and tries NOT to overwrite your changes.


As you already have a reference to a dangling tree object, you're well on your way. The following should work: first recover the dangling tree into Git's index:

git read-tree bfe11a30d57a0233d3b0c840a3b66f6421987304

Next, update your working directory from the now-recovered index:

git checkout-index -a