基本合并冲突
有时,这个过程不会顺利进行。 如果您在要合并的两个分支中以不同的方式更改了同一文件的同一部分,Git 将无法干净地合并它们。 如果您对 issue #53 的修复程序修改了与 hotfix 分支相同的文件部分,您将遇到如下所示的合并冲突。
$ git merge iss53
Auto-merging index.html
CONFLICT (content): Merge conflict in index.html
Automatic merge failed; fix conflicts and then commit the result.
Git 没有自动创建新的合并提交。 它已暂停该过程,同时您解决冲突。 如果您想在合并冲突后的任何时候查看哪些文件未合并,您可以运行 git status。
$ git status
On branch master
You have unmerged paths.
(fix conflicts and run "git commit")
Unmerged paths:
(use "git add
both modified: index.html
no changes added to commit (use "git add" and/or "git commit -a")
任何具有合并冲突且尚未解决的内容都列为未合并。 Git 将标准的冲突解决标记添加到具有冲突的文件中,因此您可以手动打开它们并解决这些冲突。 您的文件包含如下所示的部分。
<<<<<<< HEAD:index.html
=======
>>>>>>> iss53:index.html
这意味着 HEAD 中的版本(您的 master 分支,因为那是您在运行 merge 命令时检出的分支)是该块的顶部(======= 以上的所有内容),而您的 iss53 分支中的版本看起来像底部部分中的所有内容。 为了解决冲突,您必须选择一方或另一方,或者自己合并内容。 例如,您可以通过将整个块替换为以下内容来解决此冲突
此解决方案包含每个部分的一些内容,并且 <<<<<<<、======= 和 >>>>>>> 行已完全删除。 在您解决每个冲突文件中这些部分之后,在每个文件上运行 git add 以将其标记为已解决。 暂存文件将其标记为在 Git 中已解决。
如果您想使用图形工具来解决这些问题,您可以运行 git mergetool,它会启动一个合适的视觉合并工具,并引导您完成冲突。
$ git mergetool
This message is displayed because 'merge.tool' is not configured.
See 'git mergetool --tool-help' or 'git help config' for more details.
'git mergetool' will now attempt to use one of the following tools:
opendiff kdiff3 tkdiff xxdiff meld tortoisemerge gvimdiff diffuse diffmerge ecmerge p4merge araxis bc3 codecompare vimdiff emerge
Merging:
index.html
Normal merge conflict for 'index.html':
{local}: modified file
{remote}: modified file
Hit return to start merge resolution tool (opendiff):
如果您想使用默认工具之外的合并工具(在这种情况下,Git 选择 opendiff 是因为该命令是在 macOS 上运行的),您可以在顶部的“以下工具之一”之后看到列出的所有受支持的工具。 只需键入您更喜欢使用的工具的名称即可。
注意
如果您需要更高级的工具来解决棘手的合并冲突,我们将在 高级合并 中介绍更多关于合并的内容。
退出合并工具后,Git 会询问您合并是否成功。 如果您告诉脚本它是成功的,它会暂存该文件以将其标记为已为您解决。 您可以再次运行 git status 以验证是否已解决所有冲突。
$ git status
On branch master
All conflicts fixed but you are still merging.
(use "git commit" to conclude merge)
Changes to be committed:
modified: index.html
如果您对此感到满意,并且您验证了所有存在冲突的内容都已暂存,您可以键入 git commit 以完成合并提交。 默认情况下,提交消息如下所示
Merge branch 'iss53'
Conflicts:
index.html
#
# It looks like you may be committing a merge.
# If this is not correct, please remove the file
# .git/MERGE_HEAD
# and try again.
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# On branch master
# All conflicts fixed but you are still merging.
#
# Changes to be committed:
# modified: index.html
#
如果您认为这对将来查看此合并的其他人有帮助,您可以修改此提交消息,其中包含有关您如何解决合并的详细信息,并解释您进行所做更改的原因(如果这些原因不明显)。