How do you restore a corrupted object in a git repository (for newbies)?

Okay, so. We can see from the second error message that the corrupt object which you moved was a commit. (HEAD was pointing to it!) Unfortunately, this means that it’s hard to manually repair it. (By “hard” I mean likely impossible unless you can remember exactly what the commit message was and what time you made the commit.) Fortunately, this does mean that it’s easy to resurrect a new commit with the same file contents – you’ll just have to write a new message for it.

Before you start, have a look at the contents of .git/HEAD – if it’s a branch name, remember that for later.

First, we need to figure out what the parent of this commit should’ve been. You can use git reflog to look at the reflog of HEAD, and find the SHA1 of where HEAD was just before you made commit 016660b. It should look something like this:

016660b HEAD@{n}: commit: <subject of commit>
1234abc HEAD@{n-1}: ...

You can copy the SHA1 of the previous position of HEAD, and check out that commit:

git checkout 1234abc

Then you can read in the tree that your corrupted commit had:

git read-tree 2c1033501b82e301d47dbf53ba0a199003af25a8

And then commit!

git commit

Now, there’s some question here about what should’ve happened to your branches. If HEAD was pointing to a branch (say master) which in turn pointed to the corrupted commit, we definitely want to fix that up:

git branch -d master       # remove the original master branch
git checkout -b master     # recreate it here

If there are other branches which contained the corrupted commit, you’ll have to do some restoration on them too – let me know if you need help with that.

Leave a Comment