Git: 解决合并冲突

Git: resolving merge conflicts

我以下面的例子来问一个我在工作中遇到的合并冲突问题

假设我在master分支中有一个名为mainFile.txt的文件,其内容是:

  1 this is the first line in master branch
  2 this is the second line in master branch
  3 this is the third line in master branch

我从 master 分支创建了两个分支:branchA 和 branchB,每个分支都有新行(来自两个分支中的第 4 行)添加到同一个 mainFile.txt 文件:

mainFile.txtbranchA中的内容:

  1 this is the first line in master branch
  2 this is the second line in master branch
  3 this is the third line in master branch
  4 This is the fourth line in branchA
  5 this is the fifth line in branchA

mainFile.txtbranchB中的内容:

  1 this is the first line in master branch
  2 this is the second line in master branch
  3 this is the third line in master branch
  4 This is the fourth line in branchB
  5 This is the fifth line in branchB
  6 This is the sixth line in branchB

现在,我需要将两个分支合并回 master。当我先合并branchA到master时没有问题。但是,当我将 branchB 合并到 master 时,会出现合并冲突。从以下合并冲突的附加屏幕截图中,我需要保留 branchA 和 branchB 的所有行。我想知道我应该如何解决合并冲突。我一直在尝试使用 vimdiff,但在我看来,我需要决定保留其中一个分支(而不是两个分支)。

感谢帮助!

首先你可以合并branchA到master。之后,当您尝试从命令行将 branchB 合并到 master 时,您会看到类似于

的错误

Automatic merge failed; fix conflicts and then commit the result

现在打开您的 mainFile.txt 分支 B。您将获得一行代码

<<<<<<< HEAD

因为这一行下面的代码你的分支有冲突。根据您的最终要求手动更改代码。

之后添加、提交并推送您的 mainFile.txt。在此之后你应该能够解决你的冲突。

最好使用像 meld 这样的任何三向合并工具 http://meldmerge.org/,它还考虑了这两个分支的共同祖先,这意味着您可以更轻松地识别更改并通过合并进行工作.使用 vi 或文本编辑器合并大而冲突的代码片段变得很困难,因为如果不向下滚动就无法在同一屏幕中看到比较。您可以 select 在启动合并时保留两个分支,当您有冲突时使用 git mergetool