Back

Explore Courses Blog Tutorials Interview Questions
+6 votes
2 views
in DevOps and Agile by (19.4k points)
edited by

When merging topic branch "B" into "A" using git merge, I get some conflicts. I know all the conflicts can be solved using the version in "B".

I am aware of git merge -s ours. But what I want is something like git merge -s theirs.

Why doesn't it exist? How can I achieve the same result after the conflicting merge with existing git commands? (git checkout every unmerged file from B)

UPDATE: The "solution" of just discarding anything from branch A (the merge commit point to B version of the tree) is not what I am looking for.

2 Answers

+5 votes
by (27.5k points)

We need to add -X to theirs. 

Here's an example:

$ git checkout branchOne

$ git merge -X theirs branchTwo

This will merge everything in the desired way. But if some files were deleted from branchTwo that may cause some error. 

In order to fix this just run git rm with the name of any files that were deleted:

$ git rm <DELETED-FILE-NAME>

Don't forget to perform git merge -X theirs after that. Of course, doing the actual removal with the git rm command will prevent the conflict from happening in the first place.

Note that a longer form option also exists. All you need to do is replace -X theirs with --strategy-option=theirs

+5 votes
by (62.9k points)

A possible and tested solution for merging branchB into our checked-out branchA:

# in case branchA is not our current branch

git checkout branchA

# make merge commit but without conflicts!!

# the contents of 'ours' will be discarded later

git merge -s ours branchB    

# make temporary branch to merged commit

git branch branchTEMP         

# get contents of working tree and index to the one of branchB

git reset --hard branchB

# reset to our merged commit but 

# keep contents of working tree and index

git reset --soft branchTEMP

# change the contents of the merged commit

# with the contents of branchB

git commit --amend

# get rid off our temporary branch

git branch -D branchTEMP

# verify that the merge commit contains only contents of branchB

git diff HEAD branchB

To automate it you can wrap it into a script using branchA and branchB as arguments.

This solution preserves the first and second parent of the merge commit, just as you would expect of git merge -s theirs branchB

If you thinking that why we need branchTEMP? We could have just done git reset --soft branchA? Note that git reset --hard changes which commit branchA points to.

Browse Categories

...