You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Git迁移:合并两个仓库至新仓库并同步后续提交

Git仓库合并与后续同步方案

初始合并步骤(创建仓库C并整合A、B历史)

1. 初始化新仓库C

mkdir repo-C && cd repo-C
git init

2. 导入仓库A的完整提交历史

# 添加仓库A为远程源并拉取所有历史
git remote add repo-A <仓库A的Git地址>
git fetch repo-A

# 创建临时分支存放A的历史,合并到C的主分支
git checkout -b temp-a repo-A/main  # 替换main为A的实际默认分支名(如master)
git checkout main
git merge temp-a --allow-unrelated-histories

3. 重写仓库B的历史,将所有文件迁移至/B目录

注:推荐使用git filter-repo(Git 2.22+官方推荐工具)替代老旧的filter-branch,稳定性和效率更高。

# 添加仓库B为远程源并拉取所有历史
git remote add repo-B <仓库B的Git地址>
git fetch repo-B

# 创建临时分支存放B的历史,重写历史将所有文件移入/B目录
git checkout -b temp-b repo-B/main  # 替换main为B的实际默认分支名
git filter-repo --to-subdirectory-filter B

4. 合并处理后的B分支到C的主分支

git checkout main
git merge temp-b --allow-unrelated-histories

5. 清理临时资源并推送至C的远程仓库

git branch -D temp-a temp-b
git remote remove repo-A repo-B
git remote add origin <仓库C的Git地址>
git push -u origin main

后续同步原仓库的新提交

同步仓库A的新提交

git remote add repo-A <仓库A的Git地址>
git fetch repo-A
git checkout main
git merge repo-A/main
git remote remove repo-A
git push origin main

同步仓库B的新提交

每次同步B的新提交时,仍需重写临时分支的历史,确保新提交的文件自动归入/B目录:

git remote add repo-B <仓库B的Git地址>
git fetch repo-B
git checkout -b temp-b-new repo-B/main
git filter-repo --to-subdirectory-filter B
git checkout main
git merge temp-b-new
git branch -D temp-b-new
git remote remove repo-B
git push origin main

关键说明

  • 合并完成后,仓库C会完整保留A、B的所有原始提交历史,提交记录会按时间线混合展示,单个文件的提交历史可通过git log -- <文件路径>正常查看。
  • git filter-repo部分系统可能默认未包含,可通过包管理器(如apt install git-filter-repo或brew install git-filter-repo)安装。

内容的提问来源于stack exchange,提问作者TvdH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 15:45:09