如何同步原Git仓库变更至镜像仓库?Push报错求助
Git跨平台仓库镜像同步失败问题解决
需求
- 镜像Git仓库的
main分支,实现跨服务商平台同步:原仓库发生变更时,新平台的镜像仓库自动同步更新
执行操作
$ git clone --mirror git@example.com/old-upstream-repository.git $ cd old-upstream-repository.git $ ls HEAD branches config description hooks info objects packed-refs refs $ git push --mirror git@example.com/new-location.git
遇到的错误
推送时的报错:
remote: error: object 0a3: hasDotgit: contains '.git' remote: fatal: fsck error in packed object error: remote unpack failed: index-pack abnormal exit To git@example.com/new-location.git ! [remote rejected] develop -> develop (unpacker error) ! [remote rejected] feature/2321-new-edit-for-all -> feature/2321-new-edit-for-all (unpacker error) error: failed to push some refs to 'git@example.com/new-location.git'
附加报错(翻译后):
fatal: this operation must be run in a work tree
翻译:致命错误:此操作必须在工作树中执行
问题分析与解决步骤
问题根源
推送失败的核心原因是原仓库的某个Git对象中包含.git目录/文件,Git的fsck安全检查会拦截这类有风险的内容,和是否使用裸仓库无关。而"必须在工作树执行"的报错,是因为你可能在裸仓库中运行了需要工作目录的命令(如git checkout),但这不是本次推送失败的直接原因。
修复步骤
清理原仓库中的
.git内容- 克隆原仓库的完整版本(带工作树):
git clone git@example.com/old-upstream-repository.git temp-repo cd temp-repo - 查找所有包含
.git的目录:find . -name ".git" -type d - 删除这些目录并提交变更:
rm -rf 找到的/.git目录路径 git add . git commit -m "移除包含.git的风险目录" git push origin main
- 克隆原仓库的完整版本(带工作树):
重新推送镜像
- 回到之前的镜像仓库(或重新克隆镜像):
cd old-upstream-repository.git git fetch origin git push --mirror git@example.com/new-location.git
- 回到之前的镜像仓库(或重新克隆镜像):
设置自动同步
- Webhook方式:在原仓库服务商后台配置Webhook,触发地址指向一个脚本,脚本内容为拉取原仓库更新并推送到镜像仓库:
#!/bin/bash cd /path/to/old-upstream-repository.git git fetch origin git push --mirror git@example.com/new-location.git - 定时任务方式:用crontab设置定时同步(比如每小时执行一次):
chmod +x /path/to/sync-mirror.sh crontab -e # 添加以下内容 0 * * * * /path/to/sync-mirror.sh
- Webhook方式:在原仓库服务商后台配置Webhook,触发地址指向一个脚本,脚本内容为拉取原仓库更新并推送到镜像仓库:
内容的提问来源于stack exchange,提问作者A.Dumas
相关产品推荐
相关产品推荐

