Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically resolve a Git conflict by taking the version in the current branch?

Let's suppose that I get a merge conflict on foo/bar.txt when running this:

$ git checkout A
$ git merge B

I'd like to automatically resolve the conflict by taking foo/bar.txt from branch A. (I know what I'm doing, and I do need this. The version in branch B is wrong, and I don't care about losing changes in the working tree in this case.) It seems that I can do it by running these commands:

$ git reset    foo/bar.txt
$ git checkout foo/bar.txt

Is there a simpler, single-command solution?

Unfortunately these commands change foo/bar.txt even if there is no conflict, and I don't want that. If there is no conflict, I want want to keep foo/bar.txt in whatever state git merge B has left it.

So I need a Unix shell command, which would detect if there is a conflict in foo/bar.txt, and if there is, it would resolve the conflict by taking the version of foo/bar.txt from the current branch. It wouldn't do anything else, i.e. it wouldn't modify other files, it wouldn't commit the changes, and it wouldn't change foo/bar.txt if there is no conflict in that file.

like image 831
pts Avatar asked Jan 06 '13 12:01

pts


People also ask

How do I accept all current changes in Git conflict?

git rebase repo. right click file with conflicts without left-click / opening file in editor pane. click "Accept all Incoming" / "Accept all Current"

How do you resolve a merge conflict on the same branch?

To fix this situation, you need to create new commits that mimic those on the branch. The easiest way to do that is with git rebase -f . Now you can merge branch in again.


2 Answers

You can specify the merge strategy option ours to the recursive (the default) merge strategy. It will do a normal merge, but in case of conflicting hunks will choose the version of the current branch.

git checkout A
git merge -Xours B
like image 200
knittl Avatar answered Oct 02 '22 05:10

knittl


If you want to do it as a one-off, the single-line command is:

$ git checkout --ours foo/bar.txt  # <-- resets it only if the merge found conflicts in this file
$ git checkout HEAD -- foo/bar.txt # <-- resets it to that specific version no matter what

To configure git's merge to permanently ignore all upstream changes to a locally-changed file:

$ git config merge.pin.driver true
$ echo foo/bar.txt merge=pin >> .git/info/attributes

(true above is just the unix true command, its success says it made the local version look right, in this case by doing nothing to it. You can of course get more sophisticated with your merge commands.)

I think you don't want merge --strategy=ours or --strategy-option=ours, those apply to entire merges.

like image 31
jthill Avatar answered Oct 03 '22 05:10

jthill