将压缩的提交从主分支合并到功能分支时避免 git 中的冲突

Ale*_*eev 7 git git-merge branching-and-merging git-squash git-merge-conflict

考虑以下做法:

  • 开发人员从main功能分支中分支并根据需要创建尽可能多的提交
  • 一旦功能完成,所有提交都会被压缩并合并到分支中main(例如,想想 GitHub 的“压缩并合并”按钮)

现在这是我感兴趣的一个用例:

  1. feature1创建分支并在分支上工作
  2. feature2从分支的最后一次提交开始创建一个分支feature1(参见C下图中的提交)
  3. 挤压并合并feature1main(参见提交G
  4. 将这个新创建的提交合并到分支Gfeature2
  5. feature2继续在分支工作

换句话说,第 4 步中合并Gfeature2分支中的操作如下所示:

user@host:~/repo (main)$ git checkout feature2
user@host:~/repo (feature2)$ git merge main     # merge G into feature2
Run Code Online (Sandbox Code Playgroud)

压缩和合并后合并冲突

通常,这种合并(请参阅提交H)会导致许多合并冲突。

如何彻底消除这些矛盾呢?

我能想到的最简单的解决方案如下(见下图):

user@host:~/repo (main)$ git checkout feature1
user@host:~/repo (feature1)$ git merge main         # merge G into feature1; essentially, an empty commit
user@host:~/repo (feature1)$ git checkout feature2
user@host:~/repo (feature2)$ git merge feature1     # merge G' into feature2
Run Code Online (Sandbox Code Playgroud)

克服压缩和合并后的合并冲突

换句话说,我们不是直接合并G到,而是先合并到,然后再合并到。feature2Gfeature1feature1feature2

有没有更简单的方法?

Gaë*_*l J 4

我会在它被压缩和合并之后重新feature2建立基础mainfeature1

就像是:

git checkout feature2
git rebase --onto main C feature2
Run Code Online (Sandbox Code Playgroud)

这会将. 之上的提交从C(独占)变基为(包含) 。feature2main

因此,feature2 不会将 main 合并到 feature2(红色)中,而是移动到 main(绿色)之上。 在此输入图像描述

但我不确定它是否更简单。一个缺点是您将main在生成的分支中获得提交(但我猜这就是您最终想要的)。

个人意见:如果分支被其他人用作参考,那么首先不要使用squash。