如何将 2 个主题分支变基到一个新分支上?

问题描述 投票:0回答:4

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

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

我想将 topic1 和 topic2 变基到 master 上,并使其像:

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

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

git git-rebase
4个回答
4
投票
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

最终结果应该与第一个选项相同(如果

topic2
包含所有
topic1
的提交!)。这种语法可能更容易理解,但如果
topic1
包含不在
topic2
中的提交,解决方案将有所不同。如果是这种情况,前一种解决方案将简单地 discard
topic1
中不在
topic2
中的任何提交,而后者会将它们合并到
topic2
中。这两种结果可能都是不可取的,但在我看来,第一个解决方案会更清楚会发生什么,这就是为什么我把它放在第一位。

为了说明,如果您的提交历史如下所示:

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。)


1
投票

如果主题 2 实际上是一个分支,它至少有一个自己的提交,那么你可以做一些嫁接。但更简单的方法是合并主题 1 和主题 2。现在使用 --preserve-merges 'rebase --onto' 这个合并分支的新位置。将主题 1 和主题 2 重置到它们应该坐的位置。


0
投票

您可以一个接一个地变基

topic1
topic2
分支。

Rebase 第一个

git checkout topic1
git rebase master

然后重新设置第二个

git checkout topic2
git rebase master

但我不确定

topic1^
点会是什么。

我建议以更复杂的方式进行,以保留分支合并历史。

首先用两个主题共享的所有提交创建新分支(您可以使用 commitish 或 tag 代替)

git checkout -b topics topic1^

然后在 master 上变基

git rebase master

然后在共享分支上重新设置两个主题。

git checkout topic1
git rebase topics
git checkout topic2
git rebase topics

这应该有效。现在你可以删除临时分支。

git branch -d topics

0
投票
$ git switch topic2
$ git rebase --update-refs master
Successfully rebased and updated refs/heads/topic2.
Updated the following refs with --update-refs:
    refs/heads/topic1
© www.soinside.com 2019 - 2024. All rights reserved.