Chester Lim
Chester Lim

Reputation: 519

Recover delete files in git after removing .git folder

I am trying to push to a repository from an existing directory so I added all the files using

git add -A

but then i realized that i should not add the node modules folder, so i did a

git reset --hard

then I decided to add folders one by one and halfway through, i realized that i should have made the .gitignore file first so i decided to remove all the git relationships in my folder using

rm -rf .git

after i re-initialized the current folder using

git init

too many files are missing from the current directory. I don't have any backup of the project. Any idea on how i can recover the files?

Upvotes: 0

Views: 1231

Answers (1)

Mark Adelsberger
Mark Adelsberger

Reputation: 45819

If you have no backups, and either your OS doesn't do "soft deletes" (trash can, recycle bin, whatever) or you deleted in a way that bypasses them, then there is no reliable way to recover the work.

The .git directory contains everything git knows about your files, other than untracked files or changes in the working tree. Removing .git/ is almost never necessary and very dangerous, as this question unfortunately illustrates. Other commands you used are also more aggressive/dangerous than what you needed, and the odds are you lost the working files pretty early in the process. Sorry the news isn't better.

For future reference:

It is likely that the reset --hard is what deleted your working files. You had done some adds and wanted to revert them, so a mixed reset (which is the default) would have been sufficient and would have left your working tree alone. A hard reset restores your working tree to the committed state (along with the index).

After the reset you started doing adds again. I guess when you had to start over a second time, you were worried that you might have git accumulating unwanted state. It wasn't. Another mixed reset would have been fine. You can always use git status to make sure the index doesn't contain anything unexpected (and clear it out if so).

The only enduring record is what's in the database, and since you hadn't committed anything you weren't affecting the database yet. Even if you had committed things you wanted to discard, as long as those things hadn't been shared with others there would be procedures for getting rid of them.

Generally git is very good at safeguarding your data, but it can't protect what you haven't committed; so asking it to use commands that are destructive toward the work tree, or nuking the repository and metadata (by deleting .git/) should only be done if you're very sure of why you're doing them.

Upvotes: 2

Related Questions