我想要重基到一个特定的提交,而不是另一个分支的HEAD:

A --- B --- C          master
 \
  \-- D                topic

to

A --- B --- C          master
       \
        \-- D          topic

而不是

A --- B --- C          master
             \
              \-- D    topic

我怎样才能做到呢?


当前回答

如果您希望返回到不止一次提交,还有另一种方法。

下面是一个返回到n次提交的例子:

git branch topic master~n

为了解决这个问题,还可以这样做:

git branch topic master~1

该命令在git 2.7.4版本上运行良好。还没在其他版本上测试过。

其他回答

添加到答案中使用——onto:

我从来没有把它背下来,所以我写了这个小助手脚本: Git:将一个分支(子)从一个基基重设为另一个基基,留下另一个基基的提交。

用法:

moveBranch <branch> from <previous-base> to <new-base>

简而言之:

git rebase --onto "$3" "$2" "$1"

除此之外,还有一个类似的解决方案,那就是选择一系列的提交:

git co <new-base> 
git cherry-pick <previous-base>..<branch>
git branch -f branch

两者的效果差不多。请注意,此语法跳过<previous-branch>本身的提交,因此它会优选下一个和后续的提交,包括<branch>的提交。

使用"onto"选项:

git rebase --onto master^ D^ D

OR

git rebase --onto <commitB> <commitA> <commitD>

最后3个参数的意思是: destination (new-parent,这里是commitB) Start-after (current-parent,第一个提交被移动的父节点), 和end-inclusive(要移动的最后一个提交)。

你可以通过在commit上创建一个临时分支来避免使用——onto参数,然后以简单的形式使用rebase:

git branch temp master^
git checkout topic
git rebase temp
git branch -d temp

既然调整基地是如此重要,下面是内斯特·米利耶夫(Nestor Milyaev)答案的扩展。结合jsz和Adam Dymitruk回答中的Simon South的评论,得到了这个命令,无论它是从主分支的提交A还是C中分支,它都可以在topic分支上工作:

git checkout topic
git rebase --onto <commit-B> <pre-rebase-A-or-post-rebase-C-or-base-branch-name>

注意,最后一个参数是必需的(否则它会倒带分支以提交B)。

例子:

# if topic branches from master commit A:
git checkout topic
git rebase --onto <commit-B> <commit-A>
# if topic branches from master commit C:
git checkout topic
git rebase --onto <commit-B> <commit-C>
# regardless of whether topic branches from master commit A or C:
git checkout topic
git rebase --onto <commit-B> master

最后一个命令是我通常使用的命令。

你甚至可以采取直接的方法:

git checkout topic
git rebase <commitB>