快速处理 Git 冲突

2019-08-16 ⏳1.7分钟(0.7千字)

我一直是在终端下使用 git 的。如果合并分支或者执行 rebase 遇到冲突,处理起来比较麻烦。今天 rebase 开发分支的时候又遇到了一堆冲突,于是就花了点时间研究如何快速处理 git 冲突。方法很简单,就是将 conflictstyle 配置改成 diff3。下面为大家细细分解。

我准备了一个演示项目,大家可以去 https://github.com/taoso/git-conflictstyle-demo 克隆。

git 的默认 conflictstylemerge,遇到冲突后(在演示项目执行 git merge feature_branch)会显示如下标记:

<<<<<<< HEAD
Alice asked her parents if she could
borrow their car. They said ok but told
=======
Alice asked her father if she could
borrow his motorbike. He said ok but told
>>>>>>> feature_branch
her she had to be back by 11pm.

这其中<<<<<<< HEAD=======之间的部分表示当前所在分支(也就是HEAD)的内容,而=======>>>>>>> feature_branch之间的部分则是 feature_branch 分支的内容。看到这个冲突就头大,因为我们无法确定要留哪一行删哪一行。

如果我们执行git config --global merge.conflictstyle diff3conflictstyle设成diff3,则结果会变成

<<<<<<< HEAD
Alice asked her parents if she could
borrow their car. They said ok but told
||||||| merged common ancestors
Alice asked her father if she could
borrow his car. He said ok but told
=======
Alice asked her father if she could
borrow his motorbike. He said ok but told
>>>>>>> feature_branch
her she had to be back by 11pm.

大家注意多出来的||||||| merged common ancestors=======之间的部分。git 在合并分支的时候用的是三路合并(3-way merge)。三路合并的关键就是找到两个分支的最新公共提交版本。在这个例子中,公共提交版本的内容就保存到了||||||| merged common ancestors=======之间。

很显然,master 分支将Alice asked her father if she could改成了Alice asked her parents if she could,也就是 Alice 现在要向她的父母借车;而 feature_branch 分支则将 borrow his car...改成了borrow his motorbike...,也就是不借车了,要借摩托。两者合并,最终结果应该是:

Alice asked her parents if she could
borrow their motorbike. They said ok but told
her she had to be back by 11pm.

我还找了一个例子。

cauliflower
<<<<<<< HEAD
peas
potatoes
=======
>>>>>>> topic
tomatoes

单看这种merge风格的冲突会很困惑,为什么 peas 会和空行冲突呢?如果开启了三路冲突展示,你会看到

cauliflower
<<<<<<< HEAD
peas
potatoes
||||||| merged common ancestors
peas
=======
>>>>>>> topic
tomatoes

这下就明了了,原来是 topic 分支删掉了 peas 一行,而当前分支又在 peas 下加了 potatoes 一行。所以正确的处理结果应该是只保留 potatoes。如果不开启 diff3选项,我们是很难正确处理这类冲突的。

好了,今天就说到这里。三路合并冲突你理解了吗?欢迎留言讨论。

  1. https://devblog.classy.org/git-merge-conflicts-resolution-made-easy-f44d9fbd7fec
  2. https://psung.blogspot.com/2011/02/reducing-merge-headaches-git-meets.html