使用Git删除不需要的合并提交和rebase

ted*_*777 5 git rebase git-merge

我有一个功能分支开发.我开始使用通过开发而不是合并来重新定义我的功能分支的做法,因为线性提交历史的好处适合于我的项目,该项目具有一些上游和下游存储库.

我正处于某人合并开发到功能分支并进行更多提交然后推送到远程的情况.我希望能够得到我删除合并提交的点,并选择分支上的后续提交.这是因为知道在分支机构工作的其他人必须基本上删除他们的本地人并下拉修改后的人.我在一个小团队工作,这是可管理的.

最好的方法是做一个交互式rebase选择合并提交的所有提交栏吗?

所以 git rebase -i commit-sha-before-merge

我知道这很可能会导致构建中断,因为合并后发生的提交依赖于合并中的代码.我将通过最终使用develop重新定义我的功能分支来解决这个问题.

小智 7

正如torek 在评论中指出的那样,在Git中有不止一种方法可以做到这一点.比如说,你有一个像这样的提交图:

develop *-------*
         \       \
  feature *---*---*---*---*
          X   M^  M   Y^  Y
Run Code Online (Sandbox Code Playgroud)

X是您的功能分支上的第一个提交,M是带有develop的合并提交,Y是功能分支上的最后一个提交.

解决方案1:Rebases

这取决于将分支B重新分支到另一个分支A上的事实相当于将分支A 合并到B中.在这种情况下,我们将使用两个rebase,一个用于在合并提交之前修改功能分支提交,另一个用于在合并之后重新提交提交:

# Create a temporary branch at the commit right before the merge commit M
git checkout -b temp M^

# Rebase onto the develop branch
git rebase develop

# Now rebase the remaining commits after M onto the temp branch
git rebase --onto temp M feature
Run Code Online (Sandbox Code Playgroud)

这将生成以下提交图

        X   M^  Y^  Y
*---*---*---*---*---*
    ^       ^       ^
 develop   temp  feature
Run Code Online (Sandbox Code Playgroud)

所以现在你可以删除临时分支git branch --delete temp.

解决方案2:Cherry-picks

以下是使用cherry-picks获得相同结果的方法,比如torek建议:

# Temporarily hard reset feature to the develop branch
git checkout feature
git reset --hard develop

# Cherry-pick all commits between X to M^.
# The start of the cherry-pick range is exclusive, i.e. it doesn't include
# the starting point X^.
git cherry-pick X^..M^

# Cherry-pick all commits between M to Y
git cherry-pick M..Y
Run Code Online (Sandbox Code Playgroud)

文档