2

I recently wanted to, as I thought, update my code on the remote git repository. I didn't realize it's not even committed yet. I did create some errors, so I wanted to reset the branch to its previous state.

As you may expect, I used git reset --hard.

Well, everything (the whole project) has been gone ever since; except the .gitignore files/folders, of course. I've been wondering, is there any way to undo that?

The only steps I did:

git add .
# Here I realized there is a bug in what I did
# I thought myself it would be better to undo that as it wasn't even something needed
git reset --hard 

Also, I'd like to point out it's probably not a duplicate of any question here as others have had some commits before. That's completely new repository, and it's been "reset hard".

Melebius
  • 6,183
  • 4
  • 39
  • 52
Dawid Zbiński
  • 5,521
  • 8
  • 43
  • 70
  • Usually, things that you (.git)ignore are generated and you would `git clean -X` and then generate them. Your use can might be different. Besides that, since you are telling git to ignore those files, git does not track them in any way, hence git does not know of any versions in those ignored files. – LinFelix Jan 30 '18 at 10:12
  • What does `git reflog` tells you? Actually if you haven't commited anything yet you shoudlnt be able to reset. if it worked you actually lost everything. – ckruczek Jan 30 '18 at 12:04
  • @ckruczek yeah I thought the same thing, but well, the opposite was true. Rudi was able to write down the great answer (I guess). It surely recovered something, but I'm not able to read it as the encoding is horrible and I have no idea which one is it. If I will be able to read them somehow, I'll let you know. – Dawid Zbiński Jan 30 '18 at 14:10
  • I realized that I accidentally opened an image, which explain the weird encoding. So @Rudi is right and helped so much. Upvotes for him. – Dawid Zbiński Jan 30 '18 at 15:05

1 Answers1

2

You can resurrect the files at the state you added them, but without their file name. With git fsck you get a list of files which are not referenced by any commit.

$ git fsck
Checking object directories: 100% (256/256), done.
Checking objects: 100% (1/1), done.
dangling blob c7c49b553f1b8c3c8f7955780e5dfdb934ce26db
dangling tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904
dangling blob 4f92ab465171608a2c713f2f5439143df2c8afc9
dangling blob 9c1216eb500c0fc2c55c263a9cf221f282c3cd7b

Then you can use git cat-file to get the file content:

for blob in `git fsck | grep 'dangling blob' | cut -d\  -f3` ; do git cat-file -p $blob > $blob ; done

Or you can also use git fsck --lost-found, which puts all dangling objects into .git/lost-found/

Rudi
  • 19,366
  • 3
  • 55
  • 77