如何解决Git中的合并冲突
有没有很好的方法来解释如何解决Git中的合并冲突?
解决方案
- 确定哪些文件有冲突(Git会告诉我们)。
- 打开每个文件并检查差异; Git将它们划分边界。希望可以很清楚地看到每个块的版本。我们可能需要与提交代码的其他开发人员进行讨论。
- 解决冲突后,在文件git中添加the_file。
- 解决所有冲突后,请执行git rebase --continue或者Git完成后说的任何命令。
如果我们经常进行小的提交,则首先使用git log --merge查看提交注释。然后git diff
将显示冲突。
对于涉及多行的冲突,更容易查看外部GUI工具中发生的情况。我喜欢opendiff -Git还支持vimdiff,gvimdiff,kdiff3,tkdiff,meld,xxdiff,可以直接安装,也可以安装其他工具:git config merge.tool" your.tool"将设置我们选择的工具,然后
合并失败后的git mergetool`将向我们显示上下文中的差异。
每次我们编辑文件以解决冲突时,git add filename
将更新索引,并且差异将不再显示它。当所有的冲突都被解决并且它们的文件已经被git add
-ed时,git commit
将完成合并。
试试:git mergetool
它将打开一个GUI,逐步引导我们解决每个冲突,然后我们可以选择如何合并。有时,之后需要进行一些手动编辑,但通常仅此一项就足够了。这肯定比手工完成整个事情要好得多。
根据@JoshGlover的评论:
除非我们安装一个GUI,否则该命令不一定会打开GUI。对我运行git mergetool
导致使用了vimdiff
。我们可以安装以下工具之一来代替使用它:meld
,opendiff
,kdiff3
,tkdiff,
xxdiff,
tortoisemerge,
gvimdiff,
diffuse,
ecmerge,
p4merge,
araxis,
vimdiff,
emerge`。
下面是使用vimdiff
解决合并冲突的示例过程。基于此链接
步骤1:在终端中运行以下命令
git config merge.tool vimdiff git config merge.conflictstyle diff3 git config mergetool.prompt false
这会将vimdiff设置为默认的合并工具。
步骤2:在终端中运行以下命令
git mergetool
步骤3:我们将看到以下格式的vimdiff显示
+----------------------+ | | | | |LOCAL |BASE |REMOTE | | | | | +----------------------+ | MERGED | | | +----------------------+
这4个视图是
LOCAL – this is file from the current branch BASE – common ancestor, how file looked before both changes REMOTE – file you are merging into your branch MERGED – merge result, this is what gets saved in the repo
我们可以使用ctrl + w在这些视图之间导航。我们可以先按ctrl + w再按j,直接进入合并视图。
有关此处和此处的vimdiff导航的更多信息
步骤4.我们可以通过以下方式编辑MERGED视图
如果我们想从REMOTE获得更改
:diffg RE
如果要从BASE获得更改
:diffg BA
如果我们想从本地获得更改
:diffg LO
步骤5.保存,退出,提交和清理
:wqa
保存并退出vi
git commit -m"消息"
git clean
删除由diff工具创建的多余文件(例如* .orig)。
请查看Stack Overflow问题中的答案,中止在Git中进行合并,尤其是Charles Bailey的答案,该答案显示了如何查看有问题的文件的不同版本,例如,
# Common base version of the file. git show :1:some_file.cpp # 'Ours' version of the file. git show :2:some_file.cpp # 'Theirs' version of the file. git show :3:some_file.cpp
从顶部开始,这是一个可能的用例:
我们将进行一些更改,但是,哦,我们不是最新的:
git fetch origin git pull origin master From ssh://[email protected]:22/projectname * branch master -> FETCH_HEAD Updating a030c3a..ee25213 error: Entry 'filename.c' not uptodate. Cannot merge.
因此,我们可以及时了解最新信息并重试,但是会发生冲突:
git add filename.c git commit -m "made some wild and crazy changes" git pull origin master From ssh://[email protected]:22/projectname * branch master -> FETCH_HEAD Auto-merging filename.c CONFLICT (content): Merge conflict in filename.c Automatic merge failed; fix conflicts and then commit the result.
因此,我们决定看一下更改:
git mergetool
哦,我,哦,我的上游更改了一些内容,但是只是为了使用我的更改...不...他们的更改...
git checkout --ours filename.c git checkout --theirs filename.c git add filename.c git commit -m "using theirs"
然后我们尝试最后一次
git pull origin master From ssh://[email protected]:22/projectname * branch master -> FETCH_HEAD Already up-to-date.