如何防止两个文件都“添加”合并冲突?

时间:2019-11-15 16:04:14

标签: git merge merge-conflict-resolution git-merge-conflict

我想合并一个分支,该分支添加了我也添加的文件:

Unmerged paths:
  (use "git add <file>..." to mark resolution)
        both added:      file

我想通过将file的版本重命名为other_file来解决此冲突,同时保留另一个分支的版本。

我的解决方法是:

git checkout --ours file
mv file other_file
git checkout --theirs file
git add file other_file

有更简单或更直接的解决方案吗?

1 个答案:

答案 0 :(得分:0)

我重新创建了这种冲突:

$ git merge b1
CONFLICT (add/add): Merge conflict in newfile
Auto-merging newfile
Automatic merge failed; fix conflicts and then commit the result.

实际上,Git尝试合并工作树中的文件:

$ cat newfile   
<<<<<<< HEAD
different contents - add a file
||||||| merged common ancestors
=======
add a file
>>>>>>> b1

您的方法可以正常工作。这不是很短,并且根据您的Git年份,可能会在行尾进行修改,从而产生小故障:

$ git show :2:newfile > other_file   # extract --ours version, to new name
$ git checkout --theirs newfile
Updated 1 path from the index
$ git add newfile other_file
$ it status -s
M  newfile
A  other_file

(简短的status显示,两个文件现在可以提交了。它们的内容是:

$ cat newfile
add a file
$ cat other_file
different contents - add a file

请注意,git show不会运行污迹过滤器,也不会进行行尾转换,至少在较旧的Git版本中(Git已获得了进行文本转换的功能,也许还有git show现在默认情况下会执行这些操作-我尚未对此进行测试。