合并两个Git仓库并保留主分支历史记录

10
我需要将两个Git存储库合并为一个全新的第三方存储库。 我按照以下说明进行操作,它们有效,但结果并非我所期望的。在不破坏文件历史记录的情况下合并两个Git存储库 看这个:

Git Merge operation

主分支未对齐。

  • 是否有可能将所有内容合并到同一个主分支上?
  • 我希望主分支上的历史记录保持清晰。

你可以自由地使用我的示例代码库 在GitHub上

这是我的合并结果

我希望的情况是:(涂鸦解决方案!!!)

Painted solution!!

我如何到达当前的情况:

# Assume the current directory is where we want the new repository to be created
# Create the new repository
git init

# Before we do a merge, we have to have an initial commit, so we'll make a dummy commit
dir > Read.md
git add .
git commit -m "initial commit"

# Add a remote for and fetch the old RepoA
git remote add -f RepoA https://github.com/DimitriDewaele/RepoA

# Merge the files from RepoA/master into new/master
git merge RepoA/master --allow-unrelated-histories

# Do the same thing for RepoB
git remote add -f RepoB https://github.com/DimitriDewaele/RepoB

# Merge the files from RepoB/master into new/master
git merge RepoB/master --allow-unrelated-histories

非常感谢您的帮助!

更新:答案

正确的答案是重新基于,而不是合并。

代码:

# Rebase the working branch (master) on top of repoB
git rebase RepoB/master

# Rebase teh working branch (master with RepoB) on top op repoA
git rebase RepoA/master

一个问题尚未解决。第二个仓库丢失了父视图。我发了一个后续问题: 合并两个Git仓库并保留历史记录

enter image description here


1
你能详细解释一下你的期望以及这与现实有何不同吗? - Josh Lee
你把所有东西都放在一个主库里面,我不确定你所谓的“对齐”是什么意思。试着从本地移除RepoA和RepoB的远程分支,看看图形是什么样的。 - Adrian
我已经添加了一个“绘制的解决方案”。 - Dimitri Dewaele
1个回答

3
很容易,不要合并,而是使用rebase。假设您想先有repoA/master,那么只需执行以下操作(在获取和添加远程之后):
# starting on master
git rebase RepoB/master # place master on top of masterB
git rebase RepoA/master # place master (with masterB) on top of masterA

请注意,变基(rebase)潜在地具有破坏性,并且一开始可能有点不直观,因此我强烈建议先阅读相关资料(上面链接的SO文档是一个很好的起点)。

谢谢您的正确回答。有一个小问题:RepoA的rebase使我失去了合并历史记录。请参见上面的图片(我已添加了当前状态)。是否可能保留这个历史记录? - Dimitri Dewaele
@DimitriDewaele 请尝试使用 rebase--preserve-merges 选项。 - Dunno
1
正如@DimitriDewaele的后续问题所指出的那样,rebase并不是您想要用于此操作的正确命令:https://dev59.com/a1gQ5IYBdhLWcg3wvGe4#42457384 - dahlbyk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接