snoofkin
snoofkin

Reputation: 8895

override merge two branches in Git

Is there any way to merge branch A into B and Override anything in B with what with A no matter if there are conflicts or not?

Upvotes: 1

Views: 186

Answers (3)

torek
torek

Reputation: 488183

The two answers already posted (-X ours and -s ours) are both correct, or, equivalently, both wrong. It depends on what you want as a result.

Here's a simple but concrete example. Suppose we have the following:

          O
        /   \
... - B       M
        \   /
          T

where B is the common base commit, O is "our" commit, T is "their" commit, and M is the merged result (that we want generated).

Suppose further that in commit B, file conflict.txt says:

I am a file
that contains
some text.

Another file, README, is completely empty.

In commit O, we changed line two to read that has instead of that contains. (That is, we changed line two a bit.) We did not touch README at all.

In commit T, they changed line two to read that used to have.(That is, they changed the word "contains" to "still contains".) They also added some text toREADME`.

Now, if you ask git to merge their branch into our branch, there will be a conflict in file conflict.txt, because git doesn't know what to do with the conflicting changes. Using -X ours tells git: in case of conflict, use our version, so commit M will keep our change and discard their change.

On the other hand, there is no conflict with README, because we did not change it. Only they changed README. With -X ours, commit M will keep their change.

Using -s ours, however, git will keep our version of README as well.

It's not clear to me, based on your question, which of these—or perhaps what third non-built-in alternative—you want.

Upvotes: 1

rageandqq
rageandqq

Reputation: 2281

You can use the -X flag to specify which to prefer, ours or theirs.

git merge <branch> -X ours will always prefer the version of the branch you are currently on, whereas git merge <branch> -X theirs will prefer the version of the branch being merged.

Checkout the following from man git-merge for more details:

ours

This option forces conflicting hunks to be auto-resolved cleanly by favoring our version. Changes from the other tree that do not conflict with our side are reflected to the merge result. For a binary file, the entire contents are taken from our side.

theirs

This is the opposite of "ours".

So in your case, running git merge B -X ours when on branch A should do the trick!

Upvotes: 1

user4938328
user4938328

Reputation:

You can do this:

$ git checkout branchA
$ git merge -s ours branchB

This merging is called the "ours" merging strategy.

Check out more on the merging documentation here.

Upvotes: 0

Related Questions