Q . How to force merge to a branch when there are conflicts?

Mike Tyson. asked, Aug 31 ' 2018

I am trying to merge a alpha branch to dev branch but getting lot of conflicts in many file. I want to merge it forcefully just want to keep alpha branch copy of dev branch. Is there any way to do it?

  • git
  • git-merge

2 Answers

There's no way to merge without resolving conflicts. Otherwise, how would git know what to merge? You can, however, checkout the version from either branch you're merging using git checkout --ours <filepath> or git checkout --theirs <filepath>. Here's an example:

Suppose you're on the master branch merging in staging:

git checkout master
git merge staging

And git shows a bunch of conflicts:

...
CONFLICT: Readme.md
...

If you want to keep the version of Readme.md that's on master, then you would run:

git checkout --ours Readme.md

Note that since you're on master --ours refers to "this" branch, i.e. master.

Now, you can simply add it to the index to mark it as resolved:

git add Readme.md

This effectively ignores any changes to Readme.md on the staging branch.

You can repeat this process for each file you want to omit from the merge. When you're done, commit as you normally would:

git commit -m "whatever..."

In order to repeat it for all files with conflicts you can do

for f in $(git diff --name-only --diff-filter=U | cat); do
   echo "Resolve conflict in $f ..."
   git checkout --theirs $f
done

There's no way around resolving conflicts, that's how revision control works (if Alice says "a" and Bob says "b", how should Git know which one is correct unless you tell it?). All you can do is direct git to resolve them itself when merging in one of several possible ways, e.g.

git merge -s recursive -X theirs <branch>

(-s recursive is the default when there's only one <branch> so you can omit it here)

Now that you already have a conflict in your tree, you either

  • follow the manual resolution route
    • edit the file to your heart's desire
    • git add it (add in Git doubles as marking a file resolved)
    • git commit to complete the merge; or
  • restore the pre-merge state with git merge --abort and retry the merge with the above-mentioned auto-resolution options

Leave a Ansewer