How to recover `.git/index` locally?
Asked Answered
U

3

47

I accidentally deleted .git/index, is there a way to recover it? It's permanently deleted. I haven't committed anything yet.

Uninspired answered 8/7, 2016 at 20:26 Comment(3)
so its a clean repository - just delete the whole directory and create a new repo?Ardenia
Had you added anything to the index yet? Were there particular versions of files that you wanted to recover that were staged but different from the copy that is now on the working tree?Capillary
thumbs up if you're here after trying to rm .git/index.lock :vGnosis
M
66

To rebuild the index file, you can try these two commands:

git reset         # re-scan the working directory
git add -u        # update the index
Maudiemaudlin answered 9/7, 2016 at 1:48 Comment(0)
P
7

You can recover the index as of the last checkout with git reset. Any content you had added since then is still added, it's in the repository, but the index was the only place that recorded the association of path and content. You can have git fsck drop unreachable objects into a lost'n'found directory, see its docs, then the quickest route over familiar territory is to just drop the content back in the worktree and add it again, git won't duplicate contents but it will recover the index entry.

Paleozoic answered 9/7, 2016 at 1:44 Comment(0)
B
6

I don't think that's possible, not via git anyway (you can try looking inside your Trash directory or whatever means of recovery your filesystem offers). You'll get a new index, though, as soon as you git add something or do something else that requires the index.

If you've lost any of the files that you've git added, you can go through ./git/objects (find .git/objects/ -type f |sed 's:\.git/objects/::; s:/::' ) , inspect the contents of each with git cat-file -p $the_hash, and once you've found the lost one, redirect the output to a file.

(When you git add, a filename entry goes to .git/index and the file contents get stored in .git/objects/. Git index is made of the file name entries of a would-be tree object that gets created when you commit. You can view a human-readable representation of the index with git ls-files --stage).

Brune answered 8/7, 2016 at 20:39 Comment(2)
The index has a bit more stuff in it, but yes, it's basically a cache of name-and-hash-es. For some completeness, it's worth mentioning that the index has four possible "slots" per name: slots 1-3 are used only during a conflicted merge, and slot zero is where the normal, next-commit-to-make entry goes.Garris
This saved me quite a bit of time. I'd staged some files and realized the repo was in the middle of a cherry-pick, doing a git cherry-pick --abort wiped out the index! I used your find | sed command to restore the index. Thanks!Sealer

© 2022 - 2024 — McMap. All rights reserved.