2
votes

I added a directory to a local git repo using git add and then accidentally did git rm -rf (without committing before). Is there some way of recovering the files from this directory?

2
Wrote you a full answer below.CodeWizard
It seems that You need to use some data recovery software if You deleted whole dir (including .git dir) - try to not place new files on dusk (especially in this dir) until You try to recover data. superuser.com/questions/279733/undo-an-rm-rf-commandbarat

2 Answers

10
votes

Yes you can,

Read this: How to undo changes in Git.


Once you add files to git they are started to be tracked and they are stored under the .git folder.

In they were just added and never commited they are refereed as dangling objects. Those object can be recovered.


Ho to restore dangling objects?

First we have to find them out

git fsck --full

enter image description here

Once you have the list of those object you need to view them and to find out which ones you need.

# Print out the content of the Object
git cat-file -p <SHA-1>

# If the object is a file you will simply see its content,
# Copy it and save it in a new file.

enter image description here

2
votes

Here is my recover.py utility, which will create a file for each hash:

enter code here


import subprocess
hashes=["01b6a7f272375bc99d98be0068c273b5bc4e9ff6",
"03620d7b53c8a48314c25a3ecdbe369553b01340","PUTYOUR HASHEZ HERE"]
for myhash in hashes:
    print "HASH", myhash
    bashCommand = "git cat-file -p "+ myhash
    process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
    output, error = process.communicate()
    file = open("recover/"+myhash, "w")
    file.write(output)
    file.close()

This will write to recover folder all files you killed with git