git - 如何将 2 个主题分支 rebase 到一个新分支上?

标签 git git-rebase

这是我的 git 存储库历史的当前状态:

--o--o--o--o--o--o--o master
            \
             o--o--o--o--o  topic2
                   |
                 topic1

我想将 topic1 和 topic2 rebase 到 master 上,并使其成为:

--o--o--o--o--o--o--o master
                     \
                      o--o--o--o--o  topic2
                            |
                          topic1

实现此目标的最佳方法是什么?

最佳答案

git rebase master topic2
git branch -f topic1 HEAD~2   # On (rebased) topic2, set topic1 pointer

请注意,这假设 topic1 只是指向 topic2 过去的指针,即 topic1 上不应该有任何提交不在 topic2 上。 (HEAD~2 假定提交历史如图所示,实际上您可能希望使用特定的提交 ID。请注意,如果 topic1 甚至没有存在:因为它没有自己的提交,指针可以任意设置。)

编辑:在这种情况下,您可以选择:

git rebase master topic1
git rebase topic1 topic2

最终结果应该与第一个选项相同(iff topic2 包含所有 topic1 的提交!)。此语法可能更容易理解,但如果 topic1 确实 包含不在 topic2 中的提交,则解决方案会有所不同。如果是这种情况,前一个解决方案将简单地丢弃 topic1 中不在 topic2 中的任何提交,而后者会将它们 merge 到 主题2。这两种结果都可能是不可取的,但在我看来,第一个解决方案更清楚会发生什么,这就是我将其放在第一位的原因。

举例说明,如果您的提交历史如下所示:

a1 - a2 - a3 - a4 - a5 - a6 - a7 master
               \
                b1 - b2 - b3 - b4 - b5 topic2
                          \
                           c1 topic1

那么第一个解决方案(rebase, branch)会给你:

a1 - a2 - a3 - a4 - a5 - a6 - a7 - b1' - b2' - b3' - b4' - b5' topic2
                               \ master         \ topic1

第二个(rebase, rebase):

a1 - a2 - a3 - a4 - a5 - a6 - a7 - b1' - b2' - b3' - c1' - b4' - b5' topic2
                               \ master               \ topic1

但是,在这种情况下,您可能想要得到的是:

a1 - a2 - a3 - a4 - a5 - a6 - a7 - b1' - b2' - b3' - b4' - b5' topic2
                               \ master         \
                                                 c1' topic1

这个结果的解决方案是:

git branch tmp id_of_b3_commit   # In this case id_of_b3_commit == topic1^
git rebase master tmp
git rebase tmp topic1
git rebase tmp topic2
git branch -d tmp

(如果您将其制作成脚本,您可以使用 git merge-base topic1 topic2 找到要放入 tmp 分支的提交 ID。)

关于git - 如何将 2 个主题分支 rebase 到一个新分支上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8665882/

相关文章:

git - 如何在 git 中执行多行提交消息?

git - 显示提交之间的差异

Git 在分支之前拆分提交

git - 在这种情况下执行 git-rebase 的正确命令是什么?

Git Rebase 重复上次 Rebase 的冲突

git - 两个git仓库不小心 merge 了,如何清理

git clone 如何伪造用户代理

git 'merge' 只有现有文件

git - 压缩 Git 中的前两个提交?

git - 如何修复 "corrupted"交互式 rebase ?