I had this git message after a forced VM shutdown, which obviously corrupted the git index
Git: Failed to read object abcdef.... Invalid argument
I looked at these existing answers
Restore a corrupted index
Recover damaged git by HD failure
None seemed to work.
Lets get into it and try to solve it. Use this approach only when git reflog
also won't work, because obviously your index is corrupted, and reflog cannot read from a broken index.
Open your .git/
folder
Look at the file called HEAD
.
This has the name of the branch your git is currently at.
Now look for a file called ORIG_HEAD
.
This probably
has the SHA of the last good commit that git was able to register. If it is, Voila!
Copy it (say X), in terminal do:
git show X > interim.patch
This copies your last successful changes into a standard diff.
Also copy this SHA (X) to HEAD
file's contents.
This tells git to consider this change as the current position, which it could live with, as it had registered it some time back.
By now if you do a git branch
, you would have moved to (no branch)
.
So now you have your changes. Do git checkout -f <branch-name>
This will overwrite your changes with the remote contents, but you still have them in that patch.
So by now, you are
Do a git apply interim.patch
which if goes through well, means you have your changes.
Then go ahead with normal git steps.
git add .
git commit -am 'Message'
And you are back to normal peaceful life.