git 推送失败,错误对象 hasDotgit: 包含 '.git'

git push failed with error object hasDotgit: contains '.git'

我想将 git 存储库推送到自托管 git 实验室服务器,但出现以下错误:

# git push -u origin --all --no-thin
Enumerating objects: 854410, done.
Counting objects: 100% (854410/854410), done.
Delta compression using up to 4 threads
Compressing objects: 100% (209251/209251), done.
remote: error: object 57364fe6ff4138ec58762676f24a581f5810025a: hasDotgit: contains '.git'
remote: fatal: fsck error in packed object
error: remote unpack failed: index-pack abnormal exit

使用git show检查对象57364fe6ff4138ec58762676f24a581f5810025a,我得到以下输出:

# git show 57364fe6ff4138ec58762676f24a581f5810025a
tree 57364fe6ff4138ec58762676f24a581f5810025a      
                                               
.clang-format                                      
.editorconfig                                      
.git/                                              
.gitignore                                         
.style.yapf                                        
AUTHORS                                            
LICENSE                                            
OWNERS                                             
README.md                                          
base/                                              
build/                                             
docs/                                              
infra/                                             
out/                                               
tools/                                             
util/           

有谁知道如何处理这种情况?这是一个由团队维护的回购协议,该团队在此提交后有数千次提交。我无法对其进行 git 重置。 我认为一些专家工具,如“git filter-repo”或“git filter-branch”也许可以帮助我,但我不知道如何使用它们。

您可以使用以下几个命令修复错误:

git reset --soft 57364fe6ff4138ec58762676f24a581f5810025a #delete all commits after the last good one (5736), but keep files (--soft)

git rm --cached "." -r -f #git rm all files but keep them locally (--cached)

git add . #git add everything back

git commit -m "commit message"

您必须找到包含 .git 目录的提交,然后编辑它们。


查找提交:

起点是在您当前的工作目录中找到 .git 目录,然后列出修改该目录的所有提交:

# from your directory root :
find . -name .git -type f

# if you find directories other than the root .git directory :
git log --oneline --graph -- path/to/.git

编辑提交:

基本上:如果你发现一个流氓 .git 文件夹已经在你的仓库中进行了版本控制,你需要在包含它的提交上调用 git rm --cached path/to/.git

  • 如果这个流氓 .git 目录仅出现在您的最后一次提交中:

    git rm --cached path/to/.git
    git commit --amend
    
  • 如果您在上面的 git 日志命令中看到少量提交:使用 git rebase -i,将目标提交设置为“编辑”,并删除错误目录

  • 也可以使用系统改写工具,比如git filter-branch或者git filter-repo

    git filter-branch --index-filter 'git rm --cached path/to/.git' --all