合并两个 Git 存储库而不破坏文件历史记录

2023-12-31

我需要将两个 Git 存储库合并到一个全新的第三个存储库中。我发现了许多关于如何使用子树合并来执行此操作的描述(例如雅库布·纳伦布斯基的回答 https://stackoverflow.com/a/1426163 on 如何合并两个 Git 存储库? https://stackoverflow.com/questions/1425892/how-do-you-merge-two-git-repositories)并遵循这些说明大部分都有效,除了当我提交子树合并时,旧存储库中的所有文件都被记录为新添加的文件。当我这样做时,我可以看到旧存储库的提交历史记录git log,但如果我这样做git log <file>它只显示该文件的一次提交 - 子树合并。从对上述答案的评论来看,我并不是唯一一个看到这个问题的人,但我没有找到已发布的解决方案。

有什么方法可以合并存储库并保持单个文件历史记录完整吗?


事实证明,如果您只是尝试将两个存储库粘合在一起并使其看起来一直如此,而不是管理外部依赖项,那么答案会简单得多。您只需将遥控器添加到旧存储库,将它们合并到新主存储库,将文件和文件夹移动到子目录,提交移动,然后对所有其他存储库重复此操作。子模块、子树合并和奇特的变基旨在解决稍微不同的问题,但不适合我想要做的事情。

下面是一个将两个存储库粘合在一起的 Powershell 脚本示例:

# 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
git commit --allow-empty -m "Initial dummy commit"

# Add a remote for and fetch the old repo
# (the '--fetch' (or '-f') option will make git immediately fetch commits to the local repo after adding the remote)
git remote add --fetch old_a <OldA repo URL>

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

# Move the old_a repo files and folders into a subdirectory so they don't collide with the other repo coming later
mkdir old_a
dir -exclude old_a | %{git mv $_.Name old_a}

# Commit the move
git commit -m "Move old_a files into subdir"

# Do the same thing for old_b
git remote add -f old_b <OldB repo URL>
git merge old_b/master --allow-unrelated-histories
mkdir old_b
dir –exclude old_a,old_b | %{git mv $_.Name old_b}
git commit -m "Move old_b files into subdir"

显然,如果您愿意的话,您可以将 old_b 合并到 old_a (这将成为新的合并存储库) - 修改脚本以适应。

如果您还想引入正在进行的功能分支,请使用以下命令:

# Bring over a feature branch from one of the old repos
git checkout -b feature-in-progress
git merge -s recursive -Xsubtree=old_a old_a/feature-in-progress

这是该过程中唯一不明显的部分 - 这不是子树合并,而是正常递归合并的一个参数,它告诉 Git 我们重命名了目标,并帮助 Git 正确排列所有内容。

我写了一个稍微详细一点的解释here http://saintgimp.org/2013/01/22/merging-two-git-repositories-into-one-repository-without-losing-file-history/.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

合并两个 Git 存储库而不破坏文件历史记录 的相关文章

随机推荐