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

如何将无关仓库的分支合并至Git仓库master分支并保留历史

解决方法

方案一:保留两个仓库全部提交历史(对应期望结果1)

  • 进入本地的Repo 1目录,将Repo 2添加为远程仓库:
    git remote add repo2 <Repo2的本地路径或远程仓库URL>
    
  • 拉取Repo 2的所有提交到本地:
    git fetch repo2
    
  • 切换到Repo 1的master分支:
    git checkout master
    
  • 执行合并操作,由于两个仓库无共同提交祖先,需添加--allow-unrelated-histories参数:
    git merge repo2/master --allow-unrelated-histories
    
  • 处理合并时的文件冲突,冲突解决后提交合并结果:
    git add .
    git commit -m "Merge repo2 master into repo1 master"
    

完成后Repo 1的master分支历史就会变为A - B - C - D - E - F。

方案二:仅合并Repo2的最终提交状态(对应期望结果2)

如果不需要保留Repo2中的E提交,只需要最终可运行的F状态,可选择以下两种方式:

方式1:用cherry-pick提取单个提交

  • 先在Repo1中添加并拉取Repo2的内容:
    git remote add repo2 <Repo2的本地路径或远程URL>
    git fetch repo2
    
  • 查看Repo2的提交历史,找到F提交的哈希值:
    git log repo2/master
    
  • 切换到Repo1的master分支,执行cherry-pick:
    git checkout master
    git cherry-pick <F提交的哈希值>
    
  • 解决冲突后提交变更:
    git add .
    git commit
    

方式2:直接复制文件提交

  • 把Repo2目录下的所有文件(排除.git文件夹)复制到Repo1目录中,根据需求保留或覆盖冲突文件
  • 在Repo1中提交变更:
    git add .
    git commit -m "Apply final working state from repo2"
    

这种方式会生成一个新的提交,对应Repo2的最终状态,最终历史结构为A - B - C - D - F。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 21:10:35