Меню

Git ошибка при построении деревьев

I did a git pull from a shared git repository, but something went really wrong, after I tried a git revert. Here is the situation now:

$ git stash
Source/MediaStorageAndFileFormat/gdcmImageCodec.cxx: needs merge
Source/MediaStorageAndFileFormat/gdcmJPEGLSCodec.cxx: needs merge
Source/MediaStorageAndFileFormat/gdcmPNMCodec.cxx: needs merge
Testing/Source/DataStructureAndEncodingDefinition/Cxx/TestDS.cxx: needs merge
Utilities/socketxx/socket++/sockstream.cpp: needs merge
Source/MediaStorageAndFileFormat/gdcmImageCodec.cxx: needs merge
Source/MediaStorageAndFileFormat/gdcmJPEGLSCodec.cxx: needs merge
Source/MediaStorageAndFileFormat/gdcmPNMCodec.cxx: needs merge
Testing/Source/DataStructureAndEncodingDefinition/Cxx/TestDS.cxx: needs merge
Utilities/socketxx/socket++/sockstream.cpp: needs merge
Source/MediaStorageAndFileFormat/gdcmImageCodec.cxx: unmerged (2aafac967c35fa4e77c3086b83a3c102939ad168)
Source/MediaStorageAndFileFormat/gdcmImageCodec.cxx: unmerged (78cc95e8bae85bf8345a7793676e878e83df167b)
Source/MediaStorageAndFileFormat/gdcmImageCodec.cxx: unmerged (2524db713fbde0d7ebd86bfe2afc4b4d7d48db33)
Source/MediaStorageAndFileFormat/gdcmJPEGLSCodec.cxx: unmerged (4bb4ba78973091eaa854b03c6ce24e8f4af9e7cc)
Source/MediaStorageAndFileFormat/gdcmJPEGLSCodec.cxx: unmerged (ad0982b8b8b4c4fef23e69bbb639ca6d0cd98dd8)
Source/MediaStorageAndFileFormat/gdcmJPEGLSCodec.cxx: unmerged (4868371b7218c6e007fb6c582ad4ab226167a80a)
Source/MediaStorageAndFileFormat/gdcmPNMCodec.cxx: unmerged (f7a1b386b5b13b8fa8b6a31ce1258d2d5e5b13c5)
Source/MediaStorageAndFileFormat/gdcmPNMCodec.cxx: unmerged (6ce299c416fbb3bb60e11ef1e54962ffd3449a4c)
Source/MediaStorageAndFileFormat/gdcmPNMCodec.cxx: unmerged (75c8043a60a56a1130a34cdbd91d130bc9343c1c)
Testing/Source/DataStructureAndEncodingDefinition/Cxx/TestDS.cxx: unmerged (79c2843f2649ea9c87fa57662dafd899a5fa39ee)
...
fatal: git-write-tree: error building trees
Cannot save the current index state

Is there a way to reset all that ?

Thanks

asked Mar 30, 2011 at 7:25

malat's user avatar

malatmalat

11.9k13 gold badges83 silver badges148 bronze badges

Use

git reset --mixed

instead of git reset --hard. You will not lose any changes.

Boris Verkhovskiy's user avatar

answered Apr 17, 2013 at 9:19

heracek's user avatar

heracekheracek

7,2513 gold badges14 silver badges10 bronze badges

6

This worked for me:

Do

$ git status

And check if you have Unmerged paths

# Unmerged paths:
#   (use "git reset HEAD <file>..." to unstage)
#   (use "git add <file>..." to mark resolution)
#
#   both modified:      app/assets/images/logo.png
#   both modified:      app/models/laundry.rb

Fix them with git add to each of them and try git stash again.

git add app/assets/images/logo.png

answered Mar 28, 2014 at 19:37

David Rz Ayala's user avatar

David Rz AyalaDavid Rz Ayala

2,1451 gold badge20 silver badges21 bronze badges

4

To follow up on malat’s response, you can avoid losing changes by creating a patch and reapply it at a later time.

git diff --no-prefix > patch.txt
patch -p0 < patch.txt

Store your patch outside the repository folder for safety.

answered Jul 3, 2012 at 19:14

afilina's user avatar

afilinaafilina

8051 gold badge11 silver badges24 bronze badges

2

I used:

 git reset --hard

I lost some changes, but this is ok.

answered Mar 30, 2011 at 10:31

malat's user avatar

malatmalat

11.9k13 gold badges83 silver badges148 bronze badges

2

maybe there are some unmerged paths in your git repository that you have to resolve before stashing.

Peter Oram's user avatar

Peter Oram

5,9732 gold badges27 silver badges40 bronze badges

answered Sep 15, 2011 at 6:23

npeters's user avatar

npetersnpeters

691 silver badge1 bronze badge

1

This happened to me when trying to merge another branch. The merge failed with fatal: git-write-tree: error building trees and complained about a different file that had nothing to do with the merge. My branch then contained the files it had tried to merge, as uncommitted changes.

I cleared the changes it had attempted to merge, then removed the problem file and rebuilt the hash:

git reset --hard;

git rm --cache problem_file.txt;

git hash-object -w problem_file.txt;

The merge then worked.

answered Mar 22, 2022 at 12:42

BadHorsie's user avatar

BadHorsieBadHorsie

13.9k30 gold badges112 silver badges186 bronze badges

This happened for me when I was trying to stash my changes, but then my changes had conflicts with my branch’s current state.

So I did git reset --mixed and then resolved the git conflict and stashed again.

answered Jul 16, 2019 at 18:06

mfaani's user avatar

mfaanimfaani

31.3k18 gold badges155 silver badges277 bronze badges

I have a local git repository on my Mac that is managed by Xcode. I recently created a new branch and have made a lot of changes since then. I was about to perform my first commit to this new branch and was presented with an error dialog:

The working copy «app name» failed to commit files.
error: invalid object 100644
888688965… for ‘Supporting Files/animage.png’
error: Error building trees

I searched the Interwebs for a solution and found this question which appears to be the same issue. I tried both answers to this question and neither solved the problem for me. I have done everything I can think of to solve the problem but have not been successful.

  • I tried looking for the problematic file as the answer suggested but there are no files in /repo/.git/objects/88. I also looked in backups (I have hourly Time Machine backups) but there never were files in that folder.
  • I tried git reset --hard and this removed uncommitted changes, but after doing so I cannot commit a simple change. The exact same error message is presented.
  • I tried to trash the image referenced in the error message, but then the next time I attempt to commit the same error is displayed referencing a different image. After trashing all images it started listing code files.
  • I tried creating a new branch and committing to that branch, but the same error is presented.
  • I switched to my other partition where I previously worked on this project (the files sync over Dropbox which may have been the cause of the problem) and attempted a commit only to experience the same error message.
  • I finally decided to restore the entire project to an earlier point in time, I went back two months ago before I even made any branches, yet still a simple commit refuses to work. This makes me believe an external factor is involved, something outside of the project folder. I know it worked back then so this has me very confused. This is the error presented:

The working copy «app name» failed to commit files.
fatal: unable to read tree 781d…

After running git fsck --full I see there are several broken links from trees, a lot of dangling blobs, several missing blobs, and two missing trees.

The result of git for-each-ref --format='%(refname)' | while read ref; do git rev-list --objects $ref >/dev/null || echo "in $ref"; done:
fatal: missing blob object ‘8886889658056c4ce52d46a485933c8df7a4de84’
in refs/heads/UniversalStoryboard
fatal: missing blob object ‘8886889658056c4ce52d46a485933c8df7a4de84’
in refs/heads/Update1
fatal: missing blob object ‘8886889658056c4ce52d46a485933c8df7a4de84’
in refs/heads/iOS-8-Update
fatal: missing blob object ‘8886889658056c4ce52d46a485933c8df7a4de84’
in refs/heads/master

After attempting to clone the repo, this is what is logged:
error: unable to read sha1 file of appname/Images.xcassets/AppIcon.appiconset/Icon-Small-1.png (86672e7aa0d5ad36563feef30c15a5d31f921802)
error: unable to read sha1 file of appname/Images.xcassets/AppIcon.appiconset/Icon-Small.png (86672e7aa0d5ad36563feef30c15a5d31f921802)
error: unable to read sha1 file of appname/Images.xcassets/LaunchImage.launchimage/DefaultPortrait@2x.png (7d97eba35cf392ddb1a705109b721fcd6a20ea29)
error: unable to read sha1 file of appname/appname-Prefix.pch (82a2bb45076d290ce7461b28d5a579e649777779)
fatal: unable to checkout working tree
warning: Clone succeeded, but checkout failed.

At this point in time I am willing to do anything to prevent having to trash the entire git repository and start over. I don’t want to lose my branches and history. How can I fix this issue? I have a working copy of the project directory exactly as it was when I first discovered the error as well as Time Machine backups for the entire history of this project. Anything you can suggest is appreciated.

I have a local git repository on my Mac that is managed by Xcode. I recently created a new branch and have made a lot of changes since then. I was about to perform my first commit to this new branch and was presented with an error dialog:

The working copy «app name» failed to commit files.
error: invalid object 100644
888688965… for ‘Supporting Files/animage.png’
error: Error building trees

I searched the Interwebs for a solution and found this question which appears to be the same issue. I tried both answers to this question and neither solved the problem for me. I have done everything I can think of to solve the problem but have not been successful.

  • I tried looking for the problematic file as the answer suggested but there are no files in /repo/.git/objects/88. I also looked in backups (I have hourly Time Machine backups) but there never were files in that folder.
  • I tried git reset --hard and this removed uncommitted changes, but after doing so I cannot commit a simple change. The exact same error message is presented.
  • I tried to trash the image referenced in the error message, but then the next time I attempt to commit the same error is displayed referencing a different image. After trashing all images it started listing code files.
  • I tried creating a new branch and committing to that branch, but the same error is presented.
  • I switched to my other partition where I previously worked on this project (the files sync over Dropbox which may have been the cause of the problem) and attempted a commit only to experience the same error message.
  • I finally decided to restore the entire project to an earlier point in time, I went back two months ago before I even made any branches, yet still a simple commit refuses to work. This makes me believe an external factor is involved, something outside of the project folder. I know it worked back then so this has me very confused. This is the error presented:

The working copy «app name» failed to commit files.
fatal: unable to read tree 781d…

After running git fsck --full I see there are several broken links from trees, a lot of dangling blobs, several missing blobs, and two missing trees.

The result of git for-each-ref --format='%(refname)' | while read ref; do git rev-list --objects $ref >/dev/null || echo "in $ref"; done:
fatal: missing blob object ‘8886889658056c4ce52d46a485933c8df7a4de84’
in refs/heads/UniversalStoryboard
fatal: missing blob object ‘8886889658056c4ce52d46a485933c8df7a4de84’
in refs/heads/Update1
fatal: missing blob object ‘8886889658056c4ce52d46a485933c8df7a4de84’
in refs/heads/iOS-8-Update
fatal: missing blob object ‘8886889658056c4ce52d46a485933c8df7a4de84’
in refs/heads/master

After attempting to clone the repo, this is what is logged:
error: unable to read sha1 file of appname/Images.xcassets/AppIcon.appiconset/Icon-Small-1.png (86672e7aa0d5ad36563feef30c15a5d31f921802)
error: unable to read sha1 file of appname/Images.xcassets/AppIcon.appiconset/Icon-Small.png (86672e7aa0d5ad36563feef30c15a5d31f921802)
error: unable to read sha1 file of appname/Images.xcassets/LaunchImage.launchimage/DefaultPortrait@2x.png (7d97eba35cf392ddb1a705109b721fcd6a20ea29)
error: unable to read sha1 file of appname/appname-Prefix.pch (82a2bb45076d290ce7461b28d5a579e649777779)
fatal: unable to checkout working tree
warning: Clone succeeded, but checkout failed.

At this point in time I am willing to do anything to prevent having to trash the entire git repository and start over. I don’t want to lose my branches and history. How can I fix this issue? I have a working copy of the project directory exactly as it was when I first discovered the error as well as Time Machine backups for the entire history of this project. Anything you can suggest is appreciated.

Я не могу зафиксировать изменение:

$ git commit
error: invalid object 100644 13da9eeff5a9150cf2135aaed4d2e337f97b8114 for 'spec/routing/splits_routing_spec.rb'
error: Error building trees

Я пробовал пока:

$ git fsck | grep 13da
missing blob 13da9eeff5a9150cf2135aaed4d2e337f97b8114

а также:

$ git prune
error: Could not read 1394dce6fd1ad15a70b2f2623509082007dc5b6c
fatal: bad tree object 1394dce6fd1ad15a70b2f2623509082007dc5b6c

а также:

$ git fsck | grep 13da
missing blob 13da9eeff5a9150cf2135aaed4d2e337f97b8114

но ничего не помогло. Должен ли я удалить файл, зафиксировать и снова ввести его? Я готов потерять немного истории, если это вернет git commit.

15 ответы

Эта ошибка означает, что у вас есть файл с хешем 13da9eeff5a9150cf2135aaed4d2e337f97b8114, и этого хеша нет в .git/objects/../, или он пуст. Когда произошла эта ошибка, у меня в ошибке был только этот хеш, без пути к файлу. Затем я попытался сделать git gc --auto и git reset --hard. После одной из этих команд (эти команды не решили мою проблему) я получил путь к файлу, который вызывает ошибку.

Вам просто нужно сгенерировать хэш объекта:

git hash-object -w spec/routing/splits_routing_spec.rb

Для получения дополнительной информации см. документации. В документации есть дополнительный способ исправления этой ошибки.

PS Это был единственный способ, который мне помог.

ответ дан 23 дек ’18, 19:12

У вас может быть поврежденный объект в вашем репозитории git.

Если у вас есть удаленный или другие клоны этого репозитория, вы можете взять оттуда проблемный файл и просто заменить его в локальном репозитории.

Файл, который вы хотите, будет в:

/repo/.git/objects/13/da9eeff5a9150cf2135aaed4d2e337f97b8114

Создан 22 янв.

git reset --hard должен вернуть ваш репозиторий в нормальное состояние, но вы потеряете незафиксированные изменения.

Создан 21 янв.

Если проблемный файл добавляется вашим изменением, вы можете просто удалить его из индекса и добавить снова:

git reset <file> 
git add <file>

ответ дан 03 мар ’15, в 19:03

Для меня это была просто проблема с разрешениями. Когда я бегу с sudo, это сработало. возможно, что-то делать с окружением Mac

Создан 23 сен.

В моем случае я решил это:

git reset --mixed

Создан 23 сен.

Это может быть вызвано некоторыми сторонними приложениями синхронизации, такими как Dropbox и Jianguoyun. По моему опыту может быть два пути:

  1. Вы можете попробовать отменить недавние операции синхронизации.
  2. Удалите связанные файлы из папки, зафиксируйте, а затем переместите файлы обратно.

ответ дан 19 окт ’17, 11:10

Простое обходное решение, если вас не очень беспокоит путь файла, вы можете продублировать файл и удалить оригинал, сначала зафиксировать удаление и добавление, а затем снова переименовать в оригинал.

Git должен восстановиться нормально

ответ дан 07 апр.

В моем случае поврежден файл в удаленной ветке. Я решил это:

  1. удалить удаленные ветки вообще $ git remote rm origin
  2. снова добавьте пульт: $ git remote add origin <the-remote-url>
  3. снова получить пульт: $ git fetch origin
  4. reset-hard на нужную ветку в начале (скажем, develop): $ git reset --hard origin/develop

Потом все возвращается в норму.

ответ дан 16 дек ’15, 07:12

В моем случае это было связано с другой версией git. Я использовал свой репозиторий через официальный порт git для Windows и начал использовать порт MinGW с тем же номером версии.

Я начал сталкиваться с этой проблемой при попытке зафиксировать с помощью MinGW git. Переключение обратно на Windows Git решило проблему.

Создан 17 сен.

это так же просто, как клонирование из удаленного репо в новую папку, удаление всех файлов в этой новой папке с сохранением файла .git. А затем копирование всех файлов из старой папки в новую клонированную папку без копирования папки .git.

Создан 25 июн.

ну, я также столкнулся с этой проблемой, что я сделал: скопировал измененную папку или файлы в другой проект в VSCode, удалил этот репозиторий и снова клонировал и снова передал эти файлы или папки. похоже, что это долгий путь, но я думаю, что лучше убедиться, что вы не потеряете свои файлы, которые вы еще не зафиксировали

ответ дан 05 окт ’21, 21:10

Самый простой способ решить эту проблему:

  1. Скопируйте незафиксированные файлы.
  2. Затем используйте $ git reflog -1
  3. использование $ git reset --hard xxxxxx (xxxxx ваш последний коммит)
  4. Затем снова вставьте файлы.

Это сработало для меня. Нет необходимости клонировать репо или удалять пульт.

ответ дан 11 дек ’21, 20:12

git status 

а затем он показывает вам, какие файлы были изменены/вызвали проблему… тогда вы можете либо добавить их через git add "filename" — без кавычек или удалить через git rm "filename"

ответ дан 10 апр.

Простой трюк, упомянутый в это Статья Medium решила мой случай, когда я столкнулся с похожими проблемами «недопустимый объект» и «дерево ошибок при построении». Решение довольно простое:

git hash-object -w <file-name-which-is-creating-problem>

После этого git сделает Sha1 для файла, чьи хэши не совпали, и его репозиторий будет исправлен.

Теперь я могу использовать git add * и git commit -m без каких-либо проблем. Вот и все.

[Примечание: если у вас есть локальная копия или изменения, которые вам нужны, используйте этот трюк. Потому что вы можете потерять свои локальные изменения. В моем случае я скопировал строку, которую хотел вставить в репозиторий и исправить проблему, а затем повторно отредактировал файл и вставил эту строку.]

ответ дан 26 мая ’22, 07:05

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

git

or задайте свой вопрос.


Я сделал git pullиз общего репозитория git, но что-то пошло не так после того, как я попыталсяgit revert . Вот ситуация сейчас:

$ git stash
Source/MediaStorageAndFileFormat/gdcmImageCodec.cxx: needs merge
Source/MediaStorageAndFileFormat/gdcmJPEGLSCodec.cxx: needs merge
Source/MediaStorageAndFileFormat/gdcmPNMCodec.cxx: needs merge
Testing/Source/DataStructureAndEncodingDefinition/Cxx/TestDS.cxx: needs merge
Utilities/socketxx/socket++/sockstream.cpp: needs merge
Source/MediaStorageAndFileFormat/gdcmImageCodec.cxx: needs merge
Source/MediaStorageAndFileFormat/gdcmJPEGLSCodec.cxx: needs merge
Source/MediaStorageAndFileFormat/gdcmPNMCodec.cxx: needs merge
Testing/Source/DataStructureAndEncodingDefinition/Cxx/TestDS.cxx: needs merge
Utilities/socketxx/socket++/sockstream.cpp: needs merge
Source/MediaStorageAndFileFormat/gdcmImageCodec.cxx: unmerged (2aafac967c35fa4e77c3086b83a3c102939ad168)
Source/MediaStorageAndFileFormat/gdcmImageCodec.cxx: unmerged (78cc95e8bae85bf8345a7793676e878e83df167b)
Source/MediaStorageAndFileFormat/gdcmImageCodec.cxx: unmerged (2524db713fbde0d7ebd86bfe2afc4b4d7d48db33)
Source/MediaStorageAndFileFormat/gdcmJPEGLSCodec.cxx: unmerged (4bb4ba78973091eaa854b03c6ce24e8f4af9e7cc)
Source/MediaStorageAndFileFormat/gdcmJPEGLSCodec.cxx: unmerged (ad0982b8b8b4c4fef23e69bbb639ca6d0cd98dd8)
Source/MediaStorageAndFileFormat/gdcmJPEGLSCodec.cxx: unmerged (4868371b7218c6e007fb6c582ad4ab226167a80a)
Source/MediaStorageAndFileFormat/gdcmPNMCodec.cxx: unmerged (f7a1b386b5b13b8fa8b6a31ce1258d2d5e5b13c5)
Source/MediaStorageAndFileFormat/gdcmPNMCodec.cxx: unmerged (6ce299c416fbb3bb60e11ef1e54962ffd3449a4c)
Source/MediaStorageAndFileFormat/gdcmPNMCodec.cxx: unmerged (75c8043a60a56a1130a34cdbd91d130bc9343c1c)
Testing/Source/DataStructureAndEncodingDefinition/Cxx/TestDS.cxx: unmerged (79c2843f2649ea9c87fa57662dafd899a5fa39ee)
...
fatal: git-write-tree: error building trees
Cannot save the current index state

Есть ли способ сбросить все это?

Спасибо

Ответы:


Использование:

git reset --mixed

вместо git reset --hard. Вы не потеряете никаких изменений.







Это сработало для меня:

Делать

$ git status

И проверьте, есть ли у вас Unmerged paths

# Unmerged paths:
#   (use "git reset HEAD <file>..." to unstage)
#   (use "git add <file>..." to mark resolution)
#
#   both modified:      app/assets/images/logo.png
#   both modified:      app/models/laundry.rb

Прикрепите их git addк каждому из них и попробуйте git stashснова.

git add app/assets/images/logo.png





Чтобы следить за реакцией Малата, вы можете избежать потери изменений, создав патч и применив его позже.

git diff --no-prefix > patch.txt
patch -p0 < patch.txt

Храните ваш патч вне папки репозитория для безопасности.




Я использовал:

 git reset --hard

Я потерял некоторые изменения, но это нормально.




может быть, в вашем git-репозитории есть несколько незакрепленных путей, которые вы должны решить, прежде чем копировать.



Это произошло для меня, когда я пытался скрыть свои изменения, но затем мои изменения вступили в конфликт с текущим состоянием моей ветви.

Я так git reset --mixedи сделал, а затем решил конфликт с git и снова спрятал.

I’m trying to import a large subversion repository into git using git-svn (so that I can work in git but still dcommit to subversion from time to time). After importing more than 4000 revisions I’m now getting the following error whenever I run git svn fetch or git svn rebase, which I don’t manage to get rid of:

$ git svn fetch
error: invalid object 100644 1f2....742 for 'src/path/.../file.cs'
fatal: git-write-tree: error building trees
write-tree: command returned error: 128

What I’ve tried so far:

  • git fsck --full doesn’t report anything, neither does git fsck --unreachable or git fsck --no-reflog
  • git gc --aggressive doesn’t help
  • moving the single pack file away and reimporting it with git unpack-objects doesn’t help
  • git svn reset -rXY with XY a bit lower than the latest imported revsion doesn’t seem to help either, neither does manually removing the latest entries from the reflog up to XY.
  • reboot. Sounds silly, but I did observe some weird issues while importing the first ~4000 revision, as if something was leaking a lot of kernel resources (most likely in windows subsystem), might be related to msys/mingw (or the avira virus scanner, which I disabled for testing).

I also didn’t find out what error 128 really stands for. Any ideas? Thanks in advance!

Might be related to this question which is about error 128 as well but with different error messages, and without a solution.

msysgit version 1.6.4.msysgit.0 with bash on xp sp3

Community's user avatar

asked Aug 31, 2009 at 7:25

Christoph Rüegg's user avatar

Christoph RüeggChristoph Rüegg

4,5761 gold badge20 silver badges34 bronze badges

1

git svn gc

(possibly git gc and git prune before)

bdukes's user avatar

bdukes

149k23 gold badges147 silver badges175 bronze badges

answered Sep 17, 2009 at 2:04

user174710's user avatar

3

Short answer: Try resolving any merge conflicts, committing them, and they fetch/pull again.

Longer explanation:
I’m guessing you resolved this issue, since it was posted so long ago. I’m writing this since Google’s ranking of StackOverflow articles is high enough that other people with this problem would be very likely to visit this page if they had this error.

I encountered a similar error when trying to do a «git stash», what turned out to be the problem was that a merge conflict had occurred after a pull. I had not resolved & committed the conflict, and this left the repository in a state that prevented me from pulling/merging/etc…

If you make sure you don’t have any blocking files, try again.

Good luck!

answered Oct 20, 2010 at 1:18

Levon Karayan's user avatar

I’m trying to import a large subversion repository into git using git-svn (so that I can work in git but still dcommit to subversion from time to time). After importing more than 4000 revisions I’m now getting the following error whenever I run git svn fetch or git svn rebase, which I don’t manage to get rid of:

$ git svn fetch
error: invalid object 100644 1f2....742 for 'src/path/.../file.cs'
fatal: git-write-tree: error building trees
write-tree: command returned error: 128

What I’ve tried so far:

  • git fsck --full doesn’t report anything, neither does git fsck --unreachable or git fsck --no-reflog
  • git gc --aggressive doesn’t help
  • moving the single pack file away and reimporting it with git unpack-objects doesn’t help
  • git svn reset -rXY with XY a bit lower than the latest imported revsion doesn’t seem to help either, neither does manually removing the latest entries from the reflog up to XY.
  • reboot. Sounds silly, but I did observe some weird issues while importing the first ~4000 revision, as if something was leaking a lot of kernel resources (most likely in windows subsystem), might be related to msys/mingw (or the avira virus scanner, which I disabled for testing).

I also didn’t find out what error 128 really stands for. Any ideas? Thanks in advance!

Might be related to this question which is about error 128 as well but with different error messages, and without a solution.

msysgit version 1.6.4.msysgit.0 with bash on xp sp3

Community's user avatar

asked Aug 31, 2009 at 7:25

Christoph Rüegg's user avatar

Christoph RüeggChristoph Rüegg

4,5761 gold badge20 silver badges34 bronze badges

1

git svn gc

(possibly git gc and git prune before)

bdukes's user avatar

bdukes

149k23 gold badges147 silver badges175 bronze badges

answered Sep 17, 2009 at 2:04

user174710's user avatar

3

Short answer: Try resolving any merge conflicts, committing them, and they fetch/pull again.

Longer explanation:
I’m guessing you resolved this issue, since it was posted so long ago. I’m writing this since Google’s ranking of StackOverflow articles is high enough that other people with this problem would be very likely to visit this page if they had this error.

I encountered a similar error when trying to do a «git stash», what turned out to be the problem was that a merge conflict had occurred after a pull. I had not resolved & committed the conflict, and this left the repository in a state that prevented me from pulling/merging/etc…

If you make sure you don’t have any blocking files, try again.

Good luck!

answered Oct 20, 2010 at 1:18

Levon Karayan's user avatar

У меня есть локальный репозиторий git на моем Mac, которым управляет Xcode. Недавно я создал новую ветку и с тех пор внес много изменений. Я собирался выполнить свою первую фиксацию в этой новой ветке, и мне было представлено диалоговое окно с ошибкой:

Рабочей копии «название приложения» не удалось зафиксировать файлы.
ошибка: неверный объект 100644
888688965… для «Поддерживающих файлов/animage.png»
error: Ошибка построения деревьев

Я искал в Interwebs решение и нашел этот вопрос, который кажется быть той же проблемой. Я попробовал оба ответа на этот вопрос, и ни один из них не решил проблему для меня. Я сделал все, что мог придумать, чтобы решить проблему, но безуспешно.

  • Я попытался найти проблемный файл, как было предложено в ответе, но в /repo/.git/objects/88 файлов нет. Я также смотрел в резервных копиях (у меня есть ежечасные резервные копии Time Machine), но в этой папке никогда не было файлов.
  • Я попробовал git reset --hard, и это удалило незафиксированные изменения, но после этого я не могу зафиксировать простое изменение. Представлено точно такое же сообщение об ошибке.
  • Я попытался удалить изображение, указанное в сообщении об ошибке, но в следующий раз, когда я попытаюсь совершить ту же ошибку, отображается ссылка на другое изображение. После уничтожения всех изображений он начал перечислять файлы кода.
  • Я попытался создать новую ветку и зафиксировать ее, но появляется та же ошибка.
  • Я переключился на другой раздел, где ранее работал над этим проектом (файлы синхронизируются через Dropbox, что могло быть причиной проблемы), и попытался зафиксировать только для получения того же сообщения об ошибке.
  • В конце концов я решил восстановить весь проект на более ранний момент времени, я вернулся два месяца назад, прежде чем даже сделал какие-либо ветки, но простой коммит все еще отказывается работать. Это заставляет меня поверить, что задействован внешний фактор, что-то вне папки проекта. Я знаю, что тогда это работало, так что это меня очень смутило. Это представленная ошибка:

Рабочей копии «название приложения» не удалось зафиксировать файлы.
фатально: невозможно прочитать дерево 781d…

После запуска git fsck --full я вижу несколько неработающих ссылок из деревьев, множество оборванных BLOB-объектов, несколько отсутствующих BLOB-объектов и два отсутствующих дерева.

Результат git for-each-ref --format='%(refname)' | while read ref; do git rev-list --objects $ref >/dev/null || echo "in $ref"; done:
fatal: отсутствует объект blob ‘8886889658056c4ce52d46a485933c8df7a4de84’
в refs/heads/UniversalStoryboard
фатальный: отсутствует объект blob ‘8886889658056c4ce52d46a485933c8df7a4de84’
в refs/heads/Update1
фатальный: отсутствует объект blob ‘8886889658056c4ce52d46a485933c8df7a4de84’
в refs/heads/iOS-8-Update
фатальный: отсутствует объект blob ‘8886889658056c4ce52d46a485933c8df7a4de84’
в refs/heads/master

После попытки клонировать репозиторий в журнал записывается следующее:
ошибка: невозможно прочитать файл sha1 appname/Images.xcassets/AppIcon.appiconset/Icon-Small-1.png (86672e7aa0d5ad36563feef30c15a5d31f921802)
ошибка: невозможно прочитать файл sha1 appname/Images.xcassets/AppIcon.appiconset/Icon-Small.png (86672e7aa0d5ad36563feef30c15a5d31f921802)
ошибка: невозможно прочитать файл sha1 appname/Images.xcassets/LaunchImage.launchimage/DefaultPortrait@2x.png (7d97eba35cf392ddb1a705109b721fcd6a20ea29)
ошибка: невозможно прочитать файл sha1 appname/appname-Prefix.pch (82a2bb45076d290ce7461b28d5a579e649777779)
фатально: невозможно проверить рабочее дерево
предупреждение: Клонирование выполнено успешно, но оформить заказ не удалось.

На данный момент я готов сделать все, чтобы мне не пришлось уничтожать весь репозиторий git и начинать все сначала. Я не хочу терять свои ветки и историю. Как я могу решить эту проблему? У меня есть рабочая копия каталога проекта точно такой же, какой она была, когда я впервые обнаружил ошибку, а также резервные копии Time Machine для всей истории этого проекта. Все, что вы можете предложить, приветствуется.

2 ответа

Одно исправление заключается в следующем:

  • вернуться в командную строку.
  • клонировать ваш текущий репо
  • попробуйте создать новую ветку/новую фиксацию в этом клоне.

Если вы ранее отправили репозиторий, попробуйте клонировать удаленный репозиторий вместо локального.
Или попробуйте клонировать репо, сохранив его на машине времени.

Если это не сработает, у вас сломанный репозиторий. , и вы можете попробовать некоторые из методов, представленных в «Дерево содержит повторяющиеся записи файла».


2

Community
23 Май 2017 в 14:43

Вы изменили версию git? Вы используете только тот, который поставляется с Xcode, или у вас установлена ​​устаревшая версия в Терминале? Тот, который может повредить репо. (Попробуйте «git —version» — текущая версия — 2.0.4, и ее легко установить с помощью homebrew).

Есть ли странные разрешения в папке репо, которые мешают работе git?


2

Graham Perks
13 Авг 2014 в 06:00

Я не могу зафиксировать изменения:

$ git commit
error: invalid object 100644 13da9eeff5a9150cf2135aaed4d2e337f97b8114 for 'spec/routing/splits_routing_spec.rb'
error: Error building trees

Я пробовал до сих пор:

$ git fsck | grep 13da
missing blob 13da9eeff5a9150cf2135aaed4d2e337f97b8114

а также:

$ git prune
error: Could not read 1394dce6fd1ad15a70b2f2623509082007dc5b6c
fatal: bad tree object 1394dce6fd1ad15a70b2f2623509082007dc5b6c

а также:

$ git fsck | grep 13da
missing blob 13da9eeff5a9150cf2135aaed4d2e337f97b8114

но ничего не помогло. Должен ли я удалить файл, зафиксировать и повторно ввести обратно? Я готов потерять немного истории, если он вернет git.

4b9b3361

Ответ 1

У вас может быть поврежден объект в репозитории git.

Если у вас есть удаленный или другой клон этого репозитория, вы можете получить там проблемный файл и просто заменить его на локальное репо.

Файл, который вы хотите, будет находиться в:

/repo/.git/objects/13/da9eeff5a9150cf2135aaed4d2e337f97b8114

Ответ 2

Эта ошибка означает, что у вас есть файл с hash 13da9eeff5a9150cf2135aaed4d2e337f97b8114, и этот хеш отсутствует в .git/objects/../ или он пуст, когда эта ошибка произошла, у меня есть только этот хеш по ошибке, без пути к файлу, то я попытался сделать git gc --auto и git reset --hard, и после одной из этих команд (эти команды не исправили мою проблему), у меня есть путь к файлу, который вызывает эту ошибку.

Вам нужно просто сгенерировать хэш объекта:

git hash-object -w spec/routing/splits_routing_spec.rb

Для получения дополнительной информации см. документация, в этой документации есть дополнительный способ устранения этой ошибки.

P.S.
Это был единственный способ, который мне помог.

Ответ 3

git reset --hard должен вернуть ваш репозиторий в нормальное состояние, но вы потеряете незафиксированные изменения.

Ответ 4

Если проблемный файл добавляется вашим изменением, вы можете просто удалить его из индекса и добавить его снова:

git reset <file> 
git add <file>

Ответ 5

Для меня это были только проблемы с разрешениями. Когда я бегаю с ‘sudo’, это сработало. возможно, что-то связано с mac environmentmnet

Ответ 6

Простота решения проблемы, если вы не очень заинтересованы в отслеживании файла, вы можете дублировать файл и удалять оригинал, сначала зафиксировать удаление и добавление, а затем снова переименовать в оригинал.

Git должен вернуться обратно нормально

Ответ 7

Это может быть вызвано некоторыми сторонними приложениями синхронизации, такими как Dropbox и Jianguoyun. На мой опыт могут быть два пути:

  • Вы можете попытаться отменить последние операции синхронизации.
  • Удалите связанные файлы из папки, зафиксируйте, а затем верните файлы.

Ответ 8

В моем случае это поврежден файл в удаленной ветке.
Я решил это:

  • удалите удаленные ветки вообще $ git remote rm origin
  • снова добавьте удаленный компьютер: $ git remote add origin <the-remote-url>
  • снова введите пульт дистанционного управления: $ git fetch origin
  • reset -hard к нужной ветки по происхождению (скажем, develop): $ git reset --hard origin/develop

Затем все возвращается к норме.

Я пытаюсь импортировать большой репозиторий subversion в git с помощью git-svn (чтобы я мог работать в git, но все же dcommit для subversion время от времени). После импорта более 4000 версий я теперь получаю следующую ошибку при каждом запуске git svn fetch или git svn rebase, от которого мне не удается избавиться:

$ git svn fetch
error: invalid object 100644 1f2....742 for 'src/path/.../file.cs'
fatal: git-write-tree: error building trees
write-tree: command returned error: 128

что я пробовал до сих пор:

  • git fsck --full ничего не сообщает, и не делает git fsck --unreachable или git fsck --no-reflog
  • git gc --aggressive не помогает
  • переместить один файл упаковать и импортировать его с git unpack-objects не помогает
  • git svn reset -rXY С XY немного ниже, чем последняя импортированная версия, похоже, тоже не помогает, равно как и ручное удаление последних записей из reflog до XY.
  • перезагрузка. Звучит глупо, но я заметил некоторые странные проблемы при импорте первой версии ~4000, как будто что-то протекало много ресурсов ядра (скорее всего, в windows подсистема), может быть связана с msys / mingw (или антивирусным сканером avira, который я отключил для тестирования).

Я также не узнал, что на самом деле означает ошибка 128. Есть идеи? Заранее спасибо!

может быть связано с этот вопрос что касается ошибки 128, но с различными сообщениями об ошибках и без решения.

msysgit версия 1.6.4.msysgit.0 С bash на xp sp3

2 ответов


git svn gc

(возможно git gc и git prune до)


короткий ответ: попробуйте разрешить любые конфликты слияния, зафиксировав их, и они снова извлекут/потянут.

больше объяснений:
Я предполагаю, что вы решили эту проблему, так как она была опубликована так давно. Я пишу это, так как рейтинг статей StackOverflow Google достаточно высок, чтобы другие люди с этой проблемой могли бы посетить эту страницу, если бы у них была эта ошибка.

Я столкнулся с аналогичной ошибкой при попытке сделать «git stash», что оказалось проблема заключалась в том, что конфликт слияния произошел после вытягивания. Я не разрешил и не совершил конфликт, и это оставило репозиторий в состоянии, которое помешало мне вытащить/объединить/и т. д…

Если вы убедитесь, что у вас нет блокирующих файлов, повторите попытку.

удачи!


0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Git ошибка non fast forward
  • Git ошибка error src refspec master does not match any