简体   繁体   中英

override merge two branches in Git

有没有办法将分支A合并到B中并用A覆盖B中的任何内容,而不管是否存在冲突?

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!

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 to README`.

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM