如何将两个独立Git仓库合并为含完整历史的项目仓库?
将两个独立Git仓库合并为一个全局仓库并保留提交历史的方法
操作步骤:
初始化全局项目仓库
- 进入项目根目录:
cd project - 创建并初始化全局Git仓库:
git init
- 进入项目根目录:
导入前端仓库的完整提交历史
- 将本地frontend仓库设为临时远程源:
git remote add frontend ./frontend - 拉取frontend仓库的所有分支与提交记录:
git fetch frontend - 合并frontend主分支(若分支名为master则替换):
git merge --allow-unrelated-histories frontend/main --no-commit - 重写提交历史,将所有frontend的文件路径统一调整到
frontend目录下:git filter-repo --to-subdirectory-filter frontend - 移除临时远程源:
git remote remove frontend
- 将本地frontend仓库设为临时远程源:
导入后端仓库的完整提交历史
- 重复类似操作处理backend仓库:
- 添加临时远程源:
git remote add backend ./backend - 拉取所有提交记录:
git fetch backend - 合并主分支:
git merge --allow-unrelated-histories backend/main --no-commit - 调整文件路径到
backend目录:git filter-repo --to-subdirectory-filter backend - 移除临时远程源:
git remote remove backend
- 添加临时远程源:
- 重复类似操作处理backend仓库:
清理原仓库的独立Git记录(可选)
- 若无需保留frontend和backend的独立仓库历史,直接删除各自的
.git文件夹:rm -rf frontend/.gitrm -rf backend/.git
- 若无需保留frontend和backend的独立仓库历史,直接删除各自的
推送到远程全局仓库
- 添加远程仓库地址:
git remote add origin <你的远程仓库URL> - 推送所有提交历史到远程:
git push -u origin main
- 添加远程仓库地址:
注意事项:
- 若原仓库的主分支不是
main,请替换为实际分支名(如master) git filter-repo是官方推荐的历史重写工具,需提前安装(可通过pip install git-filter-repo安装);若无法使用,也可替代为git filter-branch命令,但前者更稳定高效- 操作前建议备份原
frontend和backend文件夹,避免数据丢失
内容的提问来源于stack exchange,提问作者Arctomachine
相关产品推荐
相关产品推荐

