我如何在我的 Git 存储库中解决合并冲突?


当前回答

我发现的最好的东西是使用“diff3”合并冲突风格:

<<<<<<<
Changes made on the branch that is being merged into. In most cases,
this is the branch that I have currently checked out (i.e. HEAD).
|||||||
The common ancestor version.
=======
Changes made on the branch that is being merged in. This is often a 
feature/topic branch.
>>>>>>>

如果冲突更长,那么我会把三个部分切成三个单独的文件,如“小”,“普通”和“天花板”。

diff common mine
diff common theirs

提示2

git log --merge -p <name of file>

如果你有自动测试,运行这些,如果你有绳子,运行它,如果这是一个可构建的项目,然后在你承诺之前建造它,等等,在所有情况下,你需要做一些测试,以确保你的变化没有打破任何东西。

例如,如果你知道你和另一个人都在不同的重复工作,这两者都会影响相同的文件集,你应该提前彼此谈话,并更好地了解你每个人都在做什么类型的变化。

如果你不确定合并,不要强迫它。

其他回答

如果你只是想恢复远程主机,那么

git reset --hard origin/master

警告:所有本地变更将被丢失,请参见 https://stackoverflow.com/a/8476004/11769765.

下面是可能的使用案例,从顶部:

你会拖一些变化,但哦,你没有到目前为止:

git fetch origin
git pull origin master

From ssh://gitosis@example.com: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://gitosis@example.com: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://gitosis@example.com:22/projectname
 * branch            master     -> FETCH_HEAD
Already up-to-date.

是的!

你可以以一些方式解决合并冲突,因为其他人已经详细说明了。

我认为真正的关键是知道如何在本地和远程存储库中流动的变化。 关键是理解跟踪分支. 我发现我认为跟踪分支是我之间的“中间失落的片段”我的本地,实际的文件目录和远程定义为起源。

而不是:

git add .
git commit -m"some msg"

相反,我做:

git add file,file2,file3...
git commit # Then type the files in the editor and save-quit.

因此,你更有意识到哪些文件被添加,你也可以查看列表,并在使用编辑器为消息时思考更多。

[更新 - 随着时间的流逝,我已经更换到:

git status # Make sure I know whats going on
git add .
git commit # Then use the editor

)

此外(更重要的是你的情况),我试图避免:

git pull

git pull origin master.

git checkout master
git fetch   
git rebase --hard origin/master # or whatever branch I want.

你也可能會發現這有用:

git 分支, fork, fetch, merge, rebase 和 clone,什么是差异?

简单地说,如果你知道其中一个存储库的变化并不重要,并且想解决所有变化,有利于另一个,请使用:

git checkout . --ours

以您的存储库的利益来解决更改,或者

git checkout . --theirs

以解决其他或主要存储库的利益的变更。

或者你将不得不使用一个 GUI 合并工具,一步一步通过文件,说合并工具是 p4merge,或者写下你已经安装的任何一个的名字。

git mergetool -t p4merge

完成文件后,您将不得不保存和关闭,以便下一个将打开。

对于使用 Visual Studio 的用户(Visual Studio 2015 在我的情况下)

关闭您的项目在Visual Studio. 特别是在大型项目,Visual Studio倾向于在使用UI合并时脱离。 立即在命令中进行合并. git checkout target_branch git merge source_branch 然后在Visual Studio中打开项目,然后转到Team Explorer → Branch。