git 如何将两个主题分支转换为一个新分支?

lokaqttq  于 2023-05-05  发布在  Git
关注(0)|答案(4)|浏览(200)

这是我的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

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

7rfyedvj

7rfyedvj1#

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的所有提交!这个语法可能更容易理解,但是如果topic1does 包含不在topic2中的提交,解决方案会有所不同。如果是这种情况,前一种解决方案将简单地 * 丢弃 * 任何不在topic2中的提交,而后者将它们合并到topic2中。这两种结果可能都是不可取的,但在我看来,从第一种解决方案中可以更清楚地看到会发生什么,这就是为什么我把它放在第一位。
举例来说,如果你的提交历史看起来像这样:

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

那么第一个解(rebasebranch)会给予你:

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

第二个(rebaserebase):

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

(If如果你把它做成了一个脚本,你可以使用git merge-base topic1 topic2来找到提交的id,并把它放到tmp分支中。

fsi0uk1n

fsi0uk1n2#

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

nlejzf6q

nlejzf6q3#

你可以一个接一个地对topic1topic2分支进行变基。
重定第一个的基

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
c0vxltue

c0vxltue4#

$ 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

相关问题