首页 > 解决方案 > 将压缩提交从主分支合并到功能分支时避免 git 中的冲突

问题描述

考虑以下做法:

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

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

换句话说,第 4 步中的合并Gfeature2分支中看起来像这样:

user@host:~/repo (main)$ git checkout feature2
user@host:~/repo (feature2)$ git merge main     # merge G into feature2

挤压和合并后的合并冲突

通常,这种合并(参见 commit 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

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

换句话说,我们不是直接merge Ginto feature2,而是先merge Ginto feature1,然后merge feature1into feature2

有没有更简单的方法?

标签: gitgit-mergebranching-and-merginggit-merge-conflictgit-squash

解决方案


我会feature2在压缩和合并main之后重新定位。feature1

就像是:

git checkout feature2
git rebase --onto main C feature2

Cfeature2main.

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

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


推荐阅读