当将分支(例如功能分支)合并到主分支之前进行变基时,我必须手动查找分支创建的时间,以告诉 git rebase
变基的起始点。
我有强烈的感觉这可以自动化 - 有没有一种方法可以告诉 git rebase
从分支创建时开始?
当将分支(例如功能分支)合并到主分支之前进行变基时,我必须手动查找分支创建的时间,以告诉 git rebase
变基的起始点。
我有强烈的感觉这可以自动化 - 有没有一种方法可以告诉 git rebase
从分支创建时开始?
master
的分支feature/foo
上工作。 F--J--K--|feature/baz|
/
A--B--D--G--|master|
\
C--E--H--|feature/foo|HEAD|
master
进行rebase
,有不同的选择:
As explained by remram you can explicitly name the target commit using the --onto
:
// 1.1. Will move the flag `feature/foo`
git rebase --onto master B feature/foo
// 1.2. Will not move the flag `feature/foo`
git rebase --onto master B H
// 1.3. If the HEAD is at H
git rebase --onto master B
Since the --onto
lets you define the target commit it is useful if you want to rebase feature/foo
onto feature/baz
which do not share a common branch base.
// 1.4. Will rebase `feature/foo` onto `feature/baz`
git rebase --onto feature/baz B feature/foo
/--|feature/baz|
/
F--J--K--C'--E'--H'--|feature/foo|HEAD|
/
A--B--D--G--|master|
As explained by Stefan Fleiter you do not have to name the ancestor if feature/foo
is based on master
:
// 2.1. Explicitly naming feature/foo as the branch to be rebased onto master
git rebase master feature/foo
// 2.2. Assuming that feature/foo is currently checked out aka. HEAD
git checkout feature/foo
git rebase master
If you do not feel comfortable with the rebase
process since your former branch feature/foo
"disappears" cherry-pick
might be a feel-good alternative for you. The command allows to specify a range of commits and behaves very similar to rebase --onto
. The difference is that the branch you are cherry-picking from will remain untouched.
// 3.1.1. Start by creating a new branch where master is
git checkout master
git checkout -b feature/foo-cherried
F--J--K--|feature/baz|
/
A--B--D--G
\ \
\ \-|master|feature/foo-cherried|HEAD|
\
C--E--H--|feature/foo|
// 3.1.2. Pick a range starting at the common branch base
git cherry-pick B..H
F--J--K--|feature/baz|
/
A--B--D--G--C'--E'--H'--|feature/foo-cherried|HEAD|
\ \
\ \-|master|
\
C--E--H--|feature/foo|
// 3.1.3. Later on if everything worked fine you can
// delete the unmerged branch feature/foo
git branch -D feature/foo
F--J--K--|feature/baz|
/
A--B--D--G--C'--E'--H'--|feature/foo-cherried|HEAD|
\
\-|master|
想要了解关于 git rebase --onto
更多信息,我推荐这篇博客文章:
对我来说非常有效的方法是只使用git rebase master -i
。
这假设你 1) 站在你想要变基的分支上,2) 变基到主分支上。它还允许我编辑每个提交(如果必要)。
git rebase --onto 目标 开始点 我的分支
。如果省略我的分支
,将使用当前分支。git rebase 目标
即可。在这种情况下,将使用当前分支(我的分支
)和目标
的最后一个共同祖先(参见merge-base)。因此,如果您正在将功能分支重新基于其所依赖的分支,则应该使用最后一种形式。当使用git进行特性分支的变基时,您不必知道公共祖先。只需切换到您的特性分支即可。
git checkout my-feature-branch
将分支变基到主分支或其他你喜欢的分支
git rebase master
切换回主分支
git checkout master
并且(快进)将功能分支合并到主分支中,将HEAD设置为最新的重新基础化提交。
git merge my-feature-branch
更多详细信息,请查看Pro Git书中的详细说明。希望这能回答您的问题。