简体   繁体   中英

Undo 'git reset --hard' before first commit

Basically I had a codebase on my local machine, I ran:

git init

git add .

At this point, I realized I wanted to add a .gitignore file.

So I thought I needed to unstage commits, and in an amateur move, executed the following command

git reset --hard 

Now my entire code base is gone...

Is it possible to undo this??

git add. has added the content of your files into git; unfortunately, it hasn't created a 'directory' structure which lists your files with their names .

What you can do:

run

git fsck --full --unreachable --no-reflog | grep blob > blobs.txt

# the content of blobs.txt will look like :
unreachable blob 08bf360988858a012dab3af4e0b0ea5f370a2ae8
unreachable blob 21bf7ea93f9f9cc2b3ecbed0e5ed4fa45c75eb89
unreachable blob 08c12ef37075732cf4645269ab5687ba6ba68943
...

For each of these blobs, you can dump the content to disk:

cat blobs.txt | awk '{ print $3 }' | while read blobid; do
    git show $blobid > $blobid.txt
done

You will now have a list of files:

08bf360988858a012dab3af4e0b0ea5f370a2ae8.txt
21bf7ea93f9f9cc2b3ecbed0e5ed4fa45c75eb89.txt
08c12ef37075732cf4645269ab5687ba6ba68943.txt
...

The good news is: all the files that were present in the initial git add. should be represented in there.

The bad news is:

  • this list will also contain the files you wanted to ignore initially (I assume you added your node_modules/ folder, so you would have the code for all the js libs you added...),
  • you will have to figure out what files went where, and rename them to src/my_controller.js , src/model/my_model.js ...

One first filter you could apply, to try to take the node_modules/ files away is:

  • in the list of blobs above, try to find your package.json file ( grep -e some_package_I_remember ),
  • rename it to package.json (you may also find the lockfile), and run npm install or yarn install
  • this should create a node_modules/ folder, which looks a lot like the previous one you had
  • add that node_modules/ folder, and create a commit,
  • now, the blobs in node_modules are no longer unreachable; re-run the git fsck... > blobs.txt above, you should have a list of what wasn't under node_modules ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM