gpt4 book ai didi

git - 在不破坏文件历史记录的情况下 merge 两个 Git 存储库

转载 作者:IT王子 更新时间:2023-10-29 01:15:24 24 4
gpt4 key购买 nike

我需要将两个 Git 存储库 merge 到一个全新的第三个存储库中。我发现了很多关于如何使用子树 merge (例如 Jakub Narębski's answer 上的 How do you merge two Git repositories? )来执行此操作的描述,并且遵循这些说明大多有效,除了当我提交子树 merge 时,旧存储库中的所有文件都是记录为新添加的文件。当我执行 git log 时,我可以从旧存储库中看到提交历史记录, 但如果我这样做 git log <file>它只显示该文件的一个提交 - 子树 merge 。从对上述答案的评论来看,我不是唯一看到这个问题的人,但我没有找到针对它的已发布解决方案。

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

最佳答案

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

这是一个将两个存储库粘合在一起的示例 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 merge 到 old_a(它成为新的 merge 存储库)——修改脚本以适应。

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

# 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

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

我写了一个更详细的解释here .

关于git - 在不破坏文件历史记录的情况下 merge 两个 Git 存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13040958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com