How to recover LOST WORK resulting from the use of git?

atlassian-sourcetree, git, git-commit

Solution

If the file has been staged (it looks like yours was), a snapshot will exist is Git's database. We can get it back!

Git stores snapshots internally in the `.git/objects/` direction in your repository. Each object is stored in a file named for its hash, split into directories by the first 2 characters. Snapshots will exist here until they are either packed into files in `.git/objects/pack/` (which won't happen to a snapshot that was never part of a commit) or garbage collected (which will eventually happen to your missing file). The hard part will be figuring out which object it is.

To find the object, run

ls -lRt .git/objects

to get a list of all objects sorted by last modified time. Here's what my hypothetical repository looks like:

$ ls -lRt .git/objects

.git/objects/22:
total 4
-r--r--r-- 1 peter peter 17 Sep  1 11:18 3b7836fb19fdf64ba2d3cd6173c6a283141f78

.git/objects/f7:
total 4
-r--r--r-- 1 peter peter 17 Sep  1 11:09 0f10e4db19068f79bc43844b49f3eece45c4e8

.git/objects/54:
total 4
-r--r--r-- 1 peter peter 51 Sep  1 11:08 3b9bebdc6bd5c4b22136034a95dd097a57d3dd

.git/objects/e8:
total 4
-r--r--r-- 1 peter peter 134 Sep  1 11:08 e8417380c89509ec1e5b67c15469547a4489c2

.git/objects/e6:
total 4
-r--r--r-- 1 peter peter 15 Sep  1 11:08 9de29bb2d1d6434b8b29ae775ad8c2e48c5391

Run

git cat-file -p <hash>

on candidate objects until you find the one you're missing. Remember to add the 2 characters from the directory name to the hash. In my case, if I'm interested in the file from 11:09

git cat-file -p f70f10

Happy hunting.

Problem

I'm using SourceTree and what happened is that I clicked on "Commit", then added all changed files, but before committing I wanted to remove one of the files in order to commit it later. I right-clicked on my file and was offered the following choices: - Remove - Discard - Stop Tracking - Unstage from index I was really confused by those choices, I clicked "Discard" and now all the work done in this file was lost!!! PANIC MODE! How can I recover my changes in this file? Thank you!

Original source