Git corrupted repo: how to pick a git object from a clean repository
Asked Answered
S

1

8

This is one of the numerous questions regarding a Git repo that is corrupted, precisely a loose object that went wrong:

$ git gc
Counting objects: 3299, done.
error: inflate: data stream error (unknown compression method)
error: unable to unpack 831a5d31af4a0af2f5a367689bee27a44efc22c9 header
Delta compression using up to 6 threads.
Compressing objects: 100% (3283/3283), done.
error: inflate: data stream error (unknown compression method)
fatal: loose object 831a5d31af4a0af2f5a367689bee27a44efc22c9 (stored in .git/objects/83/1a5d31af4a0af2f5a367689bee27a44efc22c9) is corrupt
error: failed to run repack

Following existing answers on the subject (How do I deal with corrupted git object files?, How to fix corrupted git repository?, or What can I do with Git corruption due to a missing object?) I already removed the object 831a5d31 from the corrupted repository.

In my case I have a clone of the repository, that seems to hold the object I'm missing, but there's no file at objects/83/1a5d31af4a0af2f5a367689bee27a44efc22c9. How can I do to fix my repository?

Selfdenial answered 27/8, 2014 at 12:57 Comment(0)
S
11

If the file exists elsewhere

The object of the clean repository has been repacked, that's why it doesn't exist anymore as a file.

To restore it, first save it as a file, from the clean repository, with

git show 831a5d31af4a0af2f5a367689bee27a44efc22c9 > 831a5-file

Move 831a5-file in the corrupted repo, and run

git hash-object -w 831a5-file

Make sure that the SHA1 given in the output is 831a5d31af4a0af2f5a367689bee27a44efc22c9

This will store the object, and the repository is fixed!

If the file does not exist elsewhere

If the file doesn't exist elsewhere, i.e. the corruption occurred after commit but before you were able to push, there is a way to restore your repo and and re-commit the changes. See this answer to a related question.

Selfdenial answered 27/8, 2014 at 12:57 Comment(4)
This works for blob objects; is there a way to import/export tree objects?Miscreated
To answer my own question, to do this for tree etc objects: git cat-file tree <hash> > temp git hash-object -t tree -w tempMiscreated
Thanks, you saved my repo! Note that if your clean repo is from a different OS, the SHA1 may not match if line endings aren't the same across OSes. The solution still worked, though.Ineffectual
This didn't work for me but copying over the missing object files as specified by git fsck didGoodrich

© 2022 - 2024 — McMap. All rights reserved.