So, I did something very stupid: i started a project, did quite a lot of work on it, and then I initialized a git repo. I ran git add
to add all of the project files, but i wanted to exclude one file, so I quickly ran git reset --hard
before making an initial commit.
Now all the files have disappeared from the repo and I have no clue how to restore them, so any help will be appreciated!
CodePudding user response:
If you've run git add
, the blobs have been added to the repository and are stored there, even though they've been deleted from the working tree. You can find all of these blobs by running git fsck --dangling
, like so:
$ git fsck --dangling
Checking object directories: 100% (256/256), done.
notice: HEAD points to an unborn branch (dev)
notice: No default references
dangling blob 257cc5642cb1a054f08cc83f2d943e56fd3ebe99
missing tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904
Then, you can take each of the dangling blobs and inspect them:
$ git cat-file blob 257cc5642cb1a054f08cc83f2d943e56fd3ebe99
foo
Once you know where the file is supposed to be, you can redirect the output of that command to an appropriate file. Do that with all the dangling blobs, and you can recover your working tree.
For future reference, git reset --hard
completely blows away the contents of your working tree, removing all changes. If you've added a file for the first time and decide later that you'd rather not have, you can simply run git rm --cached FILE
to unstage it. Note that by default, git status
provides this hint for you to help you out.